Remote / Declared writes
A write ledger
A write ledger stores applied operations inside the same database transaction (or D1 batch) as the row update (see examples/writes/src/server.ts):
ts
const ledgered = writer<Option.Option<User>>(Db.Product, {
ledger: {
table: ledger,
scope: principal => Option.match(principal, { onNone: () => '', onSome: user => user.id }),
},
})sql
create table write_ledger (
scope text not null, operation text not null, target text not null,
answer text not null, at bigint not null, request text,
primary key (scope, operation, target)
);
create index write_ledger_at on write_ledger (at);scopeandtarget: Isolate operation IDs per caller principal and target row.requestdigest: Detects if an operation ID is reused with different parameters (alter table write_ledger add column request textupgrades older tables).- Concurrency: Postgres serializes duplicate operations with a transaction-scoped advisory lock; D1 writes both in one batch so the primary key collision rolls back the duplicate and reads the recorded answer.
- Retention: Entries prune automatically after retention expires (default 1 day), indexed by
at. - Inserts and deletes: Retried inserts return the original created row from the ledger, while colliding IDs without a matching ledger entry return
Taken.
Ledgered retries skip re-running guards (which already passed when the write landed) and return the row's current state filtered by read permissions.
Moving the revision from database triggers
If raw SQL or handlers also update the table, install revisionTrigger with your migrations so every external update bumps revision (the column must be NOT NULL, and Sync-managed tables using applyEdits omit it):
ts
import { revisionTrigger } from 'foldkit-remote-drizzle'
sqlite.exec(revisionTrigger(Db.Product, 'revision'))