Remote / foldkit-remote-drizzle
Mutations
A mutation declared as a Write (Mutation.write(name, Write.update(input,
{ id }))) needs no handler: writer(binding) lands it in the binding's table,
and RemoteServer.write serves it.
import { sqliteTable, text } from 'drizzle-orm/sqlite-core'
import { Schema } from 'effect'
import { Entity, Write } from 'foldkit-entity'
import { Mutation } from 'foldkit-remote'
import { RemoteServer } from 'foldkit-remote-server'
import { bind, source, writer } from 'foldkit-remote-drizzle'
const Project = Entity.define('Project', Schema.Struct({ id: Schema.String, name: Schema.String }))
const projects = sqliteTable('projects', { id: text('id').primaryKey(), name: text('name').notNull() })
const Db = bind({ Project }, { Project: { table: projects } })
const EditProject = Mutation.write(
'EditProject',
Write.update(Entity.input(Project, Schema.Struct({ id: Schema.String, name: Schema.String })), {
id: 'id',
}),
)
const Server = RemoteServer.make({
entities: [source(Db.Project)],
mutations: [RemoteServer.write(EditProject, writer(Db.Project))],
})It is one update ... returning of the row by id, each field's column set to
the value as the store encodes it, and only the keys the client named when it
named some, so two authors editing different fields of a row both land. The
written fields answer as the mutation's patch. A write that expects a revision
is guarded by that column and moves it on by one in the same statement: of two
writes made from one revision, the second finds no row and is refused as a
conflict. A write that expects none, to a row that is not there, fails. A
write's when is compiled into the same statement's WHERE, beside the id and
the revision, so it holds of the row the write changes, on SQLite and Postgres
alike. When nothing was written, the row read back says why: gone, moved on
(a conflict), or else not holding the precondition (unmet). A row that already
holds every value the write sets is the retry of one that landed, and answers as
written. An increment is column = column + amount in the same statement, and
its sum is in the answer. Over a column that holds integers (SQLite integer;
Postgres integer, smallint, bigint read as a number) its amount must be
Schema.Int, whatever the field is declared as: Postgres refuses a fraction
there and SQLite would store it, so the writer refuses the write where it is
served. For a write with one, neither recognition applies: a
row a revision on could hold another client's increment, so a retry is a
conflict and the field moves once. A computed assignment is its compiled
computation in the same set (computationSql, its operators by the binding's
SQL table, its values cast as a call's arguments are), held to a retry as an
increment is, and its operators are checked where the write is served. A binding with a
visible rule reads the answer back through it: the row as its writer may now
see it, or, when the write hid it from them, a deletion.
An insert is one insert ... on conflict do nothing returning under the id the
client chose. An id already taken is refused as Refusal.taken (a 409 over
HTTP), with one answer whatever the row there holds, since comparing it with
the insert would tell the asker what it holds; only a
ledger tells a retry from another
create of that id. A delete is one delete by id, guarded by the revision when
it expects one; a row already gone is gone.
A delete takes what the domain says goes with it. A row pointing at the
deleted one through a relation declared Relation.one(Post, { onDelete:
'cascade' }) is removed too, and so on from it (a reply's replies, the likes
of each), by the writer itself in the transaction that deletes, or on D1 in
the same batch: first what each removal will take, then the rest, leaves
first, each only while the row named is still there and holds its revision,
when and guard, then the row itself, so a delete that missed removes
nothing. It holds on a store without foreign keys (sql.js, a
connection without pragma foreign_keys = on). The writer answers what it
removed that the principal may see (visible) as DeleteOutcome.Deleted({
cascaded }), which RemoteServer.write names as deleted, re-reading what each
pointed at; the client predicted the same over the rows it holds. Every
Entity a cascade reaches is bound beside it (bind), with its relation stored
on its own table ({ field }); a cascade that comes back through another
Entity is refused where the writer is made. bind refuses a table whose
foreign key on such a column says otherwise: one that cascades where the
relation does not declare it, and one that does not where it does (the
writer removes its own rows, so the foreign key must agree).
A delete refuses a row the domain says must stay. A row pointed at
through a relation declared Relation.one(Topic, { onDelete: 'restrict' })
is not deleted: the delete statement itself holds not exists of a row
pointing there, so no check runs apart from the delete (but see below for
Postgres). A miss then reads whether such a row is there, and answers
DeleteOutcome.Referenced, which RemoteServer.write sends as
Refusal.referenced (its entity and relation), a 409. It names the relation and
none of the rows, which the deleter may not see; a guard judges the
deleter's own Delete rule first, so only someone allowed to delete learns
even that. The restricting relation is bound beside it, stored on its own
table, and a foreign key on it says restrict or no action, or nothing. A
cascade that would take rows of an Entity something restricts is refused
where the writer is made: restrict the root, or cascade those pointers too.
A delete clears the links the domain says point nowhere after. A row
pointing at the deleted one through Relation.one(Folder, { optional: true,
onDelete: 'setNull' }) stays, with its link set to null, in the transaction
(or D1 batch) that deletes, and only while the row named is still there and
holds what the delete asks, so a delete that missed clears nothing. The
writer answers the cleared rows the principal could see before the clear
(their visible may read the link) as DeleteOutcome.Deleted({ cleared }), and RemoteServer.write reads them
again for the answer, so a page holding one sees its link gone. delete
takes clearing, each Entity's rules for unlinking such a row as a
CascadeRequirement: Guard's GuardServer.writer hands over the row's
Update rule and the relation's Unlink rule, given the Entity in
children, and the writer refuses the whole delete as Forbidden where a
row it would clear does not hold them (unknown counts as not), naming the
Entity and none of the rows. A clear is held to the cleared row's
invariants too, judged with each cleared link null: where one would break
(unknown counts as broken), the row keeps the one it points at, and the
delete is refused as DeleteOutcome.Referenced for that relation, as a
restriction is, naming neither the rows nor the invariant. A cascade into an
Entity whose links something clears is refused where the writer is made.
bind refuses a foreign key that sets null (or a default) on a relation that
does not declare setNull, since the store would clear links no client
foresaw. One that refuses the delete (restrict, no action, or no
onDelete, the default) is let through on a relation that declares nothing:
the delete then fails as a database error, not Referenced, so declare
onDelete: 'restrict' to have it answered.
A link through such a relation points at a row. An insert or update
that sets a link through a relation declared onDelete writes it only while
the row it points at is there, in the statement that writes
(checksTargets), and otherwise answers Invalid with the relation's key
as the path. A taken id is still answered as taken.
On Postgres, keep the foreign key. A cascade, a restriction, a clear or
a link the writer holds alone sees what had committed when its statement
ran. On SQLite and D1, which write one transaction at a time, that is
everything. On Postgres at read committed a link committed while the delete
runs is not seen, and would outlive its target, so RemoteServer.write
refuses such a delete, and such a link, through writer(binding) there,
naming the relation, what it needs and the store. It registers where the
table's foreign key holds the relation, one on the link's column that
references the target's id (on delete cascade, restrict or
no action, or set null, as the relation declares, which bind checks
against it), or with isolation: 'serializable', where the link's write
reads the row the delete removes, so one of the two is refused.
A cascade takes no row its deleter may not delete. delete takes
cascading, each Entity's Delete rule as a CascadeRequirement (Guard's
GuardServer.writer hands them over), and judges it in the statement that
deletes the row named, over every row the cascade would take through a
relation that holds rows to their own rule (authorizedBy: 'child', the
default): not exists a row that does not hold it. A rule unknown for a row
(a null it compares) refuses it. Refused, the row stays, so nothing after it
goes, and the writer fails Forbidden, naming the Entity, never the row; on
D1 the same statement sits in the same batch, so the decision is read before
anything is written. A row reached only through authorizedBy: 'parent' is
not judged, and a requirement for an Entity the delete takes nothing of under
its own rule is refused as its caller's mistake. A writer given none judges
nothing: without a guard there is no rule.
A retry is safe without a request log. A guarded write whose answer was
lost is sent again with the same revision, and the guard misses. The writer
then reads the row: one revision past the expected one and holding exactly
these values means this write landed, and the row answers; anything else is a
conflict. A field the write stamps from its clock (Entity.sets with
Expr.now) is left out of that comparison, since each attempt stamps it anew.
A guarded delete that finds no row succeeds. (Two clients writing identical
values from one revision are not told apart, which leaves the row as both
asked.)
Invariants: the row a write leaves
An Entity's invariants (Entity.invariant, kept on the binding by bind) are
judged over the row a write would leave, in the statement that writes it. Each
is compiled into the update's WHERE with the fields the write sets read as
their new values, each incremented field as its column moved by the amount and
each computed one as its computation; every other field is its column. So quantity = 3 against reserved <= quantity
is … where id = ? and reserved <= 3, and a reserved another writer raised
after the client read the row is judged too. A row whose invariant comes to SQL's
unknown (a null) is not written, as a WHERE drops it.
An insert has no row yet: its values, with its id, are judged before it is
written. RemoteServer.write refuses an insert that leaves a field an invariant
reads unset, since a default the writer cannot see would decide it.
A write that would break one is refused as Invalid, naming the first that
fails and its path. When nothing was written, the row read back says why in this
order: gone, moved on (a conflict), not holding the precondition (unmet), then
breaking an invariant. A row already holding what the write sets is answered as
written, as the retry of a write that landed finds it: writing it again changes
nothing, so it is judged as a row and not as a change. A write that repairs a
row already invalid is judged by the row it leaves, so it lands. An invariant the database cannot compile is
refused when the writer is made, not at the first write. A table-only binding
(entity) has no Entity, so no invariants; a handler's writes, and raw SQL, are
not judged by the writer.
An invariant that reads the row before too (a transition invariant, before.status)
is judged the same way over the change an update makes: the row before is the
columns themselves, and the row after is as above. A write setting the status to 'placed' makes
shippedStaysShipped … where not (status = 'shipped'): its after side is
known, so it is decided before the SQL is written. A field the write leaves alone
is unchanged after, and one it increments is its column moved. A miss that
breaks one is refused as Invalid too. A create and a delete do not judge it,
and it is not a constraint: a CHECK sees one row.
To hold an invariant against those too, install it as a constraint, with the field rules beside it.
CHECKs: the database holds the domain's rules
The Entity owns which values a field admits and which rows are valid together;
the table owns how they are stored. So a table's CHECK constraints are compiled
from the Entity, never written again in SQL, while its columns stay yours and
bind holds each to its field (kind, nullability). Two routes, one derivation:
import { sqliteTable, text } from 'drizzle-orm/sqlite-core'
import { bind, checkConstraints, entityChecks } from 'foldkit-remote-drizzle'
// drizzle-kit writes the migration: the table holds the CHECKs.
const posts = sqliteTable(
'posts',
{ id: text('id').primaryKey(), body: text('body').notNull() },
t => entityChecks(Post, t),
)
const Db = bind({ Post }, { Post: { table: posts } })
// A migration written in SQL: the same CHECKs as clauses.
const { constraints, serverOnly } = checkConstraints(Db.Post)
sqlite.exec(`create table posts (…, ${constraints.map(c => c.constraint).join(', ')})`)entityChecks takes the Entity, not the binding, because Drizzle reads the
callback lazily and the binding is made from the table. An invariant over a
one relation ("you cannot follow yourself") reads the column it is stored
on, which the table's columns do not name by the relation's key: give it as
entityChecks(Follow, t, { relations: { follower: t.followerId, followee:
t.followeeId } }), as bind is given { field }. Each column with rules
gets one constraint "<table>_<column>_check"; each state invariant gets
constraint "<table>_<id>" check ((…) is true) (is true, because a plain
check passes a row its condition calls unknown, and an invariant does not).
A rule compiles only where SQL says it exactly: for every value of the field's
kind that the column can hold, the database accepts it when the Schema does and
refuses it when the Schema does (tested on SQLite and Postgres, NaN, infinities
and NUL included). That covers lengths in code points (isMaxCodePoints and its
kin, and isNonEmpty), a whole-string pattern of one ASCII bracket
(/^[a-z0-9_]{3,15}$/, with unit lengths beside it), numeric bounds,
isFinite, isInt (a safe integer), isStartingWith, isEndingWith and
isIncluding (by bytes on SQLite and under the binary collation on Postgres,
so a column's own collation cannot loosen them), and literals. Everything else is in serverOnly, a sentence per
rule, and is held by the server's writes alone: a length in UTF-16 units with
no ASCII pattern (isMaxLength: SQL counts code points), a custom filter, a
rule made after a transformation, a rule inside a record, an array or a
recursive schema, a transition invariant. One the dialect cannot compile, such
as an invariant over an operator with no SQL, is refused by name.
What a column cannot hold is where the dialects part:
- NaN. Effect's upper bounds (
isLessThan,isLessThanOrEqualTo) accept NaN; its lower bounds andisBetweenrefuse it. Postgres orders NaN above every number, so each bound's CHECK says what it does with NaN. SQLite stores a NaN it is sent as NULL, so there a bound compiles only over a finite field (Schema.Finite, orSchema.Int), which refuses NaN itself; any other is inserverOnly. - NUL in text. SQLite's
lengthandGLOBstop at the first NUL, so its length CHECK counts through JSON, where a NUL is an escape, and a pattern's CHECK refuses a NUL outright, as the pattern does. Postgres refuses NUL in text before any CHECK reads it. realon Postgres is float4, which holds a rounding of the number written:isLessThanOrEqualTo(0.1)would refuse 0.1. A number rule over a float4 column is inserverOnly; usedouble precisionto compile it.binddoes not refuse the column, since how a field is stored stays yours. A binding's first write throughwriterreports itsserverOnlyrules as oneServerOnlyRulesdiagnostic, since a write past the server (raw SQL, another service) is not refused by them.
bind compares a table's own Drizzle CHECKs with the derived ones and refuses
one that says another rule, a column's check whose rules are gone, or a derived
check missing beside the others. A column named without its table
(length("body"), as drizzle-kit pull writes it) reads as the same column. It
reads the table's definition, not the database: a migration not yet run, or a
constraint changed there by hand, goes unseen. A table holding none of them is
not checked.
- Postgres adds one to a table (
alter table … add). A table already holding rows that break it refuses the constraint; add itnot valid, repair the rows, thenalter table … validate constraint "<name>". - SQLite cannot add or change a constraint on a table: write each in the
table's
create table, and for an existing table rebuild it (create the new one, copy the rows, drop the old, rename, and recreate its triggers), which fails on a row that breaks one. - Changing a rule is a migration too: drop the constraint by its name and add the new one.
- The writer still judges first, so a declared write keeps its typed
Invalid; a handler or raw SQL meeting a constraint fails as a database error.
A ledger: a retry is never applied twice
Where it sits beside expected revisions and plain assignments is in the declared writes guide.
writer(binding, { ledger: { table, scope } }) records each update and insert
it lands under the operation that asked for it (the client's operation id) and the row
it wrote, in the
transaction that writes the row, and answers a retry of that operation from the
record instead of writing again. So an increment of an integer needs no
expect: two made from one read both land, and a lost answer's retry is not
written again. A computed assignment field := op(field, amount), its amount
reading no field, lands without one too when both of the binding's tables record
op's commutativity and associativity as tested over every value (Operators.withEvidence,
DrizzleOperators.withEvidence, from Conformance.laws and Conformance.lawsBy
over compileCall); any other needs expect. It is
answered, as every write is, with the row as it now is, read back under its
reader's rules: a later write's values, and none it may no longer see.
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);at is milliseconds, past a Postgres integer (SQLite's integer holds it;
bigint there reads as one). The index on at keeps pruning from scanning the
table.
scope(principal)names whose operations they are, so no one is answered with another's write; an operation id is only unique per client that minted it.- A record is kept for
retentionmilliseconds, a day unless given; a retry later than that is a new operation. Records are pruned as new ones are made. - Updates and inserts are recorded. A retried insert is answered from its
record with the row it made; any other create of a taken id, and without a
ledger a retry too, is refused as
Refusal.taken. A retried delete finds the row gone. - The ledger runs in a transaction: synchronous on SQLite, awaited on Postgres.
D1 refuses a transaction's
BEGIN, so there the ledger reads the record first and then writes the row and its record in onebatch, which commits whole or not at all (see Cloudflare D1). - A write from a client that sends no operation id is written as without a ledger, except an increment that expects no revision, which is refused.
requestholds a SHA-256 digest of what the operation asked: its mutation, the keys it writes and its input, which every retry repeats. The same operation id sent with another request is refused (Operation "…" cannot be sent again with another mutation, keys or input: a retry sends the same ones), never answered as its retry. A ledger table made before it gains the column withalter table write_ledger add column request text, and its Drizzle tablerequest: text('request')(pgTexton Postgres); a record without one is answered as a retry, as before, until its retention passes.- On Postgres a retry sent while its original is still writing waits for it (a transaction-scoped advisory lock on the operation and the row), then is answered from its record, rather than failing on the record's key.
- A write the ledger holds no record of is judged as new: its precondition and its transition invariants hold of it, even when the row already holds what it sets. Without a ledger, an update whose row already holds what it sets is taken for a retry that landed: a guess, which a new write the row happens to agree with passes too.
A revision the database moves
A writer moves a revision only with the writes it lands. revisionTrigger(binding,
'revision') is the SQL that makes the database move it on every other update
too (a handler's, raw SQL), so a guarded writer pinned to it sees every change.
An update that sets the revision itself, by one or to any value, is left as it
set it. Run it with the migration that makes the table (SQLite and Postgres);
running it again keeps the trigger on SQLite and replaces it on Postgres, and a
Postgres table in a pgSchema is named by its schema. Its trigger (and a
Postgres function) is named once per database, as <table>_<column>_moves,
followed by the table name's length where either name holds _, so a_b's c
and a's b_c get two; a Postgres name past 63 bytes is refused, since
Postgres would cut it. The revision column must be not null: the trigger
compares it with =, which a null never satisfies, so a null revision is never
moved. Not for a table Sync writes: applyEdits keeps one revision for two
changes in one operation, which the trigger would move past its sequence.
A journal's edits
A table a foldkit-sync journal writes (editsJournal) takes its apply from
the binding: applyEdits(Db.Product) writes one committed cell edit to the
member's column, and the sequence it committed at to revision, in one
statement that never moves a row back, so recovery may run it again. A table
whose revision field has another name gives it as revision, which is typed
by the binding's fields. The
column is the binding's, never one named by the change. Here the revision is
the journal's sequence, so such a table should not also take writes that
expect a counter.
Given { live: hub }, it tells that liveHub of each edit it applied (the
member and the revision), so a Remote reader following the row with
live(Data, …) hears a settled edit as the journal applies it, with no refresh.
An edit the row had already passed, run again by recovery, is not told. The
hub is in-memory, so this reaches readers of the same process; across
Workers requests, a live source reads the table instead.
Writing in a handler
Anything a declared write cannot say (several rows, a value computed from
another row, another table) is a
RemoteServer.mutation handler using Drizzle directly. The adapter helps
normalize rows you already chose to return, and runs each statement so a
database error fails as a RemoteServerError whose message says only what
failed and whose cause is the driver's own error (which carries the SQL and
its parameters). The caller reads Internal error and an incident; the
driver's error is reported as a StatementFailed diagnostic
and in the server's ServerDefect, never sent (see
When the database fails):
import { eq } from 'drizzle-orm'
import { Effect } from 'effect'
import { RemoteServer } from 'foldkit-remote-server'
import { returning, runStatement } from 'foldkit-remote-drizzle'
const project = returning(Project, [
'id',
'name',
'owner',
])
const RenameProjectSource = RemoteServer.mutation(
RenameProject,
({ input }) =>
Effect.gen(function* () {
const rows = yield* runStatement(
() =>
db
.update(projects)
.set({ name: input.name })
.where(eq(projects.id, input.id))
.returning(project.columns),
'Database write failed',
)
return {
output: { id: input.id },
entities: project.patches(rows),
}
}),
)returning(binding, fields) pairs the Drizzle column projection with the
normalizer for those exact fields, so the mutation cannot accidentally select
one shape and normalize another. Singular relation foreign keys are rewritten
to Remote ref keys. The columns are typed by the table's dialect (PgColumn
for a pgTable, SQLiteColumn for a sqliteTable), so either dialect's
.returning takes them without a cast.
selectColumns and normalize are the lower-level halves when you need them
separately.
Name every row you wrote. The client's store learns only of the rows a
mutation's entities name, so a handler that updates a title and returns
{ output: {} } leaves every screen showing the old title. Of each row named,
the answer carries what the client's Surfaces show, read after the write
(What an answer carries),
so Remote.patch(Post, input.id, {}) is enough for the page that asked.
Return the row's values too when live subscribers should hear them, since they
hear the patch, not that read: returning.row(binding, id) reads the row
back, every column with each one relation as its ref:
import { drizzleWrites, returning } from 'foldkit-remote-drizzle'
const PublishPostSource = RemoteServer.mutation(PublishPost, ({ input }) =>
Effect.gen(function* () {
const writes = yield* drizzleWrites
yield* Effect.promise(() =>
Promise.resolve(writes.update(posts).set({ title: input.title }).where(eq(posts.id, input.id))),
)
return { output: {}, entities: yield* returning.row(Post, input.id) }
}),
)drizzleWrites is the provided database's insert, update and delete,
typed by each table's columns, so a handler writes without casting the
DrizzleDatabase service, which names only the reads a Source makes.
Several rows: the driver's own transaction. A declared write is one
statement, so it is atomic already. A handler that writes several rows wraps
them in its driver's transaction; the adapter adds none, because the drivers
disagree on what one is. A synchronous SQLite driver (node-sqlite,
better-sqlite3) takes a synchronous callback: given an async one, it
commits before the awaits run, and a later failure rolls nothing back. A
Postgres driver takes an async callback. D1 has no interactive transaction;
db.batch([...]) runs its statements as one. From
examples/entity, over node-sqlite:
const DeletePost = RemoteServer.mutation(DeletePostMutation, ({ input }) =>
Effect.sync(() => {
db.transaction(tx => {
tx.delete(comments).where(eq(comments.postId, input.id)).run()
tx.delete(posts).where(eq(posts.id, input.id)).run()
})
return { output: {}, deleted: [{ entity: 'Post', id: input.id }] }
}),
)