@quickback-dev/cli 0.66.18 → 0.66.20

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.
Files changed (32) hide show
  1. package/dist/index.js +1 -1
  2. package/dist/lib/compiler-stubs.d.ts +29 -8
  3. package/dist/lib/compiler-stubs.d.ts.map +1 -1
  4. package/dist/lib/compiler-stubs.js +29 -16
  5. package/dist/lib/compiler-stubs.js.map +1 -1
  6. package/dist/skill/SKILL.md +18 -0
  7. package/dist/skill/docs/api/actions.md +1 -1
  8. package/dist/skill/docs/api/query-params.md +4 -1
  9. package/dist/skill/docs/api/typescript.md +2 -1
  10. package/dist/skill/docs/define/actions/defining.md +1 -0
  11. package/dist/skill/docs/define/actions/index.md +17 -2
  12. package/dist/skill/docs/define/actions/record-and-standalone.md +43 -0
  13. package/dist/skill/docs/define/actions/scoped-db.md +6 -0
  14. package/dist/skill/docs/define/changesets.md +24 -4
  15. package/dist/skill/docs/define/escape-hatches.md +2 -2
  16. package/dist/skill/docs/define/firewall.md +1 -1
  17. package/dist/skill/docs/define/schema.md +271 -6
  18. package/dist/skill/docs/platform/webhooks/inbound.md +20 -7
  19. package/package.json +1 -1
  20. package/src/skill/SKILL.md +18 -0
  21. package/src/skill/docs/api/actions.md +1 -1
  22. package/src/skill/docs/api/query-params.md +4 -1
  23. package/src/skill/docs/api/typescript.md +2 -1
  24. package/src/skill/docs/define/actions/defining.md +1 -0
  25. package/src/skill/docs/define/actions/index.md +17 -2
  26. package/src/skill/docs/define/actions/record-and-standalone.md +43 -0
  27. package/src/skill/docs/define/actions/scoped-db.md +6 -0
  28. package/src/skill/docs/define/changesets.md +24 -4
  29. package/src/skill/docs/define/escape-hatches.md +2 -2
  30. package/src/skill/docs/define/firewall.md +1 -1
  31. package/src/skill/docs/define/schema.md +271 -6
  32. package/src/skill/docs/platform/webhooks/inbound.md +20 -7
@@ -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()` |
118
- | `q.json()` | `jsonb(...)` | `z.unknown()` (or the type you pass in) |
121
+ | `q.date()` | `date(...)` | `z.iso.date()` (`YYYY-MM-DD`) |
122
+ | `q.json()` / `q.json(z.object({...}))` | `jsonb(...)` | `z.unknown()`, or the value schema you pass in — see [Typed JSON columns](#typed-json-columns) |
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
 
@@ -129,12 +136,98 @@ In request bodies a column that is not `.required()` is `.optional().nullable()`
129
136
 
130
137
  `q.id()` emits a plain text primary key. Actual ID assignment at insert time is driven by the provider's `generateId` setting. This keeps q's output decoupled from any specific ID library.
131
138
 
139
+ #### Typed JSON columns
140
+
141
+ Pass `q.json()` a Zod schema to give the column's value a shape. A table file may import `{ z }` from `zod` for this:
142
+
143
+ ```typescript title="quickback/features/journal-entries/journal-entries.ts"
144
+ import { feature, q } from "@quickback/compiler";
145
+ import { z } from "zod";
146
+
147
+ export default feature("journalEntries", {
148
+ columns: {
149
+ id: q.id(),
150
+ organizationId: q.scope("organization"),
151
+ autocatResult: q.json(z.object({ method: z.string(), confidence: z.number().min(0).max(1) })).optional(),
152
+ applications: q.json(z.array(z.object({ invoiceId: z.string(), amount: z.string() }))).optional(),
153
+ raw: q.json().optional(),
154
+ ...q.audit(),
155
+ ...q.softDelete(),
156
+ },
157
+ read: { access: { roles: ["member"] } },
158
+ create: { access: { roles: ["admin"] } },
159
+ });
160
+ ```
161
+
162
+ The schema validates create and update bodies (and changeset ops), and its JSON Schema types the column in `openapi.json`, `api-types.gen.ts`, `quickback.gen.ts` and the MCP tools. A bare `q.json()` stays `unknown` there. Storage doesn't change: the column is `jsonb` on Postgres and JSON text on SQLite/D1.
163
+
164
+ The schema must be written inline from `z` and literals, because the compiler copies it into the generated routes and converts it to JSON Schema itself. These are compile errors:
165
+
166
+ - a reference to another binding: `q.json(Shape)`, or `z.object({ a: Shape })`
167
+ - a callback such as `.refine(...)` or `.transform(...)`
168
+ - using `z` anywhere else in the table file
169
+ - importing anything from `zod` other than `{ z }`
170
+
132
171
  For `generateId: "cuid"`, there is one important nuance: import-capable runtime
133
172
  paths can emit real `createId()` usage, but compiler-managed schema
134
173
  auto-injection may keep the same `createId()` call site and back it with a
135
174
  file-local `crypto.randomUUID()` polyfill so schema-generation sandboxes do not
136
175
  depend on project `node_modules`.
137
176
 
177
+ ### Decimals, dates, 64-bit integers, and arrays
178
+
179
+ 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:
180
+
181
+ | Builder | Postgres | SQLite / D1 | Wire value | Rejected with 400 |
182
+ |---------|----------|-------------|------------|-------------------|
183
+ | `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 |
184
+ | `q.date()` | `date` | `TEXT` (`YYYY-MM-DD`) | string, `"2026-03-31"` | impossible dates (`2026-02-30`), any time or zone part |
185
+ | `q.bigint()` | `bigint` | `INTEGER` | number | non-integers, anything outside ±(2^53 − 1) |
186
+ | `q.smallint()` | `smallint` | `INTEGER` | number | anything outside −32768..32767 |
187
+ | `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"]`) |
188
+
189
+ ```typescript
190
+ import { feature, q } from "@quickback/compiler";
191
+
192
+ export default feature("invoices", {
193
+ columns: {
194
+ id: q.id(),
195
+ number: q.text({ maxLength: 40 }).required(),
196
+ total: q.decimal({ precision: 12, scale: 2 }).required().filterable("eq"),
197
+ taxRate: q.decimal({ precision: 6, scale: 5 }).optional(),
198
+ issuedOn: q.date().required().filterable("range"),
199
+ amountCents: q.bigint().required(),
200
+ lineCount: q.smallint().default(1).required(),
201
+ labels: q.text().array().default([]).required(),
202
+ channels: q.enum(["web", "phone", "store"]).array().optional(),
203
+ organizationId: q.scope("organization"),
204
+ ...q.audit(),
205
+ },
206
+ read: { access: { roles: ["owner", "admin", "member"] } },
207
+ create: { access: { roles: ["owner", "admin"] } },
208
+ update: { access: { roles: ["owner", "admin"] } },
209
+ delete: { access: { roles: ["owner", "admin"] }, mode: "hard" },
210
+ });
211
+ ```
212
+
213
+ - **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.
214
+ - **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.
215
+ - **`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.
216
+ - **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"`.
217
+ - **`.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.
218
+
219
+ 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:
220
+
221
+ | Type | `?search=` | `.filterable()` | `?sort=` |
222
+ |------|------------|-----------------|----------|
223
+ | `q.decimal` on Postgres | no | `eq`, `in`, `range` | yes |
224
+ | `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. |
225
+ | `q.date` | no | `eq`, `in`, `range` | yes (`YYYY-MM-DD` sorts correctly on both dialects) |
226
+ | `q.bigint`, `q.smallint` | no | `eq`, `in`, `range` | yes |
227
+ | `.array()` | no | no | no |
228
+
229
+ `.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()`.
230
+
138
231
  ### q.scope() — tenant scope columns
139
232
 
140
233
  `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 +310,125 @@ For one-off overrides on a specific column, pass an explicit name as the positio
217
310
  organizationId: q.scope('organization', { sqlName: 'org_id' }), // SQL name: 'org_id'
218
311
  ```
219
312
 
313
+ ### Constraints — CHECK and unique
314
+
315
+ Declare CHECK constraints on a column or on the `feature()` config, and unique
316
+ constraints as `unique` entries. They compile to Drizzle's `check()`,
317
+ `uniqueIndex()` and `unique()`, so drizzle-kit writes the DDL into the
318
+ migration on both dialects.
319
+
320
+ ```typescript
321
+ // quickback/features/line_items/line_items.ts
322
+ import { feature, q } from '@quickback/compiler';
323
+
324
+ export default feature('line_items', {
325
+ columns: {
326
+ id: q.id(),
327
+ sku: q.text().required(),
328
+ quantity: q.int().required().check('> 0'),
329
+ unitPriceCents: q.int().required().check('>= 0'),
330
+ productId: q.text().optional(),
331
+ serviceId: q.text().optional(),
332
+ organizationId: q.scope('organization'),
333
+ ...q.audit(),
334
+ ...q.softDelete(),
335
+ },
336
+ check: [
337
+ // exactly one of productId / serviceId
338
+ { name: 'line_items_one_target', sql: '(product_id IS NULL) <> (service_id IS NULL)' },
339
+ ],
340
+ unique: [
341
+ { columns: ['organizationId', 'sku'], whereNotDeleted: true },
342
+ ],
343
+ read: { access: { roles: ['member'] } },
344
+ create: { access: { roles: ['member'] } },
345
+ update: { access: { roles: ['member'] } },
346
+ delete: { access: { roles: ['admin'] } },
347
+ });
348
+ ```
349
+
350
+ | Declaration | DDL |
351
+ |-------------|-----|
352
+ | `quantity: q.int().check('> 0')` | `CONSTRAINT "line_items_quantity_check" CHECK ("quantity" > 0)` |
353
+ | `check: [{ name, sql }]` | `CONSTRAINT "<name>" CHECK (<sql>)` |
354
+ | `unique: [{ columns }]` | `CREATE UNIQUE INDEX …` |
355
+ | `unique: [{ columns, where: '…' }]` | `CREATE UNIQUE INDEX … WHERE …` (a partial unique index) |
356
+ | `unique: [{ columns, whereNotDeleted: true }]` | `CREATE UNIQUE INDEX … WHERE "deleted_at" IS NULL` |
357
+ | `unique: [{ columns, nullsNotDistinct: true }]` | `CONSTRAINT … UNIQUE NULLS NOT DISTINCT (…)`. Postgres 15+ only. |
358
+
359
+ **How the SQL is written.** Column-level `.check(expr)` is appended to the
360
+ quoted physical column name, as `"<column>" <expr>`. Write only what follows
361
+ the column: `'> 0'`, `"IN ('draft', 'open')"`, `'BETWEEN 1 AND 5'`. The
362
+ table-level `sql` and the unique `where` are complete expressions over the
363
+ **physical (snake_case) column names**: `product_id`, not `productId`.
364
+
365
+ **Nothing is translated per dialect.** The SQL must be valid for your
366
+ database. `num_nonnulls(a, b, c) = 1` works on Postgres only. On D1, write
367
+ `(a IS NOT NULL) + (b IS NOT NULL) + (c IS NOT NULL) = 1`. An invalid
368
+ expression fails when the migration is applied, not at compile time.
369
+
370
+ **Names.** A column check is named `<table>_<column>_check`. A table-level
371
+ check needs an explicit `name` that matches `/^[A-Za-z_][A-Za-z0-9_]*$/`. The
372
+ name can be at most 63 characters, because Postgres truncates longer
373
+ identifiers. It must also differ from every other check, unique and index name
374
+ on the table. A column takes one `.check()`: combine conditions with `AND`,
375
+ or use a table-level check.
376
+
377
+ **Compile errors instead of silent drops.** The compiler reads these options
378
+ from source, and it fails the compile on any of the following:
379
+
380
+ - a value that isn't a literal
381
+ - an unknown key
382
+ - `where` together with `whereNotDeleted`
383
+ - `nullsNotDistinct` on a partial unique
384
+ - `whereNotDeleted` on a table without `...q.softDelete()`
385
+ - `nullsNotDistinct` in a SQLite/D1 project, since SQLite always treats NULLs
386
+ as distinct
387
+
388
+ **Enforced by the database.** CHECK is not part of the request validator. A
389
+ violating write reaches the database and comes back as
390
+ `400 DB_CHECK_VIOLATION` naming the constraint. A unique collision comes back
391
+ as `409 DB_UNIQUE_VIOLATION`. See [Errors](/api/errors). Mirror a check at the
392
+ edge (e.g. `maxLength`) when you want a field-level validation message
393
+ instead.
394
+
395
+ The Postgres-only options, as a fragment:
396
+
397
+ ```typescript
398
+ // Postgres (Neon / PlanetScale Postgres) only
399
+ check: [{ name: 'contacts_one_channel', sql: 'num_nonnulls(email, phone, address) = 1' }],
400
+ unique: [{ columns: ['organizationId', 'externalRef'], nullsNotDistinct: true }],
401
+ ```
402
+
403
+ #### Unique constraints and soft delete
404
+
405
+ A soft-deleted row is still a row. A plain unique on `(organizationId, sku)`
406
+ keeps counting it, so after `DELETE /line_items/:id` the same SKU can't be
407
+ created again. The insert returns `409 DB_UNIQUE_VIOLATION` against a row the
408
+ caller can no longer see. Column-level `.unique()` has the same problem.
409
+
410
+ On a soft-delete table, make the unique **partial**. `whereNotDeleted: true`
411
+ adds `WHERE "deleted_at" IS NULL`, using the table's actual soft-delete column
412
+ under your naming convention. Uniqueness then holds among live rows only, and
413
+ a deleted value can be reused. Restoring a soft-deleted row whose value a live
414
+ row has since taken fails with a unique violation. That is the correct
415
+ outcome, because the two rows would otherwise collide.
416
+
417
+ **ON CONFLICT.** Generated CRUD, `PUT` and batch upsert don't use `ON
418
+ CONFLICT`: they look the row up by id and then insert or update, so partial
419
+ uniques need nothing from them. An action that upserts against a partial unique
420
+ with Drizzle's `onConflictDoUpdate` / `onConflictDoNothing` must repeat the
421
+ predicate as `targetWhere`. Postgres and SQLite only match a partial index to
422
+ a conflict target that carries its `WHERE`:
423
+
424
+ ```typescript
425
+ await db.insert(lineItems).values(row).onConflictDoUpdate({
426
+ target: [lineItems.organizationId, lineItems.sku],
427
+ targetWhere: sql`"deleted_at" IS NULL`,
428
+ set: { quantity: row.quantity },
429
+ });
430
+ ```
431
+
220
432
  ## Drizzle interop
221
433
 
222
434
  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 +1065,56 @@ Do this even when a column name appears obvious, such as `sessionId` beside a
853
1065
  relationship might be missing; it is not enough evidence to silently invent
854
1066
  one. CMS-ready schemas state the relationship explicitly.
855
1067
 
1068
+ ### Self-references
1069
+
1070
+ A column that points at another row of the **same** table — a parent folder,
1071
+ the version a document replaces — uses `.references('self')`. It targets the
1072
+ table's own `id`:
1073
+
1074
+ ```typescript
1075
+ // quickback/features/folders/folders.ts
1076
+ import { feature, q } from '@quickback/compiler';
1077
+
1078
+ export default feature('folders', {
1079
+ columns: {
1080
+ id: q.id(),
1081
+ name: q.text().required(),
1082
+ parentId: q.text().optional().references('self', { onDelete: 'set null' }),
1083
+ organizationId: q.scope('organization'),
1084
+ ...q.audit(),
1085
+ ...q.softDelete(),
1086
+ },
1087
+ read: { access: { roles: ['member'] } },
1088
+ create: { access: { roles: ['member'] } },
1089
+ update: { access: { roles: ['member'] } },
1090
+ });
1091
+ ```
1092
+
1093
+ `() => folders.id` cannot work here: inside `feature()` there is no `folders`
1094
+ binding. In the [two-export form](#qtable--definetable--the-expanded-form)
1095
+ the binding exists, but a bare `() => folders.id` inside its own initializer
1096
+ is a TypeScript cycle (TS7022/TS7024) in your editor and in `quickback check`.
1097
+ Either use `'self'` there too, or annotate the thunk's return type the way
1098
+ Drizzle does: `.references((): AnyQuickbackColumn => folders.id)`, with
1099
+ `type AnyQuickbackColumn` imported from `@quickback/compiler`. All three
1100
+ spellings generate the same schema.
1101
+
1102
+ A self-reference is a normal FK everywhere else:
1103
+
1104
+ - **Writes** check it through the table's **own** firewall, like any
1105
+ [FK referential check](/define/firewall#foreign-key-referential-checks): a
1106
+ row can't point at another tenant's row or a soft-deleted one. `null`
1107
+ detaches the row.
1108
+ - **Reads** resolve the parent's display label (`parent_label` on
1109
+ `GET /:id` and the list) through the same firewall, and the CMS renders the column as a picker over the same
1110
+ table.
1111
+ - **Cycles are not refused.** A row may point at itself, and A → B → A passes
1112
+ too: each write checks one hop. If your data must stay a tree, enforce that
1113
+ in an [action](/define/actions) or a [trigger](/define/triggers).
1114
+ - A batch create checks parents that exist **before** the batch. A record
1115
+ can't name a sibling from the same batch as its parent; create the parent
1116
+ first.
1117
+
856
1118
  The legacy resource-level `references: { vendorId: "contact" }` map can override
857
1119
  schema-registry target metadata for an alias, but it does not create a database
858
1120
  foreign key. Prefer `.references(() => contacts.id)` whenever the target is a
@@ -862,7 +1124,7 @@ rows live in `AUTH_DB`, outside the feature database.
862
1124
 
863
1125
  ## Input Hints
864
1126
 
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:
1127
+ 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
1128
 
867
1129
  {/* 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
1130
  ```typescript
@@ -939,7 +1201,8 @@ create a database foreign-key constraint. On Neon, use
939
1201
  for fully qualified cross-schema or composite constraints that cannot be
940
1202
  declared alongside a table. The ordered source and target column tuples must
941
1203
  have equal arity, and the referenced target tuple must have a matching unique
942
- or primary-key constraint before the foreign key migration runs.
1204
+ or primary-key constraint before the foreign key migration runs. A partial
1205
+ unique (`where` / `whereNotDeleted`) does not qualify as an FK target.
943
1206
 
944
1207
  Use these constraints for relational integrity only. Authorization, pass
945
1208
  consumption, state transitions, and other business logic belong in the API
@@ -1006,7 +1269,9 @@ export const jobs = pgTable('jobs', {
1006
1269
  |---------|--------|------------|
1007
1270
  | Boolean | `integer({ mode: 'boolean' })` | `boolean()` |
1008
1271
  | 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 |
1272
+ | 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 |
1273
+ | Exact decimal | `q.decimal()` lowers to `TEXT` (not sortable or range-filterable) | `numeric(p, s)` |
1274
+ | Date | `q.date()` lowers to `TEXT` `YYYY-MM-DD` | `date` |
1010
1275
  | Auto-increment | `integer().primaryKey()` | `serial()` |
1011
1276
  | UUID | `text()` | `uuid()` |
1012
1277
 
@@ -352,23 +352,36 @@ provider signed, never over re-serialised JSON.
352
352
  {/* doc-compile: skip — excerpt: `decryptValue` and the `connections` table live in the generated project; the fence shows the shape only. */}
353
353
  ```ts title="quickback/features/comms/actions/resendEvents.ts"
354
354
  import { z } from "zod";
355
- import { defineAction } from "../.quickback/define-action";
355
+ import { eq } from "drizzle-orm";
356
+ import { defineAction, ActionError } from "../.quickback/define-action";
356
357
  import { decryptValue } from "../../../../src/lib/encryption";
358
+ import { connections } from "../connections";
357
359
 
358
360
  export default defineAction({
359
361
  description: "Per-org Resend events — secret lives on the connection row",
360
- path: "/resend/events/:orgId",
362
+ path: "/resend/events/:connectionId",
361
363
  method: "POST",
362
364
  access: { roles: ["PUBLIC"] },
365
+ // A webhook carries no session, so no org claim: the scoped `db` reads
366
+ // nothing from an org-scoped table. Look the org up with `unsafeDb`, then
367
+ // pin every later query to it with `scopeTo`. `crossTenant: false` — the
368
+ // default (true) requires a sysadmin session and would 403 every delivery.
369
+ unsafe: { reason: "Resend webhook — tenant resolved from the connection row", crossTenant: false },
363
370
  rawBody: true,
364
371
  input: z.object({ type: z.string(), data: z.record(z.unknown()) }),
365
- execute: async ({ c, env, db, rawBody, input }) => {
366
- const orgId = c.req.param("orgId");
367
- const row = await db.query.connections.findFirst({ where: (t, { eq }) => eq(t.organizationId, orgId) });
372
+ execute: async ({ c, env, unsafeDb, rawBody, input }) => {
373
+ const [conn] = await unsafeDb.select().from(connections)
374
+ .where(eq(connections.id, c.req.param("connectionId")));
375
+ if (!conn) throw new ActionError("Unknown connection", "NOT_FOUND", 404);
376
+
368
377
  // ctx.crypto is hydrated for authenticated requests only — a PUBLIC
369
378
  // action reads an .encrypted() column through decryptValue directly.
370
- const secret = await decryptValue(env, db, orgId, row.signingSecret);
371
- // verify `rawBody` + the provider's signature headers with `secret`; throw a 401 ActionError on failure
379
+ const secret = await decryptValue(env, unsafeDb, conn.organizationId, conn.signingSecret);
380
+ // verify `rawBody` + the provider's signature headers with `secret`;
381
+ // throw a 401 ActionError on failure — BEFORE touching any tenant data.
382
+
383
+ const db = unsafeDb.scopeTo({ organizationId: conn.organizationId });
384
+ // every query on `db` now carries that org's firewall; inserts are stamped with it
372
385
  return { ok: true, type: input.type };
373
386
  },
374
387
  });