References and Relations
Foreign keys with q.references, matching a referenced row’s parent, requiring its state, self-references, and Drizzle relations.
How a column references another table, how the compiler proves a referenced row belongs to the same parent and is in an allowed state, and when to add Drizzle relations. Start at Database Schema for the table forms.
References
Declare every feature-table foreign key in the schema with .references().
That one declaration creates the database relationship and gives the API,
schema registry, and CMS the same target for label resolution and
selector/typeahead controls, and brands the column with the target table's
Id in quickback.gen.ts. The resource-level
references: map and the <table>Id naming convention resolve the same
way for the CMS and the type tree, but create no database constraint:
// features/applications/applications.ts
import candidates from "../candidates/candidates";
import jobs from "../jobs/jobs";
const applications = q.table("applications", {
id: q.id(),
candidateId: q.text().required().references(() => candidates.id),
jobId: q.text().required().references(() => jobs.id),
});When the target table lives in another feature, import it in the table
file — import <table> from "../<feature>/<table>", one ../, since table
files sit at features/<feature>/. The thunk names a real binding; without
the import the generated schema fails migration generation.
Do this even when a column name appears obvious, such as sessionId beside a
sessions table. A matching *Id name is not enough evidence to silently
invent a relationship, so the compiler refuses the omission instead:
SCHEMA_UNDECLARED_FK fails the
build when a *Id column names a feature table in the same database, is
client-writable or used in a firewall / relationship arm, and declares no
.references(). When the column genuinely is not a pointer into that table,
say so with a reason:
references: {
cventEventId: { references: false, reason: 'Cvent-side id; no row in this database' },
},When both tables carry an org column, the compiler also derives the org
match on the FK. Opt out with
references: { eventId: { match: false, reason: '…' } };
SCHEMA_FK_MATCH_REQUIRED warns only where the pair cannot be derived.
Self-references
A column that points at another row of the same table — a parent folder,
the version a document replaces — uses .references('self'). It targets the
table's own id:
// quickback/features/folders/folders.ts
import { feature, q } from '@quickback/compiler';
export default feature('folders', {
columns: {
id: q.id(),
name: q.text().required(),
parentId: q.text().optional().references('self', { onDelete: 'set null' }),
organizationId: q.scope('organization'),
...q.audit(),
...q.softDelete(),
},
read: { access: { roles: ['member'] } },
create: { access: { roles: ['member'] } },
update: { access: { roles: ['member'] } },
});() => folders.id cannot work here: inside feature() there is no folders
binding. In the two-export form
the binding exists, and .references(() => folders.id) inside its own
initializer works: the compiler reads the thunk as source, so its return is
not part of the table's type and there is no TypeScript cycle in your editor
or in quickback check. 'self' and the annotated
.references((): AnyQuickbackColumn => folders.id) (with
type AnyQuickbackColumn from @quickback/compiler) are also accepted. All
three spellings generate the same schema.
A self-reference is a normal FK everywhere else:
-
Writes check it through the table's own firewall, like any FK referential check: a row can't point at another tenant's row or a soft-deleted one.
nulldetaches the row. -
Reads resolve the parent's display label (
parent_labelonGET /:idand the list) through the same firewall, and the CMS renders the column as a picker over the same table. -
Cycles are not refused. A row may point at itself, and A → B → A passes too: each write checks one hop. If your data must stay a tree, enforce that in an action or a trigger.
-
A batch create checks parents that exist before the batch. A record can't name a sibling from the same batch as its parent; create the parent first.
-
Soft deletes stop at the row unless you say otherwise. The generated DELETE route's soft-delete cascade reaches child rows in other tables only; it never follows a self-reference, so children stay live when their parent is soft-deleted. To take the whole subtree with its root, add
onSoftDelete: 'cascade':parentId: q.text().optional().references('self', { onSoftDelete: 'cascade' }),Soft-deleting a row then soft-deletes every descendant, with the same
deletedAtanddeletedBy, in the same statement. It is a database trigger, so it holds on every write path (the DELETE route, actions, batch, raw SQL), on D1 and inside tenant databases. Descendants that were already deleted keep their own stamp, a cycle ends, and restoring the root does not restore them. The option is for self-references on a soft-delete table; apermanenttable can't declare it.
The legacy resource-level references: { vendorId: "contact" } map can override
schema-registry target metadata for an alias, but it does not create a database
foreign key. Prefer .references(() => contacts.id) whenever the target is a
feature table in the same database. Do not add .references() for Better
Auth ids (userId, organizationId, memberId, or auth sessionId): those
rows live in AUTH_DB, outside the feature database.
Match a referenced row's parent
An ordinary FK checks that its target exists and is visible. It does not infer that two rows belong to the same project, event, or other parent. Declare that rule on the FK when both rows must share one:
stageId: q.text().optional().references(() => projectStages.id, {
match: { source: 'projectId', target: 'projectId' },
}),Here source names a column on this table and target names one on the
referenced table. If stageId is set, both values must be non-null and equal.
If stageId is null, the match is not required. The compiler rejects unknown
columns or an unresolved target table. A match on a parent column like
projectId is opt-in: some visible records may legitimately link across
projects. The organization column is different — see below.
The org match is on by default. When an FK links two tables that both
carry an organization column, the compiler derives
match: { source: <child org>, target: <target org> } for you, so a row of
one organization can never point at another organization's row — not through
generated CRUD, an action, or raw SQL. The derived rule is exactly the one you
would write by hand (same triggers, same 400 DB_RELATIONSHIP_MISMATCH). It
applies when all of these hold:
- both tables are q-DSL tables (
q.table/feature), on D1 or a Postgres provider, and neither lives in a tenant database (one organization per database there, so the rule would be vacuous); - each table has exactly one org column — a
q.scope('organization')column, elseorganizationId/organisationId/orgId— and it is NOT NULL on both sides (a nullable org column usually means shared, org-less rows); - the FK declares no
matchof its own. An authoredmatchis never widened: if it is on another column, add the org rule to its list yourself.
When an FK may link organizations by design, opt out with a reason:
references: {
partnerEventId: { match: false, reason: 'guests may be invited to a partner org event' },
},Where the compiler cannot derive the pair (raw Drizzle tables, nullable or
ambiguous org columns, an authored match on another column, a firewall whose
org arm is a different column), SCHEMA_FK_MATCH_REQUIRED
warns in one line and names the match to add.
Upgrading a deployed project. The derived rule adds no column, index or
constraint, so the schema migration is unchanged and no table is rebuilt.
The next build appends one compiler-owned trigger migration
(NNNN_quickback_triggers_<hash>.sql) that drops and recreates the
project's triggers, now including the match_* ones. CREATE TRIGGER never
reads existing rows, so the migration cannot fail on data, on D1 or Postgres.
What changes is the next write. A row that already points at another
organization's row stays editable on its other columns: the source-side check
runs only when an update changes the foreign key or the organization column.
Changing either one is refused until the pair matches again, and a new
cross-organization insert is refused outright.
The build that first adds a derived rule's triggers to a project with
deployed migrations prints one [quickback:notice] listing each new FK, the
rule it now enforces, and a query that finds the rows those triggers would
refuse to move:
[quickback:notice] org FK match: 1 foreign key between organization tables now gets a database-enforced organization match (triggers in this build's *_quickback_triggers_* migration) on a database that already has rows:
applications.jobId → jobs (applications.organizationId must equal jobs.organizationId; feature "hiring")
find rows that already cross organizations: SELECT c.* FROM "applications" c LEFT JOIN "jobs" t ON t."id" = c."job_id" WHERE c."job_id" IS NOT NULL AND (t."id" IS NULL OR t."organization_id" <> c."organization_id");
Existing rows that point across organizations (or at a missing row) stay readable and editable on their other columns, but any write that changes the foreign key or the organization column is refused with DB_RELATIONSHIP_MISMATCH until the row is repaired. Run each query against the deployed database before deploying and repair what it returns, or opt the column out with `references: { <column>: { match: false, reason } }`.The query runs unchanged on D1 and Postgres. "First" is read from the latest compiler-owned triggers migration in your history: a rule whose triggers are already there is not reported again, and a fresh project (no prior migrations) gets no notice, nor does a table missing from the deployed features snapshot.
A CLI older than 0.74.0 does not send that history, so the compiler cannot tell which matches are new. On a deployed project it then prints a different notice instead: it says it cannot tell, lists every derived FK once with its repair query, and asks you to upgrade the CLI. It never claims the matches are new. That notice repeats on each build until the CLI is upgraded:
[quickback:notice] org FK match: cannot tell which organization matches are new — your Quickback CLI is older than 0.74.0 and does not send which ones the deployed database already enforces. 1 foreign key between organization tables has a derived database-enforced organization match (triggers in the *_quickback_triggers_* migration); any of them may be new on a database that already has rows:
applications.jobId → jobs (applications.organizationId must equal jobs.organizationId; feature "hiring")
find rows that already cross organizations: SELECT c.* FROM "applications" c LEFT JOIN "jobs" t ON t."id" = c."job_id" WHERE c."job_id" IS NOT NULL AND (t."id" IS NULL OR t."organization_id" <> c."organization_id");
Existing rows that point across organizations (or at a missing row) stay readable and editable on their other columns, but any write that changes the foreign key or the organization column is refused with DB_RELATIONSHIP_MISMATCH until the row is repaired. Run each query against the deployed database before deploying and repair what it returns, or opt the column out with `references: { <column>: { match: false, reason } }`.
Upgrade the CLI (npm i -g @quickback-dev/cli@latest, 0.74.0 or later) so the compiler reports only the matches this build actually adds; until then this notice repeats on every build.Null-safe matches. When "no project" is a value both rows can share, add
nulls: 'equal'. The comparison becomes null-safe (SQLite IS, Postgres
IS NOT DISTINCT FROM): a line with no project may point at a receipt with no
project, and a line with a project may not point at one without (or the other
way round).
receiptId: q.text().required().references(() => receipts.id, {
match: { source: 'projectId', target: 'projectId', nulls: 'equal' },
}),The default, nulls: 'distinct', is the strict rule above.
Several rules on one FK. match also takes a list, and every rule must
hold. A payment allocation that must carry its bill allocation's bill and
its project (or no project):
billAllocationId: q.text().optional().references(() => billAllocations.id, {
match: [
{ source: 'billId', target: 'billId' },
{ source: 'projectId', target: 'projectId', nulls: 'equal' },
],
}),A row with two optional FKs that must each agree with it, such as a credit
application tied to either a bill or a vendor credit, declares one match on
each FK. Whichever FK is set is checked.
Which writes, which rows, which answer. On SQLite (D1 and tenant databases) a rule takes four more options:
| Option | Effect |
|---|---|
on: 'insert' (or a list of 'insert', 'update', 'target') | Check only these writes. 'target' is a change to the referenced row's column. Default: all three |
where: { supersededAt: null } | Hold only rows of this table that match the condition, from both sides |
nulls: 'ignore' | A null on either side matches anything. Only two set values that differ are a mismatch |
code / message | Answer 422 TRIGGER_REJECTED with this details.code, like an invariant, instead of 400 DB_RELATIONSHIP_MISMATCH |
on: 'insert' is a stamp-time check. A receipt line takes its receipt's
project when it is written, and the receipt can move to another project later
while its superseded lines keep the tag they had:
receiptId: q.text().required().references(() => receipts.id, {
match: { source: 'projectId', target: 'projectId', nulls: 'equal', on: 'insert', code: 'RECEIPT_LINE_PROJECT_MISMATCH' },
}),With where: { supersededAt: null } instead, live lines are held to the
receipt at all times and superseded ones are not.
A parent value set by its first tagged child. With adopt: true the
referenced row takes this row's value while its own column is null. After
that the match holds: a later row with a different value is refused, and a row
with no value never conflicts.
// A bill takes the project of its first project-tagged allocation.
billId: q.text().required().references(() => bills.id, {
match: { source: 'projectId', target: 'projectId', adopt: true, on: 'insert', code: 'BILL_ALLOCATION_PROJECT_MISMATCH' },
}),The value is sticky: it stays when the row that set it is voided or deleted.
For a parent column that should always equal what its children say, use a
derived column instead.
The compiler emits database triggers for inserts and updates of the source
row, and for changes to the target's parent column (one pair per rule). They
are emitted the same way on a shared database and inside each
tenant database. Use the Quickback API for
client writes; the triggers backstop generated CRUD, batch writes, changesets,
and actions at the database boundary. The source update check fires only
when the update changes the foreign key or the matched column (BEFORE UPDATE OF "stage_id", "project_id", guarded so a re-sent unchanged value doesn't
count). Updating projectId while leaving stageId unchanged still checks
the resulting pair; an edit to any other column doesn't run the check, so a
row that crossed before the rule existed stays editable until someone moves
it. Extended rules (where, on, adopt, code, message or nulls: 'ignore') lower separately and still check on every
update. A mismatch returns
400 DB_RELATIONSHIP_MISMATCH from generated write routes. Apply the generated
trigger migration before using the new rule; it validates future writes, so
check existing rows for mismatches before rollout. The ordinary target
firewall check remains in
place for generated CRUD writes.
Require the referenced row's state
match compares a column on both rows. To require something of the
referenced row itself (its kind, or that it isn't archived), add requires.
The database checks it from both sides: a source write that points at a
failing row is refused, and so is a target update that would break a live
reference.
itemLineId: q.text().required().references(() => itemLines.id, {
requires: { kind: 'reimbursable' },
}),See Invariants → requires for the
condition syntax and the per-rule when form.
Never FK Better Auth tables
.references(() => users.id) (or user, organization, member, session) on a feature column is illegal. Those tables live in AUTH_DB; your features live in DB. SQLite cannot FK across D1 databases, and drizzle-kit fails generating features migrations:
Critical command failed: Generate features database migrations
A Start chat compile (complete=false) still succeeds — it never runs drizzle-kit. The complete compile (complete=true — Generated Backend, or quickback compile) is the first time that command runs.
A junction's userId is a plain text Better Auth id, not a SQL FK:
userId: q.text().required(), // ctx.userId — no .references()
channelId: q.text().required().references(() => channels.id, { onDelete: 'cascade' }),authz.relationships subject: { column: 'userId', equals: 'ctx.userId' } does not need, and must not create, a SQL FK. See Relationships. To query Better Auth tables, use c.get("authDb") from an action — see Scoped DB.
- Indexes and constraints: column-level
.index()/.unique()/.check(expr), or table-levelindexes/unique/checkas a third arg toq.table(name, cols, { indexes, unique, check }). Withfeature(), passindexes,uniqueandcheckas top-level keys alongsidecolumns— the sugar forwards them into the sameq.tableopts. In the two-export form they go onq.table; ondefineTable(...)they are a compile error, because they describe the table, not the resource. See Constraints. - Race-safe write kinds (on
defineTable):ledger: { grants, reserve }makes the table the debits side of a balance served asdb.ledger.<name>(Ledgers);idempotency: { rowToken, clientId? }makesPOST /andPOST /batchreplay a create whose row token is already stored (Row-token idempotency).
Relations (Optional)
Drizzle supports defining relations for type-safe joins:
import { relations } from 'drizzle-orm';
import { organizations } from '../organizations/organizations';
import { applications } from './applications';
export const jobsRelations = relations(jobs, ({ one, many }) => ({
organization: one(organizations, {
fields: [jobs.organizationId],
references: [organizations.id],
}),
applications: many(applications),
}));Drizzle relations(...) describe application-side joins; they do not always
create a database foreign-key constraint. On Neon, use
compiler.migrations.foreignKeys
for fully qualified cross-schema or composite constraints that cannot be
declared alongside a table. The ordered source and target column tuples must
have equal arity, and the referenced target tuple must have a matching unique
or primary-key constraint before the foreign key migration runs. A partial
unique (where / whereNotDeleted) does not qualify as an FK target.
Use these constraints for relational integrity only. Authorization, pass consumption, state transitions, and other business logic belong in the API action layer.
Managed Columns
Audit fields, soft-delete fields, q.scope tenant columns, q.stamp identity columns and q.storageKey — columns the compiler populates from verified context.
Constraints and Indexes
CHECK and unique constraints, unique constraints under soft delete, and the default index set the compiler generates.