Quickback Docs
Database Schema

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.

Managed columns hold values the compiler and the generated runtime populate from verified request context, never from the request body: audit fields, soft-delete fields, tenant scope columns, proven-identity stamps and R2 storage keys. Declare them visibly in columns; supply domain fields only. Start at Database Schema for the table forms.

Audit Fields

Quickback maintains four audit columns on every table (including child/junction tables without defineTable):

FieldTypeDescription
createdAttimestampSet on insert
createdBytextActor that performed the insert (ctx.userId)
modifiedAttimestampSet on every insert and update
modifiedBytextActor that performed the latest insert/update (ctx.userId)

Audit fields are a separate concept from soft-delete (deletedAt/deletedBy) — they're always present, regardless of delete mode. See Soft-Delete Fields below.

Opt out of audit injection entirely with compiler.features.auditFields: false in quickback.config.ts. (You almost never want to.)

Writing through a raw handle — auditStamp(ctx)

The scoped db injected into actions stamps these four columns for you. A handle built directly from createDb() does not — that's the documented escape hatch for system writes, credential doors, and broad reads the scoped wrapper over-narrows.

Those writes still land in audit-managed tables. A Drizzle insert that omits createdAt / modifiedAt gets the insert time (Postgres DEFAULT now(); on SQLite the column's $defaultFn), but on SQLite nothing fills createdBy / modifiedBy — they stay NULL. (On Postgres the database's audit triggers fill them — see How auto-injection works.) On SQLite the managed timestamps also carry a DDL default of the unix epoch (so ALTER TABLE ADD COLUMN works on populated tables), so raw SQL that omits them does not fail on NOT NULL — it silently persists 1970-01-01T00:00:00.000Z, which reads as a real timestamp everywhere downstream.

Spread the stamp instead of hand-writing four columns at each call site:

import { auditStamp } from '../lib/audit-wrapper';

await db.insert(invoices).values({ ...auditStamp(ctx), amount, organizationId });
await db.update(invoices).set({ ...auditStamp(ctx, 'update'), status });

'insert' (the default) returns all four columns; 'update' returns only modifiedAt / modifiedBy, so an update never rewrites createdAt. Actor resolution is identical to the wrapper's, including the delegated-principal lane, and it fails closed the same way — a raw handle is not a licence to write an anonymous audit row.

For genuinely context-free writes — cron, seed scripts, backfills that must preserve historical timestamps — pass your own values. auditStamp needs a real caller and throws without one, by design.

Declaring them visibly — ...q.audit() / ...q.softDelete()

Historically these columns were invisible: injected into the generated schema only, so the table object in your editor didn't have them. They are now declared visibly (required by default — see below) so $infer, your editor, and the emitted schema all agree:

export default feature("candidates", {
  columns: {
    id:             q.id(),
    name:           q.text({ maxLength: 200 }).required(),
    organizationId: q.scope("organization"),
    ...q.audit(),        // createdAt / modifiedAt / createdBy / modifiedBy
    ...q.softDelete(),   // deletedAt / deletedBy — matches crud.delete.mode
  },
})

The spreads are declarative, not definitional: the compiler expands them to the exact canonical column lines it would otherwise inject, so emitted output is identical either way. Raw Drizzle tables declare the canonical column lines literally instead (under a ── quickback:audit (compiler-managed — edits are validated, not merged) ── marker). Run quickback migrate visible-columns to add either form across an existing project in one shot.

Two rules keep this safe:

  • The compiler validates managed columns against canon — on by default. A createdAt missing its default chain, a .notNull() createdBy, a defaulted deletedAt, a renamed SQL name — each breaks a security pillar (audit integrity, ownership predicates, the Firewall's soft-delete ridge, name-keyed guards/RLS), so divergence is a compile error, and every feature table must declare the audit quartet visibly (soft-delete pair iff the resource soft-deletes). Never silently normalized. compiler.features.visibleAuditColumns: false opts out — invisible injection returns and divergence downgrades to a warning.
  • Unknown spreads are a compile error. The columns object is compiled from source, so ...someSharedCols can't be resolved — it fails the build rather than silently dropping columns.

The scoped db an action receives types every managed key as ?: never on .insert().values(), so supplying one is a compile error, not a silently discarded value (below).

How auto-injection works (two layers)

"Auto-injection" covers two distinct steps. Conflating them is the most common source of confusion:

  1. Schema injection (compile-time) — the compiler adds the four columns to any Drizzle table that doesn't already declare them. Idempotent: a column you authored yourself is left alone. With visibleAuditColumns on (the default) this only ever fires for internal child tables — a route-backed table that hasn't declared them fails the compile instead.
  2. Runtime injection (per-write) — a Proxy around the request-context db (createAuditDb, generated to src/lib/audit-wrapper.ts) intercepts .insert(...).values(...) and .update(...).set(...) and writes the audit columns from ctx.userId and the actual write moment.

The runtime layer hard-stamps every audit field on every write, so the audit log can never be forged by a crafted request body or by a client echoing a row back into a PATCH.

On Postgres the RLS migration adds a database-side backstop: BEFORE INSERT / BEFORE UPDATE triggers on every feature table (public.set_audit_fields_on_insert() / _on_update()). They set created_at / modified_at to the database's now() truncated to the millisecond (date_trunc('milliseconds', now())) and apply the same actor rule as the wrapper — the actor column always names whoever did the write:

  • a verified caller (auth.user_id()) always wins, so no request can write someone else's id;
  • with no verified caller — a scope: principal, a delegated principal, the service lane, a system: actor — the actor the Worker already stamped is kept;
  • only a write that carries no actor at all (raw SQL) gets system:<database role>.

created_at / created_by never change on update.

Postgres stores managed timestamps at millisecond precision. createdAt / modifiedAt / deletedAt are timestamp(3) with time zone, the same precision as D1's ISO text, a JS Date, and the wire format (.sssZ). A keyset cursor carries its boundary value through a Date, so a microsecond column would never compare equal to the cursor: ascending pages repeated rows and descending pages skipped rows that shared a millisecond (#602). The triggers truncate rather than round, so a stamp never lands after the transaction's now(). The column DEFAULT now() (reached only by raw SQL on a table without the triggers) is rounded to the millisecond by Postgres. Timestamp columns you declare yourself keep the precision you give them.

Recompiling a Postgres project last compiled by 0.69.0 or earlier adds a migration that changes each managed column's type:

ALTER TABLE "app"."notes" ALTER COLUMN "created_at" SET DATA TYPE timestamp (3) with time zone USING "created_at"::timestamp (3) with time zone;

Existing values are rounded to the nearest millisecond (…08.624500 becomes …08.625). The type change rewrites the table under an ACCESS EXCLUSIVE lock, so apply it in a quiet window on large tables. The same compile re-emits the trigger functions (CREATE OR REPLACE) in a new RLS migration.

Because the value would be discarded anyway, the generated db handle refuses it at the type level: on the scoped db, .insert().values() types createdAt / modifiedAt / createdBy / modifiedBy / deletedAt / deletedBy as ?: never, and .update().set() types the audit quartet plus deletedBy the same way. Supplying one is a compile error — not a silent discard.

// In a custom action — this does not compile
await db.insert(records).values({
  status: 'active',
  createdBy: 'admin',           // ✗ Type 'string' is not assignable to type 'never'
  modifiedAt: '1999-01-01',     // ✗ same
});

Drop the keys and let the wrapper write them from ctx.userId and the actual write moment.

One deliberate exception: .set({ deletedAt: ... }) is allowed on update — that assignment is the soft-delete signal, and the stored value is normalized to the write moment and the verified caller. The raw unsafeDb handle an unsafe: action receives is unwrapped Drizzle and carries none of these type fences.

What the caller is responsible for: the domain fields. (id auto-fills via the column's $defaultFn — q.id() and injected ids both carry one, and the typed db treats id as optional on insert for every id strategy except serial and false.)

What the caller does not need to set: id, the scope column, or any of the audit fields, ever.

Actors: who shows up in createdBy / modifiedBy

The wrapper writes whatever string is in ctx.userId. For user-driven requests this is the authenticated user's id — set by auth middleware before the handler runs. For non-user-driven entry points (inbound webhooks, cron, queue workers), you mint a synthetic actor id at the boundary so the audit log preserves provenance.

Inherit before you mint. If a real user's request triggers cascades, hooks, or enqueues background jobs, every downstream write should carry that user's id — not a synthetic one. The cascade is part of the user's action. Only mint when there is genuinely no upstream user.

When you do mint, use a single namespace and a stable convention:

BoundaryActor id
Inbound webhooksystem:webhook-<provider> (e.g. system:webhook-stripe)
Scheduled / cronsystem:cron-<job> (e.g. system:cron-cleanup-stale)
Queue workersystem:queue-<queue> (e.g. system:queue-embeddings-retry)
Quickback platform-internal write with no user upstreamsystem:quickback
Out-of-band operator scriptsystem:script-<name>

The system: prefix marks "not a real user" — readable by anyone joining the audit columns to users, and cheap to filter on. Don't use tenant:admin or quickback:admin: those imply a human role nobody is actually playing. The tenant context is already on the row (in organizationId); the actor id is purely about source.

Failure mode: missing ctx.userId

If a write reaches the wrapper without a ctx.userId, the wrapper throws:

audit-wrapper: insert reached without ctx.userId.
If this is an intentional system-side write, use the unwrapped db directly.

Two paths to fix it, depending on intent:

  • Mint a synthetic actor (preferred — preserves attribution) — populate ctx.userId with one of the conventions above before calling into your handler.
  • Bypass the wrapper entirely — use the unwrapped createDb instead of the request-context db. Use this only for migrations, schema repair, or backfill scripts where you genuinely don't want any audit attribution. createdAt/modifiedAt still get the insert time from their column default (a raw SQL insert that omits them on SQLite gets the epoch — set them yourself); createdBy/modifiedBy end up NULL.

Disabling Audit Fields

To disable automatic audit fields for your project:

// quickback.config.ts
export default defineConfig({
  // ...
  compiler: {
    features: {
      auditFields: false,  // Disable for entire project
    }
  }
});

This turns off both layers — schema injection and the runtime wrapper.

Soft-Delete Fields

deletedAt and deletedBy are not audit fields. They're a separate, per-table mechanism for soft delete:

FieldTypeDescription
deletedAttimestampSet when the record is soft-deleted
deletedBytextActor that performed the soft delete (ctx.userId)

A resource soft-deletes unless both delete paths — single and batch — resolve to 'hard'. Soft is the default, so most tables carry the pair. When both resolve to 'hard' the table skips them entirely, which also drops the isNull(deletedAt) predicate from the firewall WHERE clause.

The batch path inherits the single path's mode. batch picks up delete.mode whenever it doesn't set its own — whether batch is absent, false, or an object with no mode key. So delete: { mode: 'hard' } on its own is already a hard-delete resource; you don't need to repeat the mode on batch.

// soft delete (default) — table gets deletedAt + deletedBy
delete: {}

// hard delete — batch inherits mode: 'hard'
delete: { mode: 'hard' }

// hard delete — the same thing, stated explicitly
delete: { mode: 'hard', batch: { mode: 'hard' } }

// SOFT delete — the one case that flips back: batch names a different mode
delete: { mode: 'hard', batch: { mode: 'soft' } }

Because the columns' presence must agree with the resolved mode, a hard-delete resource that declares ...q.softDelete() (or the deletedAt / deletedBy lines) is a compile error, and a soft-delete resource that omits them is too.

Caller contract

In custom-action handlers, passing deletedAt in .set({}) is the signal that this update is a soft delete. Any value works — the wrapper detects the field and overwrites both deletedAt and deletedBy with now and ctx.userId:

await db.update(records)
  .set({ deletedAt: new Date() })  // signal — value is overwritten
  .where(eq(records.id, id));

You don't set deletedBy yourself; the wrapper pairs it with the deletedAt signal.

Retention and permanent erasure

Soft delete is the recoverable default, not a fixed data-retention policy. Quickback leaves the retention window in application code because legal holds, customer contracts, and record classes rarely share one universal timer.

The platform provides the pieces for an explicit policy:

  • Immediate permanent deletion — configure delete: { mode: 'hard' } (the batch path inherits the mode). Generated hard-delete routes record the deletion in the security audit pipeline before removing the row.
  • Time-based purging — declare a defineSchedule job that hard-deletes rows whose deletedAt is older than your policy cutoff. The scheduler emits the Worker cron trigger and runs the same code on D1 or Neon.
  • Aggregate deletion — use database foreign keys with onDelete: 'cascade' for same-database ownership, and orchestrate cross-database records, R2 objects, and external systems from an explicit offboarding action or queued job. For a whole organization, tenancy.purge derives the table list from the firewall and deletes the rows' storage-key objects with them.
  • Encrypted data — deleting an organization's wrapped DEK makes its envelope-encrypted fields unreadable, provided no backup or export still holds that row (crypto-shredding is a manual, service-role delete). Sealed deployments should include their vault grants, recovery records, and key versions in the same reviewed offboarding workflow.

That makes retention ordinary, version-controlled business logic rather than a global platform timer that might erase the wrong class of record. It also keeps the compliance claim honest: the schedule and erasure workflow implement your policy; enabling soft delete alone does not assert GDPR, HIPAA, or SOC 2 compliance.

Protected system fields

These fields never take their value from client input, even with guards: false — but the mechanism differs by field class:

  • createdAt, createdBy (audit — always present)
  • modifiedAt, modifiedBy (audit — always present)
  • deletedAt, deletedBy (soft-delete — present when delete mode allows soft)

The six audit/soft-delete columns are overwritten by the runtime wrapper — a request body that carries one is server-stamped before the SQL is built.

id (when generateId is not false) is rejected at the edge instead: it is omitted from the .strict() Zod body schema, so a body carrying it is a 400 VALIDATION_ERROR, and the guards createable allow-list backstops that. Nothing overwrites id at the insert — the Zod/guards boundary is the protection. Under allowClientIds: true a strategy-shaped id is accepted on create only.

q.scope() — tenant scope columns

q.scope(kind) is the canonical way to declare a column that holds a tenant-scope value (org / owner / team). It compiles to text(...).notNull() like a regular required text column, plus metadata that the compiler reads to:

  1. Auto-derive the firewall predicate — q.scope('organization') produces [{ field: 'organizationId', equals: 'ctx.activeOrgId' }] so you can omit the explicit firewall: block. (If deletedAt is present — and it is whenever the resource uses soft delete, which is the default — the isNull(deletedAt) predicate is appended automatically.)
  2. Reject the column from client input — scope fields land in GUARDS_CONFIG.systemManaged alongside the audit fields, so POST { organizationId: 'org_other' } returns 400 even if guards aren't otherwise configured.
  3. Auto-populate on create / upsert — the value is taken from the request context, not the request body.
columns: {
  organizationId: q.scope('organization'),  // → ctx.activeOrgId
  ownerId:        q.scope('owner'),         // → ctx.userId
  teamId:         q.scope('team'),          // → ctx.activeTeamId
}

Override the context source for non-default sources:

ownerId: q.scope('owner', { source: 'ctx.userId' }),

q.scope() is preferred over q.text().required() for tenant columns. Auto-detection on column names (organizationId, userId, etc.) still works as a fallback for projects bringing forward Drizzle schemas, but the explicit q.scope() form locks in the semantics in the source.

q.stamp() — proven-principal identity columns

q.stamp({ fromScope, claim }) server-stamps a column from a proven scope claim — the caller's own identity within a relationship they were cryptographically proven to hold (e.g. an event attendee's own guest id). It is the identity sibling of q.scope:

q.scope('<kind>')q.stamp({ fromScope, claim })
Purposetenant isolation columnproven-principal identity column
Valuectx.scope.<kind>.id / activeOrgId / userIdctx.scope.<kind>.<claim> (id | subjectId | a scalar sub-key)
Firewall arm?yes — it is the tenant WHEREnever — identity is not a tenant scope
Guarantee"stamp and verify" (firewall re-checks on read/patch/delete)"stamp and prove" (un-spoofable by token provenance)
columns: {
  eventId:  q.scope('event'),                                    // tenant firewall column
  authorId: q.stamp({ fromScope: 'event', claim: 'subjectId' }), // proven identity — un-spoofable
}

Runtime precedence — the org/admin hierarchy takes priority. The stamp fires only when this request proved the claim: the namespace relationship lane that admitted the caller (a session or an instance-bound OAuth token) records the claims it proved, and the column is force-stamped from the proven claim with any client-sent value ignored. A caller admitted via the org role hierarchy (member / admin / owner) writes the column through the org path — a normal client-settable value, bounded by the org firewall. So a table whose create admits both org roles and a scope role needs no split: each identity writes the column the way its principal allows. A relationship-proven caller can never set a stamped column to anything but its proven claim.

Fail-closed. If a proven caller reaches the write without the required claim (ctx.scope.<kind>.<claim> absent) the write is refused with 403 before the insert — never a NULL identity row — for nullable stamp columns too. A q.stamp column may not also be a firewall arm, live on an exception: true table, or be sourced from a set-valued sub-key; each is a compile error.

optional: true makes the DDL column nullable (an org caller may then omit it); it does not relax that 403.

Set-on-insert, immutable thereafter. A q.stamp column is a create-time identity — it is never re-derived on update. On every update-shaped write (PATCH, PUT, batch update, upsert, and a changeset root/child patch) the column is systemManaged: a client value for it is rejected (400), regardless of your guards.updatable list. Re-keying a proven identity is not an operation. (The force-stamp and the org-writable-on-create allowance apply to the create path only.)

A non-nullable stamp on the org path must be supplied by the caller. The force-stamp fires for relationship-proven callers; an org-admitted caller writes the column as normal client input. So a NOT NULL q.stamp column (the default) that an org caller omits lands on the database NOT NULL constraint (a deterministic field-named 400), not a NULL row. Add the column to guards.createable so org callers can supply it, or mark it optional: true if an org-created row may legitimately have no identity.

The relationship lane needs a scope-reachable write. The force-stamp only runs once the relationship-proven caller actually reaches the insert. A table with a hard organization firewall arm (an organizationId sourced from ctx.activeOrgId) emits an ORG_REQUIRED gate that denies a relationship caller (who has no active org) before the stamp — so on such tables the stamp serves the org-admitted caller, and the relationship caller writes these rows as a changeset child that inherits organizationId from a firewall-verified parent. For a plain create/batch by a relationship caller, firewall the table on the scope arm only (e.g. firewall: { any: [{ field: 'eventId', equals: 'ctx.scope.event' }] }, no org column) so no ORG_REQUIRED gate is emitted.

Idempotency (at-least-once). The stamp rides inside the write, so it inherits the endpoint's replay semantics: a keyed replay (a repeated Idempotency-Key whose handler is skipped) neither re-writes nor re-stamps; a keyless retry re-writes and therefore re-stamps from the caller's then-current proven claim.

q.storageKey() — R2 object keys the compiler owns

q.storageKey(...) declares a column that holds an R2 object key. The compiler, not the client, writes the key:

r2Key: q.storageKey({
  bucket: "MEDIA",                                   // a bindings.r2Buckets binding
  key: "media/{organizationId}/{eventId}/{uuid}.{ext}",
  mime: ["image/*", "application/pdf"],
  maxBytes: 10_000_000,
}),
  • Never client-writable. No generated write body (create, update, batch, PUT, changeset) carries the column. Listing it in guards.createable, updatable, immutable or protected is a compile error (STORAGE_KEY_GUARDED).
  • Written only by db.allocateUpload(table, { ...rowValues, ext, mime, size }) inside an action. It renders the key from the template, with {column} values from the row, a fresh {uuid}, and {ext} from the call. It then returns { row, putUrl, headers }: a PUT signed for exactly the declared mime and at most maxBytes.
  • Prefix-checked. The row's prefix is the template up to {uuid} with the row's own values (media/org_abc/evt_1/). Reads (db.signDownload), deletes, and tenant purge refuse a stored key outside it. Each firewall tenant column (organizationId, ownerId, a scope column) must be a placeholder before {uuid}. Each placeholder fills a whole path segment.
  • Deleted with the row. A hard delete through the generated routes or the action db deletes the object too.
  • Tenant tables (tenancy.isolation: 'durable-object') need tenancy.bridges.files. The object reserves keys and records deletes. The edge signs, verifies and deletes. A tenant upload stays pending until db.finalizeUpload (or its grant's expiry) verifies it. See Tenant databases → Managed files.

The column takes .required(), .optional(), .unique() and .index(). Other modifiers fail the compile. The template rules, the error codes, and the full upload and download flow are in Using R2 → Signed upload.

On this page