@quickback-dev/cli 0.66.18 → 0.66.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import pc from "picocolors";
12
12
  // Version injected at build time by scripts/inject-version.ts
13
- const CLI_VERSION = "0.66.18";
13
+ const CLI_VERSION = "0.66.19";
14
14
  function getPackageVersion() {
15
15
  return CLI_VERSION;
16
16
  }
@@ -51,20 +51,40 @@ export declare const defineResource: <TSchema>(schema: TSchema, config: Record<s
51
51
  export declare const defineActions: <TSchema>(schema: TSchema, config: Record<string, unknown>) => Record<string, unknown> & {
52
52
  __schema: TSchema;
53
53
  };
54
+ /**
55
+ * Stub for the `q` schema DSL. Returns chainable column builders and a `table`
56
+ * function that collects columns into a placeholder object. The CLI never
57
+ * evaluates feature source files during `compile` — it only reads them — so
58
+ * this stub exists solely for quickback.config.ts evaluation, where users
59
+ * may import `q` from `@quickback/compiler` alongside `defineTable`.
60
+ */
61
+ declare function makeQColumn(): Record<string, unknown>;
54
62
  export declare const q: {
55
63
  table: <T extends Record<string, unknown>>(name: string, columns: T, _opts?: unknown) => {
56
64
  __quickbackTable: boolean;
57
65
  name: string;
58
66
  columns: T;
59
67
  };
60
- text: (_name?: string) => Record<string, unknown>;
61
- int: (_name?: string) => Record<string, unknown>;
62
- bool: (_name?: string) => Record<string, unknown>;
63
- uuid: (_name?: string) => Record<string, unknown>;
64
- timestamp: (_name?: string) => Record<string, unknown>;
65
- json: (_zod?: unknown, _name?: string) => Record<string, unknown>;
66
- enum: (_values: readonly string[], _name?: string) => Record<string, unknown>;
67
- id: () => Record<string, unknown>;
68
+ feature: (definition: unknown) => unknown;
69
+ text: typeof makeQColumn;
70
+ url: typeof makeQColumn;
71
+ int: typeof makeQColumn;
72
+ bigint: typeof makeQColumn;
73
+ smallint: typeof makeQColumn;
74
+ decimal: typeof makeQColumn;
75
+ date: typeof makeQColumn;
76
+ bool: typeof makeQColumn;
77
+ uuid: typeof makeQColumn;
78
+ timestamp: typeof makeQColumn;
79
+ json: typeof makeQColumn;
80
+ id: typeof makeQColumn;
81
+ enum: typeof makeQColumn;
82
+ scope: typeof makeQColumn;
83
+ stamp: typeof makeQColumn;
84
+ vaultRef: typeof makeQColumn;
85
+ audit: () => {};
86
+ softDelete: () => {};
87
+ indexes: () => {};
68
88
  };
69
89
  /**
70
90
  * Stub for defineAction - returns a curried function that returns the config
@@ -92,4 +112,5 @@ export declare class TransitionLostError extends Error {
92
112
  readonly attemptedTo: string;
93
113
  constructor(field: string, expectedFrom: string, attemptedTo: string);
94
114
  }
115
+ export {};
95
116
  //# sourceMappingURL=compiler-stubs.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"compiler-stubs.d.ts","sourceRoot":"","sources":["../../src/lib/compiler-stubs.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AA4BH,eAAO,MAAM,YAAY,kEAAoC,CAAC;AAC9D,+EAA+E;AAC/E,eAAO,MAAM,UAAU,kEAAoC,CAAC;AAC5D,mCAAmC;AACnC,eAAO,MAAM,WAAW,kEAAoC,CAAC;AAC7D,sCAAsC;AACtC,eAAO,MAAM,cAAc,kEAAoC,CAAC;AAChE,kCAAkC;AAClC,eAAO,MAAM,WAAW,kEAAoC,CAAC;AAC7D,qCAAqC;AACrC,eAAO,MAAM,cAAc,kEAAoC,CAAC;AAChE,uCAAuC;AACvC,eAAO,MAAM,eAAe,kEAAoC,CAAC;AACjE,4CAA4C;AAC5C,eAAO,MAAM,UAAU,kEAAoC,CAAC;AAE5D,eAAO,MAAM,aAAa,SAzBlB,MAAM,WACH,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAC/B;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAuBb,CAAC;AACtC,eAAO,MAAM,cAAc,SA1BnB,MAAM,WACH,MAAM,CAAC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I,EAAE,MAAM,EACZ,UAAU,GAAE,MAAY,EACxB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;CAQpC;AAED;;;GAGG;AACH,qBAAa,mBAAoB,SAAQ,KAAK;IAC5C,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;gBAEjB,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM;CAOrE"}
@@ -55,30 +55,43 @@ export const defineActions = withSchema;
55
55
  * may import `q` from `@quickback/compiler` alongside `defineTable`.
56
56
  */
57
57
  function makeQColumn() {
58
- const col = {
59
- required: () => col,
60
- optional: () => col,
61
- default: (_v) => col,
62
- unique: () => col,
63
- index: () => col,
64
- references: (_ref, _opts) => col,
65
- };
58
+ const col = {};
59
+ for (const modifier of [
60
+ 'required', 'optional', 'default', 'defaultNow', 'unique', 'check', 'index', 'array',
61
+ 'references', 'filterable', 'searchable', 'encrypted', 'sealed',
62
+ ]) {
63
+ col[modifier] = () => col;
64
+ }
66
65
  return col;
67
66
  }
67
+ // Keys must match the compiler's `q` exactly — `compiler-stub-q-drift.test.ts`
68
+ // in apps/compiler fails when a builder is added there and not here.
68
69
  export const q = {
69
70
  table: (name, columns, _opts) => ({
70
71
  __quickbackTable: true,
71
72
  name,
72
73
  columns,
73
74
  }),
74
- text: (_name) => makeQColumn(),
75
- int: (_name) => makeQColumn(),
76
- bool: (_name) => makeQColumn(),
77
- uuid: (_name) => makeQColumn(),
78
- timestamp: (_name) => makeQColumn(),
79
- json: (_zod, _name) => makeQColumn(),
80
- enum: (_values, _name) => makeQColumn(),
81
- id: () => makeQColumn(),
75
+ feature: (identity),
76
+ text: makeQColumn,
77
+ url: makeQColumn,
78
+ int: makeQColumn,
79
+ bigint: makeQColumn,
80
+ smallint: makeQColumn,
81
+ decimal: makeQColumn,
82
+ date: makeQColumn,
83
+ bool: makeQColumn,
84
+ uuid: makeQColumn,
85
+ timestamp: makeQColumn,
86
+ json: makeQColumn,
87
+ id: makeQColumn,
88
+ enum: makeQColumn,
89
+ scope: makeQColumn,
90
+ stamp: makeQColumn,
91
+ vaultRef: makeQColumn,
92
+ audit: () => ({}),
93
+ softDelete: () => ({}),
94
+ indexes: () => ({}),
82
95
  };
83
96
  /**
84
97
  * Stub for defineAction - returns a curried function that returns the config
@@ -1 +1 @@
1
- {"version":3,"file":"compiler-stubs.js","sourceRoot":"","sources":["../../src/lib/compiler-stubs.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH;;;;;;;;;;;;;GAaG;AACH,MAAM,QAAQ,GAAG,CAAI,UAAa,EAAK,EAAE,CAAC,UAAU,CAAC;AAErD,MAAM,QAAQ,GAAG,CACf,IAAY,EACZ,MAAgC,EACmB,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,IAAI,EAAE,EAAE,CAAC,CAAC;AAEzF,MAAM,UAAU,GAAG,CACjB,MAAe,EACf,MAA+B,EACkB,EAAE,CAAC,CAAC,EAAE,GAAG,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;AAExF,MAAM,CAAC,MAAM,YAAY,GAAG,CAAA,QAAiC,CAAA,CAAC;AAC9D,+EAA+E;AAC/E,MAAM,CAAC,MAAM,UAAU,GAAG,CAAA,QAAiC,CAAA,CAAC;AAC5D,mCAAmC;AACnC,MAAM,CAAC,MAAM,WAAW,GAAG,CAAA,QAAiC,CAAA,CAAC;AAC7D,sCAAsC;AACtC,MAAM,CAAC,MAAM,cAAc,GAAG,CAAA,QAAiC,CAAA,CAAC;AAChE,kCAAkC;AAClC,MAAM,CAAC,MAAM,WAAW,GAAG,CAAA,QAAiC,CAAA,CAAC;AAC7D,qCAAqC;AACrC,MAAM,CAAC,MAAM,cAAc,GAAG,CAAA,QAAiC,CAAA,CAAC;AAChE,uCA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multi-sort format is detected (comma or `-` prefix), the `order` parame
133
133
 
134
134
  A client-supplied `?sort=` naming an unknown column — or one outside a view's
135
135
  `query.sortable` — returns `400`, for the same reason unknown filters do: rows
136
- would come back in some other order that reads as the requested one. A view's
136
+ would come back in some other order that reads as the requested one. Array
137
+ columns, and `q.decimal()` columns on D1 (stored as `TEXT`, so they would sort
138
+ as strings), are never sortable — see
139
+ [Decimals, dates, 64-bit integers, and arrays](/define/schema#decimals-dates-64-bit-integers-and-arrays). A view's
137
140
  own `defaultSort` fallback is config, not caller input, and is never rejected.
138
141
 
139
142
  ## Field Selection
@@ -5,10 +5,10 @@
5
5
  compiled to Drizzle. It turns
6
6
 
7
7
  ```
8
- feature(name, { columns, indexes, unique, ...rest })
8
+ feature(name, { columns, indexes, unique, check, ...rest })
9
9
  ```
10
10
 
11
- into `q.table(name, columns, { indexes, unique })` plus `defineTable(name, rest)`,
11
+ into `q.table(name, columns, { indexes, unique, check })` plus `defineTable(name, rest)`,
12
12
  passing every other key through verbatim. Both forms produce byte-identical output.
13
13
 
14
14
  `defineTable()` is **not deprecated**. It is the layer underneath, and it is what you
@@ -529,7 +529,7 @@ Every generated write handler — `POST /`, `POST /batch`, `PATCH /:id`, `PATCH
529
529
  }
530
530
  ```
531
531
 
532
- This closes a cross-tenant injection vector: even if an attacker knows a foreign tenant's row ID, they cannot attach a child record to it — at creation or by repointing an existing row later — and they cannot trigger a cross-tenant cascade delete. The check uses the target table's `buildXFirewallConditions(ctx)` helper, so it honors whatever firewall predicates the target declared (organization, owner, team, custom). FKs to tables with `{ exception: true }` get a plain existence check (still verifies the row exists, doesn't tenant-scope it).
532
+ This closes a cross-tenant injection vector: even if an attacker knows a foreign tenant's row ID, they cannot attach a child record to it — at creation or by repointing an existing row later — and they cannot trigger a cross-tenant cascade delete. The check uses the target table's `buildXFirewallConditions(ctx)` helper, so it honors whatever firewall predicates the target declared (organization, owner, team, custom). FKs to tables with `{ exception: true }` get a plain existence check (still verifies the row exists, doesn't tenant-scope it). A [self-reference](/define/schema#self-references) (`parentId: q.text().references('self')`) is checked against the table's own firewall the same way.
533
533
 
534
534
  The check runs after guards but before the write, so it appears as `layer: "validation"` in error responses. Status code is `400`, not `404` — returning `404` would leak existence of out-of-scope rows.
535
535
 
@@ -82,7 +82,7 @@ A few mechanics to know:
82
82
  - **Column names** default to snake_case of the JS key — `organizationId` ↔ `organization_id`, `salaryMin` ↔ `salary_min`. Pass a positional argument to override: `q.text('custom_name')`.
83
83
  - **`q.id()`** emits `text('id').primaryKey()` with a provider-driven app-layer default.
84
84
  - **`.required()` / `.optional()`** control NOT NULL. Chain before or after `.default(x)`.
85
- - **References:** `q.text().required().references(() => other.id, { onDelete: 'cascade' })`. An FK declares a *pointer*, not ownership — when the child rows are a **composition** of one root (junctions, phones/emails, line items), also declare [`owns`](/define/changesets) on the root to generate the atomic aggregate write path. `other` must be a **feature table in the same database**.
85
+ - **References:** `q.text().required().references(() => other.id, { onDelete: 'cascade' })`, or `.references('self')` for a column pointing at another row of the same table (see [Self-references](#self-references)). An FK declares a *pointer*, not ownership — when the child rows are a **composition** of one root (junctions, phones/emails, line items), also declare [`owns`](/define/changesets) on the root to generate the atomic aggregate write path. `other` must be a **feature table in the same database**.
86
86
 
87
87
  > **Never FK Better Auth tables**
88
88
  >
@@ -103,7 +103,7 @@ A few mechanics to know:
103
103
  > `authz.relationships` `subject: { column: 'userId', equals: 'ctx.userId' }` does not need, and must not create, a SQL FK. See [Relationships](/define/relationships). To query Better Auth tables, use `c.get("authDb")` from an action — see [Scoped DB](/define/actions/scoped-db#reaching-better-auth-tables-authdb).
104
104
 
105
105
 
106
- - **Indexes:** column-level `.index()` or table-level `indexes` / `unique` as a third arg to `q.table(name, cols, { indexes, unique })`. With `feature()`, pass `indexes` and `unique` as top-level keys alongside `columns` — the sugar forwards them into the same `q.table` opts.
106
+ - **Indexes and constraints:** column-level `.index()` / `.unique()` / `.check(expr)`, or table-level `indexes` / `unique` / `check` as a third arg to `q.table(name, cols, { indexes, unique, check })`. With `feature()`, pass `indexes`, `unique` and `check` as top-level keys alongside `columns` — the sugar forwards them into the same `q.table` opts. See [Constraints](#constraints--check-and-unique).
107
107
 
108
108
  ### Column Types
109
109
 
@@ -112,14 +112,21 @@ A few mechanics to know:
112
112
  | `q.text()` | `text(...)` | `z.string()` |
113
113
  | `q.url()` | `text(...)` | `z.string().url()` |
114
114
  | `q.int()` | `integer(...)` | `z.number().int()` |
115
+ | `q.bigint()` | `bigint(..., { mode: 'number' })` | `z.number().int()` within ±(2^53 − 1) |
116
+ | `q.smallint()` | `smallint(...)` | `z.number().int()` within −32768..32767 |
117
+ | `q.decimal({ precision, scale })` | `numeric(..., { precision, scale })` | decimal string within precision/scale |
115
118
  | `q.bool()` | `boolean(...)` | `z.boolean()` |
116
119
  | `q.uuid()` | `uuid(...)` | `z.string().uuid()` |
117
120
  | `q.timestamp()` | `timestamp(...)` (converted to SQLite `text` on sqlite targets) | `z.coerce.date()` |
121
+ | `q.date()` | `date(...)` | `z.iso.date()` (`YYYY-MM-DD`) |
118
122
  | `q.json()` | `jsonb(...)` | `z.unknown()` (or the type you pass in) |
119
123
  | `q.enum(['a','b'])` | `text(..., { enum: [...] })` | `z.enum([...])` |
120
124
  | `q.id()` | `text('id').primaryKey()` | `z.string()` |
121
125
  | `q.scope(kind)` | `text(...).notNull()` | `z.string()` |
122
126
  | `q.stamp({ fromScope, claim })` | `text(...).notNull()` (nullable with `optional: true`) | `z.string().optional()` |
127
+ | `.array()` on `q.text()` / `q.enum()` / `q.int()` / `q.uuid()` | `text(...).array()` etc. | `z.array(<element>)` |
128
+
129
+ The Drizzle column is the Postgres form; on SQLite/D1 the compiler lowers it. The next section has the per-dialect storage for the exact-numeric, date, and array types.
123
130
 
124
131
  In request bodies a column that is not `.required()` is `.optional().nullable()` — omit it to leave it untouched, send `null` to clear it. `""` is not a blank: it is validated like any other value. `.required()` columns never accept `null`.
125
132
 
@@ -135,6 +142,60 @@ auto-injection may keep the same `createId()` call site and back it with a
135
142
  file-local `crypto.randomUUID()` polyfill so schema-generation sandboxes do not
136
143
  depend on project `node_modules`.
137
144
 
145
+ ### Decimals, dates, 64-bit integers, and arrays
146
+
147
+ Each of these has native Postgres DDL. SQLite has no equivalent type, so on D1 the compiler lowers it to a storage class that keeps the value exact, and the wire format is the same on both dialects:
148
+
149
+ | Builder | Postgres | SQLite / D1 | Wire value | Rejected with 400 |
150
+ |---------|----------|-------------|------------|-------------------|
151
+ | `q.decimal({ precision: 12, scale: 2 })` | `numeric(12, 2)` | `TEXT` | string, `"1234.50"` | more than `precision − scale` integer digits or `scale` fraction digits, JSON numbers, exponents |
152
+ | `q.date()` | `date` | `TEXT` (`YYYY-MM-DD`) | string, `"2026-03-31"` | impossible dates (`2026-02-30`), any time or zone part |
153
+ | `q.bigint()` | `bigint` | `INTEGER` | number | non-integers, anything outside ±(2^53 − 1) |
154
+ | `q.smallint()` | `smallint` | `INTEGER` | number | anything outside −32768..32767 |
155
+ | `q.text().array()`, `q.enum([...]).array()`, `q.int().array()`, `q.uuid().array()` | `text[]`, `text[]`, `integer[]`, `uuid[]` | `TEXT` holding JSON | JSON array | non-arrays, and any element the scalar would reject (`q.enum(["a"]).array()` refuses `["b"]`) |
156
+
157
+ ```typescript
158
+ import { feature, q } from "@quickback/compiler";
159
+
160
+ export default feature("invoices", {
161
+ columns: {
162
+ id: q.id(),
163
+ number: q.text({ maxLength: 40 }).required(),
164
+ total: q.decimal({ precision: 12, scale: 2 }).required().filterable("eq"),
165
+ taxRate: q.decimal({ precision: 6, scale: 5 }).optional(),
166
+ issuedOn: q.date().required().filterable("range"),
167
+ amountCents: q.bigint().required(),
168
+ lineCount: q.smallint().default(1).required(),
169
+ labels: q.text().array().default([]).required(),
170
+ channels: q.enum(["web", "phone", "store"]).array().optional(),
171
+ organizationId: q.scope("organization"),
172
+ ...q.audit(),
173
+ },
174
+ read: { access: { roles: ["owner", "admin", "member"] } },
175
+ create: { access: { roles: ["owner", "admin"] } },
176
+ update: { access: { roles: ["owner", "admin"] } },
177
+ delete: { access: { roles: ["owner", "admin"] }, mode: "hard" },
178
+ });
179
+ ```
180
+
181
+ - **Decimals are strings**, so no value passes through a float. Send `"19.9"` and the API stores and returns `"19.90"`: the value is padded to `scale` digits and leading zeros are dropped, which is how Postgres prints `numeric(p,s)`. D1 stores that same canonical text, so both dialects return identical strings. `precision` (1–1000) and `scale` (0–`precision`) must be number literals, or the compile fails.
182
+ - **Dates have no time zone.** A `q.date()` value is never converted, so `"2026-03-31"` is the same day for every caller. Use `q.timestamp()` for an instant.
183
+ - **`q.bigint()` values are JSON numbers, and are capped at ±(2^53 − 1).** Past that, a JSON number can't hold an exact integer, and D1 returns every `INTEGER` as a JS number. The cap still takes a cents column past $90 trillion, where `q.int()` (Postgres `integer`) stops at about $21.4 million. Values written to a Postgres `bigint` outside the API beyond 2^53 will read back rounded.
184
+ - **Defaults are checked at compile time** against the same rules, because nothing re-validates a DDL default. `q.smallint().default(40000)` fails the compile. A decimal default must already be in canonical form, so write `.default("0.00")` for scale 2, not `"0"`.
185
+ - **`.array()`** works on `q.text()`, `q.enum()`, `q.int()`, and `q.uuid()`, and must be written once. `.default([])` gives Postgres `'{}'` and D1 `'[]'`. An array column can't declare `.references()`: Postgres has no foreign keys over array elements, so use a join table.
186
+
187
+ What you can query depends on the type. The compiler refuses the rest at compile time, and the list endpoint refuses them at runtime too:
188
+
189
+ | Type | `?search=` | `.filterable()` | `?sort=` |
190
+ |------|------------|-----------------|----------|
191
+ | `q.decimal` on Postgres | no | `eq`, `in`, `range` | yes |
192
+ | `q.decimal` on D1 | no | `eq`, `in` (the filter value is canonicalized, so `?total=19.9` matches `"19.90"`) | no. It is `TEXT` there, so both sorting and range filters would compare strings. |
193
+ | `q.date` | no | `eq`, `in`, `range` | yes (`YYYY-MM-DD` sorts correctly on both dialects) |
194
+ | `q.bigint`, `q.smallint` | no | `eq`, `in`, `range` | yes |
195
+ | `.array()` | no | no | no |
196
+
197
+ `.searchable()` and `.filterable("like")` are text-only. Masks that format strings (`email`, `phone`, `partial`, and the rest) are refused on `q.bigint()`, `q.smallint()`, and array columns; use `redact` or `custom` there. Decimal and date values are strings, so every mask type works on them. `.defaultNow()` is only accepted on `q.timestamp()`.
198
+
138
199
  ### q.scope() — tenant scope columns
139
200
 
140
201
  `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:
@@ -217,6 +278,125 @@ For one-off overrides on a specific column, pass an explicit name as the positio
217
278
  organizationId: q.scope('organization', { sqlName: 'org_id' }), // SQL name: 'org_id'
218
279
  ```
219
280
 
281
+ ### Constraints — CHECK and unique
282
+
283
+ Declare CHECK constraints on a column or on the `feature()` config, and unique
284
+ constraints as `unique` entries. They compile to Drizzle's `check()`,
285
+ `uniqueIndex()` and `unique()`, so drizzle-kit writes the DDL into the
286
+ migration on both dialects.
287
+
288
+ ```typescript
289
+ // quickback/features/line_items/line_items.ts
290
+ import { feature, q } from '@quickback/compiler';
291
+
292
+ export default feature('line_items', {
293
+ columns: {
294
+ id: q.id(),
295
+ sku: q.text().required(),
296
+ quantity: q.int().required().check('> 0'),
297
+ unitPriceCents: q.int().required().check('>= 0'),
298
+ productId: q.text().optional(),
299
+ serviceId: q.text().optional(),
300
+ organizationId: q.scope('organization'),
301
+ ...q.audit(),
302
+ ...q.softDelete(),
303
+ },
304
+ check: [
305
+ // exactly one of productId / serviceId
306
+ { name: 'line_items_one_target', sql: '(product_id IS NULL) <> (service_id IS NULL)' },
307
+ ],
308
+ unique: [
309
+ { columns: ['organizationId', 'sku'], whereNotDeleted: true },
310
+ ],
311
+ read: { access: { roles: ['member'] } },
312
+ create: { access: { roles: ['member'] } },
313
+ update: { access: { roles: ['member'] } },
314
+ delete: { access: { roles: ['admin'] } },
315
+ });
316
+ ```
317
+
318
+ | Declaration | DDL |
319
+ |-------------|-----|
320
+ | `quantity: q.int().check('> 0')` | `CONSTRAINT "line_items_quantity_check" CHECK ("quantity" > 0)` |
321
+ | `check: [{ name, sql }]` | `CONSTRAINT "<name>" CHECK (<sql>)` |
322
+ | `unique: [{ columns }]` | `CREATE UNIQUE INDEX …` |
323
+ | `unique: [{ columns, where: '…' }]` | `CREATE UNIQUE INDEX … WHERE …` (a partial unique index) |
324
+ | `unique: [{ columns, whereNotDeleted: true }]` | `CREATE UNIQUE INDEX … WHERE "deleted_at" IS NULL` |
325
+ | `unique: [{ columns, nullsNotDistinct: true }]` | `CONSTRAINT … UNIQUE NULLS NOT DISTINCT (…)`. Postgres 15+ only. |
326
+
327
+ **How the SQL is written.** Column-level `.check(expr)` is appended to the
328
+ quoted physical column name, as `"<column>" <expr>`. Write only what follows
329
+ the column: `'> 0'`, `"IN ('draft', 'open')"`, `'BETWEEN 1 AND 5'`. The
330
+ table-level `sql` and the unique `where` are complete expressions over the
331
+ **physical (snake_case) column names**: `product_id`, not `productId`.
332
+
333
+ **Nothing is translated per dialect.** The SQL must be valid for your
334
+ database. `num_nonnulls(a, b, c) = 1` works on Postgres only. On D1, write
335
+ `(a IS NOT NULL) + (b IS NOT NULL) + (c IS NOT NULL) = 1`. An invalid
336
+ expression fails when the migration is applied, not at compile time.
337
+
338
+ **Names.** A column check is named `<table>_<column>_check`. A table-level
339
+ check needs an explicit `name` that matches `/^[A-Za-z_][A-Za-z0-9_]*$/`. The
340
+ name can be at most 63 characters, because Postgres truncates longer
341
+ identifiers. It must also differ from every other check, unique and index name
342
+ on the table. A column takes one `.check()`: combine conditions with `AND`,
343
+ or use a table-level check.
344
+
345
+ **Compile errors instead of silent drops.** The compiler reads these options
346
+ from source, and it fails the compile on any of the following:
347
+
348
+ - a value that isn't a literal
349
+ - an unknown key
350
+ - `where` together with `whereNotDeleted`
351
+ - `nullsNotDistinct` on a partial unique
352
+ - `whereNotDeleted` on a table without `...q.softDelete()`
353
+ - `nullsNotDistinct` in a SQLite/D1 project, since SQLite always treats NULLs
354
+ as distinct
355
+
356
+ **Enforced by the database.** CHECK is not part of the request validator. A
357
+ violating write reaches the database and comes back as
358
+ `400 DB_CHECK_VIOLATION` naming the constraint. A unique collision comes back
359
+ as `409 DB_UNIQUE_VIOLATION`. See [Errors](/api/errors). Mirror a check at the
360
+ edge (e.g. `maxLength`) when you want a field-level validation message
361
+ instead.
362
+
363
+ The Postgres-only options, as a fragment:
364
+
365
+ ```typescript
366
+ // Postgres (Neon / PlanetScale Postgres) only
367
+ check: [{ name: 'contacts_one_channel', sql: 'num_nonnulls(email, phone, address) = 1' }],
368
+ unique: [{ columns: ['organizationId', 'externalRef'], nullsNotDistinct: true }],
369
+ ```
370
+
371
+ #### Unique constraints and soft delete
372
+
373
+ A soft-deleted row is still a row. A plain unique on `(organizationId, sku)`
374
+ keeps counting it, so after `DELETE /line_items/:id` the same SKU can't be
375
+ created again. The insert returns `409 DB_UNIQUE_VIOLATION` against a row the
376
+ caller can no longer see. Column-level `.unique()` has the same problem.
377
+
378
+ On a soft-delete table, make the unique **partial**. `whereNotDeleted: true`
379
+ adds `WHERE "deleted_at" IS NULL`, using the table's actual soft-delete column
380
+ under your naming convention. Uniqueness then holds among live rows only, and
381
+ a deleted value can be reused. Restoring a soft-deleted row whose value a live
382
+ row has since taken fails with a unique violation. That is the correct
383
+ outcome, because the two rows would otherwise collide.
384
+
385
+ **ON CONFLICT.** Generated CRUD, `PUT` and batch upsert don't use `ON
386
+ CONFLICT`: they look the row up by id and then insert or update, so partial
387
+ uniques need nothing from them. An action that upserts against a partial unique
388
+ with Drizzle's `onConflictDoUpdate` / `onConflictDoNothing` must repeat the
389
+ predicate as `targetWhere`. Postgres and SQLite only match a partial index to
390
+ a conflict target that carries its `WHERE`:
391
+
392
+ ```typescript
393
+ await db.insert(lineItems).values(row).onConflictDoUpdate({
394
+ target: [lineItems.organizationId, lineItems.sku],
395
+ targetWhere: sql`"deleted_at" IS NULL`,
396
+ set: { quantity: row.quantity },
397
+ });
398
+ ```
399
+
220
400
  ## Drizzle interop
221
401
 
222
402
  If you have an existing Drizzle schema you're bringing forward — or need a dialect-specific column option `q` doesn't expose — use `pgTable` / `sqliteTable` / `mysqlTable` directly:
@@ -853,6 +1033,56 @@ Do this even when a column name appears obvious, such as `sessionId` beside a
853
1033
  relationship might be missing; it is not enough evidence to silently invent
854
1034
  one. CMS-ready schemas state the relationship explicitly.
855
1035
 
1036
+ ### Self-references
1037
+
1038
+ A column that points at another row of the **same** table — a parent folder,
1039
+ the version a document replaces — uses `.references('self')`. It targets the
1040
+ table's own `id`:
1041
+
1042
+ ```typescript
1043
+ // quickback/features/folders/folders.ts
1044
+ import { feature, q } from '@quickback/compiler';
1045
+
1046
+ export default feature('folders', {
1047
+ columns: {
1048
+ id: q.id(),
1049
+ name: q.text().required(),
1050
+ parentId: q.text().optional().references('self', { onDelete: 'set null' }),
1051
+ organizationId: q.scope('organization'),
1052
+ ...q.audit(),
1053
+ ...q.softDelete(),
1054
+ },
1055
+ read: { access: { roles: ['member'] } },
1056
+ create: { access: { roles: ['member'] } },
1057
+ update: { access: { roles: ['member'] } },
1058
+ });
1059
+ ```
1060
+
1061
+ `() => folders.id` cannot work here: inside `feature()` there is no `folders`
1062
+ binding. In the [two-export form](#qtable--definetable--the-expanded-form)
1063
+ the binding exists, but a bare `() => folders.id` inside its own initializer
1064
+ is a TypeScript cycle (TS7022/TS7024) in your editor and in `quickback check`.
1065
+ Either use `'self'` there too, or annotate the thunk's return type the way
1066
+ Drizzle does: `.references((): AnyQuickbackColumn => folders.id)`, with
1067
+ `type AnyQuickbackColumn` imported from `@quickback/compiler`. All three
1068
+ spellings generate the same schema.
1069
+
1070
+ A self-reference is a normal FK everywhere else:
1071
+
1072
+ - **Writes** check it through the table's **own** firewall, like any
1073
+ [FK referential check](/define/firewall#foreign-key-referential-checks): a
1074
+ row can't point at another tenant's row or a soft-deleted one. `null`
1075
+ detaches the row.
1076
+ - **Reads** resolve the parent's display label (`parent_label` on
1077
+ `GET /:id` and the list) through the same firewall, and the CMS renders the column as a picker over the same
1078
+ table.
1079
+ - **Cycles are not refused.** A row may point at itself, and A → B → A passes
1080
+ too: each write checks one hop. If your data must stay a tree, enforce that
1081
+ in an [action](/define/actions) or a [trigger](/define/triggers).
1082
+ - A batch create checks parents that exist **before** the batch. A record
1083
+ can't name a sibling from the same batch as its parent; create the parent
1084
+ first.
1085
+
856
1086
  The legacy resource-level `references: { vendorId: "contact" }` map can override
857
1087
  schema-registry target metadata for an alias, but it does not create a database
858
1088
  foreign key. Prefer `.references(() => contacts.id)` whenever the target is a
@@ -862,7 +1092,7 @@ rows live in `AUTH_DB`, outside the feature database.
862
1092
 
863
1093
  ## Input Hints
864
1094
 
865
- Control how the CMS renders form inputs for specific columns. By default the CMS infers the control from the column itself — `q.timestamp()` → date-time picker, `q.bool()` → checkbox, `q.int()` → number, `q.enum()` → select, `q.url()` → URL input, `q.json()` → textarea, and name patterns for plain text (`*Url`, `*Notes`, `email`). The registry carries the q column `kind`, so this works on SQLite too, where every timestamp is `text` at the SQL layer. `inputHints` overrides the inference:
1095
+ Control how the CMS renders form inputs for specific columns. By default the CMS infers the control from the column itself — `q.timestamp()` → date-time picker, `q.date()` → date picker, `q.bool()` → checkbox, `q.int()` / `q.bigint()` / `q.smallint()` → number, `q.decimal()` → text (so the exact string is sent), `q.enum()` → select, `q.url()` → URL input, `q.json()` → textarea, and name patterns for plain text (`*Url`, `*Notes`, `email`). The registry carries the q column `kind`, so this works on SQLite too, where every timestamp is `text` at the SQL layer. The CMS has no editor for `.array()` columns yet. `inputHints` overrides the inference:
866
1096
 
867
1097
  {/* doc-compile: skip — one-key excerpt: the fence is the `inputHints` map only, with firewall/guards/crud already elided to `// ...`. This page's whole-file examples are the `feature()` and `q.table()`+`defineTable()` forms at the top, which the gate does compile. */}
868
1098
  ```typescript
@@ -939,7 +1169,8 @@ create a database foreign-key constraint. On Neon, use
939
1169
  for fully qualified cross-schema or composite constraints that cannot be
940
1170
  declared alongside a table. The ordered source and target column tuples must
941
1171
  have equal arity, and the referenced target tuple must have a matching unique
942
- or primary-key constraint before the foreign key migration runs.
1172
+ or primary-key constraint before the foreign key migration runs. A partial
1173
+ unique (`where` / `whereNotDeleted`) does not qualify as an FK target.
943
1174
 
944
1175
  Use these constraints for relational integrity only. Authorization, pass
945
1176
  consumption, state transitions, and other business logic belong in the API
@@ -1006,7 +1237,9 @@ export const jobs = pgTable('jobs', {
1006
1237
  |---------|--------|------------|
1007
1238
  | Boolean | `integer({ mode: 'boolean' })` | `boolean()` |
1008
1239
  | JSON | `text({ mode: 'json' })` with D1 JSON functions and `->` / `->>` operators | `jsonb()` or `json()` with PostgreSQL JSON indexing |
1009
- | Arrays | Relational child rows or JSON arrays (`json_each`) | Native arrays, relational rows, or JSONB |
1240
+ | Arrays | `.array()` lowers to JSON text; also relational child rows or JSON arrays (`json_each`) | `.array()` is a native `T[]`; also relational rows or JSONB |
1241
+ | Exact decimal | `q.decimal()` lowers to `TEXT` (not sortable or range-filterable) | `numeric(p, s)` |
1242
+ | Date | `q.date()` lowers to `TEXT` `YYYY-MM-DD` | `date` |
1010
1243
  | Auto-increment | `integer().primaryKey()` | `serial()` |
1011
1244
  | UUID | `text()` | `uuid()` |
1012
1245
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.66.18",
3
+ "version": "0.66.19",
4
4
  "description": "CLI for Quickback — define your backend in TypeScript, compile to a fully wired Cloudflare Worker (or Bun / Node) with auth, database, migrations, security, CMS, and Account UI.",
5
5
  "author": "Kardoe Incorporated <paul@kardoe.com>",
6
6
  "license": "MIT",
@@ -133,7 +133,10 @@ When the multi-sort format is detected (comma or `-` prefix), the `order` parame
133
133
 
134
134
  A client-supplied `?sort=` naming an unknown column — or one outside a view's
135
135
  `query.sortable` — returns `400`, for the same reason unknown filters do: rows
136
- would come back in some other order that reads as the requested one. A view's
136
+ would come back in some other order that reads as the requested one. Array
137
+ columns, and `q.decimal()` columns on D1 (stored as `TEXT`, so they would sort
138
+ as strings), are never sortable — see
139
+ [Decimals, dates, 64-bit integers, and arrays](/define/schema#decimals-dates-64-bit-integers-and-arrays). A view's
137
140
  own `defaultSort` fallback is config, not caller input, and is never rejected.
138
141
 
139
142
  ## Field Selection
@@ -5,10 +5,10 @@
5
5
  compiled to Drizzle. It turns
6
6
 
7
7
  ```
8
- feature(name, { columns, indexes, unique, ...rest })
8
+ feature(name, { columns, indexes, unique, check, ...rest })
9
9
  ```
10
10
 
11
- into `q.table(name, columns, { indexes, unique })` plus `defineTable(name, rest)`,
11
+ into `q.table(name, columns, { indexes, unique, check })` plus `defineTable(name, rest)`,
12
12
  passing every other key through verbatim. Both forms produce byte-identical output.
13
13
 
14
14
  `defineTable()` is **not deprecated**. It is the layer underneath, and it is what you
@@ -529,7 +529,7 @@ Every generated write handler — `POST /`, `POST /batch`, `PATCH /:id`, `PATCH
529
529
  }
530
530
  ```
531
531
 
532
- This closes a cross-tenant injection vector: even if an attacker knows a foreign tenant's row ID, they cannot attach a child record to it — at creation or by repointing an existing row later — and they cannot trigger a cross-tenant cascade delete. The check uses the target table's `buildXFirewallConditions(ctx)` helper, so it honors whatever firewall predicates the target declared (organization, owner, team, custom). FKs to tables with `{ exception: true }` get a plain existence check (still verifies the row exists, doesn't tenant-scope it).
532
+ This closes a cross-tenant injection vector: even if an attacker knows a foreign tenant's row ID, they cannot attach a child record to it — at creation or by repointing an existing row later — and they cannot trigger a cross-tenant cascade delete. The check uses the target table's `buildXFirewallConditions(ctx)` helper, so it honors whatever firewall predicates the target declared (organization, owner, team, custom). FKs to tables with `{ exception: true }` get a plain existence check (still verifies the row exists, doesn't tenant-scope it). A [self-reference](/define/schema#self-references) (`parentId: q.text().references('self')`) is checked against the table's own firewall the same way.
533
533
 
534
534
  The check runs after guards but before the write, so it appears as `layer: "validation"` in error responses. Status code is `400`, not `404` — returning `404` would leak existence of out-of-scope rows.
535
535
 
@@ -82,7 +82,7 @@ A few mechanics to know:
82
82
  - **Column names** default to snake_case of the JS key — `organizationId` ↔ `organization_id`, `salaryMin` ↔ `salary_min`. Pass a positional argument to override: `q.text('custom_name')`.
83
83
  - **`q.id()`** emits `text('id').primaryKey()` with a provider-driven app-layer default.
84
84
  - **`.required()` / `.optional()`** control NOT NULL. Chain before or after `.default(x)`.
85
- - **References:** `q.text().required().references(() => other.id, { onDelete: 'cascade' })`. An FK declares a *pointer*, not ownership — when the child rows are a **composition** of one root (junctions, phones/emails, line items), also declare [`owns`](/define/changesets) on the root to generate the atomic aggregate write path. `other` must be a **feature table in the same database**.
85
+ - **References:** `q.text().required().references(() => other.id, { onDelete: 'cascade' })`, or `.references('self')` for a column pointing at another row of the same table (see [Self-references](#self-references)). An FK declares a *pointer*, not ownership — when the child rows are a **composition** of one root (junctions, phones/emails, line items), also declare [`owns`](/define/changesets) on the root to generate the atomic aggregate write path. `other` must be a **feature table in the same database**.
86
86
 
87
87
  > **Never FK Better Auth tables**
88
88
  >
@@ -103,7 +103,7 @@ A few mechanics to know:
103
103
  > `authz.relationships` `subject: { column: 'userId', equals: 'ctx.userId' }` does not need, and must not create, a SQL FK. See [Relationships](/define/relationships). To query Better Auth tables, use `c.get("authDb")` from an action — see [Scoped DB](/define/actions/scoped-db#reaching-better-auth-tables-authdb).
104
104
 
105
105
 
106
- - **Indexes:** column-level `.index()` or table-level `indexes` / `unique` as a third arg to `q.table(name, cols, { indexes, unique })`. With `feature()`, pass `indexes` and `unique` as top-level keys alongside `columns` — the sugar forwards them into the same `q.table` opts.
106
+ - **Indexes and constraints:** column-level `.index()` / `.unique()` / `.check(expr)`, or table-level `indexes` / `unique` / `check` as a third arg to `q.table(name, cols, { indexes, unique, check })`. With `feature()`, pass `indexes`, `unique` and `check` as top-level keys alongside `columns` — the sugar forwards them into the same `q.table` opts. See [Constraints](#constraints--check-and-unique).
107
107
 
108
108
  ### Column Types
109
109
 
@@ -112,14 +112,21 @@ A few mechanics to know:
112
112
  | `q.text()` | `text(...)` | `z.string()` |
113
113
  | `q.url()` | `text(...)` | `z.string().url()` |
114
114
  | `q.int()` | `integer(...)` | `z.number().int()` |
115
+ | `q.bigint()` | `bigint(..., { mode: 'number' })` | `z.number().int()` within ±(2^53 − 1) |
116
+ | `q.smallint()` | `smallint(...)` | `z.number().int()` within −32768..32767 |
117
+ | `q.decimal({ precision, scale })` | `numeric(..., { precision, scale })` | decimal string within precision/scale |
115
118
  | `q.bool()` | `boolean(...)` | `z.boolean()` |
116
119
  | `q.uuid()` | `uuid(...)` | `z.string().uuid()` |
117
120
  | `q.timestamp()` | `timestamp(...)` (converted to SQLite `text` on sqlite targets) | `z.coerce.date()` |
121
+ | `q.date()` | `date(...)` | `z.iso.date()` (`YYYY-MM-DD`) |
118
122
  | `q.json()` | `jsonb(...)` | `z.unknown()` (or the type you pass in) |
119
123
  | `q.enum(['a','b'])` | `text(..., { enum: [...] })` | `z.enum([...])` |
120
124
  | `q.id()` | `text('id').primaryKey()` | `z.string()` |
121
125
  | `q.scope(kind)` | `text(...).notNull()` | `z.string()` |
122
126
  | `q.stamp({ fromScope, claim })` | `text(...).notNull()` (nullable with `optional: true`) | `z.string().optional()` |
127
+ | `.array()` on `q.text()` / `q.enum()` / `q.int()` / `q.uuid()` | `text(...).array()` etc. | `z.array(<element>)` |
128
+
129
+ The Drizzle column is the Postgres form; on SQLite/D1 the compiler lowers it. The next section has the per-dialect storage for the exact-numeric, date, and array types.
123
130
 
124
131
  In request bodies a column that is not `.required()` is `.optional().nullable()` — omit it to leave it untouched, send `null` to clear it. `""` is not a blank: it is validated like any other value. `.required()` columns never accept `null`.
125
132
 
@@ -135,6 +142,60 @@ auto-injection may keep the same `createId()` call site and back it with a
135
142
  file-local `crypto.randomUUID()` polyfill so schema-generation sandboxes do not
136
143
  depend on project `node_modules`.
137
144
 
145
+ ### Decimals, dates, 64-bit integers, and arrays
146
+
147
+ Each of these has native Postgres DDL. SQLite has no equivalent type, so on D1 the compiler lowers it to a storage class that keeps the value exact, and the wire format is the same on both dialects:
148
+
149
+ | Builder | Postgres | SQLite / D1 | Wire value | Rejected with 400 |
150
+ |---------|----------|-------------|------------|-------------------|
151
+ | `q.decimal({ precision: 12, scale: 2 })` | `numeric(12, 2)` | `TEXT` | string, `"1234.50"` | more than `precision − scale` integer digits or `scale` fraction digits, JSON numbers, exponents |
152
+ | `q.date()` | `date` | `TEXT` (`YYYY-MM-DD`) | string, `"2026-03-31"` | impossible dates (`2026-02-30`), any time or zone part |
153
+ | `q.bigint()` | `bigint` | `INTEGER` | number | non-integers, anything outside ±(2^53 − 1) |
154
+ | `q.smallint()` | `smallint` | `INTEGER` | number | anything outside −32768..32767 |
155
+ | `q.text().array()`, `q.enum([...]).array()`, `q.int().array()`, `q.uuid().array()` | `text[]`, `text[]`, `integer[]`, `uuid[]` | `TEXT` holding JSON | JSON array | non-arrays, and any element the scalar would reject (`q.enum(["a"]).array()` refuses `["b"]`) |
156
+
157
+ ```typescript
158
+ import { feature, q } from "@quickback/compiler";
159
+
160
+ export default feature("invoices", {
161
+ columns: {
162
+ id: q.id(),
163
+ number: q.text({ maxLength: 40 }).required(),
164
+ total: q.decimal({ precision: 12, scale: 2 }).required().filterable("eq"),
165
+ taxRate: q.decimal({ precision: 6, scale: 5 }).optional(),
166
+ issuedOn: q.date().required().filterable("range"),
167
+ amountCents: q.bigint().required(),
168
+ lineCount: q.smallint().default(1).required(),
169
+ labels: q.text().array().default([]).required(),
170
+ channels: q.enum(["web", "phone", "store"]).array().optional(),
171
+ organizationId: q.scope("organization"),
172
+ ...q.audit(),
173
+ },
174
+ read: { access: { roles: ["owner", "admin", "member"] } },
175
+ create: { access: { roles: ["owner", "admin"] } },
176
+ update: { access: { roles: ["owner", "admin"] } },
177
+ delete: { access: { roles: ["owner", "admin"] }, mode: "hard" },
178
+ });
179
+ ```
180
+
181
+ - **Decimals are strings**, so no value passes through a float. Send `"19.9"` and the API stores and returns `"19.90"`: the value is padded to `scale` digits and leading zeros are dropped, which is how Postgres prints `numeric(p,s)`. D1 stores that same canonical text, so both dialects return identical strings. `precision` (1–1000) and `scale` (0–`precision`) must be number literals, or the compile fails.
182
+ - **Dates have no time zone.** A `q.date()` value is never converted, so `"2026-03-31"` is the same day for every caller. Use `q.timestamp()` for an instant.
183
+ - **`q.bigint()` values are JSON numbers, and are capped at ±(2^53 − 1).** Past that, a JSON number can't hold an exact integer, and D1 returns every `INTEGER` as a JS number. The cap still takes a cents column past $90 trillion, where `q.int()` (Postgres `integer`) stops at about $21.4 million. Values written to a Postgres `bigint` outside the API beyond 2^53 will read back rounded.
184
+ - **Defaults are checked at compile time** against the same rules, because nothing re-validates a DDL default. `q.smallint().default(40000)` fails the compile. A decimal default must already be in canonical form, so write `.default("0.00")` for scale 2, not `"0"`.
185
+ - **`.array()`** works on `q.text()`, `q.enum()`, `q.int()`, and `q.uuid()`, and must be written once. `.default([])` gives Postgres `'{}'` and D1 `'[]'`. An array column can't declare `.references()`: Postgres has no foreign keys over array elements, so use a join table.
186
+
187
+ What you can query depends on the type. The compiler refuses the rest at compile time, and the list endpoint refuses them at runtime too:
188
+
189
+ | Type | `?search=` | `.filterable()` | `?sort=` |
190
+ |------|------------|-----------------|----------|
191
+ | `q.decimal` on Postgres | no | `eq`, `in`, `range` | yes |
192
+ | `q.decimal` on D1 | no | `eq`, `in` (the filter value is canonicalized, so `?total=19.9` matches `"19.90"`) | no. It is `TEXT` there, so both sorting and range filters would compare strings. |
193
+ | `q.date` | no | `eq`, `in`, `range` | yes (`YYYY-MM-DD` sorts correctly on both dialects) |
194
+ | `q.bigint`, `q.smallint` | no | `eq`, `in`, `range` | yes |
195
+ | `.array()` | no | no | no |
196
+
197
+ `.searchable()` and `.filterable("like")` are text-only. Masks that format strings (`email`, `phone`, `partial`, and the rest) are refused on `q.bigint()`, `q.smallint()`, and array columns; use `redact` or `custom` there. Decimal and date values are strings, so every mask type works on them. `.defaultNow()` is only accepted on `q.timestamp()`.
198
+
138
199
  ### q.scope() — tenant scope columns
139
200
 
140
201
  `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:
@@ -217,6 +278,125 @@ For one-off overrides on a specific column, pass an explicit name as the positio
217
278
  organizationId: q.scope('organization', { sqlName: 'org_id' }), // SQL name: 'org_id'
218
279
  ```
219
280
 
281
+ ### Constraints — CHECK and unique
282
+
283
+ Declare CHECK constraints on a column or on the `feature()` config, and unique
284
+ constraints as `unique` entries. They compile to Drizzle's `check()`,
285
+ `uniqueIndex()` and `unique()`, so drizzle-kit writes the DDL into the
286
+ migration on both dialects.
287
+
288
+ ```typescript
289
+ // quickback/features/line_items/line_items.ts
290
+ import { feature, q } from '@quickback/compiler';
291
+
292
+ export default feature('line_items', {
293
+ columns: {
294
+ id: q.id(),
295
+ sku: q.text().required(),
296
+ quantity: q.int().required().check('> 0'),
297
+ unitPriceCents: q.int().required().check('>= 0'),
298
+ productId: q.text().optional(),
299
+ serviceId: q.text().optional(),
300
+ organizationId: q.scope('organization'),
301
+ ...q.audit(),
302
+ ...q.softDelete(),
303
+ },
304
+ check: [
305
+ // exactly one of productId / serviceId
306
+ { name: 'line_items_one_target', sql: '(product_id IS NULL) <> (service_id IS NULL)' },
307
+ ],
308
+ unique: [
309
+ { columns: ['organizationId', 'sku'], whereNotDeleted: true },
310
+ ],
311
+ read: { access: { roles: ['member'] } },
312
+ create: { access: { roles: ['member'] } },
313
+ update: { access: { roles: ['member'] } },
314
+ delete: { access: { roles: ['admin'] } },
315
+ });
316
+ ```
317
+
318
+ | Declaration | DDL |
319
+ |-------------|-----|
320
+ | `quantity: q.int().check('> 0')` | `CONSTRAINT "line_items_quantity_check" CHECK ("quantity" > 0)` |
321
+ | `check: [{ name, sql }]` | `CONSTRAINT "<name>" CHECK (<sql>)` |
322
+ | `unique: [{ columns }]` | `CREATE UNIQUE INDEX …` |
323
+ | `unique: [{ columns, where: '…' }]` | `CREATE UNIQUE INDEX … WHERE …` (a partial unique index) |
324
+ | `unique: [{ columns, whereNotDeleted: true }]` | `CREATE UNIQUE INDEX … WHERE "deleted_at" IS NULL` |
325
+ | `unique: [{ columns, nullsNotDistinct: true }]` | `CONSTRAINT … UNIQUE NULLS NOT DISTINCT (…)`. Postgres 15+ only. |
326
+
327
+ **How the SQL is written.** Column-level `.check(expr)` is appended to the
328
+ quoted physical column name, as `"<column>" <expr>`. Write only what follows
329
+ the column: `'> 0'`, `"IN ('draft', 'open')"`, `'BETWEEN 1 AND 5'`. The
330
+ table-level `sql` and the unique `where` are complete expressions over the
331
+ **physical (snake_case) column names**: `product_id`, not `productId`.
332
+
333
+ **Nothing is translated per dialect.** The SQL must be valid for your
334
+ database. `num_nonnulls(a, b, c) = 1` works on Postgres only. On D1, write
335
+ `(a IS NOT NULL) + (b IS NOT NULL) + (c IS NOT NULL) = 1`. An invalid
336
+ expression fails when the migration is applied, not at compile time.
337
+
338
+ **Names.** A column check is named `<table>_<column>_check`. A table-level
339
+ check needs an explicit `name` that matches `/^[A-Za-z_][A-Za-z0-9_]*$/`. The
340
+ name can be at most 63 characters, because Postgres truncates longer
341
+ identifiers. It must also differ from every other check, unique and index name
342
+ on the table. A column takes one `.check()`: combine conditions with `AND`,
343
+ or use a table-level check.
344
+
345
+ **Compile errors instead of silent drops.** The compiler reads these options
346
+ from source, and it fails the compile on any of the following:
347
+
348
+ - a value that isn't a literal
349
+ - an unknown key
350
+ - `where` together with `whereNotDeleted`
351
+ - `nullsNotDistinct` on a partial unique
352
+ - `whereNotDeleted` on a table without `...q.softDelete()`
353
+ - `nullsNotDistinct` in a SQLite/D1 project, since SQLite always treats NULLs
354
+ as distinct
355
+
356
+ **Enforced by the database.** CHECK is not part of the request validator. A
357
+ violating write reaches the database and comes back as
358
+ `400 DB_CHECK_VIOLATION` naming the constraint. A unique collision comes back
359
+ as `409 DB_UNIQUE_VIOLATION`. See [Errors](/api/errors). Mirror a check at the
360
+ edge (e.g. `maxLength`) when you want a field-level validation message
361
+ instead.
362
+
363
+ The Postgres-only options, as a fragment:
364
+
365
+ ```typescript
366
+ // Postgres (Neon / PlanetScale Postgres) only
367
+ check: [{ name: 'contacts_one_channel', sql: 'num_nonnulls(email, phone, address) = 1' }],
368
+ unique: [{ columns: ['organizationId', 'externalRef'], nullsNotDistinct: true }],
369
+ ```
370
+
371
+ #### Unique constraints and soft delete
372
+
373
+ A soft-deleted row is still a row. A plain unique on `(organizationId, sku)`
374
+ keeps counting it, so after `DELETE /line_items/:id` the same SKU can't be
375
+ created again. The insert returns `409 DB_UNIQUE_VIOLATION` against a row the
376
+ caller can no longer see. Column-level `.unique()` has the same problem.
377
+
378
+ On a soft-delete table, make the unique **partial**. `whereNotDeleted: true`
379
+ adds `WHERE "deleted_at" IS NULL`, using the table's actual soft-delete column
380
+ under your naming convention. Uniqueness then holds among live rows only, and
381
+ a deleted value can be reused. Restoring a soft-deleted row whose value a live
382
+ row has since taken fails with a unique violation. That is the correct
383
+ outcome, because the two rows would otherwise collide.
384
+
385
+ **ON CONFLICT.** Generated CRUD, `PUT` and batch upsert don't use `ON
386
+ CONFLICT`: they look the row up by id and then insert or update, so partial
387
+ uniques need nothing from them. An action that upserts against a partial unique
388
+ with Drizzle's `onConflictDoUpdate` / `onConflictDoNothing` must repeat the
389
+ predicate as `targetWhere`. Postgres and SQLite only match a partial index to
390
+ a conflict target that carries its `WHERE`:
391
+
392
+ ```typescript
393
+ await db.insert(lineItems).values(row).onConflictDoUpdate({
394
+ target: [lineItems.organizationId, lineItems.sku],
395
+ targetWhere: sql`"deleted_at" IS NULL`,
396
+ set: { quantity: row.quantity },
397
+ });
398
+ ```
399
+
220
400
  ## Drizzle interop
221
401
 
222
402
  If you have an existing Drizzle schema you're bringing forward — or need a dialect-specific column option `q` doesn't expose — use `pgTable` / `sqliteTable` / `mysqlTable` directly:
@@ -853,6 +1033,56 @@ Do this even when a column name appears obvious, such as `sessionId` beside a
853
1033
  relationship might be missing; it is not enough evidence to silently invent
854
1034
  one. CMS-ready schemas state the relationship explicitly.
855
1035
 
1036
+ ### Self-references
1037
+
1038
+ A column that points at another row of the **same** table — a parent folder,
1039
+ the version a document replaces — uses `.references('self')`. It targets the
1040
+ table's own `id`:
1041
+
1042
+ ```typescript
1043
+ // quickback/features/folders/folders.ts
1044
+ import { feature, q } from '@quickback/compiler';
1045
+
1046
+ export default feature('folders', {
1047
+ columns: {
1048
+ id: q.id(),
1049
+ name: q.text().required(),
1050
+ parentId: q.text().optional().references('self', { onDelete: 'set null' }),
1051
+ organizationId: q.scope('organization'),
1052
+ ...q.audit(),
1053
+ ...q.softDelete(),
1054
+ },
1055
+ read: { access: { roles: ['member'] } },
1056
+ create: { access: { roles: ['member'] } },
1057
+ update: { access: { roles: ['member'] } },
1058
+ });
1059
+ ```
1060
+
1061
+ `() => folders.id` cannot work here: inside `feature()` there is no `folders`
1062
+ binding. In the [two-export form](#qtable--definetable--the-expanded-form)
1063
+ the binding exists, but a bare `() => folders.id` inside its own initializer
1064
+ is a TypeScript cycle (TS7022/TS7024) in your editor and in `quickback check`.
1065
+ Either use `'self'` there too, or annotate the thunk's return type the way
1066
+ Drizzle does: `.references((): AnyQuickbackColumn => folders.id)`, with
1067
+ `type AnyQuickbackColumn` imported from `@quickback/compiler`. All three
1068
+ spellings generate the same schema.
1069
+
1070
+ A self-reference is a normal FK everywhere else:
1071
+
1072
+ - **Writes** check it through the table's **own** firewall, like any
1073
+ [FK referential check](/define/firewall#foreign-key-referential-checks): a
1074
+ row can't point at another tenant's row or a soft-deleted one. `null`
1075
+ detaches the row.
1076
+ - **Reads** resolve the parent's display label (`parent_label` on
1077
+ `GET /:id` and the list) through the same firewall, and the CMS renders the column as a picker over the same
1078
+ table.
1079
+ - **Cycles are not refused.** A row may point at itself, and A → B → A passes
1080
+ too: each write checks one hop. If your data must stay a tree, enforce that
1081
+ in an [action](/define/actions) or a [trigger](/define/triggers).
1082
+ - A batch create checks parents that exist **before** the batch. A record
1083
+ can't name a sibling from the same batch as its parent; create the parent
1084
+ first.
1085
+
856
1086
  The legacy resource-level `references: { vendorId: "contact" }` map can override
857
1087
  schema-registry target metadata for an alias, but it does not create a database
858
1088
  foreign key. Prefer `.references(() => contacts.id)` whenever the target is a
@@ -862,7 +1092,7 @@ rows live in `AUTH_DB`, outside the feature database.
862
1092
 
863
1093
  ## Input Hints
864
1094
 
865
- Control how the CMS renders form inputs for specific columns. By default the CMS infers the control from the column itself — `q.timestamp()` → date-time picker, `q.bool()` → checkbox, `q.int()` → number, `q.enum()` → select, `q.url()` → URL input, `q.json()` → textarea, and name patterns for plain text (`*Url`, `*Notes`, `email`). The registry carries the q column `kind`, so this works on SQLite too, where every timestamp is `text` at the SQL layer. `inputHints` overrides the inference:
1095
+ Control how the CMS renders form inputs for specific columns. By default the CMS infers the control from the column itself — `q.timestamp()` → date-time picker, `q.date()` → date picker, `q.bool()` → checkbox, `q.int()` / `q.bigint()` / `q.smallint()` → number, `q.decimal()` → text (so the exact string is sent), `q.enum()` → select, `q.url()` → URL input, `q.json()` → textarea, and name patterns for plain text (`*Url`, `*Notes`, `email`). The registry carries the q column `kind`, so this works on SQLite too, where every timestamp is `text` at the SQL layer. The CMS has no editor for `.array()` columns yet. `inputHints` overrides the inference:
866
1096
 
867
1097
  {/* doc-compile: skip — one-key excerpt: the fence is the `inputHints` map only, with firewall/guards/crud already elided to `// ...`. This page's whole-file examples are the `feature()` and `q.table()`+`defineTable()` forms at the top, which the gate does compile. */}
868
1098
  ```typescript
@@ -939,7 +1169,8 @@ create a database foreign-key constraint. On Neon, use
939
1169
  for fully qualified cross-schema or composite constraints that cannot be
940
1170
  declared alongside a table. The ordered source and target column tuples must
941
1171
  have equal arity, and the referenced target tuple must have a matching unique
942
- or primary-key constraint before the foreign key migration runs.
1172
+ or primary-key constraint before the foreign key migration runs. A partial
1173
+ unique (`where` / `whereNotDeleted`) does not qualify as an FK target.
943
1174
 
944
1175
  Use these constraints for relational integrity only. Authorization, pass
945
1176
  consumption, state transitions, and other business logic belong in the API
@@ -1006,7 +1237,9 @@ export const jobs = pgTable('jobs', {
1006
1237
  |---------|--------|------------|
1007
1238
  | Boolean | `integer({ mode: 'boolean' })` | `boolean()` |
1008
1239
  | JSON | `text({ mode: 'json' })` with D1 JSON functions and `->` / `->>` operators | `jsonb()` or `json()` with PostgreSQL JSON indexing |
1009
- | Arrays | Relational child rows or JSON arrays (`json_each`) | Native arrays, relational rows, or JSONB |
1240
+ | Arrays | `.array()` lowers to JSON text; also relational child rows or JSON arrays (`json_each`) | `.array()` is a native `T[]`; also relational rows or JSONB |
1241
+ | Exact decimal | `q.decimal()` lowers to `TEXT` (not sortable or range-filterable) | `numeric(p, s)` |
1242
+ | Date | `q.date()` lowers to `TEXT` `YYYY-MM-DD` | `date` |
1010
1243
  | Auto-increment | `integer().primaryKey()` | `serial()` |
1011
1244
  | UUID | `text()` | `uuid()` |
1012
1245