Quickback Docs
Database Schema

Constraints and Indexes

CHECK and unique constraints, unique constraints under soft delete, and the default index set the compiler generates.

Declare CHECK and unique constraints on a table, keep uniqueness correct under soft delete, and control the indexes the compiler adds by default. Start at Database Schema for the table forms.

Constraints — CHECK and unique

Declare CHECK constraints on a column or on the feature() config, and unique constraints as unique entries. They compile to Drizzle's check(), uniqueIndex() and unique(), so drizzle-kit writes the DDL into the migration on both dialects.

// quickback/features/line_items/line_items.ts
import { feature, q } from '@quickback/compiler';

export default feature('line_items', {
  columns: {
    id:             q.id(),
    sku:            q.text().required(),
    quantity:       q.int().required().check('> 0'),
    unitPriceCents: q.int().required().check('>= 0'),
    productId:      q.text().optional(),
    serviceId:      q.text().optional(),
    organizationId: q.scope('organization'),
    ...q.audit(),
    ...q.softDelete(),
  },
  check: [
    // exactly one of productId / serviceId
    { name: 'line_items_one_target', sql: '(product_id IS NULL) <> (service_id IS NULL)' },
  ],
  unique: [
    { columns: ['organizationId', 'sku'], whereNotDeleted: true },
  ],
  read:   { access: { roles: ['member'] } },
  create: { access: { roles: ['member'] } },
  update: { access: { roles: ['member'] } },
  delete: { access: { roles: ['admin'] } },
});
DeclarationDDL
quantity: q.int().check('> 0')CONSTRAINT "line_items_quantity_check" CHECK ("quantity" > 0)
check: [{ name, sql }]CONSTRAINT "<name>" CHECK (<sql>)
unique: [{ columns }]CREATE UNIQUE INDEX …
unique: [{ columns, where: '…' }]CREATE UNIQUE INDEX … WHERE … (a partial unique index)
unique: [{ columns, where: { deletedAt: null, status: 'active' } }]CREATE UNIQUE INDEX … WHERE "deleted_at" IS NULL AND "status" = 'active'
unique: [{ columns, whereNotDeleted: true }]CREATE UNIQUE INDEX … WHERE "deleted_at" IS NULL
unique: [{ columns, nullsNotDistinct: true }]CONSTRAINT … UNIQUE NULLS NOT DISTINCT (…). Postgres 15+ only.

How the SQL is written. Column-level .check(expr) is appended to the quoted physical column name, as "<column>" <expr>. Write only what follows the column: '> 0', "IN ('draft', 'open')", 'BETWEEN 1 AND 5'. The table-level sql and a string unique where are complete expressions over the physical (snake_case) column names: product_id, not productId.

The object form of where takes the JS column names and renders the physical ones for you, AND-joined. Each value is a literal: null (IS NULL), { notNull: true } (IS NOT NULL), a string, a finite number, or a boolean (= TRUE / = FALSE, valid on Postgres and on the SQLite D1 ships). A key that is not a column of the table, or any other value, is a compile error.

Nothing is translated per dialect. The SQL must be valid for your database. num_nonnulls(a, b, c) = 1 works on Postgres only. On D1, write (a IS NOT NULL) + (b IS NOT NULL) + (c IS NOT NULL) = 1. An invalid expression fails when the migration is applied, not at compile time.

Names. A column check is named <table>_<column>_check. A table-level check needs an explicit name that matches /^[A-Za-z_][A-Za-z0-9_]*$/. The name can be at most 63 characters, because Postgres truncates longer identifiers. It must also differ from every other check, unique and index name on the table. A column takes one .check(): combine conditions with AND, or use a table-level check.

Compile errors instead of silent drops. The compiler reads these options from source, and it fails the compile on any of the following:

  • a value that isn't a literal
  • an unknown key
  • where together with whereNotDeleted
  • an object where naming an unknown column, or a non-literal value
  • nullsNotDistinct on a partial unique
  • whereNotDeleted on a table without ...q.softDelete()
  • nullsNotDistinct in a SQLite/D1 project, since SQLite always treats NULLs as distinct

Enforced by the database. CHECK is not part of the request validator. A violating write reaches the database and comes back as 400 DB_CHECK_VIOLATION naming the constraint. A unique collision comes back as 409 DB_UNIQUE_VIOLATION. See Errors. Mirror a check at the edge (e.g. maxLength) when you want a field-level validation message instead.

The Postgres-only options, as a fragment:

// Postgres (Neon / PlanetScale Postgres) only
check:  [{ name: 'contacts_one_channel', sql: 'num_nonnulls(email, phone, address) = 1' }],
unique: [{ columns: ['organizationId', 'externalRef'], nullsNotDistinct: true }],

Unique constraints and soft delete

A soft-deleted row is still a row. A plain unique on (organizationId, sku) keeps counting it, so after DELETE /line_items/:id the same SKU can't be created again. The insert returns 409 DB_UNIQUE_VIOLATION against a row the caller can no longer see. Column-level .unique() has the same problem.

On a soft-delete table, make the unique partial. whereNotDeleted: true (or the object form where: { deletedAt: null }) adds WHERE "deleted_at" IS NULL, using the table's actual soft-delete column under your naming convention. Uniqueness then holds among live rows only, and a deleted value can be reused. Restoring a soft-deleted row whose value a live row has since taken fails with a unique violation. That is the correct outcome, because the two rows would otherwise collide.

ON CONFLICT. Generated CRUD, PUT and batch upsert don't use ON CONFLICT: they look the row up by id and then insert or update, so partial uniques need nothing from them. An action that upserts against a partial unique with Drizzle's onConflictDoUpdate / onConflictDoNothing must repeat the predicate as targetWhere. Postgres and SQLite only match a partial index to a conflict target that carries its WHERE:

await db.insert(lineItems).values(row).onConflictDoUpdate({
  target: [lineItems.organizationId, lineItems.sku],
  targetWhere: sql`"deleted_at" IS NULL`,
  set: { quantity: row.quantity },
});

The default index set

Drizzle owns every index in a Quickback project. The compiler writes a default set into your schema source before drizzle-kit reads it, so the indexes are generated, diffed and dropped by the same journal as your tables — there is no second emitter putting indexes in the security migration.

The pass runs after audit-field injection (so deletedAt and createdAt are present) and is idempotent.

TriggerIndexWhy
Tenant column (organizationId / organisationId / userId) + deletedAtComposite (<isolation_col>, deletedAt)Every list query filters by isolation AND deletedAt IS NULL — a composite index lets the planner prune both predicates in one btree walk.
Any FK column (.references(() => other.id))Single-column (<fk_col>)SQLite/D1 don't auto-index FK columns, and the generated FK existence checks read by id on the parent.
A filtered column — anything named *status* or *type*, the boolean flags (isActive, isDefault, …) and the date columns (createdAt, startDate, endDate, expiresAt, …)Single-column (<col>)These are what list endpoints filter and order on.
Any column in a view's read.query.sortable allowlist (or defaultSort)Single-column (<col>)Sort scans go through an index instead of a full-table scan.

Entries are named <table>_<col>_idx (or <table>_<col1>_<col2>_idx for a composite) and emitted into the table's Drizzle extras callback. The index import is added to your schema's drizzle-orm/<dialect>-core import line if it isn't already there.

Coverage — what suppresses a default index

A default index is skipped when a non-partial index already has its columns as a leading prefix. So the tenant composite (organizationId, deletedAt) suppresses a bare (organizationId) index, and an index you author yourself suppresses the default on the same columns:

  • Leading prefix wins. (organizationId, deletedAt, status) covers (organizationId) and (organizationId, deletedAt), but not (status) — status is not a leading column.
  • Unique counts. A uniqueIndex on the same leading columns serves the same lookups, so it suppresses the non-unique default.
  • Partial covers nothing. An index with .where(...) may exclude the rows the default index exists for, so it never suppresses one.
  • Order modifiers are ignored. .on(t.status.desc()) still covers (status).

...q.indexes(t) — placing the defaults yourself

In a Drizzle interop table you can declare exactly where the default set lands, the same way ...q.audit() declares the audit columns:

import { pgTable, uniqueIndex } from "drizzle-orm/pg-core";
import { q } from "@quickback/compiler";

export const invoices = pgTable("invoices", {
  // …columns
}, (t) => ({
  ...q.indexes(t),
  invoices_number_unique: uniqueIndex("invoices_number_unique").on(t.number),
}));

The spread is expanded in place at compile time into literal index(...).on(...) entries and disappears from the emitted schema. Without it the same entries are appended to the end of the callback and a compile warning points you here — the emitted schema is identical either way.

Tables authored with the q DSL (feature() / q.table()) don't take the placeholder: the compiler writes their index callback, and q.<col>().index() and q.table(…, { indexes }) are the authoring controls there.

On this page