This guide covers the day-to-day pg-fluent API. For the full option/shape reference, see the API reference.
Queries and filters
Use from() to select a table or view, then chain filters and modifiers. Builders execute when awaited.
const { data, error } = await db
.from('todos')
.select('id, task, done, priority')
.eq('done', false)
.gte('priority', 2)
.order('created_at', { ascending: false })
.limit(10)
Common filters and modifiers include eq, neq, gt, gte, lt, lte, like, ilike, match, imatch, is, in, contains, containedBy, overlaps, range*, textSearch, not, or, and, and filter.
// OR filter
await db.from('todos').select('*').or('done.eq.true,priority.gt.3')
// JSON path selection/filtering
await db.from('todos').select('id, meta->>author').eq('meta->>wip', 'true')
// Pagination + exact count
const page = await db
.from('todos')
.select('*', { count: 'exact' })
.range(0, 9)
Cardinality and response shape
Use single() when exactly one row is required, and maybeSingle() when zero or one row is acceptable.
const one = await db.from('users').select('*').eq('id', id).single()
const maybe = await db.from('users').select('*').eq('email', email).maybeSingle()
No rows is a successful empty result ([], or null for maybeSingle()). Cardinality mismatch from single()/maybeSingle() returns PGRST116.
Counts
count supports exact, planned, and estimated.
exactreturns the real number of matching rows.plannedreturns PostgreSQL's planner estimate (depends on statistics freshness /ANALYZE).estimatedreturns an exact count when the match is at mostmaxRows; otherwisemax(estimate, maxRows + 1).
Counts respect the same filters as the read, including top-level !inner embed conditions. A failing count query fails the request.
toSQL()
.toSQL() renders SQL without executing the query. It is async. On a cold schema cache it may still issue catalog lookups.
const plan = await db
.from('todos')
.select('id')
.eq('done', false)
.toSQL()
// { text, values }
console.log(plan.text, plan.values)
// Plain row SQL without the JSON response envelope
const dataPlan = await db.from('todos').select('id').toSQL({ shape: 'data' })
toSQL() returns the primary statement only. Secondary count/EXPLAIN statements used for count=planned and count=estimated are internal.
Embedded resources
pg-fluent resolves relationships from the live schema cache. It supports many-to-one, one-to-many, and many-to-many embeds (through a junction), plus aliases, inner joins, FK/column disambiguation, nested embeds, and to-one spreads.
// many-to-one
await db.from('posts').select('id, title, author:users(name)')
// inner embed
await db.from('users').select('id, posts!inner(title)').eq('posts.title', 'hello')
// spread a to-one relation
await db.from('posts').select('id, ...users(name)')
// embedded ordering
await db.from('users').select('id, posts(title)').order('posts.title')
A dotted filter or embedded modifier (for example posts.title=eq.x) requires the embed to be present in select(). If missing, pg-fluent rejects the request with PGRST100 instead of silently dropping the filter.
Embedding views is not supported in v1.
Writes and safe mutations
Mutations follow the postgrest-js shape. Rows are returned only when you call .select().
// insert
await db.from('todos').insert({ task: 'write docs' }).select().single()
// bulk insert (single JSON parameter; safe, no param-count blowup)
await db.from('todos').insert([{ task: 'a' }, { task: 'b' }]).select()
// update
await db.from('todos').update({ done: true }).eq('id', 1).select()
// upsert
await db
.from('todos')
.upsert({ id: 1, task: 'x' }, { onConflict: 'id' })
.select()
// delete
await db.from('todos').delete().eq('id', 1)
Without .select(), an UPDATE or DELETE with no filter is refused client-side with PGFLUENT_UNFILTERED_MUTATION. Opt in only when intentional with allowUnfilteredMutations: true or .allowUnfiltered().
Use .maxAffected(n) to roll back and error when a mutation affects more rows than expected.
await db
.from('todos')
.update({ done: true })
.eq('project_id', projectId)
.maxAffected(100)
Transactions and savepoints
db.transaction() runs a callback on a dedicated connection. It resolves with the callback value, or rejects if the callback throws (after rollback).
const user = await db.transaction(async (trx) => {
const { data, error } = await trx
.from('users')
.insert({ name: 'G' })
.select()
.single()
if (error) throw error
await trx.from('profiles').insert({ user_id: data.id })
await trx.savepoint(async (sp) => {
// throwing here rolls back to this savepoint only
await sp.from('events').insert({ user_id: data.id, kind: 'created' })
})
return data
}, {
isolationLevel: 'read committed',
readOnly: false,
// retry: 2, // retries 40001/40P01; callback must be idempotent
// timeoutMs: 5000,
})
Call trx.rollback() to roll back deliberately and resolve with undefined. Nested transactions use savepoints. The connection is always released in finally.
Raw SQL
Use db.sql for parameterized SQL templates. Interpolations are bound as parameters — a plain string interpolation never becomes SQL text.
const id = 42
const { data, error } = await db.sql`select * from users where id = ${id}`
Compose structure with db.identifier() or nested sql fragments:
const table = db.identifier('users')
const cols = db.sql`id, name`
const rows = await db.sql`select ${cols} from ${table} where active = ${true}`
db.unsafe(text, params?) executes caller-supplied SQL text. It is the only API that executes raw SQL text you build yourself. Parameters are still bound.
const { data } = await db.unsafe('select * from users where id = $1', [id])
Both sql and unsafe return { data, error, count, status, statusText } and work inside transactions.
Streaming
Use .stream() for large reads. It uses a server-side cursor and holds one connection until the iterator finishes, is returned, or throws.
for await (const row of db.from('events').select('*').gt('id', 0).stream()) {
await handle(row)
}
Notes: .stream() is also thenable (you can await it to collect rows). It respects backpressure. It is available for GET/read queries only — not for head, count, .single(), non-JSON response modes, or RPC results. Embedded resources are delivered as JSON per row. A stream pins a connection and counts against pool size.
COPY
db.copyFrom() bulk-loads rows with COPY FROM STDIN. It requires the optional pg-copy-streams peer.
const { data, error } = await db.copyFrom(
'events',
rows, // array or AsyncIterable
{ columns: ['id', 'kind'], format: 'csv' }
)
// data -> { rowCount }
format defaults to csv. CSV writes an unquoted empty field for null and a quoted "" for empty text; text writes the \N sentinel for null. Values are escaped by the library. columns is required for an AsyncIterable or an empty array (column names are inferred only from a non-empty array). copyFrom() is not available inside transactions and returns { data: { rowCount }, error }.
LISTEN / NOTIFY
Use db.listen() for PostgreSQL notifications. The listener uses a dedicated, non-pooled connection shared across channels and reconnects automatically.
const sub = await db.listen(
'orders',
(payload, meta) => {
console.log(meta.channel, meta.processId, payload)
},
{
onReconnect: async () => {
// re-sync after reconnect; missed notifications are lost
},
}
)
await db.notify('orders', JSON.stringify({ id: 1 }))
await sub.unlisten()
listen(channel, callback, options?)returns{ unlisten() }(ListenSubscription).- Callback receives
(payload, meta)wheremetais{ channel, payload, processId }. sub.unlisten()removes one subscription;db.unlisten(channel)removes all callbacks for that channel.- Channel names are validated as SQL identifiers (quoted/unquoted, max 63 bytes).
notify()payloads are parameterized and capped at 8000 bytes.listen()/unlisten()are not available on transaction clients.
LISTEN/NOTIFY is not compatible with transaction-mode poolers (for example PgBouncer in transaction pooling). Use a session-mode or direct connection.
Notifications missed during a disconnect are lost (PostgreSQL semantics). The listener reconnects with backoff up to 10 attempts; after that it gives up. Use onReconnect (called after a channel is successfully re-registered) to re-sync state.
Named connections and read replicas
Configure named connections when you need more than one database. db.connection(name) returns a client bound to that connection.
const db = createClient({
connections: {
main: { connectionString: process.env.DATABASE_URL },
analytics: { connectionString: process.env.ANALYTICS_URL },
},
defaultConnection: 'main',
})
await db.connection('analytics').from('events').select('*')
Read-replica routing can be configured with primary and replicas (on a named connection or top-level single-connection config).
const db = createClient({
connectionString: process.env.PRIMARY_DATABASE_URL,
replicas: [{ connectionString: process.env.REPLICA_DATABASE_URL }],
})
SELECT/HEAD queries may go to replicas (round-robin, unhealthy-replica cool-down, fallback to primary on connection errors only). Mutations, all RPC, transactions, LISTEN/NOTIFY, and schema-cache loads always use primary. Use .primary() to force a primary read for read-your-writes.
Replication is asynchronous: a replica read may not see a just-committed write. There is no lag measurement in v1.
Type generation
Generate a Database type compatible with postgrest-js:
npx pg-fluent gen-types --connection "$DATABASE_URL" --schema public --out ./database.types.ts
# or set DATABASE_URL and omit --connection
import type { Database } from './database.types'
const db = createClient<Database>({ connectionString: process.env.DATABASE_URL })
Flags: --connection <url> (or DATABASE_URL), --schema <name> (repeatable, default public), --out <file>, --no-comments. The connection string is never printed.
Output covers nullable/default/identity/generated columns, enums, arrays, json/jsonb (as Json), composite types, domains, views, foreign-key relationships, and functions (including overloads and resolvable arg/return types).
Observability
Pass a logger and/or onQuery hook for query events.
const db = createClient({
connectionString: process.env.DATABASE_URL,
logger: console,
onQuery(event) {
console.log(event.operation, event.durationMs, event.rowCount)
},
// logParams: true, // opt-in; off by default
// redactColumns: ['password', 'secret'],
})
Event fields: operation, schema, table, queryText, params?, durationMs, rowCount, error?, connection, route, retried. operation is one of select | insert | update | delete | rpc | exec.
Parameter values are never logged by default. params is included only when logParams: true. Use redactColumns to mask sensitive fields.
With @opentelemetry/api installed, set telemetry: true for one span per query. When the peer is absent, there is zero overhead.
How it works
pg-fluent executes PostgREST-style requests directly against PostgreSQL:
- Fluent call is built by
@supabase/postgrest-js. - Adapter intercepts the request and parses method/path/headers/query/Prefer options.
- Parser turns URL/query syntax into a typed request plan.
- Schema cache introspects
pg_catalogfor tables, columns, PKs, and relationships (TTL/LRU/stampede-safe, refreshable). - Planner resolves relationships and builds SQL for reads, writes, RPC, embeds, and count variants.
- Executor quotes identifiers/literals safely, binds parameters, applies timeout/abort, and runs via
pg. - Response shapes results into PostgREST-compatible envelopes/status codes.