UNPKG

kysely-bun-sqlite

Version:

Use kysely with `bun:sqlite`, for an example please see the [Simple Example](https://github.com/dylanblokhuis/kysely-bun-sqlite/tree/master/examples/simple) in this repository.

113 lines (110 loc) 2.76 kB
// src/dialect.ts import { SqliteAdapter, SqliteIntrospector, SqliteQueryCompiler } from "kysely"; // src/driver.ts import { CompiledQuery } from "kysely"; var BunSqliteDriver = class { #config; #connectionMutex = new ConnectionMutex(); #db; #connection; constructor(config) { this.#config = { ...config }; } async init() { this.#db = this.#config.database; this.#connection = new BunSqliteConnection(this.#db); if (this.#config.onCreateConnection) { await this.#config.onCreateConnection(this.#connection); } } async acquireConnection() { await this.#connectionMutex.lock(); return this.#connection; } async beginTransaction(connection) { await connection.executeQuery(CompiledQuery.raw("begin")); } async commitTransaction(connection) { await connection.executeQuery(CompiledQuery.raw("commit")); } async rollbackTransaction(connection) { await connection.executeQuery(CompiledQuery.raw("rollback")); } async releaseConnection() { this.#connectionMutex.unlock(); } async destroy() { this.#db?.close(); } }; var BunSqliteConnection = class { #db; constructor(db) { this.#db = db; } executeQuery(compiledQuery) { const { sql, parameters } = compiledQuery; const stmt = this.#db.prepare(sql); if (stmt.columnNames.length > 0) { return Promise.resolve({ rows: stmt.all(parameters) }); } const results = stmt.run(parameters); return Promise.resolve({ insertId: BigInt(results.lastInsertRowid), numAffectedRows: BigInt(results.changes), rows: [] }); } async *streamQuery(compiledQuery) { const { sql, parameters } = compiledQuery; const stmt = this.#db.prepare(sql); if (!("iterator" in stmt)) { throw new Error("bun:sqlite supports streaming in 1.1.31 or above. Please upgrade to use streaming."); } for await (const row of stmt.iterate(parameters)) { yield { rows: [row] }; } } }; var ConnectionMutex = class { #promise; #resolve; async lock() { while (this.#promise) { await this.#promise; } this.#promise = new Promise((resolve) => { this.#resolve = resolve; }); } unlock() { const resolve = this.#resolve; this.#promise = void 0; this.#resolve = void 0; resolve?.(); } }; // src/dialect.ts var BunSqliteDialect = class { #config; constructor(config) { this.#config = { ...config }; } createDriver() { return new BunSqliteDriver(this.#config); } createQueryCompiler() { return new SqliteQueryCompiler(); } createAdapter() { return new SqliteAdapter(); } createIntrospector(db) { return new SqliteIntrospector(db); } }; export { BunSqliteDialect };