Documentation

API reference

Public API surface for pg-fluent v0.5.0. The query builder follows the postgrest-js contract; extras are documented here.

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).

OptionType / defaultDescription
connectionStringstring?PostgreSQL connection string. Prefer env var.
schemasstring[], default ['public']Exposed schema allowlist. First is default.
poolpg.Pool | PoolConfigPool 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.
maxRowsnumber, default 1000Caps read results, including explicit .limit()/.range() and embedded collections. Limits above maxRows are reduced.
statementTimeoutMsnumber | null, default 30000Server-side statement timeout. null = server default.
allowUnfilteredMutationsboolean, default falseAllow 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) => voidPer-query hook.
logParamsboolean, default falseInclude bound params in logs/events (opt-in).
redactColumnsstring[]Column names to mask in observability output.
telemetrybooleanEmit OTel spans when @opentelemetry/api is installed.
connectionsRecord<string, ConnectionConfig>Named connections.
defaultConnectionstringName of the default connection.
replicasReplicaConfig[]Read replicas for the top-level/default single connection.

Client extras

MemberDescription
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.
$poolUnderlying pg.Pool (read-only by convention).

Builder methods

pg-fluent reuses the postgrest-js builder contract. Common methods:

MethodNotes
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/inFilters.
contains/containedBy/overlaps/range*Array/range filters.
match/imatch/textSearch/filter/not/or/andAdvanced filters.
order(column, options?)Ordering, including nulls/foreign tables.
limit/rangePagination.
single/maybeSingleCardinality modifiers.
csv/geojson/explainResponse/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.