UNPKG

iagate-querykit

Version:

QueryKit: lightweight TypeScript query toolkit with models, views, triggers, events, scheduler and adapters (better-sqlite3).

49 lines (48 loc) 1.28 kB
import { createRequire } from 'node:module'; let pg; function ensurePg() { if (pg) return; const mocked = globalThis.__vitest_mocks__?.pg; if (mocked) { pg = mocked; return; } try { const req = createRequire(import.meta.url); pg = req('pg'); } catch { throw new Error('pg is required: npm install pg'); } } function toPgParams(sql) { let index = 0; const out = sql.replace(/\?/g, () => `$${++index}`); return { sql: out }; } export class PostgresExecutor { config; dialect = 'postgres'; pool; constructor(config = {}) { this.config = config; ensurePg(); const { Pool } = pg; this.pool = new Pool({ connectionString: config.connectionString, host: config.host, port: config.port, user: config.user, password: config.password, database: config.database, ssl: config.ssl, max: config.poolSize || 10, }); } async executeQuery(sql, bindings = []) { const { sql: text } = toPgParams(sql); const res = await this.pool.query({ text, values: bindings }); return { data: res.rows, affectedRows: res.rowCount }; } }