kysely
Version:
Type safe SQL query builder
122 lines (121 loc) • 4.27 kB
JavaScript
/// <reference types="./postgres-driver.d.ts" />
import { CompiledQuery } from '../../query-compiler/compiled-query.js';
import { isFunction, freeze } from '../../util/object-utils.js';
import { extendStackTrace } from '../../util/stack-trace-utils.js';
const PRIVATE_RELEASE_METHOD = Symbol();
export class PostgresDriver {
constructor(config) {
this.
}
async init() {
this.
? await this.
: this.
}
async acquireConnection() {
const client = await this.
let connection = this.
if (!connection) {
connection = new PostgresConnection(client, {
cursor: this.
});
this.
// The driver must take care of calling `onCreateConnection` when a new
// connection is created. The `pg` module doesn't provide an async hook
// for the connection creation. We need to call the method explicitly.
if (this.
await this.
}
}
if (this.
await this.
}
return connection;
}
async beginTransaction(connection, settings) {
if (settings.isolationLevel) {
await connection.executeQuery(CompiledQuery.raw(`start transaction isolation level ${settings.isolationLevel}`));
}
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 releaseConnection(connection) {
connection[PRIVATE_RELEASE_METHOD]();
}
async destroy() {
if (this.
const pool = this.
this.
await pool.end();
}
}
}
class PostgresConnection {
constructor(client, options) {
this.
this.
}
async executeQuery(compiledQuery) {
try {
const result = await this.
...compiledQuery.parameters,
]);
if (result.command === 'INSERT' ||
result.command === 'UPDATE' ||
result.command === 'DELETE' ||
result.command === 'MERGE') {
const numAffectedRows = BigInt(result.rowCount);
return {
// TODO: remove.
numUpdatedOrDeletedRows: numAffectedRows,
numAffectedRows,
rows: result.rows ?? [],
};
}
return {
rows: result.rows ?? [],
};
}
catch (err) {
throw extendStackTrace(err, new Error());
}
}
async *streamQuery(compiledQuery, chunkSize) {
if (!this.
throw new Error("'cursor' is not present in your postgres dialect config. It's required to make streaming work in postgres.");
}
if (!Number.isInteger(chunkSize) || chunkSize <= 0) {
throw new Error('chunkSize must be a positive integer');
}
const cursor = this.
try {
while (true) {
const rows = await cursor.read(chunkSize);
if (rows.length === 0) {
break;
}
yield {
rows,
};
}
}
finally {
await cursor.close();
}
}
[]() {
this.
}
}