Skip to content

Tables, queries and types

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

Applies to EngineCloud
View as Markdown
On this page
  1. Typed tables from your database
  2. Read
  3. Write
  4. Raw SQL when you want it

Typed tables from your database

sypnia.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.

Terminal
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
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

TypeScript
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

TypeScript
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):

TypeScript
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.

  1. Typed tables from your database
  2. Read
  3. Write
  4. Raw SQL when you want it

    Search pages, sections and terms