|
| 1 | +import type { CompiledSql } from "../builder/sql"; |
| 2 | +import type { DialectName } from "../builder/sql"; |
| 3 | +import type pg from "pg"; |
| 4 | +import type { Driver, ExecuteFn, QueryResult } from "./types"; |
| 5 | + |
| 6 | +// pg adapter — returns raw text strings (no driver-side deserialization). |
| 7 | +// `pg` is an *optional* peer dep (see package.json#peerDependenciesMeta). |
| 8 | +// Dynamic import keeps bundlers from pulling pg into browser builds and |
| 9 | +// lets a missing peer fail late with a real module-not-found error. |
| 10 | +export class PgDriver implements Driver { |
| 11 | + readonly dialect: DialectName = "postgres"; |
| 12 | + |
| 13 | + static async create( |
| 14 | + connectionString: string, |
| 15 | + poolOptions: pg.PoolConfig = {}, |
| 16 | + ): Promise<PgDriver> { |
| 17 | + // eslint-disable-next-line no-restricted-syntax -- optional peer, see class comment |
| 18 | + const pgMod = (await import(/* webpackIgnore: true */ "pg")).default; |
| 19 | + const pool = new pgMod.Pool({ |
| 20 | + connectionString, |
| 21 | + ...poolOptions, |
| 22 | + types: { getTypeParser: () => (v: string) => v }, |
| 23 | + }); |
| 24 | + return new PgDriver(pool); |
| 25 | + } |
| 26 | + |
| 27 | + private constructor(private pool: pg.Pool) {} |
| 28 | + |
| 29 | + async execute({ text, values }: CompiledSql): Promise<QueryResult> { |
| 30 | + return this.pool.query(text, values as unknown[]); |
| 31 | + } |
| 32 | + |
| 33 | + async runInSingleConnection<T>(cb: (execute: ExecuteFn) => Promise<T>): Promise<T> { |
| 34 | + const client = await this.pool.connect(); |
| 35 | + try { |
| 36 | + return await cb(({ text, values }) => client.query(text, values as unknown[])); |
| 37 | + } finally { |
| 38 | + client.release(); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + async close(): Promise<void> { |
| 43 | + await this.pool.end(); |
| 44 | + } |
| 45 | +} |
0 commit comments