# Tables, queries and types

> Generate typed tables from your database, and read and write with Sypnorm's query builder.

Applies to: the Sypnia engine (open source, self-hosted) and Sypnia Cloud (paid service).  
Source: https://cases.docs.sypnia.com/sypnorm/tables-and-queries/

For agents: `npx @sypnia/cases tables` ([cases.tables] in sypnia.toml: database, out) reads the schema (Sypnia Data: GET /sql/v1/schema with a secret key or the session; any Postgres: DATABASE_URL) and writes src/db/schema.gen.ts with typed tables, relations and enums. Query builder: ctx.db.<table>.where({col: value | {gt, gte, lt, lte, in, like, ilike, is}}).orderBy(col, 'desc').limit(n).all()/first()/count(); .with('relation'); .forUpdate() (direct runner); insert/insertMany(...).returning(); update(where).set({...})/increment/decrement; delete(where); ctx.db.sql`…` (direct runner). Types follow the database: nullable columns are T | null. Migrations stay with your database tool (npx @sypnia/data migrate on Sypnia Data).

## Typed tables from your database

`sypnia.toml`

```toml
[cases.tables]
database = "https://<ref>.data.sypnia.com"   # a Sypnia Data project; leave it out to use DATABASE_URL (any Postgres)
out = "src/db/schema.gen.ts"
```

Like every Sypnia product, Cases keeps its settings in its own table of `sypnia.toml`, the project's one configuration file at the root of the repository.

```bash
npx @sypnia/cases tables
```

Sypnorm reads your schema and writes typed tables: columns, nullability, defaults, enums and relations. On Sypnia Data it reads `GET /sql/v1/schema` with your session or a secret key; on any other Postgres it reads the catalog through `DATABASE_URL`. Run it again after each migration.

`src/db/index.ts`

```ts
import { tables } from './schema.gen';
export const db = tables;
```

Migrations are your database's business, not Sypnorm's: on Sypnia Data, `npx @sypnia/data migrate`; elsewhere, the tool you already use.

## Read

```ts
const open = await ctx.db.orders
  .where({ status: 'paid', total: { gte: 50_000 } })
  .with('customer')                 // the related row, typed
  .orderBy('created_at', 'desc')
  .limit(20)
  .all();

const first = await ctx.db.products.where({ slug: 'sourdough' }).first();   // or null
const n = await ctx.db.orders.where({ status: 'pending' }).count();
```

Operators: equality by value, or `{ gt, gte, lt, lte, in, like, ilike, is }`. Types follow the database: a nullable column is `T | null`.

## Write

```ts
const order = await ctx.db.orders.insert({ customer_id: userId, pickup_at }).returning();
await ctx.db.order_items.insertMany(rows);
await ctx.db.products.update({ id }).set({ price: 9_500 });
await ctx.db.products.update({ id }).decrement('left_today', 2);
await ctx.db.orders.delete({ id });
```

`update` and `delete` always take a filter. Inside a use case, `ctx.db` only lets you touch the tables in `touches`.

## Raw SQL when you want it

With a direct connection ([Runners](https://cases.docs.sypnia.com/sypnorm/runners)):

```ts
const rows = await ctx.db.sql<{ day: string; total: number }>`
  select date_trunc('day', created_at) as day, sum(total) as total from orders group by 1 order by 1`;
```

Values interpolated with the template tag are sent as parameters, never pasted into the text.
