@quickback-dev/cli 0.66.11 → 0.66.12

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 (53) hide show
  1. package/dist/commands/deploy.d.ts.map +1 -1
  2. package/dist/commands/deploy.js +14 -0
  3. package/dist/commands/deploy.js.map +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/lib/api-client.d.ts +8 -0
  6. package/dist/lib/api-client.d.ts.map +1 -1
  7. package/dist/lib/api-client.js.map +1 -1
  8. package/dist/lib/deployment-target.d.ts +29 -0
  9. package/dist/lib/deployment-target.d.ts.map +1 -1
  10. package/dist/lib/deployment-target.js +26 -2
  11. package/dist/lib/deployment-target.js.map +1 -1
  12. package/dist/lib/deployment-target.test.js +37 -1
  13. package/dist/lib/deployment-target.test.js.map +1 -1
  14. package/dist/lib/migrations/drizzle.test.js +1 -1
  15. package/dist/lib/migrations/drizzle.test.js.map +1 -1
  16. package/dist/lib/migrations/plan.js +6 -0
  17. package/dist/lib/migrations/plan.js.map +1 -1
  18. package/dist/lib/migrations/postprocessors/better-auth-upgrade.d.ts +16 -5
  19. package/dist/lib/migrations/postprocessors/better-auth-upgrade.d.ts.map +1 -1
  20. package/dist/lib/migrations/postprocessors/better-auth-upgrade.js +32 -102
  21. package/dist/lib/migrations/postprocessors/better-auth-upgrade.js.map +1 -1
  22. package/dist/lib/migrations/postprocessors/index.d.ts.map +1 -1
  23. package/dist/lib/migrations/postprocessors/index.js +73 -1
  24. package/dist/lib/migrations/postprocessors/index.js.map +1 -1
  25. package/dist/lib/migrations/postprocessors/index.test.js +95 -0
  26. package/dist/lib/migrations/postprocessors/index.test.js.map +1 -1
  27. package/dist/lib/migrations/postprocessors/trigger-sql.d.ts +18 -0
  28. package/dist/lib/migrations/postprocessors/trigger-sql.d.ts.map +1 -1
  29. package/dist/lib/migrations/postprocessors/trigger-sql.js +63 -0
  30. package/dist/lib/migrations/postprocessors/trigger-sql.js.map +1 -1
  31. package/dist/lib/migrations/types.d.ts +1 -1
  32. package/dist/lib/migrations/types.d.ts.map +1 -1
  33. package/dist/lib/migrations/types.js +1 -0
  34. package/dist/lib/migrations/types.js.map +1 -1
  35. package/dist/skill/docs/define/actions/scoped-db.md +3 -0
  36. package/dist/skill/docs/define/schema.md +58 -6
  37. package/dist/skill/docs/define/triggers.md +143 -20
  38. package/dist/skill/docs/platform/auth/index.md +37 -16
  39. package/dist/skill/docs/platform/auth/plugins/subscriptions.md +25 -5
  40. package/dist/skill/docs/platform/database/neon.md +115 -18
  41. package/dist/skill/docs/platform/database/planetscale-postgres.md +3 -3
  42. package/dist/skill/docs/platform/storage/r2.md +75 -8
  43. package/dist/skill/docs/tooling/output.md +49 -5
  44. package/package.json +2 -1
  45. package/src/skill/docs/define/actions/scoped-db.md +3 -0
  46. package/src/skill/docs/define/schema.md +58 -6
  47. package/src/skill/docs/define/triggers.md +143 -20
  48. package/src/skill/docs/platform/auth/index.md +37 -16
  49. package/src/skill/docs/platform/auth/plugins/subscriptions.md +25 -5
  50. package/src/skill/docs/platform/database/neon.md +115 -18
  51. package/src/skill/docs/platform/database/planetscale-postgres.md +3 -3
  52. package/src/skill/docs/platform/storage/r2.md +75 -8
  53. package/src/skill/docs/tooling/output.md +49 -5
@@ -59,4 +59,67 @@ export function composeTriggerMigrationSql(meta, previousNames) {
59
59
  }
60
60
  /** Journal tag shape for compiler-owned RLS migrations. */
61
61
  export const RLS_MIGRATION_TAG_RE = /^\d+_quickback_rls_[0-9a-f]+$/;
62
+ const TRIGGER_OBJECT_RE = /^-- quickback:trigger-object (\{.*\})$/gm;
63
+ export function extractTriggerObjectsFromSql(sql) {
64
+ const objects = [];
65
+ for (const m of sql.matchAll(TRIGGER_OBJECT_RE)) {
66
+ try {
67
+ const parsed = JSON.parse(m[1]);
68
+ if (typeof parsed.schema === 'string' &&
69
+ typeof parsed.table === 'string' &&
70
+ typeof parsed.trigger === 'string' &&
71
+ typeof parsed.fn === 'string') {
72
+ objects.push(parsed);
73
+ }
74
+ }
75
+ catch {
76
+ /* not ours */
77
+ }
78
+ }
79
+ return objects;
80
+ }
81
+ function composePgDropSection(objects) {
82
+ if (objects.length === 0)
83
+ return '';
84
+ const sorted = [...objects].sort((a, b) => a.schema.localeCompare(b.schema) ||
85
+ a.table.localeCompare(b.table) ||
86
+ a.trigger.localeCompare(b.trigger));
87
+ const seen = new Set();
88
+ const blocks = [];
89
+ for (const o of sorted) {
90
+ const key = `${o.schema}.${o.table}.${o.trigger}.${o.fn}`;
91
+ if (seen.has(key))
92
+ continue;
93
+ seen.add(key);
94
+ blocks.push(`DO $qb_drop$ BEGIN\n` +
95
+ ` IF to_regclass('"${o.schema}"."${o.table}"') IS NOT NULL THEN\n` +
96
+ ` EXECUTE 'DROP TRIGGER IF EXISTS "${o.trigger}" ON "${o.schema}"."${o.table}"';\n` +
97
+ ` END IF;\n` +
98
+ `END $qb_drop$;\n` +
99
+ `DROP FUNCTION IF EXISTS "${o.schema}"."${o.fn}"();`);
100
+ }
101
+ return blocks.join('\n');
102
+ }
103
+ const PG_MIGRATION_HEADER = `-- ═══════════════════════════════════════════════════════════════════
104
+ -- Quickback — table triggers migration (PostgreSQL)
105
+ -- Generated by @quickback/compiler; applied via the standard drizzle
106
+ -- journal, AFTER the schema migration and the RLS document. Content-
107
+ -- addressed: an unchanged trigger set produces no new migration.
108
+ --
109
+ -- Each declared trigger is a SECURITY INVOKER PL/pgSQL function plus the
110
+ -- trigger that calls it, so cross-table writes stay subject to RLS and
111
+ -- grants. Trigger drops are guarded on to_regclass: the preceding schema
112
+ -- migration may already have dropped the table. No CASCADE — an
113
+ -- unexpected dependency must fail loudly.
114
+ --
115
+ -- The \`-- quickback:trigger-object\` lines are the compiler's own record
116
+ -- of what this file created; the next migration reads them to compose its
117
+ -- DROP section. Do not edit them.
118
+ -- ═══════════════════════════════════════════════════════════════════
119
+ `;
120
+ export function composePgTriggerMigrationSql(meta, previousObjects) {
121
+ const drops = composePgDropSection([...previousObjects, ...(meta.objects ?? [])]);
122
+ const sections = [PG_MIGRATION_HEADER, drops, meta.createSql].filter((s) => s.trim().length > 0);
123
+ return `${sections.join('\n')}\n`;
124
+ }
62
125
  //# sourceMappingURL=trigger-sql.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"trigger-sql.js","sourceRoot":"","sources":["../../../../src/lib/migrations/postprocessors/trigger-sql.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAWH,+DAA+D;AAC/D,MAAM,CAAC,MAAM,wBAAwB,GAAG,oCAAoC,CAAC;AAE7E,6EAA6E;AAC7E,MAAM,CAAC,MAAM,yBAAyB,GAAG,yCAAyC,CAAC;AAEnF,MAAM,CAAC,MAAM,oBAAoB,GAAG,0BAA0B,CAAC;AAE/D;;;;GAIG;AACH,MAAM,UAAU,0BAA0B,CAAC,GAAW;IACpD,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,MAAM,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,kCAAkC,CAAC,EAAE,CAAC;QACjE,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACnB,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,MAAM,gBAAgB,GAAG;;;;;;;;;;;CAWxB,CAAC;AAEF;;;;GAIG;AACH,MAAM,UAAU,0BAA0B,CACxC,IAAiC,EACjC,aAAuB;IAEvB,MAAM,QAAQ,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG,aAAa,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAC/E,MAAM,KAAK,GAAG,QAAQ;SACnB,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,2BAA2B,CAAC,OAAO,oBAAoB,EAAE,CAAC;SACrE,IAAI,CAAC,IAAI,CAAC,CAAC;IACd,MAAM,QAAQ,GAAG,CAAC,gBAAgB,EAAE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AAE,CAAC,CAAC,CAAC,CAAC;IAClF,MAAM,QAAQ,GAAG,CAAC,mBAAmB,EAAE,KAAK,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IACjG,OAAO,GAAG,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;AACpC,CAAC"}
@@ -3,7 +3,7 @@ export declare const SUPPORTED_DRIZZLE_VERSION: "0.31.10";
3
3
  export declare const CLIENT_MIGRATION_TARGET_IDS: readonly ["features", "auth", "audit", "webhooks", "files"];
4
4
  export type ClientMigrationTargetId = (typeof CLIENT_MIGRATION_TARGET_IDS)[number];
5
5
  export type ClientMigrationDialect = 'sqlite' | 'postgresql';
6
- export declare const CLIENT_MIGRATION_POSTPROCESSORS: readonly ["update-journal", "reorder-pg-constraints", "harden-audit", "append-rls", "append-triggers", "d1-safety"];
6
+ export declare const CLIENT_MIGRATION_POSTPROCESSORS: readonly ["update-journal", "reorder-pg-constraints", "harden-audit", "append-rls", "append-triggers", "append-pg-triggers", "d1-safety"];
7
7
  export type ClientMigrationPostprocessor = (typeof CLIENT_MIGRATION_POSTPROCESSORS)[number];
8
8
  export interface ClientMigrationRenameHints {
9
9
  tables?: Record<string, string>;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/lib/migrations/types.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,iCAAiC,EAAG,CAAU,CAAC;AAC5D,eAAO,MAAM,yBAAyB,EAAG,SAAkB,CAAC;AAE5D,eAAO,MAAM,2BAA2B,6DAM9B,CAAC;AAEX,MAAM,MAAM,uBAAuB,GAAG,CAAC,OAAO,2BAA2B,CAAC,CAAC,MAAM,CAAC,CAAC;AACnF,MAAM,MAAM,sBAAsB,GAAG,QAAQ,GAAG,YAAY,CAAC;AAE7D,eAAO,MAAM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iB;IAChC,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,SAAS,MAAM,EAAE,CAAC;IACxB,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,WAAW,CAAC,EAAE,0BAA0B,CAAC;IACzC,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED,MAAM,WAAW,aAAa;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;;GAGG;AACH,MAAM,MAAM,sBAAsB,GAAG,CACnC,UAAU,EAAE,iBAAiB,KAC1B,OAAO,CAAC,aAAa,CAAC,CAAC;AAE5B,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,GAAG,UAAU,CAAC;CAC9B"}
@@ -13,6 +13,7 @@ export const CLIENT_MIGRATION_POSTPROCESSORS = [
13
13
  'harden-audit',
14
14
  'append-rls',
15
15
  'append-triggers',
16
+ 'append-pg-triggers',
16
17
  'd1-safety',
17
18
  ];
18
19
  //# sourceMappingURL=types.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/migrations/types.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,iCAAiC,GAAG,CAAU,CAAC;AAC5D,MAAM,CAAC,MAAM,yBAAyB,GAAG,SAAkB,CAAC;AAE5D,MAAM,CAAC,MAAM,2BAA2B,GAAG;IACzC,UAAU;IACV,MAAM;IACN,OAAO;IACP,UAAU;IACV,OAAO;CACC,CAAC;AAKX,MAAM,CAAC,MAAM,+BAA+B,GAAG;IAC7C,gBAAgB;IAChB,wBAAwB;IACxB,cAAc;IACd,YAAY;IACZ,iBAAiB;IACjB,WAAW;CACH,CAAC"}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/migrations/types.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,iCAAiC,GAAG,CAAU,CAAC;AAC5D,MAAM,CAAC,MAAM,yBAAyB,GAAG,SAAkB,CAAC;AAE5D,MAAM,CAAC,MAAM,2BAA2B,GAAG;IACzC,UAAU;IACV,MAAM;IACN,OAAO;IACP,UAAU;IACV,OAAO;CACC,CAAC;AAKX,MAAM,CAAC,MAAM,+BAA+B,GAAG;IAC7C,gBAAgB;IAChB,wBAAwB;IACxB,cAAc;IACd,YAAY;IACZ,iBAAiB;IACjB,oBAAoB;IACpB,WAAW;CACH,CAAC"}
@@ -149,6 +149,9 @@ restriction: a row that satisfies the arm is reachable even when the table
149
149
  firewall would not have matched it, and even when it is soft-deleted.
150
150
  Restrictions belong in `firewall`. The restrictive `<table>_deny_anon` and
151
151
  `<table>_principal_fence` policies remain the only arms that cap every lane.
152
+ (The fence is emitted precisely because this table declares a lane; a table
153
+ with no `databaseAccess` and no `access.principals` gets neither the fence nor
154
+ the principal arm of `deny_anon`, which blocks every principal just the same.)
152
155
 
153
156
  ### What the compiler refuses, and why
154
157
 
@@ -636,19 +636,71 @@ The six audit/soft-delete columns are **overwritten** by the runtime wrapper —
636
636
  `id` (when `generateId` is not `false`) is **rejected at the edge** instead: it is omitted from the `.strict()` Zod body schema, so a body carrying it is a `400 VALIDATION_ERROR`, and the guards `createable` allow-list backstops that. Nothing overwrites `id` at the insert — the Zod/guards boundary is the protection. Under
637
637
  [`allowClientIds: true`](/api/crud#client-supplied-ids-optimistic-updates) a strategy-shaped `id` is accepted on create only.
638
638
 
639
- ## Auto-Indexes
639
+ ## The default index set
640
640
 
641
- The compiler injects performance-critical indexes you'd otherwise have to author by hand. The pass runs after audit-field injection (so `deletedAt` is present) and is idempotent — if you already declared a matching index it's left alone.
641
+ Drizzle owns every index in a Quickback project. The compiler writes a default
642
+ set into your schema source before drizzle-kit reads it, so the indexes are
643
+ generated, diffed and dropped by the same journal as your tables — there is no
644
+ second emitter putting indexes in the security migration.
645
+
646
+ The pass runs after audit-field injection (so `deletedAt` and `createdAt` are
647
+ present) and is idempotent.
642
648
 
643
649
  | Trigger | Index | Why |
644
650
  |---------|-------|-----|
645
- | Tenant column (`organizationId` / `organisationId` / `userId`) + `deletedAt` | Composite `(<isolation_col>, deletedAt)` | Every list query filters by isolation AND `deletedAt IS NULL` — a composite index lets D1/SQLite prune both predicates in one btree walk. |
651
+ | Tenant column (`organizationId` / `organisationId` / `userId`) + `deletedAt` | Composite `(<isolation_col>, deletedAt)` | Every list query filters by isolation AND `deletedAt IS NULL` — a composite index lets the planner prune both predicates in one btree walk. |
646
652
  | Any FK column (`.references(() => other.id)`) | Single-column `(<fk_col>)` | SQLite/D1 don't auto-index FK columns, and the generated FK existence checks read by id on the parent. |
647
- | Any column that appears in a view's `read.query.sortable` allowlist (or `defaultSort`) | Single-column `(<col>)` | Sort scans go through an index instead of a full-table scan. |
653
+ | A filtered column — anything named `*status*` or `*type*`, the boolean flags (`isActive`, `isDefault`, …) and the date columns (`createdAt`, `startDate`, `endDate`, `expiresAt`, …) | Single-column `(<col>)` | These are what list endpoints filter and order on. |
654
+ | Any column in a view's `read.query.sortable` allowlist (or `defaultSort`) | Single-column `(<col>)` | Sort scans go through an index instead of a full-table scan. |
655
+
656
+ Entries are named `<table>_<col>_idx` (or `<table>_<col1>_<col2>_idx` for a
657
+ composite) and emitted into the table's Drizzle extras callback. The `index`
658
+ import is added to your schema's `drizzle-orm/<dialect>-core` import line if it
659
+ isn't already there.
660
+
661
+ ### Coverage — what suppresses a default index
662
+
663
+ A default index is skipped when a **non-partial** index already has its columns
664
+ as a **leading prefix**. So the tenant composite `(organizationId, deletedAt)`
665
+ suppresses a bare `(organizationId)` index, and an index you author yourself
666
+ suppresses the default on the same columns:
667
+
668
+ - **Leading prefix wins.** `(organizationId, deletedAt, status)` covers
669
+ `(organizationId)` and `(organizationId, deletedAt)`, but not `(status)` —
670
+ `status` is not a leading column.
671
+ - **Unique counts.** A `uniqueIndex` on the same leading columns serves the same
672
+ lookups, so it suppresses the non-unique default.
673
+ - **Partial covers nothing.** An index with `.where(...)` may exclude the rows
674
+ the default index exists for, so it never suppresses one.
675
+ - **Order modifiers are ignored.** `.on(t.status.desc())` still covers
676
+ `(status)`.
677
+
678
+ ### `...q.indexes(t)` — placing the defaults yourself
679
+
680
+ In a **Drizzle interop** table you can declare exactly where the default set
681
+ lands, the same way `...q.audit()` declares the audit columns:
682
+
683
+ {/* doc-compile: skip — illustrative fragment; the columns object is elided so the placeholder is the whole point. */}
684
+ ```typescript
685
+ import { pgTable, uniqueIndex } from "drizzle-orm/pg-core";
686
+ import { q } from "@quickback/compiler";
687
+
688
+ export const invoices = pgTable("invoices", {
689
+ // …columns
690
+ }, (t) => ({
691
+ ...q.indexes(t),
692
+ invoices_number_unique: uniqueIndex("invoices_number_unique").on(t.number),
693
+ }));
694
+ ```
648
695
 
649
- Indexes are emitted into the table's Drizzle extras callback (`(t) => ({ ... })`) and named `<table>_<col>_idx` (or `<table>_<col1>_<col2>_idx` for the composite). The `index` import is added to your schema's `drizzle-orm/<dialect>-core` import line if it isn't already there.
696
+ The spread is expanded in place at compile time into literal
697
+ `index(...).on(...)` entries and disappears from the emitted schema. Without it
698
+ the same entries are appended to the end of the callback and a compile warning
699
+ points you here — the emitted schema is identical either way.
650
700
 
651
- You can opt out of any auto-injected index by declaring your own with the same name or column set — the injector treats both as already-present and skips.
701
+ Tables authored with the `q` DSL (`feature()` / `q.table()`) don't take the
702
+ placeholder: the compiler writes their index callback, and `q.<col>().index()`
703
+ and `q.table(…, { indexes })` are the authoring controls there.
652
704
 
653
705
  ## Ownership Fields
654
706
 
@@ -6,10 +6,20 @@ Each trigger lowers one of two ways, and the compiler reports which:
6
6
 
7
7
  | You write | Lowers to | Fires on |
8
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. |
9
+ | `sql:` | A real database trigger in your migrations — a SQLite `CREATE TRIGGER` on D1, a `SECURITY INVOKER` PL/pgSQL function + trigger on Postgres | **Every** write path — REST, actions, queue handlers, cron, raw SQL. Atomic with the write. |
10
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
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.
12
+ Both lanes exist on every database provider, with the same contract.
13
+ `handler:` is the default and the business-logic lane. `sql:` is the
14
+ **invariant** lane: data rules that must hold on every write path, atomically
15
+ with the write — soft-delete mapping, counters, denormalized fields. SQL
16
+ triggers carry data rules, never business flows and never role logic; the
17
+ compiler's own audit-stamping triggers are the precedent.
18
+
19
+ There is no auto-translation between the lanes — SQL bodies stay SQL,
20
+ functions stay functions — and none between SQL **dialects** either. A `sql:`
21
+ body is authored in the target database's own dialect and validated against
22
+ it at compile time. See [Dialects](#dialects-a-sql-body-is-never-translated).
13
23
 
14
24
  ## Basic Usage
15
25
 
@@ -66,30 +76,116 @@ Events: `beforeInsert`, `afterInsert`, `beforeUpdate`, `afterUpdate`, `beforeDel
66
76
 
67
77
  ## SQL triggers (`sql:`)
68
78
 
69
- The compiler wraps your statements in a `CREATE TRIGGER` named
70
- `qb_trg_<table>_<event>_<name>` and ships it in the journaled features
79
+ The compiler owns the object names and ships the DDL in a journaled
71
80
  migration — content-addressed, so an unchanged trigger set produces no new
72
81
  migration, and removing a trigger from config drops it from the database on
73
82
  the next migrate.
74
83
 
75
- - Write **bare, `;`-terminated statements** — the compiler owns the
76
- `BEGIN`/`END` frame. (It emits the frame uppercase; lowercase `begin`
77
- breaks remote D1's statement splitter even though local D1 accepts it.)
84
+ What is the same on every provider:
85
+
86
+ - You write **bare, `;`-terminated statements**. The compiler owns the
87
+ surrounding frame — you never author `CREATE TRIGGER` (or, on Postgres,
88
+ `CREATE FUNCTION`).
78
89
  - `OLD.column` / `NEW.column` references use **SQL column names**
79
90
  (`deleted_at`, not `deletedAt`) and are validated against the table at
80
91
  compile time.
92
+ - Optional `when:` is a SQL expression guard (`WHEN` clause).
93
+ - SQL triggers run inside the triggering statement, so they are atomic with
94
+ the write, and a rejection rolls the whole statement back.
95
+ - Names are `qb_trg_<table>_<event-code>_<name>` and are the compiler's, not
96
+ yours.
97
+
98
+ ### Dialects — a `sql:` body is never translated
99
+
100
+ A `sql:` body is raw SQL for **your** database. The compiler validates it in
101
+ the target's dialect and fails the compile when it sees the other one; it
102
+ never rewrites a body to fit. Declaring `sql:` on a provider with neither
103
+ lane (anything that is not `cloudflare-d1` or a Postgres provider) is also a
104
+ compile error.
105
+
106
+ > A SQLite `RAISE(ABORT, ...)` in a project targeting Postgres is rejected with:
107
+ >
108
+ > > `RAISE(ABORT, ...)` is SQLite syntax and has no PL/pgSQL equivalent — this
109
+ > > project targets PostgreSQL. Reject the write with `RAISE EXCEPTION
110
+ > > 'message';` instead. Trigger bodies are never translated between dialects.
111
+ >
112
+ > Porting a project between D1 and Postgres means porting its `sql:` bodies by
113
+ > hand. That is deliberate: a silent translation of a rule that must hold on
114
+ > every write path is the last thing you want to be wrong about.
115
+
116
+
117
+ #### SQLite (`cloudflare-d1`)
118
+
119
+ The body is inlined into `CREATE TRIGGER ... BEGIN <body> END`.
120
+
121
+ - The compiler emits the `BEGIN`/`END` frame **uppercase**; lowercase `begin`
122
+ breaks remote D1's statement splitter even though local D1 accepts it. An
123
+ authored frame is rejected rather than double-wrapped.
81
124
  - Bare `CASE ... END` expressions, including nested cases, are supported.
82
125
  For example: `SELECT CASE WHEN NEW.total < 0 THEN RAISE(ABORT, 'invalid total') END;`.
83
- That `END` closes the expression; authored `BEGIN ... END` trigger frames
84
- are rejected.
85
- - Optional `when:` is a SQL expression guard (`WHEN` clause).
86
- - To reject a write, `SELECT RAISE(ABORT, 'message');` — this is the only
87
- trigger form that blocks *every* write path, including raw SQL.
88
- - SQL triggers run inside the triggering statement — the only
89
- transactional option on D1, which has no `db.transaction()`.
126
+ That `END` closes the expression.
127
+ - To reject a write: `SELECT RAISE(ABORT, 'message');`
128
+ - SQL triggers are the only transactional option on D1, which has no
129
+ `db.transaction()`.
130
+
131
+ #### PostgreSQL (`neon`, `planetscale-postgres`)
90
132
 
91
- Currently supported on `cloudflare-d1` only; declaring `sql:` triggers on
92
- another database provider is a compile error.
133
+ Postgres has no inline trigger body, so each declaration becomes **two**
134
+ compiler-owned objects in the `app` schema: a `RETURNS trigger` function
135
+ carrying your statements, and the trigger that calls it.
136
+
137
+ ```typescript
138
+ triggers: {
139
+ beforeInsert: [
140
+ {
141
+ // Before-row mutation: assign to NEW. The compiler adds `RETURN NEW`.
142
+ name: 'defaultNotes',
143
+ sql: `NEW."notes" := COALESCE(NEW."notes", NEW."title");`,
144
+ },
145
+ ],
146
+ beforeUpdate: [
147
+ {
148
+ name: 'lockPaid',
149
+ when: `OLD."status" = 'paid' AND NEW."status" <> 'paid'`,
150
+ sql: `RAISE EXCEPTION 'paid invoices cannot be reopened';`,
151
+ },
152
+ ],
153
+ afterInsert: [
154
+ {
155
+ // Cross-table write. Unqualified names resolve in the `app` schema.
156
+ name: 'logCreate',
157
+ sql: `INSERT INTO invoice_events (id, invoice_id, organization_id, actor)
158
+ VALUES (NEW."id" || ':ins', NEW."id", NEW."organization_id", auth.user_id());`,
159
+ },
160
+ ],
161
+ }
162
+ ```
163
+
164
+ - Write **PL/pgSQL statements**, not a function. The compiler owns
165
+ `CREATE OR REPLACE FUNCTION`, the dollar quote, and the trailing
166
+ `RETURN NEW` (or `RETURN OLD` on a hard-delete trigger) — so a `before*`
167
+ trigger that mutates `NEW` proceeds, and you never return `NULL` by
168
+ accident and silently skip a write. Authoring `CREATE FUNCTION` or
169
+ `CREATE TRIGGER` is rejected.
170
+ - `IF … END IF`, `LOOP … END LOOP` and nested `BEGIN … END` blocks are
171
+ ordinary statements here and are accepted.
172
+ - To reject a write: `RAISE EXCEPTION 'message';` (SQLSTATE `P0001`). The
173
+ whole statement rolls back.
174
+ - Functions are **`SECURITY INVOKER`** and run with a pinned
175
+ `search_path = "app", public, pg_catalog`. That is the security contract:
176
+ a cross-table write from your trigger is still subject to RLS and grants,
177
+ so it cannot reach another tenant's rows — a cross-tenant write fails with
178
+ `42501` and rolls the statement back. Quickback never elevates a user
179
+ trigger to `SECURITY DEFINER`.
180
+ - The [caller claims](/platform/database/neon) are transaction-local, so
181
+ `auth.user_id()`, `auth.org_id()` and `current_setting('request.jwt.claim.sub', true)`
182
+ all read the acting principal from inside the body.
183
+ - Your triggers sort **before** the compiler's audit-stamping triggers
184
+ (`qb_trg_*` < `set_*_audit_on_*`, and Postgres fires BEFORE row triggers by
185
+ name), so a trigger cannot forge `createdBy` / `modifiedBy`.
186
+ - Object names are bounded to Postgres' 63-byte identifier limit with a hash
187
+ suffix, so two long trigger names that differ only past the cut stay
188
+ distinct instead of silently truncating onto each other.
93
189
 
94
190
  ### Soft-delete mapping
95
191
 
@@ -101,6 +197,26 @@ raw-SQL hard deletes are still covered. `*Update` events get the inverse
101
197
  guard, so a soft delete fires delete triggers exactly once and never
102
198
  double-fires as an update.
103
199
 
200
+ Identical on both dialects. On Postgres the two delete variants are two
201
+ functions, not one, because the transition trigger fires on `UPDATE` and
202
+ returns `NEW` while the hard-delete one returns `OLD`.
203
+
204
+ ### Upgrades and removal
205
+
206
+ The trigger migration is appended to the journal after the schema migration
207
+ (and, on Postgres, after the RLS document), and is content-addressed:
208
+
209
+ - An unchanged trigger set appends **nothing** on recompile.
210
+ - Editing or renaming a trigger appends one migration that drops the previous
211
+ objects and creates the current ones.
212
+ - Removing a trigger from config appends one drop-only migration; on Postgres
213
+ the generated **function** is dropped too, so no orphan is left behind.
214
+ - Nothing already applied is ever rewritten.
215
+
216
+ Drops never use `CASCADE` — an unexpected dependency fails loudly rather than
217
+ being swept — and Postgres trigger drops are guarded on `to_regclass`, so a
218
+ table the preceding schema migration removed does not break the cleanup.
219
+
104
220
  ## Handler triggers (`handler:`)
105
221
 
106
222
  Handlers run at the same write chokepoint that powers audit stamping and
@@ -161,15 +277,21 @@ Trigger cascades are bounded in every lane:
161
277
  - **Handler hooks**: the `db` a hook receives is re-wrapped at depth + 1.
162
278
  A cascade deeper than 5 levels (a hook's write firing hooks that write
163
279
  again, …) throws with the table/op that exceeded the cap.
164
- - **SQL triggers**: SQLite's `recursive_triggers` pragma defaults off — a
165
- trigger cannot re-enter itself, directly or through a cycle.
280
+ - **SQL triggers on D1**: SQLite's `recursive_triggers` pragma defaults off —
281
+ a trigger cannot re-enter itself, directly or through a cycle.
282
+ - **SQL triggers on Postgres**: there is **no** such guard. A trigger whose
283
+ write fires another trigger that writes back will recurse until Postgres
284
+ aborts on stack depth. Cascading `sql:` triggers on Postgres are yours to
285
+ keep acyclic — a `when:` guard on the state the trigger changes is the
286
+ usual way.
166
287
 
167
288
  ### Coverage — read the compile report
168
289
 
169
290
  Handler hooks do **not** fire for queue handlers, cron jobs, or raw SQL.
170
291
  The compiler emits a per-trigger lowering report and warns at compile time
171
292
  when a `before*` handler is used as a guard — if a rule must hold for every
172
- write path, use the `sql:` lane with `RAISE(ABORT)`.
293
+ write path, use the `sql:` lane and reject with `RAISE(ABORT, ...)` (D1) or
294
+ `RAISE EXCEPTION` (Postgres).
173
295
 
174
296
  > Cron jobs themselves are first-class — declare them with
175
297
  > [`defineSchedule`](/platform/schedules) and the compiler emits the Worker
@@ -180,10 +302,11 @@ write path, use the `sql:` lane with `RAISE(ABORT)`.
180
302
 
181
303
  | Need | Use |
182
304
  |---|---|
183
- | Invariant that must hold universally (raw SQL included) | `sql:` with `RAISE(ABORT)` |
305
+ | Invariant that must hold universally (raw SQL included) | `sql:` with `RAISE(ABORT)` (D1) / `RAISE EXCEPTION` (Postgres) |
184
306
  | Denormalized columns, counters, tombstones | `sql:` |
185
307
  | Validation/derivation with application logic | `before*` `handler:` |
186
308
  | Side-effects after a write (notify, write related rows) | `after*` `handler:` |
309
+ | Business flow, or anything that reads a role | `handler:` — `sql:` carries data rules only |
187
310
  | Atomic with the write (D1 has no transactions) | `sql:` only |
188
311
 
189
312
  Planned (not yet available — declaring them is a compile error rather than
@@ -70,25 +70,23 @@ role. Better Auth's own API is the gate for its tables.
70
70
  ## Compiler-managed auth versions and upgrades
71
71
 
72
72
  The compiler pins Better Auth, its schema CLI, and the generated companion
73
- packages to **1.7.2**. Recompile and install the emitted dependencies together;
73
+ packages to **1.7.3**. Recompile and install the emitted dependencies together;
74
74
  remove older Better Auth overrides from `build.dependencies`. An incompatible
75
75
  override is rejected because it would run a different auth version from the
76
76
  one that generated your schema.
77
77
 
78
78
  For an existing project, retain its `quickback/drizzle` migration history and
79
79
  use the updated CLI when recompiling. The CLI generates the upgrade locally;
80
- migration history stays on your machine. Apply the newly generated auth migration before
81
- starting the updated Worker. Existing migration SQL is preserved. The upgrade
82
- adds the current JWT/OAuth schema, including JWKS `alg`/`crv` and resource-bound
83
- grants, and backfills account identities without resetting credentials.
84
-
85
- Automatic account backfill covers password, SIWE, Google, Apple, Facebook,
86
- Line, GitHub, and compiler-managed Cloudflare accounts. Unknown/custom provider
87
- identities and duplicate identities must be resolved with an explicit migration;
88
- the generated migration fails before replacing existing account rows. Custom
89
- foreign keys into SQLite's account table also require an explicit migration.
90
- Rehearse the migration against a database copy, and stop old auth writers during
91
- the cutover so they cannot write the previous account shape.
80
+ migration history stays on your machine. Apply the newly generated auth
81
+ migration before starting the updated Worker. Existing migration SQL is
82
+ preserved.
83
+
84
+ ### Upgrading from 1.6
85
+
86
+ The upgrade adds the current JWT/OAuth schema, including JWKS `alg`/`crv` and
87
+ resource-bound grants. The `account` table is unchanged — accounts are still
88
+ keyed by `(providerId, accountId)`, so there is no identity backfill and no
89
+ credential reset.
92
90
 
93
91
  Existing OAuth grants without a recorded resource set are revoked during the
94
92
  upgrade; clients must authorize again. Client registrations and ordinary
@@ -99,7 +97,30 @@ grants still bind resources and reject widening to an unauthorized resource.
99
97
  Projects opting into per-client resource restrictions must link their clients
100
98
  to resources using the OAuth provider's resource administration APIs.
101
99
 
100
+ ### Projects compiled between 2026-09-05 and the 1.7.3 pin
101
+
102
+ Better Auth 1.7.0–1.7.2 briefly keyed accounts by an `issuer` column with a
103
+ unique `(issuer, accountId)` index. 1.7.3 restored the 1.6 `account` schema, so
104
+ only projects compiled during that window carry the extra column.
105
+
106
+ Recompiling emits one appended migration that drops the identity index and then
107
+ the `issuer` column — index first, because SQLite refuses to drop an indexed
108
+ column. It is generated from the schema diff, so a project that never had
109
+ `issuer` gets nothing, and prior migration SQL is untouched. No backfill is
110
+ needed in either direction: `issuer` was always derived from `providerId`, and
111
+ 1.7.3 never reads it.
112
+
113
+ Apply it before the updated Worker serves traffic. A leftover `NOT NULL`
114
+ `issuer` column is an outage on 1.7.3 — Better Auth validates its schema at
115
+ init and refuses a required column it never writes.
116
+
117
+ Generated projects keep that validation **on** at runtime
118
+ (`advanced.database.validateSchema: !!env` in `src/lib/auth.ts`). It is off in
119
+ exactly one case: when the schema CLI imports `auth.ts` there are no bindings,
120
+ so the adapter holds a stub with no tables to check and the validator would
121
+ report every table as missing.
122
+
102
123
  The bundled Account UI uses `signIn.social` and `linkSocial` for generic OAuth
103
- providers, including Cloudflare. Their callback is now
104
- `/auth/v1/callback/cloudflare`; update the registered redirect URI when upgrading
105
- an existing Cloudflare login integration.
124
+ providers, including Cloudflare. Their callback is
125
+ `/auth/v1/oauth2/callback/cloudflare`; update the registered redirect URI when
126
+ upgrading an existing Cloudflare login integration.
@@ -2,7 +2,7 @@
2
2
 
3
3
  The subscriptions plugin adds subscription tiers and Stripe billing to Better Auth. The compiler configures it from `quickback.config.ts`, emits it into your project as source, and wires its state-sync handlers onto the [inbound webhook surface](/platform/webhooks/inbound) — so Stripe events reach your database through one verified, deduplicated path.
4
4
 
5
- The subscriptions table lives in the auth database, alongside `user` and `session`: entitlements are an access-control concern, not domain data.
5
+ The subscriptions table lives alongside `user` and `session`: entitlements are an access-control concern, not domain data. See [Where the table lives](#where-the-table-lives) for what that means on each database provider.
6
6
 
7
7
  ## Enable it
8
8
 
@@ -61,7 +61,8 @@ These are compile errors, not warnings:
61
61
  - any tier after the first has no `priceId`
62
62
  - two tiers share a `priceId` (webhooks resolve a tier *by* price, so it would be ambiguous)
63
63
  - `webhooksBinding` is not set — see [Webhook wiring](#webhook-wiring)
64
- - the auth database is not Cloudflare D1 (the table ships in the SQLite dialect)
64
+ - the database provider has no subscriptions implementation — `cloudflare-d1`, `neon` and `planetscale-postgres` do
65
+ - the provider is Neon in the deprecated `connectionMode: 'websocket'`, whose database module emits no service-role handle
65
66
 
66
67
  ## Secrets
67
68
 
@@ -214,6 +215,25 @@ API keys and OAuth bearers stamp **nothing**, deliberately. A key is an integrat
214
215
 
215
216
  Org-vs-personal precedence applies here exactly as it does everywhere else — the active organization's subscription is what gets stamped. See below.
216
217
 
218
+ ## Where the table lives
219
+
220
+ One table, two dialects, selected at compile time. `src/plugins/subscriptions/schema.ts` re-exports whichever one your database provider uses, so drizzle-kit, the schema barrel and the runtime all resolve to a single definition.
221
+
222
+ | Provider | Table | Handle |
223
+ |----------|-------|--------|
224
+ | `cloudflare-d1` | `subscriptions` in the auth D1 database (`AUTH_DB`) | `drizzle(env.AUTH_DB)` |
225
+ | `neon`, `planetscale-postgres` | `auth.subscriptions`, in the same Postgres database and the same migration journal as everything else | the database module's internal service-role handle |
226
+
227
+ Column names, nullability and the JS values you read back are identical across the two. Timestamps are `integer` epoch-milliseconds on SQLite and `timestamptz` on Postgres; both hand your code a `Date`. `limits` is a JSON string on both.
228
+
229
+ ### On Postgres it is a SYSTEM table
230
+
231
+ `auth.subscriptions` carries the same shape as the webhook store and the rate-limit counters: RLS enabled and forced, an anonymous-denial policy, and the role bootstrap's service-role policy. **There is no caller scope policy**, so a request-scoped database handle reads zero rows from it — including the caller's own — and is denied every write with `42501`.
232
+
233
+ That is not a restriction on the API: every reader and writer of entitlement state already runs on the internal service lane. The Stripe queue consumer has no caller context at all, the admin endpoints run after a platform-admin check, and tier-role resolution runs inside the auth middleware. Authorization for the endpoints above is unchanged — session, admin role and organization membership, checked before the database is touched. What the missing scope policy buys is that a bug in an unrelated route cannot read or mint a paid entitlement through a caller handle.
234
+
235
+ Neon's deprecated `connectionMode: 'websocket'` is rejected for the same reason webhooks are: its database module emits no `createServiceDb`.
236
+
217
237
  ## Webhook wiring
218
238
 
219
239
  The plugin ships **no webhook route of its own**. Stripe events arrive on the standard inbound surface, which verifies the signature and deduplicates on `(provider, externalId)`, then dispatches through `WEBHOOKS_QUEUE`.
@@ -250,9 +270,9 @@ State sync runs on the queue, which is correct for entitlement propagation. Anyt
250
270
  ## What the compiler generates
251
271
 
252
272
  1. `src/plugins/subscriptions/lib/` — the plugin itself, emitted as source. It is **not** an npm dependency; the only package added to your `package.json` is `stripe`.
253
- 2. `src/plugins/subscriptions/schema.ts` — a re-export of the table in `lib/`, so drizzle-kit, the auth schema barrel and the runtime all resolve to one definition.
254
- 3. `src/plugins/subscriptions/index.ts` — the plugin with your tiers, auth database and org-membership lookup already bound.
255
- 4. A migration creating the `subscriptions` table in the auth database.
273
+ 2. `src/plugins/subscriptions/schema.ts` — a re-export of your dialect's table from `lib/`, so drizzle-kit, the schema barrel and the runtime all resolve to one definition. See [Where the table lives](#where-the-table-lives).
274
+ 3. `src/plugins/subscriptions/index.ts` — the plugin with your tiers, database handle and org-membership lookup already bound.
275
+ 4. A migration creating the subscriptions table — in the auth D1 database, or as `auth.subscriptions` in the single Postgres journal with service-role-only RLS.
256
276
  5. Registration of the Stripe handlers into the webhooks queue consumer.
257
277
  6. `STRIPE_SECRET_KEY` and `STRIPE_WEBHOOK_SECRET` on the generated `Env` type.
258
278