Repository navigation
v0.5.0
The public API settles: models named by their createSchema key with relations as fields, $ as a rule argument, sessions with claims and read-only access, restricted fields, server queries, lazy clients with eviction, writes that apply at most once across long offline periods, retention, a round of security fixes and a faster sequencer. Old APIs are removed, not deprecated. Wire protocol v2 and schema IR v2: 0.4 and 0.5 clients and servers don't talk to each other, and open tabs reload once when you deploy. Breaking changes are listed first, each with what to change; the Swift client follows every change.
Breaking changes
-
Schema.
model(fields, options)takes no name, andcreateSchema({ user, todo }, { viewer: "user" })names models by their key. Relations are fields:project: t.belongsTo("project", { inverse: "todos", foreignKey, onDelete, eager })replacesschema(models, (relations) => …)andrelations.belongsTo.Migrating: move each model into the
createSchemaobject under its name, and eachrelations.belongsTo(…)onto the child as at.belongsTofield. -
ownedis removed; cascades come fromonDelete.t.belongsTo("todo", { inverse: "comments", onDelete: "cascade" })is the one way to cascade (default"setNull"for nullable relations,"restrict"otherwise). WithfromPrisma, the relation'sonDeleteinschema.prismadecides:Cascadecascades,SetNullclears the key, anything else restricts. Client deletes, undo,ensureUndoableand archive inheritance follow every cascading relation, and a model may cascade from several parents (archived while any of them is). Schema metadata hascascadingParents/cascadingChildreninstead ofowner/ownedChildren; the schema IR dropsowned.Migrating: replace
owned: truewithonDelete: "cascade", or give the Prisma relationonDelete: Cascade. -
Load modes are
"eager"and"lazy"."eager:critical"and"partial"are gone: a lazy model loads by its id, unique fields and foreign keys, andeager: trueon a relation loads children with their parent.db.$ready()takes no level, and<DatabaseProvider ready>is a boolean.Migrating:
"eager:critical"becomes"eager","partial"becomes"lazy",ready="critical"becomesready. -
fromPrismaoptions per model.models: { Todo: { load, id: { prefix }, restricted, archivable, relations: { project: { eager } } } }replaces the top-levelloadandownedlists;eageris the only relation option. Mistakes are type errors on the offending key, including misspelled model names inmodels,omitandnotSecret. -
Permissions take
$as an argument.defineModelRules(schema, "todo", { read: (todo, $) => { … } }),defineRule(schema, "project", (project, $) => …, { name })anddefinePermissions(schema, [rules…], { strict, groups })replacecreateRules,rules(…)andrules.fn; explicit groups move todefinePermissions'groups. -
$.canRead(row.relation), and nothing is readable implicitly.$.canRead(comment.todo)(or$.canRead(comment.todo, { except })), in read and write rules, replacescomment.todo.canRead(). Children no longer inherit their parent's read rule: every synced model needs areadrule, and outside production (strict)definePermissionsfails without one.read: (comment, $) => { return $.canRead(comment.todo); }reads exactly like the parent and is re-tagged in bulk when the parent's access changes.Migrating: add that rule to each formerly owned child.
-
updaterules are field groups:{ when, fields }or a list of them. Each changed field must belong to a group whosewhenholds before and after the write. -
Sessions replace viewers. The handlers'
viewer(request)option is nowsession(request), returning{ viewer, claims?, readOnly?, tenant? }ornull, andverifyJwt({ viewer })isverifyJwt({ session }). Sync tokens carry the whole session. On the client,db.$viewerIdisdb.$session.viewerId. Engine methods (bootstrap,pull,push,partial,connect) take aSessionfromcreateSession(viewer, { claims, readOnly, tenant })instead of tenant and viewer ids,engine.viewerGroupsisengine.sessionGroups(session), and sync ids are opaque strings.Migrating: rename
viewer:tosession:and return{ viewer: id }. -
Server mutators are removed, with
createEngine({ mutators }),db.$calland thecalloperation. Keep server logic in your own server actions or routes and call them throughdb.$action(fn). -
EntitiesOf<Schema>(DB["Todo"]) replaces the publicEntityOf<Schema, "todo">. -
db.$sync()resolves only after a pull that started after the call (a barrier on live sockets), not after one already in flight. -
Stricter security defaults, each refusing something 0.4 accepted:
- Sync token secrets (
tokens.secret,mintSyncToken) andverifyJwt({ secret })need at least 32 characters (openssl rand -base64 32). - POST bodies must be
application/json; other media types get 415. ?token=is read only on WebSocket upgrades, never on plain HTTP requests.- Without
cors, a WebSocket from another origin needs a sync token: cookies alone get 403. Passcorsif pages on other origins call the server.
- Sync token secrets (
-
Custom
Reactivityimplementations need areaction(onInvalidate)method;signalsandmobxReactivity()have it. -
Engine:
sequenceOnce()is removed.sequenceNow()takes no arguments anddrainChanges()resolves once the backlog is empty; both return nothing. -
Upgrading the database. Run
npx clientdb migrate <engine module>when you deploy (--dry-runfirst prints the plan). On engine-owned tables it adds the new columns itself. Prisma apps first re-runnpx clientdb-prisma modelsand migrate, for the newclientdb_row.field_readers,clientdb_log.created_atandnonce,clientdb_head.transactions_horizonandclientdb_transactions.headcolumns (clientdb migratenames any that are missing), and regenerate the capture triggers withnpx clientdb-prisma triggers src/sync/schema.ts: they now coverserverOnlymodels, key changes, TRUNCATE and cascaded rows, and wake the sequencer.
Features
-
Restricted fields:
.restricted()(ormodels.X.restrictedwith Prisma) and per-field read rules,read: { when, fields: { inviteCode: (project, $) => { … } } }. Hidden fields areundefinedon the client and routed in their ownfield_readerscolumn. -
Claims and read-only sessions:
declareClaim("staff"), granted by the session callback, used as a condition in rules and checked on the client withdb.$session.hasClaim($staff).readOnly: trueon a session or route refuses writes withReadOnly(ReadOnlyErroron the client), andcreateDatabaseClient({ readOnly: true })types a client without writes. Live sockets check their session again every token lifetime and renew sync tokens, and changed claims move rows on and off the device. -
Writes apply at most once, also after long offline periods. Applied transaction ids are kept for
retention.transactions(default the longer ofretention.logand 90 days). A pull from a client behind the pruned log is answered withresetbefore anything it sent is applied, and a resend the server may have applied after its id was pruned is refused with the newStalecode instead of applied twice. The client stamps each transaction with the sync position it is first sent from. -
Server queries:
db.todo.query({ where, orderBy, limit })overPOST /query, with keyset pages and per-modelquery: { fields, maxLimit }rules.wheregains text operators (contains,startsWith,endsWith). -
Lazy clients and eviction:
createDatabaseClient({ load: "lazy" })starts with no rows, andeviction: { maxRows }drops the loads used longest ago that nothing observes. -
Fields:
t.uuid({ prefix }),t.decimal(),.unique()and.generated()(Prisma autoincrement anddbgenerated()columns). -
db.$action(fn, { optimistic })previews a server action's outcome on the device until the server answers. -
Engine:
retention: { log, transactions, archived }applied byengine.prune()(hourly instart(), and byclientdb migrate); clients behind the pruned log start over.hooks: { onWriteRejected, onAccessRemoved }(no row data, safe to log),bootstrapRowWarning,cascadeRowLimitandrecentLogActions.clientdb migrate --dry-runandengine.migrationPlan()show what a migration would do. -
Prisma archives:
models.X.archivablewitharchivedAt/archivedBycolumns, so Prisma tables supportarchive(),unarchive()andretention.archived. -
Transient database failures (a lost connection, shutdown, statement timeout or deadlock) throw
Unavailable: HTTP answers 503, a live socket closes with 1011, and the client keeps the transaction and resends it, instead of dropping a write that was never wrong.
Fixes
-
Security:
- Cross-site WebSockets authenticated by cookies are refused (browsers attach cookies to any site's upgrade), and an opaque
nullOrigin no longer crashes the server. - Non-JSON POST bodies get 415, so another site can't push transactions with the viewer's cookies through a form or a no-cors fetch.
- Tokens are no longer read from URLs of plain HTTP requests, and the Swift client sends its token as a header on the WebSocket too.
- Secrets under 32 characters are refused. Malformed JWTs and JWKS keys that don't fit the token's algorithm answer 401 instead of 500.
- Written values are checked against their field (type, enum, nullability) before rules run, so a rule can't be passed with
"0"that Postgres then stores as0. - Client archives, and creates or restores of archived rows, are stamped with the server's clock and the viewer and need the archive rule, so a back-dated archive can't make retention delete a row.
- Writes to rows the viewer can't read get the same
NotFoundas writes to missing rows, and an unreadable restricted field is refused in no-op updates too, so neither reveals hidden data. - Rejections no longer carry Postgres messages (which name tables and constraints), and names such as
__proto__are unknown models and fields. - Rows are routed no wider than their read rules:
$.publicnext to other conditions, and claim or viewer conditions through related rows, no longer widen who receives a row; a negated membership inside another membership is refused when compiling.
- Cross-site WebSockets authenticated by cookies are refused (browsers attach cookies to any site's upgrade), and an opaque
-
Sync and the server:
- A database restored from a backup is detected through per-entry nonces in sync positions: clients past the backup start over, and servers drop their in-memory recent log.
- A process that would miss log entries pruned before it published them drops the affected connections, and a failed delivery drops the live connection instead of skipping the batch; the client resumes from its last position.
- A process still routing with an access plan that another process migrated away from answers
Unavailableinstead of granting rows with old rules. - Non-default tenants are refused on external (Prisma) tables, which hold one set of rows.
- Updates are recorded with the row as the database stored it (numeric scale, triggers,
updatedAt). - A connection Postgres terminates no longer crashes the process, a bootstrap or pull stream the consumer stops reading is rolled back, and concurrent capture drains no longer deadlock (the background loop survives a failed pass).
FsSnapshotStorenames files by a hash of the key, so a long client-chosen id can't break bootstraps.
-
Client:
- Tabs and IndexedDB stay consistent across fresh loads, sign-out (
$clear()stops every tab and wipes storage), stale models and storage upgrades; unsent writes survive an upgrade. - Moved rows stay out, load answers drop rows they no longer hold, and a
resetreplaces local state. - Observed lazy reads and server queries load again after access changes, and upserts kept aside for a load are dropped when the viewer loses their groups.
- Eviction keeps every load holding an observed row and settles only unsent transactions as
AccessLost. - Undo compares with the row's state without previews, and
useLive/live()keep data observed across re-renders.
- Tabs and IndexedDB stay consistent across fresh loads, sign-out (
-
Prisma: capture triggers record key changes (the old id is deleted), TRUNCATE, and rows that foreign-key cascades or app triggers change during engine writes;
captureDriftreports older triggers as missing. Captured writes toserverOnlymodels re-route the rows they affect, and fields required by Prisma's tables are checked only when writing to them.
Performance
- Captured writes are drained in batches, in the same step that sequences the outbox, interleaved so a backlog delays the log instead of stopping it (before, past ~1,000 Prisma writes/s nothing reached clients). Postgres notifications wake the sequencer and followers instead of the 250 ms poll (kept as a fallback); concurrent
sequenceNowcalls share one run, and a process publishes its own batches from memory. - Each log batch is delivered only to the connections it can reach, serialized once per group set.
- Polls and reconnects catch up from an in-memory log of recent actions (
recentLogActions, default 50,000), indexed by group so a catch-up visits only its viewer's rows. - Routing prefetches each step's rows a page at a time, side-table rows are looked up by key (adopting millions of Prisma rows is no longer quadratic), and routing metadata is written by key also on tables without statistics.