UNPKG

@jadejr/kysely-pglite

Version:

Kysely dialect for @electric-sql/pglite (temporary fork https://github.com/dnlsandiego/kysely-pglite)

93 lines 3.45 kB
import { PGlite } from '@electric-sql/pglite'; import { isFunction } from '@sindresorhus/is'; import { CompiledQuery, createQueryId, } from 'kysely'; import { parseSavepointCommand } from './parser/savepoint-parser.js'; export class PGliteDriver { #config; #client; constructor(config) { this.#config = config; } async init() { if (this.#config.PGlite instanceof PGlite) { this.#client = this.#config.PGlite; return; } if (isFunction(this.#config.PGlite)) { this.#client = await this.#config.PGlite(this.#config.PGliteOptions); return; } this.#client = new PGlite(this.#config.PGliteOptions); } async acquireConnection() { if (!this.#client) { throw new Error('PGlite client is not initialized. init() must be called first.'); } const connection = new PGliteConnection(this.#client); if (this.#config.onCreateConnection) { await this.#config.onCreateConnection(connection); } if (this.#config.onReserveConnection) { await this.#config.onReserveConnection(connection); } return connection; } async beginTransaction(connection, settings) { if (settings.isolationLevel || settings.accessMode) { let sql = 'START TRANSACTION'; if (settings.isolationLevel) { sql += ` ISOLATION LEVEL ${settings.isolationLevel}`; } if (settings.accessMode) { sql += ` ${settings.accessMode}`; } await connection.executeQuery(CompiledQuery.raw(sql)); } else { 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 savepoint(connection, savepointName, compileQuery) { await connection.executeQuery(compileQuery(parseSavepointCommand('savepoint', savepointName), createQueryId())); } async rollbackToSavepoint(connection, savepointName, compileQuery) { await connection.executeQuery(compileQuery(parseSavepointCommand('rollback to', savepointName), createQueryId())); } async releaseSavepoint(connection, savepointName, compileQuery) { await connection.executeQuery(compileQuery(parseSavepointCommand('release', savepointName), createQueryId())); } async destroy() { await this.#client.close(); } async releaseConnection(_connection) { } } export class PGliteConnection { #client; constructor(client) { this.#client = client; } async executeQuery(compiledQuery) { const res = await this.#client.query(compiledQuery.sql, [ ...compiledQuery.parameters, ]); const numAffectedRows = res.affectedRows ? BigInt(res.affectedRows) : undefined; // Remove affectedRows from the result, since it's not part of the standard QueryResult delete res.affectedRows; return { ...res, numAffectedRows, }; } async *streamQuery() { throw new Error('PGlite does not support streaming.'); } } //# sourceMappingURL=pglite-driver.js.map