Skip to main content

Database

Every project has its own Postgres database. tc.db gives you two ways in:

AccessRuns asRow-level securityWhere
tc.db.from() / tc.db.rpc()The signed-in user (tc_user role)AppliesBrowser and server
tc.db.asUser(req)The signed-in user of reqAppliesServer
tc.db.sqlThe project's service roleBypassedServer

Schema changes, policies and the SQL helpers are covered in the Data section.

tc.db.from(table)​

A postgrest-js query builder: the same syntax as supabase.from(). Results come back as { data, error }.

tc.db.from(table: string): PostgrestQueryBuilder
ParameterTypeDescription
tablestringTable or view name

Returns a builder with select, insert, update, upsert, delete and the usual filters (eq, in, order, range, …). Awaiting it gives { data, error, count, status }.

Errors are returned, not thrown. error has PostgREST's shape { code, message, details, hint }, and the platform fills hint with how to fix it:

error.codeMeaningHint
42501Row-level security or grants blocked itAdd a policy under Database → Policies
42P01, PGRST205The table doesn't exist (or the Data API hasn't seen it yet)Create it or ship a migration
PGRST204The column doesn't existCheck column names
PGRST301The identity was rejectedReload; on the server forward the current request (identities expire after 5 minutes)
PGRST302No signed-in user reached the Data APIUse tc.db on your own origin, or asUser(req) on the server
23505, 23503, 23502Unique, foreign key or not-null violation
TC_UNAUTHENTICATEDThe session expiredReload the page
TC_NO_ACCESSThe person can't open this appAsk the owner (named in the hint)

Example

src/requests.js
import { tc } from '@tenantcloud/sdk'

// Read
const { data, error } = await tc.db
.from('purchase_requests')
.select('*')
.order('created_at', { ascending: false })
if (error) console.error(error.message, error.hint)

// Insert: created_by fills itself if the column defaults to tc.user_id()
await tc.db.from('purchase_requests').insert({ title: 'Monitor', amount: 240 })

// Update
await tc.db.from('purchase_requests').update({ status: 'approved' }).eq('id', 7)
Server

On the server, tc.db.from() acts as the user of the current request, so it only works inside tc.middleware() or tc.withRequest(). Otherwise it throws NO_REQUEST; use tc.db.asUser(req).from() instead.

tc.db.rpc(fn, args, options)​

Calls a Postgres function through the Data API, as the signed-in user. Same as postgrest-js rpc.

tc.db.rpc(fn: string, args?: object, options?: { head?: boolean; get?: boolean; count?: 'exact' | 'planned' | 'estimated' })
const { data } = await tc.db.rpc('monthly_totals', { year: 2026 })

tc.db.sql​

Server only. Raw SQL as the project's service role, which bypasses row-level security. Use it for reports, jobs and admin routes, and check permissions yourself.

tc.db.sql`select … where id = ${id}`: Promise<Row[]>
tc.db.sql.query(text: string, values?: unknown[]): Promise<Row[]>
FormDescription
Tagged templateInterpolated values become $1, $2… parameters, so it's safe from SQL injection
.query(text, values)A SQL string with $1 placeholders and a values array

Returns an array of row objects.

Errors (thrown TcError)

CodeWhen
SERVER_ONLYCalled in the browser
BAD_SQL_CALLCalled as a function (tc.db.sql('…')) instead of a tagged template
DB_ERRORPostgres refused the query. details.code is the SQLSTATE; fix explains common ones (42501, 42P01, 28P01, 57014)
NOT_CONFIGUREDDATABASE_URL isn't set
server.js
app.get('/api/summary', async (req, res) => {
const since = req.query.since ?? '2026-01-01'
const rows = await tc.db.sql`
select status, count(*)::int as n, sum(amount)::float as total
from purchase_requests
where created_at > ${since}
group by status`
res.json(rows)
})

tc.db.asUser(req)​

Server only. The Data API and SQL as the signed-in user of req. Row-level security applies, and tc.user_id(), tc.has_role() and friends work exactly as through the browser.

tc.db.asUser(req?: RequestLike): {
from(table: string): PostgrestQueryBuilder
rpc(fn: string, args?: object, options?: object): PostgrestFilterBuilder
schema(name: string): PostgrestClient
sql: SqlTag // tagged template, runs as the user
}
ParameterTypeDescription
reqRequestLikeThe incoming request. Optional inside tc.middleware().

Errors: NO_REQUEST, UNAUTHENTICATED (no X-TC-User header), BAD_IDENTITY, NOT_CONFIGURED, DB_ERROR.

const { data } = await tc.db.asUser(req).from('purchase_requests').select('*')
const mine = await tc.db.asUser(req).sql`select * from purchase_requests`

asUser(req).sql runs in a transaction that sets the request's claims and switches to the user's role, so the SQL sees the same policies as the Data API.

tc.db.pool()​

Server only. Returns the underlying pg.Pool (service role) for transactions and streaming.

tc.db.pool(): Promise<pg.Pool>
const pool = await tc.db.pool()
const client = await pool.connect()
try {
await client.query('begin')
await client.query('update stock set qty = qty - $1 where sku = $2', [1, 'MON-27'])
await client.query('commit')
} finally {
client.release()
}

tc.db.end()​

Closes the pool. Useful at the end of a script or a cron job so the process can exit.

tc.db.end(): Promise<void>
Was this page helpful?