@quickback-dev/cli 0.68.0 → 0.69.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.
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.69.0";
14
14
  function getPackageVersion() {
15
15
  return CLI_VERSION;
16
16
  }
@@ -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
 
@@ -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
@@ -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
 
@@ -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`
@@ -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
@@ -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:
@@ -107,6 +107,43 @@ Quickback now adds a D1-specific safety pass around Drizzle-generated migrations
107
107
 
108
108
  If `quickback build` now fails with a D1 replay error, treat that as a real migration problem instead of a deploy-time surprise. The generated SQL needs manual intervention or a schema change that Drizzle can express more safely.
109
109
 
110
+ ### Postgres: column "…" cannot be cast automatically
111
+
112
+ On Postgres providers (`neon`, `planetscale-postgres`), Drizzle emits a column
113
+ type change as a bare `ALTER COLUMN … SET DATA TYPE`, which Postgres refuses
114
+ when no implicit cast exists — for example when the `text` audit columns of a
115
+ pre-0.68 journal become `timestamptz`. In a newly generated migration,
116
+ Quickback rewrites a change to a timestamp, date/time, numeric, boolean,
117
+ `uuid`, or `json`/`jsonb` type as `SET DATA TYPE <type> USING "<col>"::<type>`,
118
+ so existing rows convert in place. It drops the column's old default first when
119
+ the same migration sets or drops it afterwards; a default is never removed
120
+ otherwise.
121
+
122
+ Changes to length-limited types (`varchar(n)`, `char(n)`, `bit(n)`) and arrays
123
+ stay bare: an explicit cast would silently truncate values the bare statement
124
+ rejects. Add `USING` by hand if you need one there.
125
+
126
+ Existing migrations are never rewritten. If an earlier compiler generated a
127
+ type-change migration that fails with this error, it never applied — `npm run
128
+ db:migrate` runs pending migrations in one transaction, and a failure records
129
+ nothing in `drizzle.__drizzle_migrations`. Fix it in one of two ways:
130
+
131
+ - **It is the newest migration:** delete that `.sql` file, its
132
+ `meta/NNNN_snapshot.json`, and its `meta/_journal.json` entry, then rebuild
133
+ to regenerate it.
134
+ - **Later migrations follow it:** edit the failing statement in place before
135
+ applying it. Add `USING "<col>"::<type>` and, if the column has a default
136
+ that cannot be cast, a `DROP DEFAULT` statement before it:
137
+
138
+ ```sql
139
+ ALTER TABLE "app"."events" ALTER COLUMN "created_at" DROP DEFAULT;
140
+ --> statement-breakpoint
141
+ ALTER TABLE "app"."events" ALTER COLUMN "created_at" SET DATA TYPE timestamp with time zone USING "created_at"::timestamp with time zone;
142
+ ```
143
+
144
+ The drizzle migrator does not compare hashes of applied migrations, and a
145
+ recompile hands the edited file back unchanged.
146
+
110
147
  ### Recompile changed the comments at the top of an old migration
111
148
 
112
149
  A recompile hands every existing migration back byte-for-byte, including the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.68.0",
3
+ "version": "0.69.0",
4
4
  "description": "CLI for Quickback — define your backend in TypeScript, compile to a fully wired Cloudflare Worker (or Bun / Node) with auth, database, migrations, security, CMS, and Account UI.",
5
5
  "author": "Kardoe Incorporated <paul@kardoe.com>",
6
6
  "license": "MIT",
@@ -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
 
@@ -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
@@ -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
 
@@ -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`
@@ -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
@@ -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:
@@ -107,6 +107,43 @@ Quickback now adds a D1-specific safety pass around Drizzle-generated migrations
107
107
 
108
108
  If `quickback build` now fails with a D1 replay error, treat that as a real migration problem instead of a deploy-time surprise. The generated SQL needs manual intervention or a schema change that Drizzle can express more safely.
109
109
 
110
+ ### Postgres: column "…" cannot be cast automatically
111
+
112
+ On Postgres providers (`neon`, `planetscale-postgres`), Drizzle emits a column
113
+ type change as a bare `ALTER COLUMN … SET DATA TYPE`, which Postgres refuses
114
+ when no implicit cast exists — for example when the `text` audit columns of a
115
+ pre-0.68 journal become `timestamptz`. In a newly generated migration,
116
+ Quickback rewrites a change to a timestamp, date/time, numeric, boolean,
117
+ `uuid`, or `json`/`jsonb` type as `SET DATA TYPE <type> USING "<col>"::<type>`,
118
+ so existing rows convert in place. It drops the column's old default first when
119
+ the same migration sets or drops it afterwards; a default is never removed
120
+ otherwise.
121
+
122
+ Changes to length-limited types (`varchar(n)`, `char(n)`, `bit(n)`) and arrays
123
+ stay bare: an explicit cast would silently truncate values the bare statement
124
+ rejects. Add `USING` by hand if you need one there.
125
+
126
+ Existing migrations are never rewritten. If an earlier compiler generated a
127
+ type-change migration that fails with this error, it never applied — `npm run
128
+ db:migrate` runs pending migrations in one transaction, and a failure records
129
+ nothing in `drizzle.__drizzle_migrations`. Fix it in one of two ways:
130
+
131
+ - **It is the newest migration:** delete that `.sql` file, its
132
+ `meta/NNNN_snapshot.json`, and its `meta/_journal.json` entry, then rebuild
133
+ to regenerate it.
134
+ - **Later migrations follow it:** edit the failing statement in place before
135
+ applying it. Add `USING "<col>"::<type>` and, if the column has a default
136
+ that cannot be cast, a `DROP DEFAULT` statement before it:
137
+
138
+ ```sql
139
+ ALTER TABLE "app"."events" ALTER COLUMN "created_at" DROP DEFAULT;
140
+ --> statement-breakpoint
141
+ ALTER TABLE "app"."events" ALTER COLUMN "created_at" SET DATA TYPE timestamp with time zone USING "created_at"::timestamp with time zone;
142
+ ```
143
+
144
+ The drizzle migrator does not compare hashes of applied migrations, and a
145
+ recompile hands the edited file back unchanged.
146
+
110
147
  ### Recompile changed the comments at the top of an old migration
111
148
 
112
149
  A recompile hands every existing migration back byte-for-byte, including the