@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
@@ -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
  });
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.20",
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",
@@ -264,9 +264,27 @@ The action context's `db` is a Drizzle wrapper that:
264
264
  - **Does** route soft-delete `delete()` calls to a `deletedAt` / `deletedBy` UPDATE.
265
265
  - **Does** auto-populate scope columns on `insert`: any `q.scope()` column (and firewall-declared org/owner/team columns) is filled from ctx — `organizationId` ← `ctx.activeOrgId`, `ownerId` ← `ctx.userId`, etc. Audit fields (`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy`) are hard-stamped by the audit wrapper; caller-supplied values for them are dropped.
266
266
  - **Does NOT** fill ordinary business columns — anything that isn't a scope or audit column is exactly what you pass to `.values({...})`.
267
+ - **Refuses** Drizzle's relational API (`db.query.<table>.findFirst/findMany`, `with:`) — it can't be firewalled, so it's a compile error. Use `db.select()` joins.
267
268
 
268
269
  For unscoped writes (cross-tenant support, platform admin), use the `unsafe:` object form on the action — it forces an audit reason and gates on platform admin role.
269
270
 
271
+ ## Relationships between tables
272
+
273
+ There is no Drizzle `relations()` in feature code — never author or generate it. Relationships are:
274
+
275
+ | Shape | Declare |
276
+ |---|---|
277
+ | Belongs-to (post → author) | `authorId: q.text().required().references(() => users.id)` — DB constraint, `Id` type brand, CMS typeahead + labels. Cross-feature target: `import users from "../users/users"`. |
278
+ | Embed the parent on reads | `read: { include: ["authorId"] }` → `GET /posts?include=authorId` (top-level `included` map, depth 1, target's access/firewall/masking apply) |
279
+ | Owned children (order → line items) | `owns: { lineItems: { table: "orderLineItems", fk: "orderId" } }` — atomic nested writes via changesets |
280
+ | Embed owned children on reads | `read: { include: ["lineItems"] }` → `GET /orders/:id?include=lineItems` |
281
+ | Non-owned has-many (user → posts) | FK on the child only; clients call `GET /posts?userId=…` (or `defineBundle` for many lists in one trip). No inline embed. |
282
+ | Value object with no identity (address) | `q.json()` |
283
+
284
+ Never `.references()` a Better Auth id (`userId`, `organizationId`, `memberId`) — auth rows live in `AUTH_DB`. `include` targets must have role-only `read.access` (record-aware targets are a compile error), so don't add every FK by reflex.
285
+
286
+ Details: `quickback docs define/schema` (References), `quickback docs define/read` (Aggregate Reads), `quickback docs define/changesets`.
287
+
270
288
  ## Error handling in actions
271
289
 
272
290
  To return a clean 4xx from an action, throw `ActionError` — the route handler catches it by name and returns `{ error, code, details }` with your status:
@@ -243,7 +243,7 @@ export default defineAction({
243
243
  access: { roles: ['PUBLIC'] },
244
244
  unsafe: {
245
245
  reason: 'Inbound mail webhook — tenant derived from mailbox record',
246
- targetScope: 'organization',
246
+ crossTenant: false, // the default (true) requires a sysadmin session — an anonymous webhook would 403
247
247
  },
248
248
  input: z.object({ mailboxId: z.string(), body: z.string() }),
249
249
  async execute({ unsafeDb, input }) {
@@ -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
@@ -44,7 +44,8 @@ Each resource table exposes:
44
44
 
45
45
  Column types follow the wire, not the storage: `q.bool()` and
46
46
  `integer(..., { mode: "boolean" })` are `boolean`, `integer(..., { mode: "timestamp" })`
47
- and `q.timestamp()` are ISO `string`, `q.json()` is `unknown`, enum columns
47
+ and `q.timestamp()` are ISO `string`, `q.json()` is `unknown` unless it is given a
48
+ [value schema](/define/schema#typed-json-columns), enum columns
48
49
  are literal unions, and nullable columns add `| null`.
49
50
 
50
51
  Primary and foreign keys are branded by default. That makes accidentally passing a candidate ID where a job ID is required a TypeScript error, while both values remain ordinary strings or numbers at runtime.
@@ -220,6 +220,7 @@ namespace parameters.
220
220
  |--------|----------|-------------|
221
221
  | `description` | Yes | Human-readable description of the action |
222
222
  | `input` | Yes | Zod schema for request validation |
223
+ | `query` | No | Non-GET only. An inline `z.object({...})` of query-string parameters, validated apart from the JSON body and passed to `execute` as `query`. See [Query parameters on non-GET actions](/define/actions/record-and-standalone#query-parameters-on-non-get-actions) |
223
224
  | `output` | No | Portable Zod schema for the JSON success response. Generates action output types and constrains `execute`'s result. |
224
225
  | `access` | Yes | Access control (roles, record conditions, or function) |
225
226
  | `execute` | Yes | Inline async arrow function (`async (ctx) => { … }`) |
@@ -166,10 +166,25 @@ Fail-closed, one rule:
166
166
  The compile fails if the named action is missing, bound to a different table,
167
167
  the wrong shape (create needs a standalone `path:` equal to the collection URL;
168
168
  update/delete need a record-based action with no `path:`), declares a
169
- conflicting `method`, is already mapped to another verb, or the table also
170
- declares `owns` (changeset dispatch lives on the stock handler). `read.action`
169
+ conflicting `method`, or is already mapped to another verb. `read.action`
171
170
  is not supported.
172
171
 
172
+ ### Mapping a verb on an `owns` root
173
+
174
+ A table that declares [`owns`](/define/changesets) can map `create` or `update`
175
+ too. The action is then the only write path for that verb:
176
+
177
+ - A request to that verb with `Content-Type: application/vnd.quickback.changeset+json`
178
+ gets a `415`. It doesn't bypass the action, and the action's `input` doesn't
179
+ silently drop the child ops.
180
+ - OpenAPI documents only `application/json` for that operation. The unmapped
181
+ verb keeps its changeset lane.
182
+ - The changeset engine is still generated, so the action can take child
183
+ changes in its own `input` and delegate the aggregate write to
184
+ [`apply<Singular>Changeset`](/define/changesets#calling-it-from-authored-code)
185
+ (set `singular:` on the root if the default name reads wrong).
186
+ The root's crud access, guards and firewall still run inside it.
187
+
173
188
  ## The rest of this section
174
189
 
175
190
  - **[Defining actions](/define/actions/defining)** — the action file, its configuration options, protected fields, and refs
@@ -420,3 +420,46 @@ imply "this writes data" — it's the right method whenever the request body is
420
420
  load-bearing. Use the response shape (`responseType: "json"`, or just the data
421
421
  your handler returns) to convey read semantics; HTTP method choice is about
422
422
  input transport, not action intent.
423
+
424
+ ### Query parameters on non-GET actions
425
+
426
+ A POST, PUT, PATCH or DELETE action can take query-string parameters as well as
427
+ its JSON body. Declare them with `query:`. They are validated apart from
428
+ `input` and passed to `execute` as `query`. This also works when the body is a
429
+ bare array:
430
+
431
+ ```typescript
432
+ // features/journal-entries/actions/bulkCreate.ts — POST /bulk/journal-entries?expand=lines
433
+ import { z } from "zod";
434
+ import { defineAction } from "../.quickback/define-action";
435
+
436
+ export default defineAction({
437
+ description: "Create journal entries in bulk; ?expand=lines includes their lines.",
438
+ method: "POST",
439
+ path: "/bulk/journal-entries",
440
+ input: z.array(z.object({ memo: z.string().optional() })),
441
+ query: z.object({
442
+ expand: z.enum(["lines"]).optional(),
443
+ limit: z.coerce.number().int().max(100).optional(),
444
+ }),
445
+ access: { roles: ["admin"] },
446
+ async execute({ input, query }) {
447
+ // query is { expand?: "lines", limit?: number } — fully typed.
448
+ return { count: input.length, expand: query.expand ?? null };
449
+ },
450
+ });
451
+ ```
452
+
453
+ Each property is documented as an `in: query` parameter in `openapi.json`, so
454
+ it also shows up in `api-types.gen.ts`, in `quickback.gen.ts` as
455
+ `actions.<name>.Query`, and on the MCP tool. A bad value is a `400`, the same
456
+ as a bad body.
457
+
458
+ Rules, all checked at compile time:
459
+
460
+ - `query` must be an inline `z.object({...})` built from `z` and literals. The compiler converts it to JSON Schema itself.
461
+ - Not on GET actions. Their `input` already comes from the query string.
462
+ - Not together with `bulkVariant`.
463
+
464
+ Query values arrive as strings, and repeated keys become arrays. Use
465
+ `z.coerce.number()` / `z.coerce.boolean()` for typed primitives.
@@ -10,6 +10,12 @@ the same generated `WHERE` clause the table's CRUD routes use:
10
10
  | `SELECT` | the table's firewall (org / owner / team / scope / `via:` arms) AND soft-delete filter |
11
11
  | `UPDATE` / `DELETE` | the same firewall `WHERE`, AND-merged with yours |
12
12
  | `INSERT` | every required claim column the firewall binds (e.g. `organizationId` from `ctx.activeOrgId`), overwriting any value you passed |
13
+ | `INSERT … onConflictDoUpdate` | the firewall AND-merged into `setWhere` — a conflict with a row the caller can't update (another tenant's id) is a no-op, never an overwrite |
14
+
15
+ The firewall is set on the builder when you call `.from()` / `.set()` /
16
+ `.delete()`, so every executor gets it: `await`, `.all()`, `.get()`,
17
+ `.values()`, `.run()`, `.execute()`, `.prepare()`, and the builder embedded as
18
+ a subquery (`inArray(col, db.select(...).from(t))`).
13
19
 
14
20
  It is not a guess from column names. `any:` groups, `optional` arms, scope
15
21
  (`ctx.scope.*`) and `via:` relationship arms, the null-claim deny, the
@@ -121,9 +121,9 @@ to `"v2"` only if you also want the `/api/v2` prefix.
121
121
  id — an unresolvable parent lid is a pointer-carrying **400**, never a
122
122
  silent re-parent onto the root.
123
123
  - `Prefer: return=minimal` omits `root` from the response. v1 representation
124
- is **root-row-only** (re-read through the root's masking) — nested aggregate
125
- reads are the phase-2 `?include=` reader; use [`defineView`
126
- includes](/define/read) today.
124
+ is **root-row-only** (re-read through the root's masking) — read the
125
+ aggregate back with `?include=<ownsRelation>` (see [read → Aggregate
126
+ Reads](/define/read#aggregate-reads)).
127
127
 
128
128
  ### Headers
129
129
 
@@ -430,7 +430,22 @@ it; `meta.transactional` reports the actual guarantee (same contract as
430
430
  The engine is exported per root as `apply<Singular>Changeset` — the seam
431
431
  authored actions delegate through when they still need residue logic
432
432
  (preconditions, server-side transforms, notifications) around the aggregate
433
- write:
433
+ write.
434
+
435
+ `<Singular>` comes from the table name with a trailing `s` dropped, so
436
+ `projects` gives `applyProjectChangeset`. For a name that rule gets wrong,
437
+ declare `singular:` on the root to add a correctly named export:
438
+
439
+ ```ts
440
+ // journalEntries would otherwise only export applyJournalEntrieChangeset
441
+ singular: "journalEntry", // adds applyJournalEntryChangeset
442
+ owns: { /* ... */ },
443
+ ```
444
+
445
+ The default name is still exported, so existing imports keep working.
446
+ `singular` must be camelCase, and it's a compile error on a table that doesn't
447
+ declare `owns`.
448
+
434
449
 
435
450
  {/* doc-compile: skip — the fence imports `../projects.changeset`, a module the compiler only generates for a root that declares `owns`, which this fence does not carry, so the import cannot resolve. `description` / `input` / `access` are elided to `// ...` on purpose — the point is the delegation seam. */}
436
451
  ```ts title="quickback/features/projects/actions/importBoard.ts"
@@ -450,6 +465,11 @@ export default defineAction({
450
465
  });
451
466
  ```
452
467
 
468
+ This is also how a root that maps `create.action` or `update.action` writes its
469
+ children: the mapped verb has no changeset media type of its own (it answers
470
+ `415`), so its action delegates here. See
471
+ [Mapping a verb on an `owns` root](/define/actions#mapping-a-verb-on-an-owns-root).
472
+
453
473
  **There is no trusted mode.** The auth assertion, cross-tenant guard, and the
454
474
  root's own pre-record access gate are the helper's first statements — an
455
475
  authored action whose action-level access is looser than the root's crud
@@ -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