Constraints and foreign keys
Let PostgreSQL refuse bad data: pick a primary key, link tables with foreign keys and the right delete rule, add checks to existing tables, and handle each violation from the SDK.
Constraints are rules PostgreSQL checks on every write, whatever the door: SDK, REST, aura db raw or a direct connection. A row that breaks one is refused and nothing is written. Declare them in SQL with aura db raw; the schema API and Studio cover the common ones (not null, unique, check, a foreign key per column).
Prerequisites#
-
A linked project:
aura link <project-id>. -
The example schema, installed with the service role key of the project:
export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docsIt creates
profiles,orgs,org_members,posts,todos, the viewopen_todosand the functiontodo_count(p_user uuid). See Example schema.
The examples create the tables sch_cons_authors, sch_cons_books and sch_cons_bookings, then remove them. In the example schema, org_members.org_id references orgs (id) on delete cascade, and org_members has the composite primary key (org_id, user_id).
Constraint kinds#
| Constraint | Guarantees | SDK error | SQLSTATE |
|---|---|---|---|
primary key | One row per key; implies not null and unique. | 409 DUPLICATE_KEY | 23505 |
unique | No two rows with the same values (several null are allowed unless nulls not distinct). | 409 DUPLICATE_KEY | 23505 |
not null | A value is always present. | 400 NOT_NULL_VIOLATION | 23502 |
check (…) | An expression is true for every row. | 400 CHECK_VIOLATION | 23514 |
references (foreign key) | The referenced row exists. | 409 FOREIGN_KEY_VIOLATION | 23503 |
exclude using gist (…) | No two rows conflict on an operator, such as overlapping time ranges. | 400 POSTGREST_ERROR | 23P01 |
The SQLSTATE is in the upstream_code field of the REST error body. aura db raw answers 400 BAD_REQUEST with the PostgreSQL message for all of them.
Declare constraints#
create table sch_cons_authors (
id bigint generated always as identity primary key,
name text not null
);
create table sch_cons_books (
id bigint generated by default as identity primary key,
author_id bigint not null references sch_cons_authors (id) on delete cascade,
isbn text not null unique,
title text not null,
price numeric(10,2) not null check (price >= 0),
constraint sch_cons_books_title_per_author unique (author_id, title)
);
create table sch_cons_bookings (
room text not null,
during tstzrange not null,
exclude using gist (room with =, during with &&)
);
insert into sch_cons_authors (name) values ('Ursula'), ('Octavia');
insert into sch_cons_books (author_id, isbn, title, price) values
(1, '978-0441478125', 'The Left Hand of Darkness', 9.99),
(2, '978-0807083697', 'Kindred', 12.50);
insert into sch_cons_bookings values ('A', '[2026-12-01 09:00+00, 2026-12-01 10:00+00)'); ℹ No results (0 rows).The exclusion constraint compares room with = inside a GiST index, which needs the btree_gist extension: it is installed in every project. A constraint without a name gets one from PostgreSQL (sch_cons_books_isbn_key, sch_cons_books_price_check, sch_cons_books_author_id_fkey); name the ones you will look for in error messages.
What a violation returns#
Each insert below breaks one constraint:
import { createClient } from '@aurabase/aurabase-js'
const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const show = (label: string, r: { error: { status?: number; code?: string; message?: string } | null }) =>
console.log(label.padEnd(10), r.error ? `${r.error.status} ${r.error.code} ${r.error.message}` : 'ok')
show('unique', await admin.db.from('sch_cons_books').insert({ author_id: 1, isbn: '978-0807083697', title: 'Other', price: 1 }))
show('foreign', await admin.db.from('sch_cons_books').insert({ author_id: 99, isbn: '1', title: 'Ghost', price: 1 }))
show('not null', await admin.db.from('sch_cons_books').insert({ author_id: 1, isbn: '2', price: 1 }))
show('check', await admin.db.from('sch_cons_books').insert({ author_id: 1, isbn: '3', title: 'Cheap', price: -1 }))
show('exclusion', await admin.db.from('sch_cons_bookings').insert({ room: 'A', during: '[2026-12-01 09:30+00, 2026-12-01 11:00+00)' }))
show('identity', await admin.db.from('sch_cons_authors').insert({ id: 7, name: 'Iain' }))unique 409 DUPLICATE_KEY duplicate key value violates unique constraint "sch_cons_books_isbn_key"
foreign 409 FOREIGN_KEY_VIOLATION insert or update on table "sch_cons_books" violates foreign key constraint "sch_cons_books_author_id_fkey"
not null 400 NOT_NULL_VIOLATION null value in column "title" of relation "sch_cons_books" violates not-null constraint
check 400 CHECK_VIOLATION new row for relation "sch_cons_books" violates check constraint "sch_cons_books_price_check"
exclusion 400 POSTGREST_ERROR conflicting key value violates exclusion constraint "sch_cons_bookings_room_during_excl"
identity 400 POSTGREST_ERROR cannot insert a non-DEFAULT value into column "id"The full error body also carries details (for a duplicate, Key (isbn)=(978-0807083697) already exists.) and the SQLSTATE in upstream_code. Branch on error.code in your application, and show details only to people allowed to see the other row.
Identity columns and upserts#
An identity column draws its value from a sequence:
generated always as identityrefuses any value from the client (cannot insert a non-DEFAULT value into column "id"), including anidinside anupsert().todos,postsandorgsof the example schema use it. In SQL,overriding system valueforces a value, for imports only.generated by default as identityaccepts a value from the client and uses the sequence otherwise. If you insert ids yourself, the sequence does not move: the next generated id can collide with yours (409 DUPLICATE_KEYon…_pkey).uuid default gen_random_uuid(), the default of tables created by the CLI, lets the client choose the id before the insert, which suits offline writes and ids generated in the browser.
upsert() of the SDK (and POST with ?on_conflict= on the REST API) currently answers 409 DUPLICATE_KEY when the row already exists, instead of updating it: measured with SDK 0.7.5 on a unique column and on a primary key. Until this is fixed, update an existing row by filter (update(…).eq('isbn', …)) or use insert … on conflict … do update in SQL:
aura db raw "insert into sch_cons_books (author_id, isbn, title, price) values (2, '978-0807083697', 'Kindred', 14) on conflict (isbn) do update set price = excluded.price returning isbn, price" isbn │ price
───────────────┼──────
978-0807083697 │ 14.0
ℹ 1 row(s).To offer the same to signed-in users, wrap the statement in a security invoker function and call it with rpc(): Database functions.
Delete rules of foreign keys#
on delete decides what happens to the rows that point to a deleted row:
| Rule | Effect | Use it for |
|---|---|---|
no action (default), restrict | The delete is refused while rows point to it (23503). | Data that must not disappear silently, such as invoices. |
cascade | The pointing rows are deleted too. | Rows that belong to the parent: members of an org, books of an author in this example. |
set null | The pointing column becomes null (it must be nullable). | Optional links, such as the last editor of a page. |
set default | The pointing column takes its default. | A fallback owner. |
on update takes the same rules. Delete the first author: her book goes with her.
aura db raw "delete from sch_cons_authors where name = 'Ursula'"
aura db raw "select title from sch_cons_books order by title" ℹ No results (0 rows).
title
───────
Kindred
ℹ 1 row(s).PostgreSQL does not create an index on the referencing column. Add one (create index on sch_cons_books (author_id)) when the parent table is large or often deleted from: Indexes.
Ids and relationships#
Coming from a document database, model each kind of document as a table and each reference as a foreign key column:
| Relationship | Model | Example schema |
|---|---|---|
| One to many | A foreign key on the "many" side | posts.user_id, todos.user_id |
| One to one | A foreign key with unique, or the same primary key | profiles.id is the id of the user |
| Many to many | A join table with two foreign keys and a composite primary key | org_members (org_id, user_id) |
The SDK reads related rows in one request through foreign keys (select('title, sch_cons_authors(name)')); see Query data with the SDK. A user id from Aurabase Auth is a uuid: store it in a uuid column, and compare it to auth.uid() in policies.
Add a constraint to an existing table#
alter table … add constraint checks every existing row and fails if one breaks the rule. On a large table, add it not valid (new writes are checked at once), fix the old rows, then validate:
alter table sch_cons_books add constraint sch_cons_books_isbn_format check (isbn ~ '^[0-9-]+$') not valid;
alter table sch_cons_books validate constraint sch_cons_books_isbn_format; ℹ No results (0 rows).Remove a constraint with alter table … drop constraint <name>. The schema API sets not null, unique, a default and a foreign key per column (see Create and change tables); everything else goes through SQL.
Result#
aura db raw "select b.title, a.name as author, b.price from sch_cons_books b join sch_cons_authors a on a.id = b.author_id" author │ price │ title
────────┼───────┼────────
Octavia │ 14.0 │ Kindred
ℹ 1 row(s).Common errors#
| Message | Cause | Fix |
|---|---|---|
409 DUPLICATE_KEY duplicate key value violates unique constraint "…" | A value already used in a unique column or key. | Change the value, or update the existing row. |
409 FOREIGN_KEY_VIOLATION … violates foreign key constraint "…" | The referenced row does not exist, or a delete of a referenced row under no action. | Insert the parent first; choose a delete rule. |
400 NOT_NULL_VIOLATION null value in column "…" … violates not-null constraint | A required column is missing from the insert. | Send it, or give the column a default. |
400 CHECK_VIOLATION new row for relation "…" violates check constraint "…" | A value outside the rule. | Send a valid value. |
400 POSTGREST_ERROR conflicting key value violates exclusion constraint "…" | Two rows conflict, such as overlapping bookings. | Pick a free slot. |
400 POSTGREST_ERROR cannot insert a non-DEFAULT value into column "id" | A value sent to a generated always as identity column. | Leave id out. |
check constraint "…" of relation "…" is violated by some row | add constraint on a table with rows that break the rule. | Add it not valid, fix the rows, then validate constraint. |
Clean up#
drop table sch_cons_bookings;
drop table sch_cons_books;
drop table sch_cons_authors; ℹ No results (0 rows).