Giter Site home page Giter Site logo

igalklebanov / kysely-surrealdb Goto Github PK

View Code? Open in Web Editor NEW
56.0 3.0 2.0 368 KB

Kysely dialects, plugins and other goodies for SurrealDB

License: MIT License

JavaScript 3.09% TypeScript 96.91%
kysely kysely-dialect query-builder sql surrealdb surrealdb-driver type-safe typescript

kysely-surrealdb's Introduction

kysely-surrealdb

Powered by TypeScript

Kysely dialects, plugins and other goodies for SurrealDB.

SurrealQL is based on SQL, so why not? :trollface:

Installation

NPM 7+

npm i kysely-surrealdb

NPM <7

npm i kysely-surrealdb kysely surrealdb.js

Yarn

yarn add kysely-surrealdb kysely surrealdb.js

PNPM

pnpm add kysely-surrealdb kysely surrealdb.js

surrealdb.js is an optional peer dependency. It's only needed if you want to use SurrealDbWebSocketsDialect. If you don't need it, you can remove surreal.js from the install commands above.

Deno

This package uses/extends some Kysely types and classes, which are imported using its NPM package name -- not a relative file path or CDN url.

SurrealDbWebSocketsDialect uses surrealdb.js which is imported using its NPM package name -- not a relative file path or CDN url.

To fix that, add an import_map.json file.

{
  "imports": {
    "kysely": "npm:kysely@^0.25.0",
    "surrealdb.js": "https://deno.land/x/[email protected]" // optional - only if you're using `SurrealDbWebSocketsDialect`
  }
}

Usage

HTTP Dialect

SurrealDB's HTTP endpoints allow executing SurrealQL queries in the browser and are a great fit for serverless functions and other auto-scaling compute services.

Node.js 16.8+

Older node versions are supported as well, just swap undici with node-fetch.

import {Kysely} from 'kysely'
import {SurrealDatabase, SurrealDbHttpDialect, type SurrealEdge} from 'kysely-surrealdb'
import {fetch} from 'undici'

interface Database {
  person: {
    first_name: string | null
    last_name: string | null
    age: number
  }
  own: SurrealEdge<{
    time: {
      adopted: string
    } | null
  }>
  pet: {
    name: string
    owner_id: string | null
  }
}

const db = new Kysely<SurrealDatabase<Database>>({
  dialect: new SurrealDbHttpDialect({
    database: '<database>',
    fetch,
    hostname: '<hostname>', // e.g. 'localhost:8000'
    namespace: '<namespace>',
    password: '<password>',
    username: '<username>',
  }),
})

WebSockets Dialect

import {Kysely} from 'kysely'
import {SurrealDatabase, SurrealDbWebSocketsDialect, type SurrealEdge} from 'kysely-surrealdb'
import Surreal from 'surrealdb.js'

interface Database {
  person: {
    first_name: string | null
    last_name: string | null
    age: number
  }
  own: SurrealEdge<{
    time: {
      adopted: string
    } | null
  }>
  pet: {
    name: string
    owner_id: string | null
  }
}

// with username and password
const db = new Kysely<SurrealDatabase<Database>>({
  dialect: new SurrealDbWebSocketsDialect({
    database: '<database>',
    Driver: Surreal,
    hostname: '<hostname>', // e.g. 'localhost:8000'
    namespace: '<namespace>',
    password: '<password>',
    // scope: '<scope>', // optional
    username: '<username>',
  }),
})

// alternatively, with a token
const dbWithToken = new Kysely<SurrealDatabase<Database>>({
  dialect: new SurrealDbWebSocketsDialect({
    database: '<database>',
    Driver: Surreal,
    hostname: '<hostname>', // e.g. 'localhost:8000'
    namespace: '<namespace>',
    token: '<token>',
  }),
})

SurrealKysely Query Builder

The awesomeness of Kysely, with some SurrealQL query builders patched in.

This example uses SurrealDbHttpDialect but SurrealDbWebSocketsDialect works just as well.

import {SurrealDbHttpDialect, SurrealKysely, type SurrealEdge} from 'kysely-surrealdb'
import {fetch} from 'undici'

interface Database {
  person: {
    first_name: string | null
    last_name: string | null
    age: number
  }
  own: SurrealEdge<{
    time: {
      adopted: string
    } | null
  }>
  pet: {
    name: string
    owner_id: string | null
  }
}

const db = new SurrealKysely<Database>({
  dialect: new SurrealDbHttpDialect({
    database: '<database>',
    fetch,
    hostname: '<hostname>',
    namespace: '<namespace>',
    password: '<password>',
    username: '<username>',
  }),
})

await db
  .create('person:100')
  .set({
    first_name: 'Jennifer',
    age: 15,
  })
  .return('none')
  .execute()

Supported SurrealQL specific statements:

create, if else, relate.

Why not write a query builder from scratch

Kysely is growing to be THE sql query builder solution in the typescript ecosystem. Koskimas' dedication, attention to detail, experience from creating objection.js, project structure, simplicity, design patterns and philosophy, made adding code to that project a really good experience as a contributor. Taking what's great about that codebase, and patching in SurrealQL stuff seems like an easy win in the short-medium term.

License

MIT License, see LICENSE

kysely-surrealdb's People

Contributors

igalklebanov avatar naorpeled avatar sonicjhon1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

kysely-surrealdb's Issues

Can't connect to SurrealDB

Hello, its me again :)
For some reason Typescript couldn't call create because for some reason that doesn't exist(?).
Minimal reproduction project here: https://github.com/sonicjhon1/kysely-surreal-error
The code is from the Readme.md example:

await db
	.create('person:100')
	.set({
		first_name: 'Jennifer',
		age: 15,
	})
	.return('none')
	.execute()
> pnpm ts-node index.ts

D:\SJ\Devs\Github\kysely-surreal-error\node_modules\.pnpm\ts-node@10.9.1_@types+node@20.2.1_typescript@5.0.4\node_modules\ts-node\src\index.ts:859
    return new TSError(diagnosticText, diagnosticCodes, diagnostics);
           ^
TSError:  Unable to compile TypeScript:
index.ts:29:5 - error TS2339: Property 'create' does not exist on type 'Kysely<SurrealDatabase<Database>>'.

29    .create('person:100')
       ~~~~~~

    at createTSError (D:\SJ\Devs\Github\kysely-surreal-error\node_modules\.pnpm\ts-node@10.9.1_@types+node@20.2.1_typescript@5.0.4\node_modules\ts-node\src\index.ts:859:12)
    at reportTSError (D:\SJ\Devs\Github\kysely-surreal-error\node_modules\.pnpm\ts-node@10.9.1_@types+node@20.2.1_typescript@5.0.4\node_modules\ts-node\src\index.ts:863:19)
    at getOutput (D:\SJ\Devs\Github\kysely-surreal-error\node_modules\.pnpm\ts-node@10.9.1_@types+node@20.2.1_typescript@5.0.4\node_modules\ts-node\src\index.ts:1077:36)
\node_modules\ts-node\src\index.ts:1433:41)
    at Module.m._compile (D:\SJ\Devs\Github\kysely-surreal-error\node_modules\.pnpm\ts-node@10.9.1_@types+node@20.2.1_typescript@5.0.4\node_modules\ts-node\src\index.ts:1617:30)
    at Module._extensions..js (node:internal/modules/cjs/loader:1329:10)
    at Object.require.extensions.<computed> [as .ts] (D:\SJ\Devs\Github\kysely-surreal-error\node_modules\.pnpm\ts-node@10.9.1_@types+node@20.2.1_typescript@5.0.4\node_modules\ts-node\src\index.ts:1621:12)
    at Module.load (node:internal/modules/cjs/loader:1133:32)
    at Function.Module._load (node:internal/modules/cjs/loader:972:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12) {
  diagnosticCodes: [ 2339 ]
}

Also, the project above doesn't seem to do any connection to the DB even if I modified the code to not use create:

await db.selectFrom("person").selectAll().execute()
$ pnpm ts-node index.ts
> surreal start --log trace --user root --pass root --bind 0.0.0.0:8080 file://D:/SJ/Devs/DB/SurrealDB

2023-05-19T13:42:32.235373Z  INFO surrealdb::env: Running 1.0.0-beta.9+20230402.5eafebd for windows on x86_64
2023-05-19T13:42:32.235497Z  INFO surrealdb::iam: Root authentication is enabled
2023-05-19T13:42:32.235577Z  INFO surrealdb::iam: Root username is 'root'
2023-05-19T13:42:32.235655Z  INFO surrealdb::dbs: Database strict mode is disabled
2023-05-19T13:42:32.235734Z  INFO surrealdb::kvs: Starting kvs store at file://D:/SJ/Devs/DB/SurrealDB
2023-05-19T13:42:32.308941Z  INFO surrealdb::kvs: Started kvs store at file://D:/SJ/Devs/DB/SurrealDB
2023-05-19T13:42:32.309469Z  INFO surrealdb::net: Starting web server on 0.0.0.0:8080
2023-05-19T13:42:32.310541Z  INFO surrealdb::net: Started web server on 0.0.0.0:8080

Support Token authentication with HTTP

Currently the SurrealDbHttpDialect do not support using a token field in the config.

This is an option with the ExperimentalSurrealHTTP

    const db = new ExperimentalSurrealHTTP()
    await db.connect(connectionString,{
        namespace,
        database,
    })


    if (token) db.authenticate(token)

Feature: Select queries

Is this feature request related to a problem?

Yes, there is no way to query the database using this library, and the select and selectFrom functions will solve the problem.

Describe the solution

The solution would be to "port" the existing functions from the main kysely.

Alternative methods

Another method would be to implement a raw SQL function allowing the user to insert raw SurrealQL and query it that way.

SurrealDB version

1.3.0+20240222.73a90ac

Is there an existing issue for this?

  • I have searched the existing issues

Is this still active?

This hasn't been updated in 10 months, just want to know if this is being actively maintained?

TypeError: node_js_1.default is not a constructor

I've just tried out using kysely, but for some reason I couldn't get it to work. The database I'm using is SurrealDB, here are the logs from Surreal:

> surreal start --log trace --user root --pass root --bind 0.0.0.0:8080 file://D:/SJ/Devs/DB/SurrealDB

2023-05-19T06:51:40.820002Z  INFO surrealdb::env: Running 1.0.0-beta.9+20230402.5eafebd for windows on x86_64    
2023-05-19T06:51:40.820058Z  INFO surrealdb::iam: Root authentication is enabled    
2023-05-19T06:51:40.820089Z  INFO surrealdb::iam: Root username is 'root'    
2023-05-19T06:51:40.820118Z  INFO surrealdb::dbs: Database strict mode is disabled    
2023-05-19T06:51:40.820208Z  INFO surrealdb::kvs: Starting kvs store at file://D:/SJ/Devs/DB/SurrealDB
2023-05-19T06:51:40.909200Z  INFO surrealdb::kvs: Started kvs store at file://D:/SJ/Devs/DB/SurrealDB
2023-05-19T06:51:40.909557Z  INFO surrealdb::net: Starting web server on 0.0.0.0:8080    
2023-05-19T06:51:40.910596Z  INFO surrealdb::net: Started web server on 0.0.0.0:8080

The Node typescript code:

import * as dotenv from 'dotenv'
dotenv.config()
import { Kysely } from "kysely";
import type { DB } from "./generated/kysely/types";
import { SurrealDatabase, SurrealDbWebSocketsDialect, type SurrealEdge } from "kysely-surrealdb";
import Surreal from "surrealdb.js";

let db: Kysely<SurrealDatabase<DB>> | null = null;

db = new Kysely<SurrealDatabase<DB>>({
	dialect: new SurrealDbWebSocketsDialect({
		Driver: Surreal,
		hostname: process.env.DATABASE_URL || "localhost:8080",
		namespace: process.env.DATABASE_NAMESPACE || "namespace",
		database: process.env.DATABASE_NAME || "name",
		username: process.env.DATABASE_USERNAME || "root",
		password: process.env.DATABASE_PASSWORD || "root",
	}),
});

console.log(await db.selectFrom("Chat").selectAll().execute());

Node just errors out:

$ pnpm ts-node index.ts

D:\SJ\Devs\Github\sonicjhon1.github.io\node_modules\.pnpm\surrealdb.js@0.7.2_ws@8.13.0\node_modules\surrealdb.js\src\library\SurrealSocket.ts:55
                this.ws = new WebSocket(this.url);
            ^
TypeError: node_js_1.default is not a constructor
    at SurrealSocket.open (D:\SJ\Devs\Github\sonicjhon1.github.io\node_modules\.pnpm\surrealdb.js@0.7.2_ws@8.13.0\node_modules\surrealdb.js\src\library\SurrealSocket.ts:55:13)
    at WebSocketStrategy.connect (D:\SJ\Devs\Github\sonicjhon1.github.io\node_modules\.pnpm\surrealdb.js@0.7.2_ws@8.13.0\node_modules\surrealdb.js\src\strategies\websocket.ts:63:15)
    at SurrealDbWebSocketsConnection.connect (D:\SJ\Devs\Github\sonicjhon1.github.io\node_modules\.pnpm\kysely-surrealdb@0.7.0_kysely@0.24.2_surrealdb.js@0.7.2\node_modules\kysely-surrealdb\dist\src\dialect\websockets\websockets-connection.ts:32:24)
    at SurrealDbWebSocketsDriver.connect_fn (D:\SJ\Devs\Github\sonicjhon1.github.io\node_modules\.pnpm\kysely-surrealdb@0.7.0_kysely@0.24.2_surrealdb.js@0.7.2\node_modules\kysely-surrealdb\dist\src\dialect\websockets\websockets-driver.ts:51:60)
    at SurrealDbWebSocketsDriver.acquireConnection (D:\SJ\Devs\Github\sonicjhon1.github.io\node_modules\.pnpm\kysely-surrealdb@0.7.0_kysely@0.24.2_surrealdb.js@0.7.2\node_modules\kysely-surrealdb\dist\src\dialect\websockets\websockets-driver.ts:19:40)
    at RuntimeDriver.acquireConnection (D:\SJ\Devs\Github\sonicjhon1.github.io\node_modules\.pnpm\kysely@0.24.2\node_modules\kysely\dist\cjs\driver\runtime-driver.js:31:47)
    at async DefaultConnectionProvider.provideConnection (D:\SJ\Devs\Github\sonicjhon1.github.io\node_modules\.pnpm\kysely@0.24.2\node_modules\kysely\dist\cjs\driver\default-connection-provider.js:10:28)
    at async DefaultQueryExecutor.executeQuery (D:\SJ\Devs\Github\sonicjhon1.github.io\node_modules\.pnpm\kysely@0.24.2\node_modules\kysely\dist\cjs\query-executor\query-executor-base.js:36:16)
    at async SelectQueryBuilder.execute (D:\SJ\Devs\Github\sonicjhon1.github.io\node_modules\.pnpm\kysely@0.24.2\node_modules\kysely\dist\cjs\query-builder\select-query-builder.js:1202:24)
    at async sessionStore.sessionExistsStore [as sessionExists] (D:\SJ\Devs\Github\sonicjhon1.github.io\11 WA-GawrBot\src\wa\store\sessionStore.ts:14:14)
    at async RemoteAuth.extractRemoteSession (D:\SJ\Devs\Github\sonicjhon1.github.io\node_modules\.pnpm\whatsapp-web.js@1.19.5_bufferutil@4.0.7_utf-8-validate@5.0.10\node_modules\whatsapp-web.js\src\authStrategies\RemoteAuth.js:119:31)
    at async RemoteAuth.beforeBrowserInitialized (D:\SJ\Devs\Github\sonicjhon1.github.io\node_modules\.pnpm\whatsapp-web.js@1.19.5_bufferutil@4.0.7_utf-8-validate@5.0.10\node_modules\whatsapp-web.js\src\authStrategies\RemoteAuth.js:60:9)
    at async Client.initialize (D:\SJ\Devs\Github\sonicjhon1.github.io\node_modules\.pnpm\whatsapp-web.js@1.19.5_bufferutil@4.0.7_utf-8-validate@5.0.10\node_modules\whatsapp-web.js\src\Client.js:88:9)

I have also double-checked that the database is running, I could even connect to the database via Surrealist without any problems.
Screenshot 2023-05-19 153803

Edit: #10 May be related.

Is this an abandoned project?

Hello
I would like to know if someone is going to work on this project because if not, I might jump in and do some work. Pull requests can be made?

Latest SurrealQL Features

Hey,

Great work with this project! is it still under active development? If so, is there an eta for when stuff like if statements, nested clauses and websockets will be supported?

SyntaxError: Unexpected token 'export'

Fails to run kysely-surrealdb on a new project. Minimal reproduction project.

import { Kysely } from "kysely";
import type { DB } from "./src/generated/kysely/types";
import { SurrealDatabase, SurrealDbWebSocketsDialect } from "kysely-surrealdb";
import Surreal from "surrealdb.js";

const db = new Kysely<SurrealDatabase<DB>>({
	dialect: new SurrealDbWebSocketsDialect({
		Driver: Surreal,
		hostname: "localhost:8080",
		namespace: "namespace",
		database: "name",
		username: "root",
		password: "root",
	}),
});

(async function () {
	if (db == null) {
		console.log("db is null");
	} else {
		console.log(await db.selectFrom("Chat").selectAll().execute());
	}
})();

Error:

pnpm run dev

> kysely-surreal@1.0.0 dev D:\SJ\Devs\Github\kysely-surreal
> pnpm dlx prisma generate && ts-node index.ts

../../../../.pnpm-store/v3/tmp/dlx-16396 |   +2 +
../../../../.pnpm-store/v3/tmp/dlx-16396 | Progress: resolved 2, reused 2, downloaded 0, added 2, done
Prisma schema loaded from prisma\schema.prisma

 Generated Kysely types (1.4.1) to .\src\generated\kysely in 12ms

D:\SJ\Devs\Github\kysely-surreal\node_modules\.pnpm\unws@0.2.2_ws@8.13.0\node_modules\unws\src\node.js:3
export { WebSocket }
^^^^^^

SyntaxError: Unexpected token 'export'
    at internalCompileFunction (node:internal/vm:73:18)
    at wrapSafe (node:internal/modules/cjs/loader:1195:20)
    at Module._compile (node:internal/modules/cjs/loader:1239:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1329:10)
    at Object.require.extensions.<computed> [as .js] (D:\SJ\Devs\Github\kysely-surreal\node_modules\.pnpm\ts-node@10.9.1_@types+node@20.2.1_typescript@5.0.4\node_modules\ts-node\src\index.ts:1608:43)
    at Module.load (node:internal/modules/cjs/loader:1133:32)
    at Function.Module._load (node:internal/modules/cjs/loader:972:12)
    at Module.require (node:internal/modules/cjs/loader:1157:19)
    at require (node:internal/modules/helpers:119:18)
    at Object.<anonymous> (D:\SJ\Devs\Github\kysely-surreal\node_modules\.pnpm\surrealdb.js@0.7.2_ws@8.13.0\node_modules\surrealdb.js\src\library\WebSocket\node.ts:2:1)
 ELIFECYCLE  Command failed with exit code 1.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.