createClient(config)
createClient<Database = any>(config: PgFluentConfig): PgFluentClient<Database>Creates a pg-fluent client. Config accepts either a connectionString or discrete connection fields (host, port, database, user, password, ssl).
| Option | Type / default | Description |
|---|---|---|
connectionString | string? | PostgreSQL connection string. Prefer env var. |
schemas | string[], default ['public'] | Exposed schema allowlist. First is default. |
pool | pg.Pool | PoolConfig | Pool options or an existing pg.Pool (not closed by pg-fluent). When supplying an existing pool, configure statement_timeout and schema search_path on that pool yourself. |
maxRows | number, default 1000 | Caps read results, including explicit .limit()/.range() and embedded collections. Limits above maxRows are reduced. |
statementTimeoutMs | number | null, default 30000 | Server-side statement timeout. null = server default. |
allowUnfilteredMutations | boolean, default false | Allow unfiltered UPDATE/DELETE without .select(). |
retries | { max, backoffMs, idempotent? } | Read-only retry config. Default { max: 2, backoffMs: 50, idempotent: true }. |
logger | { debug, info, warn, error } | Optional logger. |
onQuery | (event) => void | Per-query hook. |
logParams | boolean, default false | Include bound params in logs/events (opt-in). |
redactColumns | string[] | Column names to mask in observability output. |
telemetry | boolean | Emit OTel spans when @opentelemetry/api is installed. |
connections | Record<string, ConnectionConfig> | Named connections. |
defaultConnection | string | Name of the default connection. |
replicas | ReplicaConfig[] | Read replicas for the top-level/default single connection. |
Client extras
| Member | Description |
|---|---|
from(table) | Start a query builder for a table/view in the default schema. |
schema(name).from(table) | Query a specific exposed schema. |
rpc(fn, args?) | Call a Postgres function. |
sql`...` | Parameterized raw SQL template. Returns { data, error, count, status, statusText }. |
unsafe(text, params?) | Execute caller-supplied SQL text with bound params (explicit escape hatch). |
identifier(name) | Safe quoted identifier fragment for SQL composition. |
transaction(fn, options?) | Run callback in a transaction. Resolves with the callback value, or rejects if the callback throws. trx.rollback() rolls back deliberately and resolves undefined. |
trx.savepoint(fn) | Savepoint on an active transaction client (trx/sp). |
trx.rollback() | Deliberate rollback of an active transaction; the transaction resolves undefined. |
connection(name) | Get a client bound to a named connection. |
primary() | Force primary routing for read-your-writes. |
listen(channel, cb, options?) | Subscribe to LISTEN notifications. Returns { unlisten() } (ListenSubscription). |
notify(channel, payload?) | Send a NOTIFY payload (parameterized, 8000-byte cap). |
unlisten(channel) / unlistenAll() | Remove listeners. unlisten(channel) removes all callbacks for the channel; sub.unlisten() removes one subscription. |
copyFrom(table, rows, options?) | Bulk load rows via COPY FROM STDIN. Returns { data: { rowCount }, error } (or error); no status/statusText. Requires pg-copy-streams. |
refreshSchema() | Refresh schema cache. |
close({ timeoutMs? }) | Drain/close owned pools and stop listeners. Idempotent. |
$pool | Underlying pg.Pool (read-only by convention). |
Builder methods
pg-fluent reuses the postgrest-js builder contract. Common methods:
| Method | Notes |
|---|---|
select(columns?, options?) | Read/query shape. Options include count, head. |
insert(values, options?) | Insert rows. Use .select() to return rows. |
update(values) | Update rows. Use filters; unfiltered updates are guarded. |
upsert(values, options?) | Upsert with onConflict etc. |
delete() | Delete rows. Use filters; unfiltered deletes are guarded. |
eq/neq/gt/gte/lt/lte/like/ilike/is/in | Filters. |
contains/containedBy/overlaps/range* | Array/range filters. |
match/imatch/textSearch/filter/not/or/and | Advanced filters. |
order(column, options?) | Ordering, including nulls/foreign tables. |
limit/range | Pagination. |
single/maybeSingle | Cardinality modifiers. |
csv/geojson/explain | Response/diagnostic modifiers. |
throwOnError() | Throw on error result. |
timeout(ms) | Per-request statement timeout. |
abortSignal(signal) | Abort the request with an AbortSignal. |
maxAffected(n) | Cap affected rows for mutations. |
allowUnfiltered() | Explicit opt-in for a specific unfiltered mutation. |
primary() | Force this read to primary. |
toSQL(options?) | Async. Returns Promise<{ text, values }>. options.shape: 'executable' | 'data'. |
stream() | Async iterable of rows (server-side cursor); also thenable. |
Types
type ListenMeta = { channel: string; payload: string; processId: number }
type ListenOptions = { onReconnect?: () => void | Promise<void> }
type ListenSubscription = { unlisten(): Promise<void> }
type TransactionOptions = {
isolationLevel?: 'read uncommitted' | 'read committed' | 'repeatable read' | 'serializable'
readOnly?: boolean
retry?: number
timeoutMs?: number
}
type CopyFromOptions = {
columns?: string[]
format?: 'csv' | 'text' // default csv
delimiter?: string
}
CLI: gen-types
npx pg-fluent gen-types --connection "$DATABASE_URL" --schema public --out ./database.types.ts
Options: --connection <url> (or DATABASE_URL), --schema <name> (repeatable), --out <file>, --no-comments. The connection string is never printed.