Direct Postgres
The same repositories over SQL, with the same results and RLS.
The repository IR compiles to SQL as well as to PostgREST. Any client with
queryRaw(text, params) can run it: ctx.postgres from @supabase/server,
or a pool from createPostgres().
import { createPostgres, postgresExecutor } from "better-supabase/postgres";
const postgres = createPostgres(); // SUPABASE_DB_URL, DATABASE_URL, POSTGRES_URL
const asUser = betterSupabase.connect(
postgresExecutor(postgres.asUser({ sub: userId, tenant_id: organizationId })),
);
const asAdmin = betterSupabase.connect(postgresExecutor(postgres.admin));Without a connectionString, createPostgres() reads the first of
SUPABASE_DB_URL, DATABASE_URL, POSTGRES_URL and
POSTGRES_URL_NON_POOLING that is set, the dbUrl order.
Each query runs in its own transaction with transaction-local settings, so
the transaction pooler that POSTGRES_URL points to works.
Results match PostgREST exactly: same row shapes, nested includes, relation filters, pagination and error kinds. The test suite runs the same queries through both and compares them.
Identities
| Client | Runs as |
|---|---|
postgres.admin | the connection-string role (bypasses RLS on Supabase) |
postgres.asUser(c) | authenticated, with request.jwt.claims set, so RLS applies |
postgres.anon | anon |
postgres.executorFor(claims) is postgresExecutor(postgres.asUser(claims)).
createServer calls it for ctx.sql and actingAs(), so the SQL compiler is
only bundled into apps that import better-supabase/postgres. A custom
BetterPostgres passed to createServer implements it too.
Claims and role are transaction-local (set_config(…, true)), so nothing
leaks back into the pool. Each transaction sets them, with its timeouts, in
one query after begin. Only authenticated and anon can be assumed this
way.
asUser, executorFor and transaction also take session options.
settings sets more transaction-local settings, such as
better_supabase.tenant for a resolved tenant;
their names need a dot, so they can't replace role or the claims.
readOnly: true opens every transaction with begin read only, so writes fail
with SQLSTATE 25006.
const reader = postgres.asUser(claims, {
settings: { "better_supabase.tenant": organizationId },
readOnly: true,
});Timeouts
set role doesn't apply a role's own settings, so the statement_timeout
Supabase sets on authenticated (8 s) and anon (3 s) would not limit these
queries. createPostgres applies those two values per transaction instead,
and leaves admin without a limit for jobs and migrations.
| Option | Default | Sets |
|---|---|---|
statementTimeout | { authenticated: 8000, anon: 3000 } | statement_timeout per transaction; a number applies to every role |
idleInTransactionTimeout | 15000 | idle_in_transaction_session_timeout, so a transaction left open ends |
connectionTimeout | 10000 | how long connect waits for a free connection |
idleTimeout | 10000 | how long an unused connection stays in the pool |
const postgres = createPostgres({
statementTimeout: { admin: 60_000, authenticated: 5000 },
idleInTransactionTimeout: 30_000,
});All values are milliseconds. connectionTimeout and idleTimeout apply to
the pool createPostgres opens, not to one you pass as pool.
TLS and one pool per process
ssl: true verifies the server certificate against the system roots; pass
ssl: { ca } for a private certificate authority, or ssl: false to turn TLS
off. A connection string that sets sslmode wins over the option.
sharedPostgres(options) takes the same options and returns one pool per
process and connection string, kept on globalThis so a hot reload, a route
and a job don't each open their own connections. The first call's options win,
and end() closes the pool so the next call opens a new one. A call that
passes pool is not shared.
A session or transaction can set its own limit with the statementTimeout
session option, for a job that runs one long query on a shared pool:
await postgres.transaction(
(tx) => tx.queryRaw("refresh materialized view stats"),
{ statementTimeout: 120_000 },
);
const reports = postgres.executorFor(claims, { statementTimeout: 20_000 });A transaction that waits longer than idleInTransactionTimeout between
statements, such as one stuck on an await to another service, is ended so
it can't hold row locks. 0 turns that off. The setting applies only inside
a transaction: an admin query with no statement timeout to set runs without
begin and commit, in one round trip. Set statementTimeout.admin and it
runs in a transaction like the others.
Pool errors
A connection that fails while it sits idle in the pool, such as one the
server closed, makes pg emit error, which crashes Node when nothing
listens. createPostgres always listens. Pass events and the error reaches
your error handlers as a DbError; otherwise it goes to logger, or the
console. A handler or logger that throws is ignored, and the pool replaces
the connection on the next connect.
const postgres = createPostgres({ events: betterSupabase.events });
betterSupabase.on("error", ({ error }) => report(error));Counts
The Postgres executor counts like PostgREST, so a page or count with
a count mode returns the same total over either path:
count | What it runs |
|---|---|
exact | count(*) over every matching row |
planned | explain (format json) of the query; the planner's row estimate |
estimated | an exact count that stops after 1000 rows, and the planner's estimate when there are more |
Counts are bigint and decode to a number; a count past
Number.MAX_SAFE_INTEGER fails instead of rounding. Pass
estimatedCountThreshold to move the cutoff, to match a different
db-max-rows:
const db = betterSupabase.connect(
postgresExecutor(client, { estimatedCountThreshold: 5000 }),
{ claims },
);Which connection string
Supabase offers three ways in, and the right one depends on where the code runs:
| Connection | Host and port | Use it for |
|---|---|---|
| Direct | db.<ref>.supabase.co:5432 (IPv6) | long-running servers, migrations |
| Supavisor, session mode | <region>.pooler.supabase.com:5432 | long-running servers on IPv4 |
| Supavisor, transaction mode | <region>.pooler.supabase.com:6543 | serverless and edge functions |
Serverless functions open a connection per invocation, so use transaction
mode there and keep max small (1 to 3 per instance). Transaction mode
doesn't keep session state between transactions, which createPostgres
doesn't need: everything it sets is transaction-local. Doctor's
BS221 flags a direct or session-mode URL in a
serverless app.
Transactions
await postgres.transaction(
async (tx) => {
const db = betterSupabase.connect(postgresExecutor(tx), { claims });
const invoice = await db.invoices.create(data).orThrow();
await db.invoiceLines.create(lines(invoice.id)).orThrow();
},
{ claims },
);A thrown error rolls everything back. Plugins run as usual inside the transaction. A nested transaction runs in a savepoint, so a step that fails rolls back alone and the outer transaction stays usable.
Blocks in the same transaction
server.transaction does the same for a user and passes a Db bound to the
transaction. Block calls on it, such as db.audit, share the transaction with
repository writes. It rolls back on a throw and on a returned Result that
is not ok, and still returns that Result:
const result = await server.transaction(
userId,
async (db) => {
const job = await db.jobs.update({ id, status: "ready" });
if (!job.ok) {
return job;
}
return db.audit.record({
eventType: "job.ready",
organizationId,
record: id,
});
},
{ tenant: organizationId },
);It needs createServer(betterSupabase, { postgres }) with a postgres that
implements transactionFor, which createPostgres() does.
Functions
db.$rpc works over the Postgres executor too, so a request that runs as an
API key or a job over a direct connection calls the same functions as one
over PostgREST:
const db = betterSupabase.connect(postgres.executorFor(claims), { claims });
const rows = await db
.$rpc("customers_by_status", { p_status: "active" })
.orThrow();It runs select ... from schema.name(arg => $1, ...) with the named
arguments and returns what PostgREST returns: an array for a set-returning
or returns table function, one value or row otherwise, and null for
void. It reads whether the function returns a set from the generated
metadata, and sends json and jsonb arguments as JSON; a function the
metadata doesn't list is looked up in pg_proc first. The executor keeps
that lookup until a call fails with an error that says the function changed
(SQLSTATE 42883, 42P13 or 42804). Arguments for OUT and TABLE parameters
are dropped, as PostgREST drops them. Errors map like any other statement,
and a function that doesn't exist fails with invalid_request, as
PostgREST's PGRST202 does.
An existing pool
Pass pool to run on a pool you already have, such as the app's pg.Pool
or a test double. Anything with connect() and end() works (the PgPool
type), and postgres.end() ends it.
import { Pool } from "pg";
import { createPostgres } from "better-supabase/postgres";
const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 5 });
await using postgres = createPostgres({ pool });When each wins
Run tests/bench/executors.ts with your own table and a real user token to
get numbers for your region. The shape of the result is stable:
| Case | Faster path | Why |
|---|---|---|
| One read, a warm server in the same region | Direct SQL | Skips the HTTP hop and PostgREST's request parsing |
| One read from a cold serverless function | PostgREST | Reuses PostgREST's pool; SQL opens a connection first |
| Several reads of one request in one wave | Direct SQL | One transaction pool slot, no per-read HTTP overhead |
| Browser-facing requests with no database URL | PostgREST | Needs no credentials and no IPv4 pooler |
| Writes that commit together | Direct SQL | One transaction |
Measure the per-request floor of the project with
tests/bench/postgrest-floor.ts first: a read that takes 20 ms over a 15 ms
floor gains little from either path.
When to use it
- jobs, scripts and webhook handlers (with
actingAsfor user-scoped work); - several writes that must commit together;
- when PostgREST is not reachable from the runtime.
For browser-facing request handling, PostgREST remains the default: it pools connections for you and needs no database credentials.
Decode raw rows
db.$decode(table) reads rows that did not come from the repository, such as queryRaw or $client results with database names, into the table's shape: .row(value) and .rows(value) apply the configured casing and the column codecs (int8 to bigint, timestamps to Temporal) and return an AsyncResult. A value that is not an object is a validation error. With lazy tables (gen.serverTables: "lazy"), they load the table and every table an embedded relation in the value reaches first:
const rows = await postgres.admin.queryRaw("select * from customers limit 10");
const customers = await db.$decode("customers").rows(rows).orThrow();Last updated on