@pgxsinkit/contracts 0.2.5 → 0.2.6
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/event-stream.d.ts +158 -0
- package/dist/event-stream.d.ts.map +1 -0
- package/dist/events.d.ts +158 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +588 -69
- package/dist/index.js.map +11 -7
- package/dist/projection.d.ts +2 -2
- package/dist/projection.d.ts.map +1 -1
- package/dist/registry-diff.d.ts +57 -4
- package/dist/registry-diff.d.ts.map +1 -1
- package/dist/registry-invariant.d.ts +110 -0
- package/dist/registry-invariant.d.ts.map +1 -0
- package/dist/registry.d.ts +144 -1
- package/dist/registry.d.ts.map +1 -1
- package/dist/sql-role-guard.d.ts +21 -0
- package/dist/sql-role-guard.d.ts.map +1 -0
- package/dist/supabase-rls.d.ts +113 -8
- package/dist/supabase-rls.d.ts.map +1 -1
- package/package.json +1 -1
- package/skills/registry-authoring/SKILL.md +280 -222
- package/src/event-stream.ts +214 -0
- package/src/events.ts +154 -0
- package/src/index.ts +4 -0
- package/src/projection.ts +7 -2
- package/src/registry-diff.ts +235 -7
- package/src/registry-invariant.ts +218 -0
- package/src/registry.ts +413 -3
- package/src/sql-role-guard.ts +33 -0
- package/src/supabase-rls.ts +336 -48
|
@@ -2,20 +2,20 @@
|
|
|
2
2
|
name: registry-authoring
|
|
3
3
|
description: >-
|
|
4
4
|
Load when defining or changing a pgxsinkit sync registry with @pgxsinkit/contracts —
|
|
5
|
-
defineSyncRegistry / defineSyncTable,
|
|
6
|
-
|
|
7
|
-
server-version managed field plus a conflictPolicy (no default), authClaim/nowMicroseconds
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
5
|
+
defineSyncRegistry / defineSyncTable, sync modes, managed fields, conflict policy, filters, RLS.
|
|
6
|
+
Teaches the rules that throw or fail closed if missed: every readwrite table needs a
|
|
7
|
+
server-version managed field plus a conflictPolicy (no default), authClaim/nowMicroseconds fields are
|
|
8
|
+
server-assigned and rejected in client payloads, enum columns must be cast to text, read filter and RLS
|
|
9
|
+
policy must derive from one predicate, and the apply function is provisioned by the pgxsinkit-generate
|
|
10
|
+
CLI as a drizzle-kit migration. Covers per-client mode projection (ADR-0025,
|
|
11
|
+
asReadonly + assertReadContractPreserved) and Event-stream registration (ADR-0053): the streams key,
|
|
12
|
+
defineEventStream, name limits at module eval, claimPath identity stamping, compatibility-bound payload
|
|
13
|
+
evolution, and streams riding the lock/diff but never the fingerprint. Load before authoring a registry,
|
|
14
|
+
adding a table, registering an Event stream, or wiring RLS.
|
|
15
15
|
metadata:
|
|
16
16
|
type: core
|
|
17
17
|
library: "@pgxsinkit/contracts"
|
|
18
|
-
library_version: "0.2.
|
|
18
|
+
library_version: "0.2.6"
|
|
19
19
|
source: https://pgxsinkit.github.io/start/getting-started/
|
|
20
20
|
---
|
|
21
21
|
|
|
@@ -29,9 +29,9 @@ is what keeps read and write authorization from drifting.
|
|
|
29
29
|
|
|
30
30
|
`defineSyncRegistry` **throws** unless every `mode: "readwrite"` table declares **both**:
|
|
31
31
|
|
|
32
|
-
1. A **server version** — a `nowMicroseconds`-on-`update` managed field, conventionally `updated_at_us`
|
|
33
|
-
|
|
34
|
-
|
|
32
|
+
1. A **server version** — a `nowMicroseconds`-on-`update` managed field, conventionally `updated_at_us` (a
|
|
33
|
+
`bigint` microsecond column). Optimistic convergence keys on it, and `reject-if-stale` compares the
|
|
34
|
+
write's base version against it.
|
|
35
35
|
2. A **`conflictPolicy`** — `"reject-if-stale"` or `"last-write-wins"`. There is **no silent default**,
|
|
36
36
|
because a silent last-write-wins is exactly the data loss the choice exists to surface.
|
|
37
37
|
|
|
@@ -58,68 +58,59 @@ widgets: defineSyncTable({
|
|
|
58
58
|
|
|
59
59
|
**Column types don't constrain sync.** The read-path backfill picks a bulk-insert tier (COPY / JSON /
|
|
60
60
|
per-row `INSERT`) statically from a table's Drizzle column types; enum columns and `GENERATED ALWAYS AS
|
|
61
|
-
IDENTITY` primary keys are fully supported (
|
|
62
|
-
|
|
63
|
-
|
|
61
|
+
IDENTITY` primary keys are fully supported (labels round-trip through COPY/JSON, a synced identity PK keeps
|
|
62
|
+
the server's value via `OVERRIDING SYSTEM VALUE`), so never avoid them for sync's sake. **Array columns are
|
|
63
|
+
supported at ONE dimension** (`uuid("source_ids").array()`) on both paths: a write sends a JSON array, `[]`
|
|
64
|
+
stores an empty array and JSON `null` stores NULL, element order preserved. Everything else about arrays
|
|
65
|
+
fails at GENERATE time, named — `.array("[][]")` (multi-dimensional), an array PK column, and an array
|
|
66
|
+
`managedFields` target (both strategies stamp one scalar).
|
|
64
67
|
|
|
65
68
|
## The `primaryKey` spec emits the physical PRIMARY KEY — it is the single source of truth
|
|
66
69
|
|
|
67
|
-
`defineSyncTable` **emits** the `primaryKey` spec as the server table's physical `PRIMARY KEY` constraint
|
|
68
|
-
|
|
69
|
-
does not produce), so DDL declared through pgxsinkit agrees with plain-Postgres inline-PK DDL and
|
|
70
|
-
drizzle-kit sees no rename churn against a real Postgres database. The spec was runtime-only metadata
|
|
71
|
-
until a consumer had drizzle-kit DROP a live composite key — seeing no PK in the generated DDL — so the
|
|
72
|
-
spec now drives DDL directly.
|
|
70
|
+
`defineSyncTable` **emits** the `primaryKey` spec as the server table's physical `PRIMARY KEY`, named `` `${tableName}_pkey` `` — Postgres's default inline-PK constraint name (which drizzle's naming does not
|
|
71
|
+
produce), so pgxsinkit DDL matches plain-Postgres inline-PK DDL and drizzle-kit sees no rename churn.
|
|
73
72
|
|
|
74
73
|
- **Composite / non-`id` key:** `primaryKey: ["org_id", "person_id"]` (default `["id"]`). Constraint
|
|
75
74
|
columns follow spec order.
|
|
76
75
|
- **Custom constraint name:** the object form `primaryKey: { name: "org_person_pk", columns: [...] }`.
|
|
77
|
-
- **Single-column key, idiomatic drizzle:**
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
- **Rejected:** a table-level `primaryKey(...)` passed through `extras`/`policies`, and more than one
|
|
83
|
-
column-level `.primaryKey()` — declare composite keys via the `primaryKey` option instead.
|
|
76
|
+
- **Single-column key, idiomatic drizzle:** `id: uuid("id").primaryKey()` on the column is allowed and
|
|
77
|
+
equivalent — it must match the spec, and emission is skipped. A custom constraint name cannot be combined
|
|
78
|
+
with a column-level `.primaryKey()` (a named constraint needs `defineSyncTable` to emit it).
|
|
79
|
+
- **Rejected:** a table-level `primaryKey(...)` through `extras`/`policies`, and more than one column-level
|
|
80
|
+
`.primaryKey()` — declare composite keys via the `primaryKey` option instead.
|
|
84
81
|
|
|
85
82
|
## `applyMode` — CDC insert-apply policy (default stays strict)
|
|
86
83
|
|
|
87
84
|
`applyMode` chooses how a **server CDC insert** for this table is applied on the client (ADR-0045).
|
|
85
|
+
**`"insert"` (default)** is a plain INSERT with no conflict clause, so a genuine primary-key collision
|
|
86
|
+
**surfaces** (the ADR-0014 invariant — a synced cache table is server-authoritative, and a duplicate insert
|
|
87
|
+
is a real bug). **`"upsert"`** applies it idempotently as `INSERT … ON CONFLICT (pk) DO UPDATE` (or a
|
|
88
|
+
pk-targeted `DO NOTHING` for a pk-only table), so the authoritative server row overwrites the provisional
|
|
89
|
+
local one.
|
|
88
90
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
(or a pk-targeted `DO NOTHING` for a pk-only table); the authoritative server row overwrites the
|
|
94
|
-
provisional local row.
|
|
95
|
-
|
|
96
|
-
**When to use `"upsert"`:** only when this table legitimately receives locally-**derived** provisional
|
|
97
|
-
rows — e.g. a local trigger on another synced table writes a provisional row here, and the server
|
|
98
|
-
independently creates the same row, so its CDC insert would otherwise collide (23505) and degrade the
|
|
99
|
-
engine. It routes all three CDC-insert paths (initial bulk snapshot, steady-state fold, per-message)
|
|
100
|
-
through the idempotent applier. Declare the exception on the table where it lives; never weaken the
|
|
101
|
-
strict default repo-wide.
|
|
91
|
+
**Use `"upsert"` only** when this table legitimately receives locally-**derived** provisional rows — a local
|
|
92
|
+
trigger on another synced table writes a row here that the server independently creates too, so its CDC insert
|
|
93
|
+
would otherwise collide (23505) and degrade the engine. It routes all three CDC-insert paths through the
|
|
94
|
+
idempotent applier. Declare the exception where it lives; never weaken the default repo-wide.
|
|
102
95
|
|
|
103
96
|
## Managed fields are server-assigned — never send them
|
|
104
97
|
|
|
105
98
|
A managed field is stamped by the apply function under the verified request claims. Two strategies:
|
|
106
99
|
|
|
107
100
|
- **`nowMicroseconds`** — `clock_timestamp()` microseconds (the audit columns; the `updated_at_us`-on-update
|
|
108
|
-
field is the strictly-monotonic server version)
|
|
109
|
-
|
|
110
|
-
**utilities migration** (`renderPgxsinkitUtilitiesMigration` / `pgxsinkit-generate --utilities`) which must
|
|
101
|
+
field is the strictly-monotonic server version), stamped by the canonical `public.pgxsinkit_clock_us()`
|
|
102
|
+
function — one home for the clock semantics: `clock_timestamp()`, never `now()`. It is installed by the
|
|
103
|
+
**utilities migration** (`renderPgxsinkitUtilitiesMigration` / `pgxsinkit-generate --utilities`), which must
|
|
111
104
|
be the **first folder** in your migration chain, before the schema and the generated sync-artifact.
|
|
112
|
-
- **`authClaim`** — a value read from a verified JWT claim at a JSON `claimPath
|
|
113
|
-
claim-stamping strategy: `["sub"]` is the auth subject (the old `auth.uid()`
|
|
114
|
-
`["app_metadata", "person_id"]`
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
these, so a client value would either be overwritten or rejected. The optimistic overlay still fills an
|
|
122
|
-
`authClaim` create field locally from the decoded claim, so the row renders attributed immediately.)
|
|
105
|
+
- **`authClaim`** — a value read from a verified JWT claim at a JSON `claimPath`, and the **single**
|
|
106
|
+
claim-stamping strategy: `["sub"]` is the auth subject (the old `auth.uid()` idiom),
|
|
107
|
+
`["app_metadata", "person_id"]` any app-minted identity. `cast` is optional and **defaults to the target
|
|
108
|
+
column's SQL type**; path segments must be plain identifiers (they are emitted into the apply-function DDL).
|
|
109
|
+
|
|
110
|
+
The write API **rejects** a payload that _includes_ a managed field, and the create-validation schema
|
|
111
|
+
**omits** managed-on-create fields — so never put `updated_at_us` or a claim-stamped owner in a client
|
|
112
|
+
payload. The optimistic overlay still fills an `authClaim` create field from the decoded claim, so the row
|
|
113
|
+
renders attributed immediately. A managed field's target column must be scalar (an array one throws).
|
|
123
114
|
|
|
124
115
|
## Omitted columns are invisible to the write path — by design
|
|
125
116
|
|
|
@@ -127,29 +118,24 @@ these, so a client value would either be overwritten or rejected. The optimistic
|
|
|
127
118
|
client, and the apply function reads **only a table's projected columns** from a write payload. A payload key
|
|
128
119
|
that is not a writable (projected) column splits into exactly two cases:
|
|
129
120
|
|
|
130
|
-
- **A projected-away / server-only column**
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
(table, key) per process** naming the dropped key — a diagnostic, not a rejection. It fires _only_ for this
|
|
137
|
-
unknown-key case, never for a projected-away column (which is rejected, not dropped).
|
|
121
|
+
- **A projected-away / server-only column** sent _explicitly_ in a payload is **400-rejected** by the write
|
|
122
|
+
route's projected-field check — not silently dropped, and the write does **not** succeed.
|
|
123
|
+
- **An unknown non-column key** (a typo, a stale field) is **silently ignored by the apply function**: that
|
|
124
|
+
write collapses to a bare server-version bump and still acks `succeeded`. To make the silence observable
|
|
125
|
+
the write API emits **one structured `console.warn` per (table, key) per process** — a diagnostic, fired
|
|
126
|
+
only here and never for a projected-away column (which is rejected, not dropped).
|
|
138
127
|
|
|
139
128
|
The rule that follows: **write a server-only (omitted) column outside the sync rail** — a server-side
|
|
140
|
-
`UPDATE`, a trigger, or a managed field (`governance.managedFields
|
|
141
|
-
try to set it from a client `create`/`update` payload; the route rejects it.
|
|
129
|
+
`UPDATE`, a trigger, or a managed field (`governance.managedFields`); the route rejects it in a payload.
|
|
142
130
|
|
|
143
131
|
## Read-path filtering: `customWhere` runs in Electric, not Postgres
|
|
144
132
|
|
|
145
|
-
A table's `shape.rowFilter.customWhere` builds the Electric shape `where
|
|
146
|
-
Postgres)
|
|
147
|
-
through `c(column)` and embed request-derived values directly
|
|
133
|
+
A table's `shape.rowFilter.customWhere` builds the Electric shape `where`, which **Electric** evaluates (not
|
|
134
|
+
Postgres) — so **return a Drizzle `SQL` fragment built from the table's columns**: reference each column
|
|
135
|
+
through `c(column)` and embed request-derived values directly, where they become **bound `$n` params**, not
|
|
148
136
|
hand-escaped literals.
|
|
149
137
|
|
|
150
138
|
```ts
|
|
151
|
-
import { c, DENY_ALL } from "@pgxsinkit/contracts";
|
|
152
|
-
|
|
153
139
|
function widgetsReadFilter(claims) {
|
|
154
140
|
if (isAdmin(claims)) return null; // null = no filter (all rows visible)
|
|
155
141
|
if (!claims.sub) return DENY_ALL; // sql`false` — the deny-all sentinel (no rows visible)
|
|
@@ -157,19 +143,16 @@ function widgetsReadFilter(claims) {
|
|
|
157
143
|
}
|
|
158
144
|
```
|
|
159
145
|
|
|
160
|
-
Two Electric where-grammar rules: columns must be **plain** (unqualified) — `c()` emits the bare
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
to block all rows.
|
|
146
|
+
Two Electric where-grammar rules: columns must be **plain** (unqualified) — `c()` emits the bare
|
|
147
|
+
`"owner_id"`, never Drizzle's qualified `"widgets"."owner_id"` (Electric rejects that) — and an **enum column
|
|
148
|
+
must be cast to text** (`${c(widgets.role)}::text = 'manager'`). Subqueries must be self-contained (not
|
|
149
|
+
correlated). A raw **string** is the escape hatch: escape embedded values yourself with `escapeSqlLiteral`,
|
|
150
|
+
and return `DENY_ALL` (not `"1 = 0"`) to block all rows.
|
|
166
151
|
|
|
167
152
|
**Inline (all-in-one `defineSyncTable`) — `rowFilter` as a function of the columns.** The example above
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
Give `shape.rowFilter` a **function of the built columns** (the same typed columns `extras` receives) and
|
|
172
|
-
keep using `c()`:
|
|
153
|
+
assumes the table is built _elsewhere_. Declaring a table and its filter in **one** call, the table object
|
|
154
|
+
does not exist yet — so don't fall back to column-name strings: give `shape.rowFilter` a **function of the
|
|
155
|
+
built columns** (the typed columns `extras` gets), still with `c()`:
|
|
173
156
|
|
|
174
157
|
```ts
|
|
175
158
|
defineSyncTable({
|
|
@@ -183,27 +166,20 @@ defineSyncTable({
|
|
|
183
166
|
});
|
|
184
167
|
```
|
|
185
168
|
|
|
186
|
-
The column callback is the only authoring form. **Prefer
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
deny.
|
|
169
|
+
The column callback is the only authoring form. **Prefer the typed fragment over the string hatch:** a
|
|
170
|
+
`customWhere` returning `null`/`""` means _no filter — every row visible_, so an owner filter returning `null`
|
|
171
|
+
for "no claim" silently exposes every row; the typed form makes `DENY_ALL` the obvious deny.
|
|
190
172
|
|
|
191
173
|
## Cross-table filters: compose a self-contained subquery from the typed columns, never a string
|
|
192
174
|
|
|
193
175
|
A **membership fan-out** — "sync a row only if the subject belongs to its container" — is a `customWhere`
|
|
194
|
-
whose predicate is a **subquery over another table
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
definition (the read-path twin of the membership RLS predicate):
|
|
176
|
+
whose predicate is a **subquery over another table**. Author it the same typed way as an owner filter, never
|
|
177
|
+
as a hand-built string: `c()` for every column (bare, as Electric needs), the **table object** for the
|
|
178
|
+
`FROM`, and the subject as a **bound param**. Factor it into a helper so the read filter and any narrower
|
|
179
|
+
variant share one definition (the read-path twin of the membership RLS predicate):
|
|
199
180
|
|
|
200
181
|
```ts
|
|
201
|
-
|
|
202
|
-
import { sql, type SQL } from "drizzle-orm";
|
|
203
|
-
|
|
204
|
-
// The containers a subject belongs to, as a self-contained subquery: bare columns via c(), the FROM
|
|
205
|
-
// from the table object, the subject bound as $n. The subquery references `membership`'s OWN columns,
|
|
206
|
-
// so its bare names resolve to its own FROM — it is self-contained, not correlated.
|
|
182
|
+
// Self-contained (not correlated): it gets its own FROM, so `membership`'s bare names resolve to it.
|
|
207
183
|
function memberContainers(subject: string): SQL {
|
|
208
184
|
return sql`select ${c(membership.containerId)} from ${membership} where ${c(membership.memberId)} = ${subject}`;
|
|
209
185
|
}
|
|
@@ -214,79 +190,94 @@ function widgetsReadFilter(claims: JwtClaims): SQL {
|
|
|
214
190
|
}
|
|
215
191
|
```
|
|
216
192
|
|
|
217
|
-
What the typed form buys
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
is
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
self-serve toggle yet; default-on intended) — ask Electric to enable it, or self-host Electric.
|
|
226
|
-
Combine with the function form when the table is defined all-in-one: the row's own column comes from
|
|
227
|
-
`(columns) => …`, the foreign table + its columns are imported already-built.
|
|
193
|
+
What the typed form buys: columns stay rename-safe and existence-checked, and the subject is a `$n` param
|
|
194
|
+
(`params: ["…"]`), never an escaped literal — so a quote in the value can't break or inject the predicate.
|
|
195
|
+
**Subqueries nest by interpolation** — wrap one `sql` fragment in another to narrow a fan-out: `` sql`${c(post.offeringId)} in (${memberOfferings(sub)}) and (${c(post.groupId)} is null or ${c(post.groupId)} in (${memberGroups(sub)}))` `` (each `${sub}`
|
|
196
|
+
is its own bound param). Two constraints: the subquery must stay **self-contained**, and the subquery
|
|
197
|
+
`where` is the **flagged Electric preview** — run Electric with `allow_subqueries,tagged_subqueries` or the
|
|
198
|
+
shape fails closed (no rows); on managed Electric Cloud, Electric staff activate it per source on request
|
|
199
|
+
(no self-serve toggle yet). Combine with the function form when the table is defined all-in-one: the row's
|
|
200
|
+
own column comes from `(columns) => …`, the foreign table is imported built.
|
|
228
201
|
|
|
229
202
|
## RLS: derive read and write from the same Drizzle columns
|
|
230
203
|
|
|
231
|
-
Authorization runs in two engines (Postgres RLS for writes
|
|
232
|
-
|
|
233
|
-
|
|
204
|
+
Authorization runs in two engines (Postgres RLS for writes, the Electric `where` for reads). Build both from
|
|
205
|
+
the **same Drizzle columns**, so a rename or typo can never make a row readable-but-unwritable (or vice
|
|
206
|
+
versa):
|
|
234
207
|
|
|
235
208
|
- Common shapes: `buildSupabaseOwnerOrAdminNativePolicies({ role, ownerColumn })` and
|
|
236
|
-
`buildSupabaseMembershipNativePolicies({ role, containerColumn, membershipTable, … })
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
table), not the `policies:` array.
|
|
209
|
+
`buildSupabaseMembershipNativePolicies({ role, containerColumn, membershipTable, … })`. They take **real
|
|
210
|
+
Drizzle columns** and derive the governed table name from them, so call them inside `defineSyncTable`'s
|
|
211
|
+
`extras: (t) => …` callback (where the columns carry their table), not the `policies:` array.
|
|
240
212
|
- Beyond them (e.g. collaborative any-member writes): compose your own with `pgPolicy` + Drizzle operators
|
|
241
|
-
|
|
242
|
-
`
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
`
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
`
|
|
213
|
+
over the columns. Use the `drizzle-orm/supabase` helpers for the auth leaves — `authUid` (emits
|
|
214
|
+
`(select auth.uid())`, the per-statement-eval idiom, not a per-row bare `auth.uid()`), `authenticatedRole`.
|
|
215
|
+
Inline a literal with `eq(col, value).inlineParams()` (type-checked against the column and inlined into the
|
|
216
|
+
DDL — `CREATE POLICY` cannot carry a bare `$n`). Drop to raw `sql` only where Drizzle has no equivalent (a
|
|
217
|
+
SECURITY DEFINER membership helper, a `current_setting('request.jwt.claims')` admin check), and inline that
|
|
218
|
+
predicate rather than referencing a not-yet-created function. For "compare OLD vs NEW" rules RLS cannot
|
|
219
|
+
help (`WITH CHECK` sees only NEW, `USING` only OLD) — use a `BEFORE UPDATE` trigger.
|
|
220
|
+
- **Do not hand-write the read half — every policy family ships its read-path mirror.** Electric cannot
|
|
221
|
+
read RLS, so the shape `where` must re-derive the same visible set in JS, from the same declaration:
|
|
222
|
+
`buildOwnershipShapeWhere(ownerColumn, claims.sub)`, `buildOwnerOrAdminShapeWhere(ownerColumn, claims)`
|
|
223
|
+
(admin → `null`, i.e. no filter, mirroring the policy's bypass branch),
|
|
224
|
+
`buildMembershipShapeWhere(columns, claims)` (pass the **same** options object you gave the policy
|
|
225
|
+
builder — write-only fields are ignored), and `buildGrantScopeAccessShapeWhere(scopeColumn, claims, …)`
|
|
226
|
+
(bypass grant → `null` too; bare `resolveGrantScopeIds` + `buildGrantScopeShapeWhere` cannot see it).
|
|
227
|
+
Return each straight from `customWhere`; they deny with `DENY_ALL`, so the filter probes claims-dependent.
|
|
228
|
+
- Two mirror properties: they cover **SELECT only** (write-gate branches stay with the INSERT/UPDATE/DELETE
|
|
229
|
+
policies), and the two surfaces render containment in **different dialects on purpose** — RLS emits
|
|
230
|
+
`= ANY(ARRAY(select …))` for the InitPlan/index-scan discipline, Electric plain `IN (subquery)`.
|
|
231
|
+
|
|
232
|
+
Give drizzle-kit `entities: { roles: { provider: "supabase" } }` in `drizzle.config.ts` so the Supabase roles
|
|
233
|
+
(`authenticated`/`anon`/`service_role`/…) are treated as externally managed — referenced in a policy's `to:`,
|
|
234
|
+
never created or dropped.
|
|
235
|
+
|
|
236
|
+
## Composition obligations: two correct policies can still break an invariant
|
|
237
|
+
|
|
238
|
+
The registry keeps ONE table's read filter and write policy from drifting. A domain invariant usually spans
|
|
239
|
+
several tables and rails, and no registry feature can see that composition. Worked example: an invite table's
|
|
240
|
+
RLS grants an offering-scoped teacher INSERT; an acceptance worker then mints a membership row. Each policy
|
|
241
|
+
is correct alone; together they violate "this offering only ever has one member". The worker's semantics are
|
|
242
|
+
invisible to per-table declarations, so the obligation is permanently the consumer's. When you add a worker,
|
|
243
|
+
route, or trigger that writes rows as a CONSEQUENCE of other rows:
|
|
244
|
+
|
|
245
|
+
- List the invariants the OUTPUT table participates in, not just the input's — the output is where the
|
|
246
|
+
violation lands — and for each ask whether the composed path enforces it or merely assumes the input row's
|
|
247
|
+
policies did. "The input was authorized" is not "the output is valid".
|
|
248
|
+
- Re-derive at mint time: re-check the invariant against current state when the worker runs, because the
|
|
249
|
+
input row may be stale (or its authority revoked) by then.
|
|
250
|
+
- Pin it with a test at the composition seam (drive the worker/route end-to-end): per-table policy tests
|
|
251
|
+
structurally cannot fail on a composition hole.
|
|
252
|
+
- Record it where the next author will look — the registry entry's comment (and its `rowClass` /
|
|
253
|
+
`assertRegistryInvariant` coverage, which audits per-entry rendered artifacts and never sees composition).
|
|
255
254
|
|
|
256
255
|
## Provision the apply function from the registry
|
|
257
256
|
|
|
258
|
-
The write path applies through one in-database PL/pgSQL function, `pgxsinkit_apply_mutations`. Generate
|
|
259
|
-
|
|
260
|
-
|
|
257
|
+
The write path applies through one in-database PL/pgSQL function, `pgxsinkit_apply_mutations`. Generate its
|
|
258
|
+
drizzle-kit migration with the `pgxsinkit-generate` CLI (a `bin` of `@pgxsinkit/server`) and apply it through
|
|
259
|
+
your normal migration flow; it is **deny-by-default** (see `deploying` for `--grant-execute-to`). It and the
|
|
260
|
+
audit/version column DEFAULTs both **call** `public.pgxsinkit_clock_us()`, so the `--utilities` migration
|
|
261
|
+
installing that clock must be **first in the chain** (hence the early-sorting name):
|
|
261
262
|
|
|
262
263
|
```bash
|
|
263
264
|
bun run pgxsinkit-generate --registry ./sync-registry.ts --export registry \
|
|
264
265
|
--project-dir ./db --config drizzle.config.ts --name sync_artifact
|
|
265
|
-
```
|
|
266
|
-
|
|
267
|
-
The apply function and the audit/version column DEFAULTs both **call** the canonical
|
|
268
|
-
`public.pgxsinkit_clock_us()` microsecond clock, so its **utilities migration must be the first folder in
|
|
269
|
-
the chain** — generate it once with `--utilities`, passing an early-sorting folder name:
|
|
270
|
-
|
|
271
|
-
```bash
|
|
272
266
|
bun run pgxsinkit-generate --utilities \
|
|
273
267
|
--project-dir ./db --config drizzle.config.ts --name 20200101000000_pgxsinkit_utilities
|
|
274
268
|
```
|
|
275
269
|
|
|
276
270
|
## Multi-client: one authoritative registry, readonly projections (ADR-0025)
|
|
277
271
|
|
|
278
|
-
When the same table is `readwrite` for one client and `readonly` for another
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
table, and the shape/row filter.
|
|
272
|
+
When the same table is `readwrite` for one client and `readonly` for another, `mode` is **per-client**, not
|
|
273
|
+
a property of the table: define it **once** in an authoritative registry at its writable capability and
|
|
274
|
+
project it per client. `mode` is baked at `defineSyncTable` time and drives the overlay/journal machinery +
|
|
275
|
+
the `_read_model` view, so a hand-spread `{ ...entry, mode: "readonly" }` is **broken** (it keeps a view over
|
|
276
|
+
overlay state the readonly client never creates). `asReadonly` re-derives a true readonly entry — dropping
|
|
277
|
+
the overlay/journal projection, the view, and `conflictPolicy`/`governance`/`writeMode`, keeping columns,
|
|
278
|
+
primary key, synced table, shape/row filter and `rowClass`.
|
|
286
279
|
|
|
287
280
|
```ts
|
|
288
|
-
import { asReadonly, assertReadContractPreserved } from "@pgxsinkit/contracts";
|
|
289
|
-
|
|
290
281
|
const authoritativeRegistry = defineSyncRegistry({ posting_restriction: postingRestrictionEntry }); // readwrite
|
|
291
282
|
const teacherRegistry = defineSyncRegistry({ posting_restriction: postingRestrictionEntry });
|
|
292
283
|
const learnerRegistry = defineSyncRegistry({ posting_restriction: asReadonly(postingRestrictionEntry) });
|
|
@@ -296,9 +287,9 @@ assertReadContractPreserved(authoritativeRegistry, teacherRegistry, { label: "te
|
|
|
296
287
|
assertReadContractPreserved(authoritativeRegistry, learnerRegistry, { label: "learner" });
|
|
297
288
|
```
|
|
298
289
|
|
|
299
|
-
- **Generate the server (apply function + proxy) from the authoritative registry** —
|
|
300
|
-
|
|
301
|
-
|
|
290
|
+
- **Generate the server (apply function + proxy) from the authoritative registry** — it emits a branch per
|
|
291
|
+
table and stamps managed fields / reject-if-stale from the entry's write contract, so it must see the
|
|
292
|
+
writable entry. A claims-branching `customWhere` then serves every client.
|
|
302
293
|
- A projection may differ **only** in write capability and lifecycle (`subscription`/`retention`/group),
|
|
303
294
|
never in the read contract — `assertReadContractPreserved` enforces it (it can't see the `customWhere`
|
|
304
295
|
body, so bump `rowFilter.revision` on a logic change).
|
|
@@ -307,14 +298,12 @@ assertReadContractPreserved(authoritativeRegistry, learnerRegistry, { label: "le
|
|
|
307
298
|
|
|
308
299
|
## A second shape over one table: read projections (ADR-0027)
|
|
309
300
|
|
|
310
|
-
`asReadonly` reuses the **same** table+columns for another client.
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
301
|
+
`asReadonly` reuses the **same** table+columns for another client. For a **different, narrower shape over an
|
|
302
|
+
existing physical table** — a column subset and/or a different row filter, under a distinct local identity —
|
|
303
|
+
use `defineReadProjection(owner, …)`: a learner reads the full `assessment_definition` (heavy QTI jsonb)
|
|
304
|
+
while an admin reads only titles.
|
|
314
305
|
|
|
315
306
|
```ts
|
|
316
|
-
import { defineReadProjection } from "@pgxsinkit/contracts";
|
|
317
|
-
|
|
318
307
|
export const assessmentDefinition = defineSyncTable({ tableName: "assessment_definition", makeColumns /* … */ });
|
|
319
308
|
|
|
320
309
|
export const assessmentDefinitionAdminSummary = defineReadProjection(assessmentDefinition, {
|
|
@@ -324,32 +313,29 @@ export const assessmentDefinitionAdminSummary = defineReadProjection(assessmentD
|
|
|
324
313
|
});
|
|
325
314
|
```
|
|
326
315
|
|
|
327
|
-
- It **owns no table**: its `table` IS the owner's, so nothing new is migrated and
|
|
328
|
-
|
|
329
|
-
- `columns` is a typed subset of the owner's keys
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
restated), and the subset becomes the Electric `columns` allow-list so an omitted (heavy) column is
|
|
316
|
+
- It **owns no table**: its `table` IS the owner's, so nothing new is migrated and nothing leaks into a
|
|
317
|
+
drizzle-kit schema barrel. Only its `localTable` (named `as`) and shape are its own.
|
|
318
|
+
- `columns` is a typed subset of the owner's keys, and the local table carries the owner's **real per-column
|
|
319
|
+
types restricted to those keys** (Picked from the owner), so a row typechecks by property key with no
|
|
320
|
+
casts. The PK is always kept **at runtime**, but the type is a safe **under-claim** — a PK column not in
|
|
321
|
+
`columns` is synced yet absent from the type, so list it to read it typed. Column definitions are reused
|
|
322
|
+
(never restated), and the subset becomes the Electric `columns` allow-list, so an omitted (heavy) column is
|
|
335
323
|
**never fetched**, not merely stripped.
|
|
336
|
-
- The physical Electric table is **derived** from the owner — you never name a source string
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
column the subset omits).
|
|
324
|
+
- The physical Electric table is **derived** from the owner — you never name a source string. The `rowFilter`
|
|
325
|
+
callback receives the OWNER's full columns (the `customWhere` runs in Electric on the physical table, so it
|
|
326
|
+
may reference a column the subset omits).
|
|
340
327
|
- It is **readonly**; put it in the authoritative registry under its own key and in the reading client's
|
|
341
|
-
registry. RLS for its reads lives on the **owner** (a projection adds no DDL to a table it doesn't own)
|
|
328
|
+
registry. RLS for its reads lives on the **owner** (a projection adds no DDL to a table it doesn't own), so
|
|
342
329
|
its `customWhere` must be a subset of what that RLS allows. The proxy resolves each shape by its unique
|
|
343
|
-
`shapeKey`, so
|
|
330
|
+
`shapeKey`, so owner and projection coexist over one physical table.
|
|
344
331
|
|
|
345
332
|
### Redacting projection: a secure "window" over a keyed table
|
|
346
333
|
|
|
347
|
-
A projection can carry its own `serverProjection` (an egress `rowTransform`, resolved by
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
stripped after the transform runs.
|
|
334
|
+
A projection can carry its own `serverProjection` (an egress `rowTransform`, resolved by its `shapeKey`) —
|
|
335
|
+
e.g. stream a `jsonb` item body while stripping the answer key per row. When the transform must READ a column
|
|
336
|
+
outside the client shape (a `keysWithheld` control flag), list it in `serverOnlyColumns`: it joins the
|
|
337
|
+
Electric fetch allow-list (so the transform sees it) yet stays out of the client keep-set. Egress order is
|
|
338
|
+
**transform first, then omission**.
|
|
353
339
|
|
|
354
340
|
```ts
|
|
355
341
|
export const secureItemWindow = defineReadProjection(secureItem, {
|
|
@@ -363,18 +349,48 @@ export const secureItemWindow = defineReadProjection(secureItem, {
|
|
|
363
349
|
```
|
|
364
350
|
|
|
365
351
|
`serverOnlyColumns` requires BOTH `serverProjection.rowTransform` and `columns`, and must be disjoint from
|
|
366
|
-
`columns` and the PK — each is a loud error.
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
352
|
+
`columns` and the PK — each is a loud error. **No inheritance — enforced.** A projection does NOT inherit its owner's `serverProjection`: an inherited
|
|
353
|
+
transform whose input column is absent from the projection's fetch list reads `undefined` and fails OPEN.
|
|
354
|
+
Since a bare projection over a redacting owner would then egress the RAW row, `defineReadProjection` THROWS
|
|
355
|
+
when the owner declares an egress `rowTransform` unless the projection declares its posture — its own
|
|
356
|
+
`serverProjection` (usually the same fn) + `serverOnlyColumns`, or the explicit opt-out `serverProjection:
|
|
357
|
+
"unredacted"` (only after confirming the kept columns leak nothing; it attaches no transform but records the
|
|
358
|
+
raw-egress decision at the definition site). `"unredacted"` over a transform-less owner is itself rejected — a
|
|
359
|
+
stale opt-out would pre-authorize a leak if the owner later gained one.
|
|
360
|
+
|
|
361
|
+
## Classify rows and assert registry invariants (ADR-0052)
|
|
362
|
+
|
|
363
|
+
`assertReadContractPreserved` pins ONE table. A privacy rule ("nothing private streams to an anonymous
|
|
364
|
+
caller") spans MANY entries and BOTH engines — and an invariant written over a hand-listed set of tables
|
|
365
|
+
silently stops covering the registry the moment someone adds an entry.
|
|
366
|
+
|
|
367
|
+
```ts
|
|
368
|
+
export const registry = defineSyncRegistry({
|
|
369
|
+
rowClasses: ["directory", "team-scoped"], // YOUR vocabulary; declaring it makes rowClass MANDATORY
|
|
370
|
+
tables: { profile, team, issue }, // …on every entry, at module eval, every offender named at once
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
assertRegistryInvariant(registry, {
|
|
374
|
+
name: "team-scoped rows are invisible to an anonymous caller",
|
|
375
|
+
appliesTo: ["team-scoped"], // classes (or a predicate); an undeclared class / zero matches throws
|
|
376
|
+
claimsFixtures: { anonymous: {}, member: { sub: memberId }, admin: adminClaims },
|
|
377
|
+
holds: ({ fixtureName, renderedWhere, renderedPolicies }) =>
|
|
378
|
+
fixtureName !== "anonymous" ||
|
|
379
|
+
(renderedWhere?.where === "false" && renderedPolicies.every((p) => p.using !== "true")) ||
|
|
380
|
+
"anonymous is not denied on one of the two surfaces", // reported as `entry (fixture): reason`
|
|
381
|
+
});
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
So a table added next month cannot inherit the obligation invisibly (omit `rowClasses` and `rowClass` is
|
|
385
|
+
unconstrained, as the bare registry-map form always is). Projections carry the class (`asReadonly`,
|
|
386
|
+
`asEphemeral`; `defineReadProjection` inherits the owner's, overridable). Each cell gets that persona's
|
|
387
|
+
RENDERED artifacts — `renderedWhere` is the proxy's own `buildRowFilterShape(…)` (`null` =
|
|
388
|
+
unfiltered), `renderedPolicies` the table's RLS as inline SQL — so one predicate covers both surfaces, and
|
|
389
|
+
ALL failing cells aggregate into one error. `rowClass` is authoring metadata, deliberately in NEITHER
|
|
390
|
+
fingerprint (classifying never wipes a cache); the **lock** carries it, so losing a class is a `risky` diff.
|
|
391
|
+
It complements `RowFilterSpec.revision`: only `revision` makes a `customWhere` logic change move the
|
|
392
|
+
fingerprint (rebuilding the cache, resetting the subscription), while the assertion renders that logic — for
|
|
393
|
+
the fixtures you hand it, and no others.
|
|
378
394
|
|
|
379
395
|
## Storage declaration: `storage.backend` and `storage.durability` (browser stores)
|
|
380
396
|
|
|
@@ -383,59 +399,101 @@ The registry carries the browser store's storage contract — `SyncRegistryDefin
|
|
|
383
399
|
minting surface, worker entry, or attach site, because both properties follow the DATA: one declaration
|
|
384
400
|
binds every open of every store minted from that registry, so no tab can disagree with another.
|
|
385
401
|
|
|
386
|
-
- **`backend`** (default `"opfs"`) —
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
declare is whether to force idb.
|
|
402
|
+
- **`backend`** (default `"opfs"`) — the normal boot everywhere: the toolkit probes OPFS sync-access at boot
|
|
403
|
+
and runs the `opfs-repacked` engine wherever handles are granted, falling back automatically to
|
|
404
|
+
in-SharedWorker idbfs (declared durability kept) only where the platform grants them nowhere.
|
|
405
|
+
`backend: "idbfs"` is the one opt-out (no probe, no election). Where the engine runs is never a knob; the
|
|
406
|
+
only decision you declare is whether to force idb.
|
|
392
407
|
- **`durability`** (default `"relaxed"`) — relaxed returns the local write before the physical flush and
|
|
393
|
-
schedules it asynchronously; `"strict"` awaits the flush per commit. Relaxed is
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
crash. See ADR-0047.
|
|
408
|
+
schedules it asynchronously; `"strict"` awaits the flush per commit. Relaxed is right for a sync toolkit
|
|
409
|
+
(the server is the source of truth, and the loss window is one recent action); declare `"strict"` only for
|
|
410
|
+
local-only data you cannot re-derive and cannot lose on a crash (ADR-0047).
|
|
397
411
|
|
|
398
|
-
|
|
399
|
-
stay memory (environment resolution is orthogonal).
|
|
412
|
+
It scopes the **browser** store only; Node mints stay `file://` and export clones stay memory.
|
|
400
413
|
|
|
401
414
|
## Consistency groups: scope them to the joined cluster
|
|
402
415
|
|
|
403
|
-
`consistencyGroup` binds tables onto one shape stream committing **atomically** at a shared LSN
|
|
404
|
-
|
|
405
|
-
|
|
416
|
+
`consistencyGroup` binds tables onto one shape stream committing **atomically** at a shared LSN frontier —
|
|
417
|
+
a reader never sees one grouped table advanced past another for the same server transaction. Default is
|
|
418
|
+
none (per-table singleton, independent frontier). Three scoping rules:
|
|
419
|
+
|
|
420
|
+
1. **Group the transactionally-joined cluster** — tables written together in one server transaction and
|
|
421
|
+
rendered joined (FK parent + children); that is what the atomic frontier protects. If the app otherwise
|
|
422
|
+
needs post-ack re-reads to hide half-applied transactions, the tables belong in a group.
|
|
423
|
+
2. **Quiet members are affordable.** A rarely-written reference table once held its whole group for a full
|
|
424
|
+
long-poll cycle (~41s on CDN-fronted Electric); the live-tail sibling nudge now caps that at ~one
|
|
425
|
+
catch-up round trip per gated commit, so don't keep a lookup table out of its natural group.
|
|
426
|
+
3. **Don't group "everything".** Every gated commit nudges each lagging member — unrelated clusters go in
|
|
427
|
+
separate groups or stay singletons.
|
|
428
|
+
|
|
429
|
+
All members of a group must agree on `subscription`, `retention`, `writeMode` (or the registry rejects it).
|
|
406
430
|
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
431
|
+
## Event streams: the second lane, registered on the same registry (ADR-0053)
|
|
432
|
+
|
|
433
|
+
High-volume append-only client facts (view/impression/interaction logs) do **not** belong on a sync table —
|
|
434
|
+
every client re-downloads its own log, and conflict machinery taxes rows that never conflict. They go on the
|
|
435
|
+
**Event lane**: a `streams` key on the registry you have, where the record **KEY is the Event-stream name**.
|
|
436
|
+
|
|
437
|
+
```ts
|
|
438
|
+
import { z } from "zod";
|
|
439
|
+
export const registry = defineSyncRegistry({
|
|
440
|
+
tables: { issue },
|
|
441
|
+
streams: {
|
|
442
|
+
issue_viewed: defineEventStream({
|
|
443
|
+
payload: z.strictObject({ issueId: z.uuid() }), // STRICT is enforced; validated at append AND at ingest
|
|
444
|
+
identity: { viewerId: { claimPath: ["sub"] } }, // SERVER-stamped from verified claims
|
|
445
|
+
}),
|
|
446
|
+
},
|
|
447
|
+
});
|
|
448
|
+
```
|
|
416
449
|
|
|
417
|
-
|
|
418
|
-
|
|
450
|
+
- **The name is validated at module eval**: lowercase `[a-z][a-z0-9_]*`, max **30 chars** (pgmq's queue-name
|
|
451
|
+
limit is 47, less the 17-char `pgxsinkit_events_` prefix) — so a bad name fails at definition, not at DDL.
|
|
452
|
+
- **An object payload MUST be strict — enforced.** `.strict()`/`z.strictObject()` on the root and every union
|
|
453
|
+
member, or `defineSyncRegistry` throws (a stripper silently drops misspellings); other roots as written. The
|
|
454
|
+
schema RUNS AT BOTH ENDS: `appendEvent` VALIDATES (output discarded; the Outbox keeps your value), ingest
|
|
455
|
+
re-parses AUTHORITATIVELY and its **JSON-NORMALIZED** output reaches the consumer (`Date` → ISO string, nested
|
|
456
|
+
`undefined` dropped). Transforms must be pure; non-JSON output is a terminal per-event `rejected`.
|
|
457
|
+
- **Identity is never client-trusted.** `claimPath` is the addressing `authClaim` managed fields use; the
|
|
458
|
+
client's envelope carries **no identity at all** and the endpoint stamps it from verified claims. Never put
|
|
459
|
+
a viewer/actor id in the **payload** — a client can lie about it. The consent/entitlement hook is likewise
|
|
460
|
+
`eventGate` on `createSyncServer` (`deploying` skill), never a registry field: registrations stay data.
|
|
461
|
+
- **Payload evolution is compatibility-bound — a rule, not a convention.** A schema may change only in ways
|
|
462
|
+
that keep accepting **every previously-valid payload** (events written offline under the old one are still
|
|
463
|
+
in flight); an incompatible change needs a **NEW Event-stream name**. The lock hashes the entry as JSON
|
|
464
|
+
Schema into a reviewable `risky` diff — but that CANNOT see a `.refine`/transform, so **bump `revision`**
|
|
465
|
+
(positive int) on any such change or the gate silently never fires. A hash detects; you judge.
|
|
466
|
+
- **Streams ride the lock/diff, not the fingerprint** (added `compatible`, removed `breaking`): a stream
|
|
467
|
+
touches no synced table, local schema or apply function, so registering one never wipes a read cache.
|
|
468
|
+
- **Per-client projections must RE-DECLARE `streams`.** A projection spreads the table map (enumerable keys
|
|
469
|
+
only) and streams ride a non-enumerable symbol — forget them and that client has **no Event lane**.
|
|
470
|
+
- Flush cadence, batch caps and per-stream overrides are **client** config (`defineSyncWorker` /
|
|
471
|
+
`createSyncClient`), never registry — a batch-size tweak must not surface as a registry diff. A stream also
|
|
472
|
+
gives the SERVER an auto-mounted `POST /api/events` + pgmq DDL (`pgxsinkit-generate --events`): `deploying`.
|
|
419
473
|
|
|
420
474
|
## Common mistakes
|
|
421
475
|
|
|
422
476
|
- Omitting `conflictPolicy` or the server-version field on a `readwrite` table (throws).
|
|
423
477
|
- Putting a managed field (`updated_at_us`, owner) in a client write payload (rejected).
|
|
424
478
|
- Trying to write an `omitColumns` (server-only) column from a client payload — the write route
|
|
425
|
-
**400-rejects** it (an unknown
|
|
426
|
-
|
|
427
|
-
managed field).
|
|
479
|
+
**400-rejects** it (an unknown typo is instead silently dropped, surfaced by a per-process `console.warn`);
|
|
480
|
+
write them outside the sync rail (a server `UPDATE`, a trigger, or a managed field).
|
|
428
481
|
- In a `customWhere`: comparing an enum without `::text`, qualifying a column (use `c()` for a bare ref),
|
|
429
482
|
or hand-escaping a value into a string instead of binding it via a Drizzle `sql` fragment.
|
|
483
|
+
- A multi-dimensional array column, an array PK, or a managed field on an array column — each fails at
|
|
484
|
+
generate time; single-dimension arrays are fully supported on both paths.
|
|
430
485
|
- Letting the read filter and RLS policy diverge instead of building both from the same Drizzle columns.
|
|
431
|
-
- Declaring a _second_ owning `defineSyncTable` to read an existing physical table (
|
|
432
|
-
|
|
486
|
+
- Declaring a _second_ owning `defineSyncTable` to read an existing physical table (the registry rejects the
|
|
487
|
+
duplicate local identity) — use `defineReadProjection` for a second shape.
|
|
433
488
|
- Calling the native policy builders in the `policies:` array (they need `extras: (t) => …` to derive the
|
|
434
489
|
table from the columns), or referencing a custom SQL function in `CREATE POLICY` before it exists.
|
|
435
490
|
- In a hand-written policy: bare `auth.uid()` instead of `authUid` (per-row vs per-statement), or a bound
|
|
436
491
|
literal (`eq(col, x)`) where `CREATE POLICY` needs an inlined one (`eq(col, x).inlineParams()`).
|
|
437
492
|
- Hand-spreading `{ ...entry, mode: "readonly" }` to downgrade a writable table for a read-only client
|
|
438
493
|
(keeps a `_read_model` view over overlay state that client never creates) — use `asReadonly`.
|
|
494
|
+
- Putting a viewer/actor id in an Event stream's **payload** instead of its `identity` map (a payload is
|
|
495
|
+
client-supplied and can lie), a non-strict object payload (the registry throws), projecting a registry
|
|
496
|
+
without re-declaring `streams`, evolving a payload incompatibly, or a `.refine` change with no `revision`.
|
|
439
497
|
|
|
440
498
|
For the surrounding model (two paths, one write path, fail-closed subquery flag), load the `core` skill
|
|
441
499
|
from `@pgxsinkit/client`. Full prose: <https://pgxsinkit.github.io/start/getting-started/>.
|