@quickback-dev/cli 0.47.6 → 0.47.8

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.
@@ -0,0 +1,169 @@
1
+ # Triggers - Postgres-Style Table Triggers
2
+
3
+ Run logic when rows change — Postgres-style `before`/`after` triggers on `insert`/`update`/`delete`, declared per table.
4
+
5
+ Each trigger lowers one of two ways, and the compiler reports which:
6
+
7
+ | You write | Lowers to | Fires on |
8
+ |---|---|---|
9
+ | `sql:` | A real SQLite `CREATE TRIGGER` in your migrations | **Every** write path — REST, actions, queue handlers, cron, raw SQL. Atomic with the write. |
10
+ | `handler:` | An application hook at the audit-wrapper write chokepoint | Writes through the wrapped `db` — REST CRUD and actions. **Not** queue handlers, cron, or raw SQL. |
11
+
12
+ There is no auto-translation between the lanes: SQL bodies stay SQL, functions stay functions. Pick the lane by what the trigger must guarantee.
13
+
14
+ ## Basic Usage
15
+
16
+ ```typescript
17
+ // features/invoices/invoices.ts
18
+ import { feature, q } from '@quickback/compiler';
19
+
20
+ export default feature('invoices', {
21
+ columns: {
22
+ id: q.id(),
23
+ title: q.text({ maxLength: 200 }).required(),
24
+ notes: q.text({ maxLength: 2000 }).optional(),
25
+ total: q.int().default(0).required(),
26
+ status: q.enum(['draft', 'sent', 'paid']).default('draft').required(),
27
+ organizationId: q.scope('organization'),
28
+ },
29
+ read: { access: { roles: ['member'] } },
30
+ create: { access: { roles: ['member'] } },
31
+ update: { access: { roles: ['member'] } },
32
+ delete: { access: { roles: ['member'] }, mode: 'soft' },
33
+
34
+ triggers: {
35
+ beforeInsert: [
36
+ {
37
+ name: 'guardTotals',
38
+ handler: ({ values }) => {
39
+ if (values.total < 0) throw new Error('total must be >= 0');
40
+ return { notes: values.notes ?? 'created' }; // merge into the write
41
+ },
42
+ },
43
+ ],
44
+ afterInsert: [
45
+ {
46
+ // SQL lane — fires for raw SQL too, atomic with the insert
47
+ name: 'stampNotes',
48
+ sql: `UPDATE invoices SET notes = NEW.title WHERE id = NEW.id;`,
49
+ },
50
+ ],
51
+ beforeUpdate: [
52
+ {
53
+ // The universal-enforcement shape: WHEN guard + RAISE(ABORT)
54
+ name: 'lockPaid',
55
+ when: `OLD.status = 'paid' AND NEW.status != 'paid'`,
56
+ sql: `SELECT RAISE(ABORT, 'paid invoices cannot be reopened');`,
57
+ },
58
+ ],
59
+ },
60
+ });
61
+ ```
62
+
63
+ Events: `beforeInsert`, `afterInsert`, `beforeUpdate`, `afterUpdate`, `beforeDelete`, `afterDelete`. Each event takes an array of named triggers; names must be unique per event.
64
+
65
+ ## SQL triggers (`sql:`)
66
+
67
+ The compiler wraps your statements in a `CREATE TRIGGER` named
68
+ `qb_trg_<table>_<event>_<name>` and ships it in the journaled features
69
+ migration — content-addressed, so an unchanged trigger set produces no new
70
+ migration, and removing a trigger from config drops it from the database on
71
+ the next migrate.
72
+
73
+ - Write **bare, `;`-terminated statements** — the compiler owns the
74
+ `BEGIN`/`END` frame. (It emits the frame uppercase; lowercase `begin`
75
+ breaks remote D1's statement splitter even though local D1 accepts it.)
76
+ - `OLD.column` / `NEW.column` references use **SQL column names**
77
+ (`deleted_at`, not `deletedAt`) and are validated against the table at
78
+ compile time.
79
+ - Optional `when:` is a SQL expression guard (`WHEN` clause).
80
+ - To reject a write, `SELECT RAISE(ABORT, 'message');` — this is the only
81
+ trigger form that blocks *every* write path, including raw SQL.
82
+ - SQL triggers run inside the triggering statement — the only
83
+ transactional option on D1, which has no `db.transaction()`.
84
+
85
+ Currently supported on `cloudflare-d1` only; declaring `sql:` triggers on
86
+ another database provider is a compile error.
87
+
88
+ ### Soft-delete mapping
89
+
90
+ On soft-delete tables (the default), `*Delete` events map to the
91
+ soft-delete *transition* — the compiler emits an
92
+ `AFTER UPDATE OF "deleted_at" ... WHEN NEW."deleted_at" IS NOT NULL AND
93
+ OLD."deleted_at" IS NULL` trigger, plus a plain `AFTER DELETE` variant so
94
+ raw-SQL hard deletes are still covered. `*Update` events get the inverse
95
+ guard, so a soft delete fires delete triggers exactly once and never
96
+ double-fires as an update.
97
+
98
+ ## Handler triggers (`handler:`)
99
+
100
+ Handlers run at the same write chokepoint that powers audit stamping and
101
+ Live Views, with full application context:
102
+
103
+ ```typescript
104
+ handler: ({ table, op, values /* before */, row /* after */, ctx, db, env }) => { ... }
105
+ ```
106
+
107
+ - **`before*` hooks are synchronous.** Return a partial object to merge
108
+ into the write payload, or throw to reject — the write never executes and
109
+ the request gets a structured `TRIGGER_REJECTED` (422) error. Audit
110
+ fields (`createdBy`, `modifiedAt`, …) are re-stamped after hooks run and
111
+ cannot be forged.
112
+ - **`after*` hooks run once per affected row and are awaited** before the
113
+ write's promise resolves. They may be `async`. A throw surfaces as
114
+ `TRIGGER_AFTER_FAILED` (500) with `details.committed: true` — the row was
115
+ already persisted (no transactions on D1), so clients must not blind-retry.
116
+ - Handlers must be **inline arrow/function expressions**. Imports they
117
+ reference are hoisted into the generated registry, and each table's
118
+ drizzle object is auto-imported under its authored name — so this works
119
+ as written:
120
+
121
+ ```typescript
122
+ import { eq } from 'drizzle-orm';
123
+
124
+ // ...
125
+ afterUpdate: [
126
+ {
127
+ name: 'syncNotes',
128
+ handler: async ({ row, db }) => {
129
+ await db.update(invoices)
130
+ .set({ notes: `updated: ${row.title}` })
131
+ .where(eq(invoices.id, row.id));
132
+ },
133
+ },
134
+ ],
135
+ ```
136
+
137
+ `after*` hooks only receive rows when the write chain used `.returning()`
138
+ — generated CRUD routes and actions do.
139
+
140
+ ### Recursion
141
+
142
+ Trigger cascades are bounded in every lane:
143
+
144
+ - **Handler hooks**: the `db` a hook receives is re-wrapped at depth + 1.
145
+ A cascade deeper than 5 levels (a hook's write firing hooks that write
146
+ again, …) throws with the table/op that exceeded the cap.
147
+ - **SQL triggers**: SQLite's `recursive_triggers` pragma defaults off — a
148
+ trigger cannot re-enter itself, directly or through a cycle.
149
+
150
+ ### Coverage — read the compile report
151
+
152
+ Handler hooks do **not** fire for queue handlers, cron jobs, or raw SQL.
153
+ The compiler emits a per-trigger lowering report and warns at compile time
154
+ when a `before*` handler is used as a guard — if a rule must hold for every
155
+ write path, use the `sql:` lane with `RAISE(ABORT)`.
156
+
157
+ ## Choosing a lane
158
+
159
+ | Need | Use |
160
+ |---|---|
161
+ | Invariant that must hold universally (raw SQL included) | `sql:` with `RAISE(ABORT)` |
162
+ | Denormalized columns, counters, tombstones | `sql:` |
163
+ | Validation/derivation with application logic | `before*` `handler:` |
164
+ | Side-effects after a write (notify, write related rows) | `after*` `handler:` |
165
+ | Atomic with the write (D1 has no transactions) | `sql:` only |
166
+
167
+ Planned (not yet available — declaring them is a compile error rather than
168
+ a silent no-op): `async: true` queue-dispatched after-hooks with retries,
169
+ and `withOld: true` previous-row access on update/delete hooks.