Data and tables

Every app has its own Postgres database. You write what it should look like in plain SQL files; each apply works out the change and makes it without losing rows. As soon as a table exists and a policy opens it, your pages, actions, workflows and outside tools can read and write it, typed from the columns you wrote.

When to use it

Always: every app starts here. Add a table for each kind of thing your users work with (a class, a booking, a ticket) and a profile table for each kind of person who signs in and needs one (a member, a client).

The files

FileWhat goes in it
db/schema/*.sqlTables, indexes, constraints, triggers, functions and views, written as the state you want. Every statement re-runnable (if not exists, or replace)
db/access/*.sqlRow-level security policies: who reads and changes which rows. See access and roles
db/seeds/*.sqlRows for dev and previews (and production, for a file marked -- @env prod)
db/queries/*.sqlNamed queries, one per file, callable from pages and over HTTP
db/extensions.sqlcreate extension if not exists … for the extensions the platform allows

Code

Two tables from the booking app:

-- db/schema/class_session.sql
create table if not exists class_session (
  id           uuid primary key default gen_random_uuid(),
  title        text not null,
  style        text not null default 'vinyasa',
  starts_at    timestamptz not null,
  capacity     int  not null,
  booked       int  not null default 0,
  garden       boolean not null default false,
  created_at   timestamptz not null default now(),
  constraint class_session_style_known check (style in ('vinyasa', 'pilates', 'yin', 'breathwork')),
  constraint class_session_never_overbooked check (booked between 0 and capacity)
);
create index if not exists class_session_starts on class_session (starts_at);
-- db/schema/booking.sql
create table if not exists booking (
  id         uuid primary key default gen_random_uuid(),
  session_id uuid not null references class_session on delete cascade,
  member_id  uuid not null references member_profile on delete cascade default ctx.profile_id('member'),
  status     text not null default 'booked',
  created_at timestamptz not null default now()
);
create index if not exists booking_session on booking (session_id);
create unique index if not exists booking_once on booking (session_id, member_id) where status = 'booked';

select ctx.lifecycle('booking', 'status', $$
  booked -> cancelled | attended | no_show
$$);
  • Name your constraints. A refused write answers with the constraint's name (class_session_never_overbooked), so a good name is a readable error.
  • Index your foreign keys yourself; nothing is indexed for you except primary keys and unique constraints. Verify's indexes check flags columns your policies filter on.
  • Defaults can ask who is writing: default ctx.uid() or default ctx.profile_id('member') stamps the row with its writer, so the page never sends it.

The ctx helpers

Installed in every app database as ordinary SQL you can read.

HelperWhat it is
ctx.email, ctx.phone, ctx.url, ctx.slugText domains with a format check (an email, an E.164 phone number, an http(s) URL, a URL slug)
ctx.moneynumeric(14,2). In TypeScript it is a decimal string ("42.00"), so nothing is lost to floating point
ctx.encryptedEncrypted at rest with the project's key; the data API decrypts it for readers. Not searchable or sortable
ctx.file, ctx.imageA file's id in the app's file store. See files
ctx.lifecycle(table, column, graph)The column's allowed values and moves (requested -> confirmed | cancelled); any other move is refused. The first state is where a new row starts
ctx.touch(table)Keeps updated_at current
ctx.soft_delete(table)A delete sets deleted_at and reads hide the row; a trash and restore
ctx.short_ref(prefix)A short readable unique reference for a default: BK-7F3K2
ctx.seed_id(label)A stable uuid for a seed row: the same label gives the same id every time
ctx.uid(), ctx.role(), ctx.has_role(r), ctx.profile_id(r), ctx.is_guest()Who is asking: for defaults, policies and triggers

A few words Postgres has no syntax for go in comments: comment on column booking.email is '@pii @hide host' (personal data; never served to the host role), comment on table ops_note is '@api off' (never served by the data API; '@api read' for read only), '@label Company booker'.

Seed data

-- db/seeds/stillwater.sql
insert into class_session (id, title, style, starts_at, capacity) values
  (ctx.seed_id('cls-sunrise'), 'Sunrise Flow', 'vinyasa', date_trunc('day', now()) + interval '1 day 6 hours 30 minutes', 14),
  (ctx.seed_id('cls-yin'),     'Slow Yin',     'yin',     date_trunc('day', now()) + interval '2 days 18 hours', 12)
on conflict (id) do nothing;

Seeds run on every apply in dev and previews, so every statement needs on conflict. Rows that already exist stay as they are, including edits people made in the app. Reference a seed row from another with the same ctx.seed_id label.

Read and write it

From a page

import { useQuery, useRow, useTable } from "@appbricx/ui";

const { rows, total, loading } = useQuery("class_session", {
  where: { style: "pilates" },                                   // equality
  filter: [{ field: "capacity", op: "gte", value: 10 }],         // clauses, all ANDed
  sort: "starts_at", limit: 20,                                   // "-starts_at" for descending
});
const { row, notFound } = useRow("class_session", id);
const q = useQuery("booking", { embed: "class_session(title,starts_at)" }); // related rows in one read

const bookings = useTable("booking");
await bookings.create({ session_id: id });                        // reads of booking refresh after each write
await bookings.update(bookingId, { status: "cancelled" });
await bookings.remove(bookingId);

Every read is made as the signed-in user, so row-level security decides what comes back. Rows are typed from your columns (a nullable column is T | null); embedded rows aren't in the type, so cast them where you use them. useList(table) is a small lookup (up to 200 rows). The full list is in the SDK reference.

From server code

// server/*.ts (an action) or workflows/*.ts
const s = await ctx.db.get("class_session", input.session);
const rows = await ctx.db.list("booking", { where: { session_id: s?.id }, sort: "-created_at", limit: 50 });
await ctx.db.update("booking", id, { status: "attended" });

// in a workflow, one recorded SQL statement:
const n = await step.sql("waiting", "select count(*)::int as n from booking where status = 'booked'");

Over HTTP

Outside tools use the data API at /__appbricx/api/v1/<table> on the app's host (list, get, create, update, delete), under the same policies. See the API reference.

Named queries

-- db/queries/week-load.sql
-- @param style text
-- @roles instructor
select to_char(starts_at, 'Dy DD') as day, sum(booked)::int as booked, sum(capacity)::int as capacity
from class_session
where style = :style and starts_at >= now() and starts_at < now() + interval '7 days'
group by 1, date_trunc('day', starts_at) order by date_trunc('day', starts_at);
const load = useNamedQuery("week-load", { style: "yin" });   // in the browser; typed params and rows

:style is bound, never pasted. The query runs as the caller under row-level security; @roles only limits who may call it. Outside tools call POST /__appbricx/queries/week-load. A query that doesn't compile fails the check with Postgres's message.

Check it

code { "project_id": "…", "action": "create", "kind": "table", "name": "class_session",
       "content": "…", "then": "check" }               // errors at db/schema/class_session.sql:line
check_contract { "project_id": "…", "files": { … }, "plan": true }   // the SQL an apply would run, as a dry run
describe_schema { "project_id": "…" }                   // the real tables, columns, indexes, triggers, policies
query_data { "project_id": "…", "entity": "booking", "as": { "role": "member" } }   // what a member reads

By hand: appbricx push <project-id> . --check from the folder that holds app.config.ts.

Change it later

Edit the file and apply. New tables, columns, indexes and looser constraints are added in one transaction, rows kept. Anything that would lose data (a table or column you removed, a tighter constraint) stays pending and is listed in the warnings until you apply with allow_destructive: true, which snapshots dev first. A rename is a new column: copy the values with SQL, then drop the old one. Production gets the same plan when you publish, additive steps first.

Gotchas

  • The only drop allowed in db/ is drop policy if exists right before its create policy. The plan makes every other drop.
  • Don't enable row-level security yourself. The platform enables and forces it on every table at each apply, and the lint refuses alter table … enable row level security.
  • A table with no policy is unreachable from pages and the API. That is the safe default; write the policy.
  • Row triggers fire for seeds on every apply. A before insert trigger must accept a seed row that already exists (the booking app's seat counter checks for it).
  • Pages render on the server first: format dates with an explicit time zone so the server and the browser print the same thing.
  • Converting a JSON app? appbricx migrate --to code <contract.json> <dir> writes these files from it.

Related