Database
Every project has its own Postgres database. tc.db gives you two ways in:
| Access | Runs as | Row-level security | Where |
|---|---|---|---|
tc.db.from() / tc.db.rpc() | The signed-in user (tc_user role) | Applies | Browser and server |
tc.db.asUser(req) | The signed-in user of req | Applies | Server |
tc.db.sql | The project's service role | Bypassed | Server |
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
| Parameter | Type | Description |
|---|---|---|
table | string | Table 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.code | Meaning | Hint |
|---|---|---|
42501 | Row-level security or grants blocked it | Add a policy under Database → Policies |
42P01, PGRST205 | The table doesn't exist (or the Data API hasn't seen it yet) | Create it or ship a migration |
PGRST204 | The column doesn't exist | Check column names |
PGRST301 | The identity was rejected | Reload; on the server forward the current request (identities expire after 5 minutes) |
PGRST302 | No signed-in user reached the Data API | Use tc.db on your own origin, or asUser(req) on the server |
23505, 23503, 23502 | Unique, foreign key or not-null violation | |
TC_UNAUTHENTICATED | The session expired | Reload the page |
TC_NO_ACCESS | The person can't open this app | Ask the owner (named in the hint) |
Example
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)
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[]>
| Form | Description |
|---|---|
| Tagged template | Interpolated 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)
| Code | When |
|---|---|
SERVER_ONLY | Called in the browser |
BAD_SQL_CALL | Called as a function (tc.db.sql('…')) instead of a tagged template |
DB_ERROR | Postgres refused the query. details.code is the SQLSTATE; fix explains common ones (42501, 42P01, 28P01, 57014) |
NOT_CONFIGURED | DATABASE_URL isn't set |
- JavaScript
- Python
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)
})
@app.get("/api/summary")
def summary(since: str = "2026-01-01"):
# %s placeholders; returns a DataFrame if pandas is installed
return tc.db.sql(
"select status, count(*) as n from purchase_requests where created_at > %s group by status",
[since],
dataframe=False,
)
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
}
| Parameter | Type | Description |
|---|---|---|
req | RequestLike | The incoming request. Optional inside tc.middleware(). |
Errors: NO_REQUEST, UNAUTHENTICATED (no X-TC-User header), BAD_IDENTITY, NOT_CONFIGURED, DB_ERROR.
- JavaScript
- Python
const { data } = await tc.db.asUser(req).from('purchase_requests').select('*')
const mine = await tc.db.asUser(req).sql`select * from purchase_requests`
res = tc.db.as_user(request).from_("purchase_requests").select("*").execute()
mine = tc.db.as_user(request).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>