# Database

Explicit, parameterized SQL through Bun.SQL on PostgreSQL. There is no ORM.

```ts
import { sql, transaction, useTenant } from '@fellowframework/core'

const rows = await sql<Document>`select * from records_documents where tenant_id = ${useTenant()} and id = ${id}`

await transaction(async () => {
  await sql`update ...`   // every sql call in here, at any depth, joins the transaction
  await sql`insert ...`
})
```

Values in `${}` are always bound as parameters, never interpolated.

## Tenant isolation

Isolation is enforced twice:

1. In the query: scope by `tenant_id = ${useTenant()}`. `useTenant()` throws when there is no tenant.
2. In the database: row-level security. Each transaction sets `app.tenant_id` (transaction-local),
   and the table policy filters on it. A forgotten `WHERE` returns only the current tenant's rows;
   without a tenant context, nothing.

A tenant table must look like this (the generators write it for you):

```sql
create table records_documents (
  id uuid primary key default gen_random_uuid(),
  tenant_id uuid not null,
  ...
);
alter table records_documents enable row level security;
alter table records_documents force row level security;
create policy tenant_isolation on records_documents
  using (tenant_id = nullif(current_setting('app.tenant_id', true), '')::uuid)
  with check (tenant_id = nullif(current_setting('app.tenant_id', true), '')::uuid);
```

`force` matters: without it the table owner bypasses the policy. Superusers and BYPASSRLS roles
always bypass it, so the application must connect with an ordinary role. `fellow doctor` checks this.

Outside a request (scripts, jobs, tests) use `runAsTenant(tenantId, fn)`.

## Migrations

Plain SQL files in `modules/<id>/migrations/NNNN_description.sql`.

- `fellow migrate --dry-run` shows the plan; `fellow migrate` applies it; `fellow migrate:status` lists states.
- Order: module dependencies first, then file name. Each migration runs in its own transaction.
- Applied migrations are immutable: editing one is refused (checksum). Add a new migration instead.
- Destructive statements (`drop table`, `drop column`, `truncate`, `delete from`, column type changes)
  require `--allow-destructive`, which is a human decision.
- A module creates only tables prefixed with its id, and no other module may reference them.
