@quickback-dev/cli 0.68.0 → 0.70.0

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 (38) hide show
  1. package/dist/index.js +1 -1
  2. package/dist/lib/audit-canon.js +3 -3
  3. package/dist/lib/audit-canon.js.map +1 -1
  4. package/dist/skill/docs/api/actions.md +2 -0
  5. package/dist/skill/docs/api/errors.md +1 -0
  6. package/dist/skill/docs/api/query-params.md +1 -1
  7. package/dist/skill/docs/configure/providers.md +4 -2
  8. package/dist/skill/docs/define/actions/scoped-db.md +14 -13
  9. package/dist/skill/docs/define/areas.md +1 -1
  10. package/dist/skill/docs/define/bundles.md +23 -3
  11. package/dist/skill/docs/define/escape-hatches.md +2 -2
  12. package/dist/skill/docs/define/firewall.md +2 -1
  13. package/dist/skill/docs/define/schema.md +12 -2
  14. package/dist/skill/docs/define/scopes.md +7 -1
  15. package/dist/skill/docs/define/triggers.md +33 -3
  16. package/dist/skill/docs/platform/auth/security.md +2 -1
  17. package/dist/skill/docs/platform/database/neon.md +62 -14
  18. package/dist/skill/docs/platform/database/planetscale-postgres.md +27 -0
  19. package/dist/skill/docs/tooling/claude-skill.md +1 -1
  20. package/dist/skill/docs/tooling/troubleshooting.md +37 -0
  21. package/package.json +1 -1
  22. package/src/skill/docs/api/actions.md +2 -0
  23. package/src/skill/docs/api/errors.md +1 -0
  24. package/src/skill/docs/api/query-params.md +1 -1
  25. package/src/skill/docs/configure/providers.md +4 -2
  26. package/src/skill/docs/define/actions/scoped-db.md +14 -13
  27. package/src/skill/docs/define/areas.md +1 -1
  28. package/src/skill/docs/define/bundles.md +23 -3
  29. package/src/skill/docs/define/escape-hatches.md +2 -2
  30. package/src/skill/docs/define/firewall.md +2 -1
  31. package/src/skill/docs/define/schema.md +12 -2
  32. package/src/skill/docs/define/scopes.md +7 -1
  33. package/src/skill/docs/define/triggers.md +33 -3
  34. package/src/skill/docs/platform/auth/security.md +2 -1
  35. package/src/skill/docs/platform/database/neon.md +62 -14
  36. package/src/skill/docs/platform/database/planetscale-postgres.md +27 -0
  37. package/src/skill/docs/tooling/claude-skill.md +1 -1
  38. package/src/skill/docs/tooling/troubleshooting.md +37 -0
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import pc from "picocolors";
12
12
  // Version injected at build time by scripts/inject-version.ts
13
- const CLI_VERSION = "0.68.0";
13
+ const CLI_VERSION = "0.70.0";
14
14
  function getPackageVersion() {
15
15
  return CLI_VERSION;
16
16
  }
@@ -15,14 +15,14 @@ export const MANAGED_COLUMN_CANON = [
15
15
  jsName: 'createdAt',
16
16
  snakeName: 'created_at',
17
17
  audit: true,
18
- pgLine: `createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),`,
18
+ pgLine: `createdAt: timestamp("created_at", { withTimezone: true, precision: 3 }).notNull().defaultNow(),`,
19
19
  sqliteLine: `createdAt: text("created_at").notNull().default(${EPOCH}).$defaultFn(${ISO_NOW}),`,
20
20
  },
21
21
  {
22
22
  jsName: 'modifiedAt',
23
23
  snakeName: 'modified_at',
24
24
  audit: true,
25
- pgLine: `modifiedAt: timestamp("modified_at", { withTimezone: true }).notNull().defaultNow().$onUpdate(() => new Date()),`,
25
+ pgLine: `modifiedAt: timestamp("modified_at", { withTimezone: true, precision: 3 }).notNull().defaultNow().$onUpdate(() => new Date()),`,
26
26
  sqliteLine: `modifiedAt: text("modified_at").notNull().default(${EPOCH}).$defaultFn(${ISO_NOW}).$onUpdate(${ISO_NOW}),`,
27
27
  },
28
28
  {
@@ -43,7 +43,7 @@ export const MANAGED_COLUMN_CANON = [
43
43
  jsName: 'deletedAt',
44
44
  snakeName: 'deleted_at',
45
45
  audit: false,
46
- pgLine: `deletedAt: timestamp("deleted_at", { withTimezone: true }),`,
46
+ pgLine: `deletedAt: timestamp("deleted_at", { withTimezone: true, precision: 3 }),`,
47
47
  sqliteLine: `deletedAt: text("deleted_at"),`,
48
48
  },
49
49
  {
@@ -1 +1 @@
1
- {"version":3,"file":"audit-canon.js","sourceRoot":"","sources":["../../src/lib/audit-canon.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAaH,MAAM,KAAK,GAAG,4BAA4B,CAAC;AAC3C,MAAM,OAAO,GAAG,gCAAgC,CAAC;AAEjD,MAAM,CAAC,MAAM,oBAAoB,GAAsC;IACrE;QACE,MAAM,EAAE,WAAW;QACnB,SAAS,EAAE,YAAY;QACvB,KAAK,EAAE,IAAI;QACX,MAAM,EAAE,oFAAoF;QAC5F,UAAU,EAAE,mDAAmD,KAAK,gBAAgB,OAAO,IAAI;KAChG;IACD;QACE,MAAM,EAAE,YAAY;QACpB,SAAS,EAAE,aAAa;QACxB,KAAK,EAAE,IAAI;QACX,MAAM,EAAE,kHAAkH;QAC1H,UAAU,EAAE,qDAAqD,KAAK,gBAAgB,OAAO,eAAe,OAAO,IAAI;KACxH;IACD;QACE,MAAM,EAAE,WAAW;QACnB,SAAS,EAAE,YAAY;QACvB,KAAK,EAAE,IAAI;QACX,MAAM,EAAE,gCAAgC;QACxC,UAAU,EAAE,gCAAgC;KAC7C;IACD;QACE,MAAM,EAAE,YAAY;QACpB,SAAS,EAAE,aAAa;QACxB,KAAK,EAAE,IAAI;QACX,MAAM,EAAE,kCAAkC;QAC1C,UAAU,EAAE,kCAAkC;KAC/C;IACD;QACE,MAAM,EAAE,WAAW;QACnB,SAAS,EAAE,YAAY;QACvB,KAAK,EAAE,KAAK;QACZ,MAAM,EAAE,6DAA6D;QACrE,UAAU,EAAE,gCAAgC;KAC7C;IACD;QACE,MAAM,EAAE,WAAW;QACnB,SAAS,EAAE,YAAY;QACvB,KAAK,EAAE,KAAK;QACZ,MAAM,EAAE,gCAAgC;QACxC,UAAU,EAAE,gCAAgC;KAC7C;CACF,CAAC"}
1
+ {"version":3,"file":"audit-canon.js","sourceRoot":"","sources":["../../src/lib/audit-canon.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAaH,MAAM,KAAK,GAAG,4BAA4B,CAAC;AAC3C,MAAM,OAAO,GAAG,gCAAgC,CAAC;AAEjD,MAAM,CAAC,MAAM,oBAAoB,GAAsC;IACrE;QACE,MAAM,EAAE,WAAW;QACnB,SAAS,EAAE,YAAY;QACvB,KAAK,EAAE,IAAI;QACX,MAAM,EAAE,kGAAkG;QAC1G,UAAU,EAAE,mDAAmD,KAAK,gBAAgB,OAAO,IAAI;KAChG;IACD;QACE,MAAM,EAAE,YAAY;QACpB,SAAS,EAAE,aAAa;QACxB,KAAK,EAAE,IAAI;QACX,MAAM,EAAE,gIAAgI;QACxI,UAAU,EAAE,qDAAqD,KAAK,gBAAgB,OAAO,eAAe,OAAO,IAAI;KACxH;IACD;QACE,MAAM,EAAE,WAAW;QACnB,SAAS,EAAE,YAAY;QACvB,KAAK,EAAE,IAAI;QACX,MAAM,EAAE,gCAAgC;QACxC,UAAU,EAAE,gCAAgC;KAC7C;IACD;QACE,MAAM,EAAE,YAAY;QACpB,SAAS,EAAE,aAAa;QACxB,KAAK,EAAE,IAAI;QACX,MAAM,EAAE,kCAAkC;QAC1C,UAAU,EAAE,kCAAkC;KAC/C;IACD;QACE,MAAM,EAAE,WAAW;QACnB,SAAS,EAAE,YAAY;QACvB,KAAK,EAAE,KAAK;QACZ,MAAM,EAAE,2EAA2E;QACnF,UAAU,EAAE,gCAAgC;KAC7C;IACD;QACE,MAAM,EAAE,WAAW;QACnB,SAAS,EAAE,YAAY;QACvB,KAAK,EAAE,KAAK;QACZ,MAAM,EAAE,gCAAgC;QACxC,UAAU,EAAE,gCAAgC;KAC7C;CACF,CAAC"}
@@ -201,6 +201,8 @@ Cross-tenant unsafe actions are generated with:
201
201
 
202
202
  Without unsafe mode, `unsafeDb` is `undefined`.
203
203
 
204
+ On Postgres providers `unsafeDb` is the service-role handle for every unsafe action, so row-level security does not narrow it to the caller — the same reach as on D1. See the [provider note](/define/actions/scoped-db#unsafe-mode).
205
+
204
206
  Raw SQL in action code is blocked by default at compile time. If you need it for a specific action, set `allowRawSql: true` on that action explicitly.
205
207
 
206
208
  ### Explicit scope with `unsafeDb.scopeTo`
@@ -329,6 +329,7 @@ form can show the conflict inline. `details.column` is the first of them.
329
329
  | `DB_TIMEOUT` | 503 | **Retryable.** A read passed [`queryTimeoutMs`](/configure/providers#database-options) (D1 only). The read had no side effects; retry. `details: { binding }` |
330
330
  | `DB_WRITE_OUTCOME_UNKNOWN` | 500 | A write passed `queryTimeoutMs`. D1 does not cancel the statement, so it may still commit after the response. **Re-read the record before retrying** — a blind retry can double-apply. `details: { binding, outcome: 'unknown' }` |
331
331
  | `ENCRYPTION_UNREADABLE` | 422 | A stored [`.encrypted()`](/define/encryption) value will not decrypt |
332
+ | `TRIGGER_REJECTED` | 422 / 403 | A [before-trigger](/define/triggers#rejection-status) refused the write; nothing was persisted. `layer: "trigger"`, `details.code` for a prefixed `sql:` rejection |
332
333
 
333
334
  The `details.column` field is only present when the driver's error message identified the offending column (SQLite/D1 do; some PG variants don't).
334
335
 
@@ -91,7 +91,7 @@ currently wired into the emitted route.
91
91
  - `count` — number of records returned on this page
92
92
  - `page` / `pageSize` — derived from `?offset=` and `?limit=`
93
93
  - `hasMore` — whether more rows exist in the queried direction. Without `?total=true` it comes from a `limit + 1` over-fetch probe, so it never lies on a final page that exactly fills the limit; with `?total=true` it is page arithmetic (`page < totalPages`) on offset pages, and the probe again on cursor pages.
94
- - `nextCursor` / `prevCursor` — keyset cursors; pass them back as `?starting_after=` and `?ending_before=`. Treat them as opaque, but they are encoded, not encrypted: they carry the boundary row's sort-key values. Either can be `null` — including when the sort includes a [masked](/define/masking) column the caller may sort by (`query.roles`) but not see (`show.roles`), or a column the response does not carry (a view sorting on a field it doesn't list, or `?fields=` without the sort key); page with `?offset=` in that case.
94
+ - `nextCursor` / `prevCursor` — keyset cursors; pass them back as `?starting_after=` and `?ending_before=`. Treat them as opaque, but they are encoded, not encrypted: they carry the boundary row's sort-key values. Either can be `null` — including when the sort includes a [masked](/define/masking) column the caller may sort by (`query.roles`) but not see (`show.roles`), or a column the response does not carry (a view sorting on a field it doesn't list, or `?fields=` without the sort key); page with `?offset=` in that case. A cursor carries a timestamp sort key at millisecond precision, so sort on a column that stores milliseconds: the managed `createdAt` / `modifiedAt` / `deletedAt` do on both dialects (Postgres stores them as `timestamptz(3)`). A Postgres timestamp column you declare with microsecond precision and fill with `now()` can repeat or skip rows across pages.
95
95
  - `total` / `totalPages` — present **only** when the request passed `?total=true` (see below)
96
96
 
97
97
  There is no `limit` or `offset` member in `pagination`.
@@ -19,7 +19,8 @@ providers: {
19
19
  | Option | Type | Description |
20
20
  |--------|------|-------------|
21
21
  | `compatibilityDate` | `string` | Emits Cloudflare `compatibility_date` in `wrangler.toml`. |
22
- | `placement.mode` | `"smart" \| "standard"` | Emits Cloudflare's `[placement]` block. |
22
+ | `placement.mode` | `"smart" \| "standard"` | Emits Cloudflare's `[placement]` block. Mutually exclusive with `placement.region`. |
23
+ | `placement.region` | `string` | Placement hint, `"<cloud>:<region>"` (e.g. `"aws:us-east-2"`): runs the Worker next to a single-region database instead of next to the user. Set it to your Postgres region. Any other `placement` key is a compile error. Named environments emit it per target; override with `environments.<name>.worker.placement`. |
23
24
  | `observability.enabled` | `boolean` | Emits top-level Workers Logs persistence under `[observability]`. |
24
25
  | `observability.headSamplingRate` | `number` | Top-level Workers Logs sample rate from `0` to `1`. |
25
26
  | `observability.logs.enabled` | `boolean` | Emits `[observability.logs]`. |
@@ -106,7 +107,7 @@ single Postgres database with no bindings or split mode (see
106
107
  | `allowClientIds` | `boolean` | `false` | Accept an optional client-supplied `id` on create, shaped like the `generateId` strategy — see [Client-supplied IDs](/api/crud#client-supplied-ids-optimistic-updates). Ignored under `generateId: false` (ids are already client-supplied and required) and `"serial"` / numeric PKs |
107
108
  | `validateIdParams` | `boolean` | `true` | Check a record route's `:id` against the table's id format and answer `400 INVALID_ID` before any database work — see [Malformed ids](/api/crud#malformed-ids-400-invalid_id). **Set `false` if any table holds rows whose ids don't match the current `generateId` shape** (the strategy changed after rows were written, imported data, ids hand-minted by actions): with the check on, those rows answer 400 instead of the row. Tables whose format the compiler can't know (`generateId: false`, an authored id default) are never checked |
108
109
  | `namingConvention` | `string` | `"snake_case"` | Column naming convention |
109
- | `usePlurals` | `boolean` | `false` | Pluralize auth table names (e.g. `user` vs `users`) |
110
+ | `usePlurals` | `boolean` | `false` (`true` on Neon / PlanetScale Postgres) | Pluralize auth table names (e.g. `user` vs `users`). The default differs by provider — porting a D1 project to Postgres, set `usePlurals: false` explicitly to keep its table names |
110
111
  | `splitDatabases` | `boolean` | `true` | Separate auth and features databases (D1 only) |
111
112
  | `queryTimeoutMs` | `number` | — | Per-statement deadline for every D1 query the generated code runs (CRUD, actions, the auth adapter, cron/queue/email runners, files, audit). Unset = no deadline. D1 only — the Postgres drivers have their own timeout options. Past the deadline a read answers `503 DB_TIMEOUT` and a write `500 DB_WRITE_OUTCOME_UNKNOWN`; see [Backend stalls](/platform/database/using-d1#backend-stalls) and [Database errors](/api/errors#database-constraint-errors). The statement is **not** cancelled on the backend |
112
113
  | `authBinding` | `string` | `"AUTH_DB"` | Binding name for auth database |
@@ -132,6 +133,7 @@ single Postgres database with no bindings or split mode (see
132
133
  | `hyperdrive.id` | `string` | — | Required Cloudflare Hyperdrive configuration ID when `connectionMode: "hyperdrive"` |
133
134
  | `hyperdrive.localConnectionString` | `string` | — | Optional local-only Postgres connection used by Wrangler dev |
134
135
  | `pooled` | `boolean` | `true` | Use the pooled Neon connection string (recommended for Workers) |
136
+ | `usePlurals` | `boolean` | `true` | Auth table names (`users`, `members`, …). **The D1 default is `false`** — a project moving from D1 must set `usePlurals: false` to keep `user`, `member`, … |
135
137
 
136
138
  The Worker connects through a single `DATABASE_URL` secret — auth and feature
137
139
  queries share it. See [Neon](/platform/database/neon) for
@@ -123,7 +123,9 @@ the lookup is gated and typed again:
123
123
  export default defineAction({
124
124
  path: '/invite/enter-event',
125
125
  access: { roles: ['PUBLIC'] },
126
- unsafe: true,
126
+ // crossTenant: false — `unsafe: true` means crossTenant + adminOnly, which
127
+ // requires a sysadmin session and 403s an anonymous caller.
128
+ unsafe: { reason: 'Invite door — tenant resolved from the invite token', crossTenant: false },
127
129
  async execute({ unsafeDb, input }) {
128
130
  const [token] = await unsafeDb.select().from(inviteTokens).where(eq(inviteTokens.code, input.code));
129
131
  if (!token) throw new ActionError('Invalid invite', 'INVITATION_INVALID_OR_EXPIRED', 404);
@@ -425,18 +427,17 @@ Unsafe cross-tenant actions are generated with:
425
427
  - sysadmin gate (`ctx.userRole === "sysadmin"`)
426
428
  - mandatory audit logging on deny/success/error
427
429
 
428
- **Provider note (Neon):** `unsafe.enabled` controls app-layer scoped-query
429
- bypass, while `unsafe.crossTenant` controls database-layer RLS bypass. An
430
- unsafe action with `crossTenant: false` receives a raw Drizzle handle backed by
431
- the request database, so the caller's organization or delegated-principal
432
- claims remain active—including inside `db.transaction()`. Its code must still
433
- provide every intended scope predicate explicitly.
434
-
435
- Only an action with `crossTenant: true` acquires the dedicated service-role
436
- handle (`createServiceDb`). That handle sets the `quickback.service_role`
437
- transaction marker instead of caller claims, and generated RLS grants it an
438
- explicit per-table bypass policy. The sysadmin guard and mandatory audit log
439
- therefore protect the same boundary that receives the RLS bypass. The
430
+ **Provider note (Neon, PlanetScale Postgres):** `unsafeDb` is the
431
+ service-role handle (`createServiceDb`, wrapped by the audit writer) for
432
+ **every** unsafe action, `crossTenant: true` or `false` — the same reach as on
433
+ D1. It sets the `quickback.service_role` transaction marker instead of caller
434
+ claims, and generated RLS grants that marker an explicit per-table policy. So
435
+ RLS does not narrow `unsafeDb` to the caller: a `PUBLIC` door's token lookup
436
+ finds the row, and a roster join over `member` sees every member. The action's
437
+ own checks — and `unsafeDb.scopeTo(...)` — govern, exactly as on D1.
438
+
439
+ `crossTenant` decides the gate, not the handle: `crossTenant: true` adds the
440
+ sysadmin guard and mandatory audit log described above. The
440
441
  audit-logging contract is otherwise identical to D1. On Cloudflare, both HTTP
441
442
  and Hyperdrive are supported. Hyperdrive is the recommended lane when an unsafe
442
443
  action also needs an interactive transaction. The deprecated Node/Bun WebSocket
@@ -424,7 +424,7 @@ The compiler emits one synthetic `src/routes/__namespace-event-scope.routes.ts`
424
424
 
425
425
  ### Multi-lane via — first match wins
426
426
 
427
- When more than one relationship can authorize a caller for the namespaced resource, pass `via:` as an array. The middleware tries each lane in declaration order and stops at the first match — `ctx.<exposeAs>` is hydrated from whichever lane fired.
427
+ When more than one relationship can authorize a caller for the namespaced resource, pass `via:` as an array. The middleware starts every lane's probe at once and takes the first match in declaration order — a later lane never wins over an earlier lane that also matches, and `ctx.<exposeAs>` is hydrated from the lane that won. A probe that fails surfaces only when every earlier lane missed; a failure in a lane after the winner is ignored.
428
428
 
429
429
  ```typescript
430
430
  authz: {
@@ -42,10 +42,30 @@ export default defineBundle({
42
42
  soft-delete filter apply by construction — and the target table's REAL
43
43
  mask function is applied (the same read projection the CRUD list endpoint
44
44
  runs), so masked columns are safe to include. Every list slice lands as
45
- `{ data: rows }` (the per-resource cache-seed contract).
45
+ `{ data: rows, hasMore, nextCursor }` — `data` is the per-resource
46
+ cache-seed contract; `hasMore` and `nextCursor` are additive.
47
+ - **Ordering is deterministic.** `orderBy` keys apply in the order you list
48
+ them. The primary key `id` is appended ascending as the final tie-break
49
+ unless you already listed it, the same rule as the
50
+ [CRUD list](/api/query-params#pagination). Without a unique final key,
51
+ `LIMIT` picks among tied rows arbitrarily on Postgres.
52
+ - **Truncation is visible.** With `limit`, the section reads one extra row:
53
+ `hasMore: true` means more rows match than were returned. Without `limit`,
54
+ `hasMore` is always `false`.
55
+ - **`nextCursor` continues on the table's CRUD list.** When `hasMore` is
56
+ true, `nextCursor` is the same keyset cursor the CRUD list emits. Fetch
57
+ the next page with that list endpoint, passing the section's `where` as
58
+ equality filters, its `orderBy` as `?sort=`, and the cursor as
59
+ `?starting_after=`. For `orderBy: [{ createdAt: "desc" }]` and
60
+ `where: { eventId }`, that is
61
+ `GET /api/v1/guests?eventId=<id>&sort=-createdAt&starting_after=<nextCursor>`.
62
+ The CRUD list appends the same `id` tie-break, so the cursor lines up.
63
+ `nextCursor` is `null` when there is nothing more, when `columns` omits a
64
+ sort key (or `id`), or when a sort key is [masked](/define/masking) for the
65
+ caller. In those cases, raise `limit` or page the CRUD list with `?offset=`.
46
66
  - **`sections` filter**: omitted/empty = all. An un-wanted list section
47
- returns `{ data: [] }` (drop-in compatible with existing clients);
48
- un-wanted `custom` sections are absent.
67
+ returns `{ data: [], hasMore: false, nextCursor: null }` (drop-in
68
+ compatible with existing clients); un-wanted `custom` sections are absent.
49
69
  - **All sections run in one `Promise.all`.**
50
70
  - **ETag**: SHA-1 hex over `{ scopeSeed: <path params>, userId, payload }`.
51
71
  An `ifNoneMatch` match returns `{ success: true, etag, notModified: true }`
@@ -157,9 +157,9 @@ Reference implementations, both ports of the same table:
157
157
  - `examples/recruitment/quickback/features/interviews/interview_scores.ts` (SQLite)
158
158
  - `examples/recruitment-neon/quickback/features/interviews/interview_scores.ts` (Postgres)
159
159
 
160
- Postgres uses `timestamp("…", { withTimezone: true }).notNull().defaultNow()` for the
160
+ Postgres uses `timestamp("…", { withTimezone: true, precision: 3 }).notNull().defaultNow()` for the
161
161
  timestamps, `.$onUpdate(() => new Date())` on `modifiedAt`, plain `text(…)` for the
162
- actor columns, and `timestamp("deleted_at", { withTimezone: true })` for `deletedAt`.
162
+ actor columns, and `timestamp("deleted_at", { withTimezone: true, precision: 3 })` for `deletedAt`.
163
163
 
164
164
  ## Attaching pillars to a raw Drizzle table
165
165
 
@@ -124,7 +124,7 @@ On Postgres the RLS scope policy mirrors the firewall's `all`/`any` tree arm for
124
124
 
125
125
  - A `via:` arm lowers to `project_id IN (SELECT r.project_id FROM public.qb_rel_<relationship>() r)` — a `SECURITY DEFINER` helper that runs the same relationship lookup as the API (subject = the caller's claim, the `where:` literals, the related table's soft delete). The generated API calls the same helper for every relationship lookup on Postgres, so a caller with no active org gets the same rows from the API as the policy admits. `[org, { any: [owner, { via }] }]` becomes `org AND (owner OR project_id IN (…))`, never `org AND owner`. See [Relationship arms in SQL](/platform/database/neon#relationship-arms-in-sql).
126
126
  - A `{ permission }` arm expands exactly as the API expands it: relation leaves become `via:` helpers, arrows become `qb_arrow_…` helpers (a recursive arrow is a `maxDepth`-bounded closure; a relation-backed arrow returns the hop's rows whose FK is in the target relationship's `qb_rel_…` set).
127
- - Inside an `any` group that also has an org arm, the relationship, scope and principal arms are tenant-bound exactly where the API binds them — `(<arm> AND (organization_id = <active org> OR <no active org>))` — so an org-claiming caller never rides them into another org.
127
+ - Inside an `any` group that also has an org arm (at any depth — see Boolean groups below), the relationship, scope and principal arms are tenant-bound exactly where the API binds them — `(<arm> AND (organization_id = <active org> OR <no active org>))` — so an org-claiming caller never rides them into another org.
128
128
  - The soft-delete filter the API adds to a table carrying `deletedAt` reaches the policy too, as `deleted_at IS NULL OR public.in_soft_delete()` in `USING` only — see [the soft-delete lane](/platform/database/neon#the-soft-delete-lane).
129
129
  - Literals, literal `in` lists, and claims the Worker never writes into the transaction (`ctx.scope.<kind>.<subKey>`, area anchors like `ctx.event.id`, string `in` sets) stay API-only and lower to `true` — the policy has nothing to compare them against, and a literal conjunct would refuse status-changing updates.
130
130
 
@@ -147,6 +147,7 @@ Null-safe scope semantics make this safe (these apply **inside `all`/`any` group
147
147
 
148
148
  - A **scope** arm (`ctx.activeOrgId`, `ctx.activeTeamId`, `ctx.scope.*`) whose claim is **absent never binds `undefined`** (the classic 500 / "match every row" trap). In an `any` group an absent arm **drops**; if **every** arm drops, the group denies with `sql\`1 = 0\`` (the empty-guard) — never a full-table read. In an `all` group an absent required scope **denies** the group.
149
149
  - **An `any` group with an org arm tenant-binds its scope and relationship arms.** Beside `{ field: 'organizationId', equals: 'ctx.activeOrgId' }`, a `ctx.scope.*` arm, a `via:` arm, or a `{ permission }` arm is emitted as `scope-arm AND (organizationId = ctx.activeOrgId OR the caller has no org claim)`. A caller with **no** org claim (a scope-only or relationship principal) is unaffected; a caller who carries org B's membership *and* a scope claim or relationship row on an org-A instance cannot ride the scope arm into org A's rows. Owner arms (`ctx.userId`), team arms, and literal `in` lists are not tenant-bound. An org claim and a scope claim in one request are therefore always the same tenant — or the scope arm yields nothing.
150
+ The org arm does not have to be a direct child of the `any`: it is found at any depth, so the common "org AND audience filter" shape — `{ all: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }, { field: 'staffAudience', isNull: true }] }` beside the `via:` arms — binds them exactly as a top-level org arm would. The arm that requires the org equality on every path (directly, or through `all:` nesting) is already anchored and stays as written. If the group's org arms name **different** columns (`organizationId` in one, `workspaceId` in another) and there is an arm to bind, the compile fails: there is no single column to bind it to, and the compiler will not pick one.
150
151
  - Mark an arm `{ optional: true }` to **drop-instead-of-deny** when absent inside an `all` group (the teamless rest-of-org slice — `ctx.activeTeamId` is implicitly optional). An optional arm only drops while a **non-optional** tenant arm still bounds the query; a sole optional arm denies when its claim is absent, exactly like the team rule below.
151
152
  - **Owner** (`ctx.userId`) and **soft-delete** (`isNull deletedAt`) are always present / always AND'd — never relaxed.
152
153
 
@@ -535,7 +535,7 @@ Default to `feature()`. Drop to Drizzle only when:
535
535
 
536
536
  Features in the same project may mix freely — Quickback dispatches per feature — so one interop table doesn't force the rest of the project off `feature()`.
537
537
 
538
- One dialect rule: interop files **without** a `defineTable(...)` default export (internal child tables) are not dialect-translated — author them in the target database's dialect. On Postgres providers (`neon`, `planetscale-postgres`), a `sqliteTable` interop source without `defineTable` is a compile-time error; write it with `pgTable` from `drizzle-orm/pg-core` instead. Sources **with** `defineTable(...)` keep compiling across dialects automatically. On Postgres, managed audit timestamps a `sqliteTable` source declares in the SQLite shape (`createdAt` / `modifiedAt` / `deletedAt` as `text`) are emitted as `timestamptz`, the same as every other Postgres table; API responses still carry the same ISO-8601 string.
538
+ One dialect rule: interop files **without** a `defineTable(...)` default export (internal child tables) are not dialect-translated — author them in the target database's dialect. On Postgres providers (`neon`, `planetscale-postgres`), a `sqliteTable` interop source without `defineTable` is a compile-time error; write it with `pgTable` from `drizzle-orm/pg-core` instead. Sources **with** `defineTable(...)` keep compiling across dialects automatically. On Postgres, managed audit timestamps a `sqliteTable` source declares in the SQLite shape (`createdAt` / `modifiedAt` / `deletedAt` as `text`) are emitted as `timestamptz(3)`, the same as every other Postgres table; API responses still carry the same ISO-8601 string.
539
539
 
540
540
  ### Drizzle Column Types
541
541
 
@@ -765,7 +765,7 @@ The scoped `db` an action receives types every managed key as `?: never` on `.in
765
765
 
766
766
  The runtime layer **hard-stamps** every audit field on every write, so the audit log can never be forged by a crafted request body or by a client echoing a row back into a PATCH.
767
767
 
768
- On Postgres the RLS migration adds a database-side backstop: `BEFORE INSERT` / `BEFORE UPDATE` triggers on every feature table (`public.set_audit_fields_on_insert()` / `_on_update()`). They set `created_at` / `modified_at` to the database's `now()` and apply the same actor rule as the wrapper — the actor column always names whoever did the write:
768
+ On Postgres the RLS migration adds a database-side backstop: `BEFORE INSERT` / `BEFORE UPDATE` triggers on every feature table (`public.set_audit_fields_on_insert()` / `_on_update()`). They set `created_at` / `modified_at` to the database's `now()` truncated to the millisecond (`date_trunc('milliseconds', now())`) and apply the same actor rule as the wrapper — the actor column always names whoever did the write:
769
769
 
770
770
  - a verified caller (`auth.user_id()`) always wins, so no request can write someone else's id;
771
771
  - with no verified caller — a `scope:` principal, a delegated principal, the service lane, a `system:` actor — the actor the Worker already stamped is kept;
@@ -773,6 +773,16 @@ On Postgres the RLS migration adds a database-side backstop: `BEFORE INSERT` / `
773
773
 
774
774
  `created_at` / `created_by` never change on update.
775
775
 
776
+ **Postgres stores managed timestamps at millisecond precision.** `createdAt` / `modifiedAt` / `deletedAt` are `timestamp(3) with time zone`, the same precision as D1's ISO text, a JS `Date`, and the wire format (`.sssZ`). A keyset cursor carries its boundary value through a `Date`, so a microsecond column would never compare equal to the cursor: ascending pages repeated rows and descending pages skipped rows that shared a millisecond (#602). The triggers truncate rather than round, so a stamp never lands after the transaction's `now()`. The column `DEFAULT now()` (reached only by raw SQL on a table without the triggers) is rounded to the millisecond by Postgres. Timestamp columns you declare yourself keep the precision you give them.
777
+
778
+ Recompiling a Postgres project last compiled by 0.69.0 or earlier adds a migration that changes each managed column's type:
779
+
780
+ ```sql
781
+ ALTER TABLE "app"."notes" ALTER COLUMN "created_at" SET DATA TYPE timestamp (3) with time zone USING "created_at"::timestamp (3) with time zone;
782
+ ```
783
+
784
+ Existing values are **rounded** to the nearest millisecond (`…08.624500` becomes `…08.625`). The type change rewrites the table under an `ACCESS EXCLUSIVE` lock, so apply it in a quiet window on large tables. The same compile re-emits the trigger functions (`CREATE OR REPLACE`) in a new RLS migration.
785
+
776
786
  Because the value would be discarded anyway, the generated `db` handle refuses it at the type level: on the scoped `db`, `.insert().values()` types `createdAt` / `modifiedAt` / `createdBy` / `modifiedBy` / `deletedAt` / `deletedBy` as `?: never`, and `.update().set()` types the audit quartet plus `deletedBy` the same way. Supplying one is a **compile error** — not a silent discard.
777
787
 
778
788
  ```ts
@@ -349,7 +349,7 @@ so it can only ever carry the role the caller actually proved this request.
349
349
  - A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) mints **no** scope role — it opens the gate via the caller's org role without proving a relationship. The gate passes; the caller carries their org role, not a minted scope role.
350
350
  - **The org claim is only ever signed beside a membership role.** Every mint site — `/scope/v1/enter`, the namespace resolver, `/api/v1/token` — writes `orgId` into the token only when a membership `role` accompanies it, and the auth middleware ignores an `orgId` claim that arrives without a `role`. A relationship-promoted tenant (the in-request `ctx.activeOrgId` stamped from the proven row so the firewall resolves) is never persisted as a bare tenant grant.
351
351
  - **`/scope/v1/enter` drops the org claims for a foreign-tenant instance.** When the relationship's `from` table carries an organization column, the enter route reads it off the proven row (the same row the probe already fetched — no extra query) and compares it with `ctx.activeOrgId`. A mismatch — an org-B member entering an org-A event — mints the token **without** `orgId` / `role`: a relationship-only principal, exactly the state the namespace resolver gives the same caller. The caller keeps their org seat for org-B requests by using their session or a plain `/api/v1/token`; the scope token is for the scope. A `from` table with no organization column (a global reference relationship) leaves the claim untouched.
352
- - **Every mint tenant-binds the instance.** A relationship row is matched without tenant scoping (a cross-tenant attendee has no `activeOrgId`), so the row alone can't prove which tenant's instance it names. When the relationship's `from` table carries an organization column, every site that mints from a relationship row — `/scope/v1/enter`, [`ctx.mintScope`](#sessionless-scope-mint--ctxmintscope), and this namespace resolver (the in-memory stamp **and** the `mintScope` token) — also loads the **instance** row, through its own firewall with tenant scopes stripped so soft-delete still applies, and grants the role only when the instance's organization equals the proving row's. A row created in org B naming org A's event proves nothing about org A and grants nothing; a deleted instance grants nothing. (The namespace gate itself still passes on the proven row; the caller just carries no scope for the foreign instance.) The instance table is `authz.scopes.<kind>.instance` when declared (`instance: 'events'`), else the target of the relationship's `resource.column` foreign key, else the one table whose firewall pins its primary key to `ctx.scope.<kind>` (`{ field: 'id', equals: 'ctx.scope.event' }`). Several such tables is a compile error naming them — set `instance`. If nothing resolves, the compiler warns: set `instance` (or declare the FK) so the instance can be bound. A `from` table with no organization column has no tenant to compare, so it gets no binding.
352
+ - **Every mint tenant-binds the instance.** A relationship row is matched without tenant scoping (a cross-tenant attendee has no `activeOrgId`), so the row alone can't prove which tenant's instance it names. When the relationship's `from` table carries an organization column, every site that mints from a relationship row — `/scope/v1/enter`, [`ctx.mintScope`](#sessionless-scope-mint--ctxmintscope), and this namespace resolver (the in-memory stamp **and** the `mintScope` token) — also loads the **instance** row, through its own firewall with tenant scopes stripped so soft-delete still applies, and grants the role only when the instance's organization equals the proving row's. A row created in org B naming org A's event proves nothing about org A and grants nothing; a deleted instance grants nothing. (The namespace gate itself still passes on the proven row; the caller just carries no scope for the foreign instance.) The instance table is `authz.scopes.<kind>.instance` when declared (`instance: 'events'`), else the target of the relationship's `resource.column` foreign key, else the one table whose firewall pins its primary key to `ctx.scope.<kind>` (`{ field: 'id', equals: 'ctx.scope.event' }`). Several such tables is a compile error naming them — set `instance`. If nothing resolves, the compiler warns: set `instance` (or declare the FK) so the instance can be bound. A `from` table with no organization column has no tenant to compare, so it gets no binding. When the namespace gate already hydrated the instance table by the same path param, the resolver takes the instance's organization from `ctx.<exposeAs>` instead of reading it again — that row passed the table's full firewall, and any row the full firewall admits, the tenant-stripped one admits too.
353
353
 
354
354
  ### The bulk-grant lane is tenant-bound
355
355
 
@@ -365,6 +365,12 @@ gets). No relationship → `403`. Any `ctx.roles`-based check in the action then
365
365
  fails for them, scoped-db inserts stamp the *instance's* org, and the
366
366
  namespace re-mint carries no org claim.
367
367
 
368
+ The check and the hydration are one read for a caller in their own org: the
369
+ resolver loads the row by id, `ctx.activeOrgId`, and the table's firewall, and
370
+ uses it as `ctx.<exposeAs>`. A miss falls back to the tenant-only check, so a
371
+ foreign instance still re-evaluates through the relationship lanes and an
372
+ own-tenant row the firewall hides (soft-deleted, say) still `404`s.
373
+
368
374
  Multi-target namespaces (lanes that hydrate *different* tables) hydrate nothing
369
375
  for a role caller, so there is nothing to bind there — put the tenant check in
370
376
  the firewall of each table instead (an org arm in an [`any` group tenant-binds
@@ -124,7 +124,8 @@ The body is inlined into `CREATE TRIGGER ... BEGIN <body> END`.
124
124
  - Bare `CASE ... END` expressions, including nested cases, are supported.
125
125
  For example: `SELECT CASE WHEN NEW.total < 0 THEN RAISE(ABORT, 'invalid total') END;`.
126
126
  That `END` closes the expression.
127
- - To reject a write: `SELECT RAISE(ABORT, 'message');`
127
+ - To reject a write: `SELECT RAISE(ABORT, 'message');` — prefix the message
128
+ to choose the [response status](#rejection-status).
128
129
  - SQL triggers are the only transactional option on D1, which has no
129
130
  `db.transaction()`.
130
131
 
@@ -170,7 +171,8 @@ VALUES (NEW."id" || ':ins', NEW."id", NEW."organization_id", auth.user_id());`,
170
171
  - `IF … END IF`, `LOOP … END LOOP` and nested `BEGIN … END` blocks are
171
172
  ordinary statements here and are accepted.
172
173
  - To reject a write: `RAISE EXCEPTION 'message';` (SQLSTATE `P0001`). The
173
- whole statement rolls back.
174
+ whole statement rolls back. Prefix the message to choose the
175
+ [response status](#rejection-status).
174
176
  - Functions are **`SECURITY INVOKER`** and run with a pinned
175
177
  `search_path = "app", public, pg_catalog`. That is the security contract:
176
178
  a cross-table write from your trigger is still subject to RLS and grants,
@@ -187,6 +189,33 @@ VALUES (NEW."id" || ':ins', NEW."id", NEW."organization_id", auth.user_id());`,
187
189
  suffix, so two long trigger names that differ only past the cut stay
188
190
  distinct instead of silently truncating onto each other.
189
191
 
192
+ ### Rejection status
193
+
194
+ A `sql:` rejection reaches the API as a database error. To answer the client
195
+ with a 4xx instead of a 500, **start** the message with a documented prefix
196
+ and a code of uppercase letters, digits and underscores:
197
+
198
+ | Message | Response |
199
+ |---|---|
200
+ | `QB_TRIGGER_REJECTED:<CODE>: <message>` | 422 `TRIGGER_REJECTED` |
201
+ | `QB_TRIGGER_FORBIDDEN:<CODE>: <message>` | 403 `TRIGGER_REJECTED` |
202
+ | anything else | 500 — the write path's ordinary failure (`DB_*_FAILED`, or `ACTION_EXECUTION_FAILED` in an action) |
203
+
204
+ ```sql
205
+ -- D1
206
+ SELECT RAISE(ABORT, 'QB_TRIGGER_FORBIDDEN:GUEST_CROSS_TENANT: event belongs to another organization');
207
+ -- Postgres
208
+ RAISE EXCEPTION 'QB_TRIGGER_REJECTED:EMAIL_LOCKED: email is fixed once linked';
209
+ ```
210
+
211
+ `<CODE>` lands in `details.code` and `<message>` is the response's error text,
212
+ so put nothing in either that the caller may not see. The mapping applies on
213
+ every write path: CRUD routes, batch, actions, changesets and the SEALED
214
+ routes. Use
215
+ `FORBIDDEN` for authorization refusals such as cross-tenant references, and
216
+ `REJECTED` for data rules. An unprefixed `RAISE` cannot be told apart from
217
+ any other driver failure, so it stays a 500.
218
+
190
219
  ### Soft-delete mapping
191
220
 
192
221
  On soft-delete tables (the default), `*Delete` events map to the
@@ -237,7 +266,8 @@ an [action](/define/actions/scoped-db#reaching-better-auth-tables-authdb).
237
266
 
238
267
  - **`before*` hooks are synchronous.** Return a partial object to merge
239
268
  into the write payload, or throw to reject — the write never executes and
240
- the request gets a structured `TRIGGER_REJECTED` (422) error. Audit
269
+ the request gets a structured `TRIGGER_REJECTED` (422) error on every
270
+ write path (CRUD, batch, actions, changesets). Audit
241
271
  fields (`createdBy`, `modifiedAt`, …) are re-stamped after hooks run and
242
272
  cannot be forged. A `before*` hook gets `values`, the pending write, and
243
273
  never the stored row: nothing is read before the write. Destructuring `row`
@@ -202,7 +202,7 @@ The compiler always emits a per-route rule for **every** credential endpoint
202
202
  Better Auth mounts — not just password sign-in — so an OTP verify door (a
203
203
  6-digit, 10<sup>6</sup>-space code) is never left under the 100/min general
204
204
  limit. Your `customRules` **merge on top**: declare a path to change its limit,
205
- or add paths for project plugins.
205
+ `false` to exempt it, or add paths for project plugins.
206
206
 
207
207
  | Route(s) | Default | Reasoning |
208
208
  |----------|---------|-----------|
@@ -214,6 +214,7 @@ or add paths for project plugins.
214
214
  | `/phone-number/send-otp`, `/phone-number/verify`, `/phone-number/request-password-reset`, `/phone-number/reset-password` | 5/min per IP | SMS OTP brute force + SMS cost |
215
215
  | `/two-factor/send-otp`, `/two-factor/verify-otp`, `/two-factor/verify-totp`, `/two-factor/verify-backup-code` | 5/min per IP | Second-factor brute force |
216
216
  | `/device/init` / `/device/poll` / `/device/token` | 5 / 30 / 10 per min per IP | Device-code enumeration, polling, token exchange |
217
+ | `/get-session`, `/token` | **exempt** | Read-only, called on every page load; not credential doors. With database storage each limited call is a counter read and write in front of the session check. Declare the path in `customRules` to limit it again |
217
218
  | Everything else under `/auth/v1` | `max` (100/min per IP) | General abuse prevention |
218
219
 
219
220
  Set an edge rate-limit binding as well for defence in depth
@@ -203,6 +203,9 @@ placeholder state.
203
203
  The environment contract is intentionally exact and fails closed:
204
204
 
205
205
  - `workersDev: true` and `previewUrls: false` must be explicit for each target.
206
+ - `worker.placement` (`{ mode }` or `{ region }`) sets that target's
207
+ [placement](/configure/providers#runtime-options); without it, the top-level
208
+ `providers.runtime.config.placement` is emitted for the target.
206
209
  - Each target declares its own `name` (the Wrangler worker name) and no two
207
210
  share one. It is the deployed script's identity — Durable Object state and
208
211
  the migration ledger belong to it — so it is never derived. An existing
@@ -339,8 +342,10 @@ connection string from the Hyperdrive configuration identified by `id`.
339
342
  > its unpooled URL for `DATABASE_MIGRATION_URL`), and `quickback` (the Worker
340
343
  > runtime role, the **only** deployed DB role — use its pooled URL for
341
344
  > `DATABASE_URL`). The first generated migration bootstraps these roles as
342
- > NOLOGIN; enable login and set passwords before use. Full walkthrough in the
343
- > generated `docs/neon-setup.md`.
345
+ > NOLOGIN; enable login and set passwords before use. It also gives `quickback`
346
+ > `statement_timeout`, `idle_in_transaction_session_timeout` and (PostgreSQL 17+)
347
+ > `transaction_timeout` — see [Worker-role timeouts](/platform/database/planetscale-postgres#worker-role-timeouts).
348
+ > Full walkthrough in the generated `docs/neon-setup.md`.
344
349
  >
345
350
  > Run the **first** `db:migrate` with your database owner credential (Neon's
346
351
  > `neondb_owner`) — that bootstrap run also grants `quickback_admin` everything
@@ -525,6 +530,11 @@ SELECT
525
530
  set_config('quickback.principal.claims', '{}', true);
526
531
  ```
527
532
 
533
+ On Hyperdrive the values are not bound parameters: each is hex-encoded and
534
+ decoded in SQL (`convert_from(decode('…', 'hex'), 'UTF8')`), so the preamble is
535
+ a single parameterless statement that shares a message with `BEGIN` and the SQL
536
+ text can never contain a claim value verbatim.
537
+
528
538
  RLS policies read those settings through Quickback-defined helper functions —
529
539
  there is no external JWT verification and no persisted session state in the
530
540
  database. `auth.user_id()` is a compiler-generated shim, not a Neon Authorize
@@ -560,6 +570,16 @@ masking. RLS exists so that a bug in a custom route, or a handle that escaped
560
570
  its scope, cannot cross a tenant, resurrect a soft-deleted row, or read another
561
571
  owner's row. It is the floor under the application, not a second application.
562
572
 
573
+ **Who RLS backstops.** The request database handle stamps caller claims only
574
+ for callers the policies can key on: a signed-in **account** (`ctx.userId`) and
575
+ a **delegated principal** (whose `databaseAccess` lane is enforced only here).
576
+ Every other caller — a `PUBLIC` door, a sessionless scope principal such as an
577
+ event pass — runs on the service lane, and the generated app firewall scopes
578
+ each of its queries, exactly as on D1. Without that, those callers would read
579
+ nothing: no policy recognises an anonymous or scope-only caller, so a pass
580
+ holder's namespace gate and a scope mint's relationship lookup both came back
581
+ empty.
582
+
563
583
  Quickback lowers your `firewall` config — and only your `firewall` config —
564
584
  into policies that read the transaction-local claims described above through
565
585
  `auth.user_id()`, `get_active_org_id()`, `get_active_team_id()`, `get_scope()`
@@ -940,7 +960,7 @@ stamps the active organization, and policies compare against that stamp.
940
960
  `is_admin()` is no part of that gate either. Enabling the admin plugin does
941
961
  **not** widen any scope policy: "admin" is a role, and a scope policy is the
942
962
  firewall predicate, full stop. An admin's cross-tenant read goes through the
943
- API on the service lane — an `unsafe: { crossTenant: true }` action stamps
963
+ API on the service lane — an `unsafe` action stamps
944
964
  `quickback.service_role`, which `<table>_service_role` admits — not by SQL
945
965
  re-deriving admin from `auth.admins`. Older databases carry the previous
946
966
  `(public.is_admin() OR (…))` form until the new security migration replaces
@@ -979,8 +999,8 @@ and existing counter rows are preserved.
979
999
 
980
1000
  ## Background jobs and cross-tenant actions
981
1001
 
982
- Some code runs with no HTTP request and therefore no caller claims: queue
983
- consumers, cron schedules, and cross-tenant `unsafe` actions. These acquire the
1002
+ Some code runs with no HTTP request and therefore no caller claims — queue
1003
+ consumers, cron schedules — and `unsafe` actions opt out of them. These acquire the
984
1004
  **service-role handle** `createServiceDb(env)` from the generated `src/db`
985
1005
  index. Instead of caller claims, it sets `quickback.service_role = 'true'` (with
986
1006
  all request claims cleared) — the same marker the Better Auth adapter's
@@ -990,7 +1010,9 @@ across tenants while the request-scoped `createDb()` client stays caller-scoped.
990
1010
 
991
1011
  The service-role marker is only ever set by Worker-internal chokepoints
992
1012
  (`createServiceDb`, the Better Auth adapter) — it is never derived from request
993
- input. Unsafe actions keep their mandatory audit contract: cross-tenant writes
1013
+ input. Every `unsafe` action gets this handle as `unsafeDb`, `crossTenant`
1014
+ or not, so it reads what it would read on D1 — RLS does not narrow it to the
1015
+ caller. Unsafe actions keep their mandatory audit contract: cross-tenant writes
994
1016
  still land audit events (the `audit` Postgres schema), unchanged from D1.
995
1017
 
996
1018
  ## Reads through a user-anchored relationship
@@ -1213,10 +1235,30 @@ providers: {
1213
1235
  ```
1214
1236
 
1215
1237
  The compiler emits the `[[hyperdrive]]` wrangler binding pointing at your Neon
1216
- **direct** connection string. Its request-scoped postgres.js client uses
1217
- `max: 5`, disables prepared statements, and skips type-fetch round trips — the
1218
- small client pool bounds origin connections per Worker isolate while
1219
- Hyperdrive owns the shared connection pool.
1238
+ **direct** connection string. Each Worker invocation (request, queue batch,
1239
+ cron, inbound email) opens **one** lease pool of up to five single-connection
1240
+ postgres.js clients, shared by every `createDb` / `createServiceDb` call in it
1241
+ — the request db, Better Auth, idempotency, the audit writer. Statements are
1242
+ **prepared** (Cloudflare's guidance for postgres.js on Hyperdrive, which caches
1243
+ named prepared statements; an unprepared statement costs an extra
1244
+ parameter-describe round trip) and type-fetch round trips are skipped;
1245
+ Hyperdrive owns the origin pool.
1246
+
1247
+ Every single statement runs as one **pipelined claims transaction** on a leased
1248
+ connection: `BEGIN` plus the claims preamble travel as one message, then the
1249
+ statement, then `COMMIT`, all written before anything is awaited. That is one
1250
+ round trip once the statement is prepared on that connection and three while it
1251
+ is cold — down from six. It fails closed by construction: a preamble that
1252
+ errors after `BEGIN` aborts the transaction so the statement is refused rather
1253
+ than run unscoped, and a failed statement turns the pipelined `COMMIT` into
1254
+ `ROLLBACK`.
1255
+
1256
+ The pool closes when the invocation ends, after its `waitUntil` work
1257
+ (deferred audit writes, after-commit effects) settles. A client that is never
1258
+ closed leaves its backends mid-transaction, holding Hyperdrive origin
1259
+ connections until Postgres times them out. Code outside an invocation — a
1260
+ Durable Object, a test — gets a fresh pool per `createDb` call and owns
1261
+ closing it.
1220
1262
 
1221
1263
  > Postgres authorizes `SELECT … FOR UPDATE` as both a read and a write: the row
1222
1264
  > must pass its `SELECT` **and** `UPDATE` policies. This matters for delegated
@@ -1418,11 +1460,11 @@ export const interviewScores = pgTable('interview_scores', {
1418
1460
  interviewId: text('interview_id').notNull(),
1419
1461
  rating: integer('rating').notNull(),
1420
1462
  // ── quickback:audit (compiler-managed — edits are validated, not merged) ──
1421
- createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
1422
- modifiedAt: timestamp('modified_at', { withTimezone: true }).notNull().defaultNow().$onUpdate(() => new Date()),
1463
+ createdAt: timestamp('created_at', { withTimezone: true, precision: 3 }).notNull().defaultNow(),
1464
+ modifiedAt: timestamp('modified_at', { withTimezone: true, precision: 3 }).notNull().defaultNow().$onUpdate(() => new Date()),
1423
1465
  createdBy: text('created_by'),
1424
1466
  modifiedBy: text('modified_by'),
1425
- deletedAt: timestamp('deleted_at', { withTimezone: true }),
1467
+ deletedAt: timestamp('deleted_at', { withTimezone: true, precision: 3 }),
1426
1468
  deletedBy: text('deleted_by'),
1427
1469
  });
1428
1470
  ```
@@ -1440,10 +1482,16 @@ Tables **with** `defineTable(...)` are unaffected — existing `sqliteTable`
1440
1482
  sources with a resource config still compile to the Postgres dialect
1441
1483
  automatically. Managed audit timestamps declared in the SQLite shape
1442
1484
  (`createdAt` / `modifiedAt` / `deletedAt` as `text`) are emitted as
1443
- `timestamptz`, like every other Postgres table — the audit wrapper and the RLS
1485
+ `timestamptz(3)`, like every other Postgres table — the audit wrapper and the RLS
1444
1486
  audit triggers both stamp timestamps, not strings. API responses carry the same
1445
1487
  ISO-8601 string as on D1.
1446
1488
 
1489
+ Managed audit timestamps are stored at millisecond precision (`timestamptz(3)`),
1490
+ and the audit triggers stamp `date_trunc('milliseconds', now())`, so keyset
1491
+ cursors page them exactly. Projects last compiled by 0.69.0 or earlier get a
1492
+ type-change migration on the next compile that rounds existing values — see
1493
+ [How auto-injection works](/define/schema#how-auto-injection-works-two-layers).
1494
+
1447
1495
  ## When to choose Neon vs D1
1448
1496
 
1449
1497
  | Factor | Neon | D1 |
@@ -79,6 +79,23 @@ ALTER ROLE quickback_admin LOGIN PASSWORD '<strong-admin-password>';
79
79
  ALTER ROLE quickback LOGIN PASSWORD '<strong-password>';
80
80
  ```
81
81
 
82
+ ### Worker-role timeouts
83
+
84
+ The role bootstrap sets three timeouts on `quickback`, so a Worker invocation
85
+ that dies mid-transaction cannot hold a connection (and its locks) open:
86
+
87
+ | Setting | Value | Ends |
88
+ |---|---|---|
89
+ | `statement_timeout` | `30s` | a runaway statement |
90
+ | `idle_in_transaction_session_timeout` | `15s` | an open transaction the Worker stopped talking to |
91
+ | `transaction_timeout` | `60s` | any transaction older than that, including one stuck mid-statement waiting on the client — PostgreSQL 17+ only |
92
+
93
+ Each is set only when the role does not already carry it, so a value you set
94
+ with `ALTER ROLE quickback SET …` survives every later migration. Existing
95
+ databases get them from the next appended `quickback_rls` migration, applied
96
+ with the setup-owner credential. If the applying user cannot alter the role,
97
+ the migration skips them with a `NOTICE`; set them as the owner instead.
98
+
82
99
  ### SQL role vs connection username
83
100
 
84
101
  PlanetScale routes a connection to a branch by a suffix on the username. The
@@ -136,6 +153,10 @@ binding = "HYPERDRIVE"
136
153
  id = "ffffffffffffffffffffffffffffffff"
137
154
  ```
138
155
 
156
+ Each Worker invocation shares one postgres.js client across every database
157
+ handle it opens and closes it when the invocation ends — see
158
+ [Neon → Interactive transactions](/platform/database/neon#interactive-transactions) for the details.
159
+
139
160
  ## No `DATABASE_URL` Worker secret
140
161
 
141
162
  Feature queries and Better Auth both read `env.HYPERDRIVE.connectionString`.
@@ -164,6 +185,12 @@ carrying `localConnectionString`. Since every environment runs the same
164
185
  bundle, a target that shares another target's Hyperdrive id shares its
165
186
  database — the compiler requires each one to declare its own.
166
187
 
188
+ Set `providers.runtime.config.placement: { region: "aws:us-east-2" }` (your
189
+ branch's region) so the Worker runs next to the database — every statement is
190
+ several round-trips, so Worker-to-database distance dominates latency. A target
191
+ whose branch lives elsewhere overrides it with
192
+ `environments.<name>.worker.placement`.
193
+
167
194
  ## What is shared with Neon, and what is not
168
195
 
169
196
  Shared — read the Neon page for the detail, it is the same generated output:
@@ -187,7 +187,7 @@ Claude generates correct syntax for your database:
187
187
  createdAt: text("created_at").notNull().default('1970-01-01T00:00:00.000Z').$defaultFn(() => new Date().toISOString())
188
188
 
189
189
  // PostgreSQL / Neon
190
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
190
+ createdAt: timestamp("created_at", { withTimezone: true, precision: 3 }).notNull().defaultNow()
191
191
  ```
192
192
 
193
193
  In the `q` DSL you write `...q.audit()` instead and the compiler emits the