Database wrapper providing a consistent query and transaction interface.
Construct via create_pg_db() from db_pg.ts or create_pglite_db() from
db_pglite.ts for proper transaction support, or via create_db() for
URL-based auto-detection.
examples
const {db, close} = await create_db('postgres://...');
const users = await db.query<User>('SELECT * FROM users WHERE active = $1', [true]);
await db.transaction(async (tx) => {
await tx.query('INSERT INTO users ...');
await tx.query('INSERT INTO audit_log ...');
});
await close();client
type DbClient
constructor
type new (options: DbDeps): Db
options
query
Execute a query and return all rows.
type <T>(text: string, values?: unknown[] | undefined): Promise<T[]>
text
stringvalues?
unknown[] | undefinedPromise<T[]>query_one
Execute a query and return the first row, or undefined if no rows.
type <T>(text: string, values?: unknown[] | undefined): Promise<T | undefined>
text
stringvalues?
unknown[] | undefinedPromise<T | undefined>transaction
Run a function inside a database transaction.
The callback receives a transaction-scoped Db. Queries inside the callback go through the transaction connection; queries outside use the pool normally. Commits on success, rolls back on error.
type <T>(fn: (tx_db: Db) => Promise<T>): Promise<T>
fn
async function receiving a transaction-scoped Db
(tx_db: Db) => Promise<T>Promise<T>the value returned by fn