Business rules

Some things must never happen, whoever tries: booking a full class, a due date in the past, a price below cost. In a code-first app a rule lives in the database, as a constraint or a trigger, so it holds for every write: from your pages, an action, a workflow, the API or SQL. If it says no, nothing is written and your user reads your message.

When to use which

The ruleWrite it as
About one row's own values (a title isn't empty, booked never exceeds capacity)A check constraint
No two rows alike (one booking per member per class)A unique index, partial if it applies to some rows
A status moves only along certain pathsctx.lifecycle
Old value against new, other rows, the time, who is writingA trigger that raises your message

Use access for "who may touch which rows", a rule for "what may be in them", and a workflow for what should happen after a write (a workflow can't stop one).

Code

Constraints and a unique index

create table if not exists class_session (
  …
  capacity int not null,
  booked   int not null default 0,
  constraint class_session_capacity_positive check (capacity > 0),
  constraint class_session_never_overbooked check (booked between 0 and capacity)
);
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 $$);

A trigger with your message

From the todo app: a due date can't be set in the past.

-- db/schema/todo.sql (continued)
create or replace function todo_due_guard() returns trigger
language plpgsql set search_path = public as $$
begin
  if new.due_on is not null and new.due_on < current_date
     and (tg_op = 'INSERT' or new.due_on is distinct from old.due_on) then
    raise exception 'Pick a due date from today on.';
  end if;
  return new;
end $$;

create or replace trigger todo_due_guard before insert or update on todo
  for each row execute function todo_due_guard();

The booking app's seat trigger refuses a full or started class the same way, and keeps the class's count current in the same transaction.

What the user sees

The database saysThe app answers
raise exception '…'422 with your message
raise exception '…' using errcode = 'unique_violation'409 with your message
A check constraint fails422 naming the constraint
A unique constraint or index fails409 CONFLICT naming it
A foreign key still in use409 IN_USE
A lifecycle move that isn't declared"status can't move from attended to booked", with the moves that are allowed

In a page, the write's promise rejects with that message: catch it and show it.

try {
  await todos.create({ title, due_on: due });
} catch (e) {
  setError(e instanceof Error ? e.message : String(e));   // "Pick a due date from today on."
}

Check it

// Try the write as a member, rolled back: the refusal comes back with Postgres's message.
sql { "project_id": "…", "dry_run": true, "as": { "role": "member" },
      "sql": "insert into todo (title, due_on) values ('Pay rent', current_date - 1)" }

// The same through the app's own write path, nothing kept:
explain { "project_id": "…", "about": "access", "table": "todo", "op": "create",
          "as": { "role": "member" }, "values": { "title": "Pay rent", "due_on": "2020-01-01" } }

check_contract { "project_id": "…", "files": { … }, "plan": true }   // the trigger's create statements in the plan

Gotchas

  • A trigger runs as the writer. Its queries see only the rows the writer may read. A rule that counts other people's rows needs security definer, with set search_path and a -- @definer <why> line above it.
  • A check constraint can't use now() (Postgres requires it to be immutable). Compare with the time in a trigger.
  • Triggers fire for seeds on every apply. A before insert rule must let an existing seed row through, or the apply fails.
  • The lint refuses drop trigger. Use create or replace trigger and create or replace function, so the file runs again cleanly at every apply.
  • Rules hold for server code too. Workflows and actions write through the same constraints and triggers; check the input in the action anyway, so the message is about the input.
  • Converted JSON apps (appbricx migrate --to code) get each table's old rules as one trigger, <table>_rules, with the same messages.

Related