@forestfuture/active-record 0.6.0 → 0.8.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forestfuture/active-record",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "A Rails-inspired Active Record for Cloudflare Workers, with an adapter per database.",
5
5
  "keywords": [
6
6
  "active-record",
@@ -8,7 +8,7 @@
8
8
  "orm",
9
9
  "workers"
10
10
  ],
11
- "homepage": "https://d1-record.forestfuture.dev",
11
+ "homepage": "https://active-record.forestfuture.dev",
12
12
  "bugs": {
13
13
  "url": "https://github.com/forestfuture/active-record/issues"
14
14
  },
@@ -24,6 +24,7 @@
24
24
  "ffar": "./dist/command.mjs"
25
25
  },
26
26
  "files": [
27
+ "config-schema.json",
27
28
  "dist",
28
29
  "llms-full.txt",
29
30
  "skills"
@@ -34,6 +35,8 @@
34
35
  ".": "./dist/index.mjs",
35
36
  "./adapter": "./dist/adapter.mjs",
36
37
  "./cli": "./dist/cli.mjs",
38
+ "./d1": "./dist/d1.mjs",
39
+ "./postgresql": "./dist/postgresql.mjs",
37
40
  "./package.json": "./package.json"
38
41
  },
39
42
  "publishConfig": {
@@ -42,6 +45,26 @@
42
45
  "dependencies": {
43
46
  "jiti": "^2.7.0"
44
47
  },
48
+ "devDependencies": {
49
+ "@electric-sql/pglite": "^0.5.14",
50
+ "pg": "^8.23.1"
51
+ },
52
+ "peerDependencies": {
53
+ "@cloudflare/workers-types": ">=4",
54
+ "@electric-sql/pglite": "^0.5.14",
55
+ "pg": "^8.23.1"
56
+ },
57
+ "peerDependenciesMeta": {
58
+ "@cloudflare/workers-types": {
59
+ "optional": true
60
+ },
61
+ "@electric-sql/pglite": {
62
+ "optional": true
63
+ },
64
+ "pg": {
65
+ "optional": true
66
+ }
67
+ },
45
68
  "scripts": {
46
69
  "build": "vp pack"
47
70
  }
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: active-record
3
- description: Active Record (`@forestfuture/active-record`, with its D1 adapter `@forestfuture/d1-record`), a Rails-style Active Record for Cloudflare Workers. Use when writing code with either package, or deciding how to model D1 data in a Worker.
3
+ description: Active Record (`@forestfuture/active-record`, with its D1 and PostgreSQL adapters as its `/d1` and `/postgresql` entries), a Rails-style Active Record for Cloudflare Workers. Use when writing code with the package, or deciding how to model D1 or Postgres data in a Worker.
4
4
  ---
5
5
 
6
6
  # Active Record
@@ -9,27 +9,31 @@ description: Active Record (`@forestfuture/active-record`, with its D1 adapter `
9
9
 
10
10
  <!-- #region rules -->
11
11
 
12
- Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for Cloudflare Workers, with an adapter per database: `@forestfuture/d1-record` for D1. Import Models, Relations, and errors from the core, and `connect`, `withSession`, `NoSession`, and `d1` from the adapter. Its guide for the installed version is `node_modules/@forestfuture/active-record/llms-full.txt`, one Markdown file with a `#` heading per page: read the part for the task before writing code with it.
12
+ Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for Cloudflare Workers, with an adapter per database inside it: `@forestfuture/active-record/d1` for D1, and `@forestfuture/active-record/postgresql` for Postgres, which needs the app's own `pg`. Import Models, Relations, and errors from the core, and what opens a database from its adapter's entry: `connect`, `withSession`, `NoSession`, and `d1` from `/d1`; `connect` and `postgresql` from `/postgresql`. Every `active-record` command reads `active-record.jsonc`, which names each database's adapter, so one project can hold a D1 database and a Postgres one: run `npx active-record init` to write it, never `--adapter` on another command (`init --adapter postgresql` adds Hyperdrive bindings to a file that names only D1 databases). Its guide for the installed version is `node_modules/@forestfuture/active-record/llms-full.txt`, one Markdown file with a `#` heading per page: read the part for the task before writing code with it.
13
13
 
14
14
  - Create tables with the generators, never by hand-declaring attributes: `npx active-record g model Post user:references 'title:string!'` writes the migration and the Model; `npx active-record g migration AddSlugToPosts slug:string:unique` writes a change. Apply them with `npx active-record migrate`. After a hand-written migration, run `npx active-record schema`. Never edit the generated `src/db/schema.ts`.
15
- - A Model extends the app's base class: `class Post extends ApplicationRecord {}`. Its table comes from its class name (`Post` → `posts`), or `static override table = "…"`, and its attributes from the schema, so it declares only behavior. Run `npx active-record schema` after adding or renaming a Model, as after a migration: a Model it hasn't seen throws `InvalidModel`. Change how a column is read with an override in the class, `static override attributes = { metadata: "json" } as const`, never by editing the schema. An `INTEGER` holding a Unix time (Drizzle's `timestamp` modes) is `{ type: "datetime", storage: "unixSeconds" }` or `"unixMilliseconds"`. A cell that isn't its attribute's type (a number in an ISO `datetime`, text in an `integer`) fails the load with a `TypeError` naming the attribute: correct the override, don't catch it.
15
+ - A Model extends the app's base class: `class Post extends ApplicationRecord {}`. Its table comes from its class name (`Post` → `posts`), or `static override table = "…"`, and its attributes from the schema, so it declares only behavior. With a bundler that renames classes (Wrangler keeps them by default), set `static override modelName = "Post"` on each Model, so its table, foreign keys and schema entry keep the name. Run `npx active-record schema` after adding or renaming a Model, as after a migration: a Model it hasn't seen throws `InvalidModel`. Change how a column is read with an override in the class, `static override attributes = { metadata: "json" } as const`, never by editing the schema. An `INTEGER` holding a Unix time (Drizzle's `timestamp` modes) is `{ type: "datetime", storage: "unixSeconds" }` or `"unixMilliseconds"`. Bytes are a `binary` attribute (a `Uint8Array`, in a `BLOB` or `bytea` column): assign a form's file as `new Uint8Array(await file.arrayBuffer())`. An exact number (a price, a quantity with a fraction) is a `decimal` attribute, held as text (`"12.5"`) in a `NUMERIC` or `DECIMAL` column, never a `real`, with `precision` and `scale` to round it as `NUMERIC(10, 2)` does; a day with no time is a `date` (`"2026-01-02"`) and a time of day a `time` (`"09:30:00"`), assigned as text, not a `Date`. A value no built-in type holds (money, a value object, a list kept as text) is a custom type: `const money = defineType({ storedAs: "integer", cast, serialize, deserialize })`, given as `priceCents: money` in the override or in `define`, rather than converting in getters, setters or callbacks; its `cast` throws for a value it can't hold. A column with a fixed set of values is an enum: `status: { enum: ["draft", "published"] }` (names stored as text) or `{ enum: { low: 0, high: 1 } }` (an integer column), which gives `post.isDraft()`, `await post.saveAsPublished()`, `Post.published()`, `Post.notPublished()` and `Post.enumValues("status")`; use those and `where({ status: "published" })` rather than a hand-written scope or a `declare status: …` narrowing. Run `npx active-record schema` after adding an enum, so its scopes are typed. A column the database restricts to a list (a Postgres enum type, `CHECK (state IN ('open', 'done'))`) already has the names in the schema, typed and checked but without methods: turn them on with `state: { enum: true }`, rather than listing the names again, or drop it with `enum: false`. An unlisted stored value reads as `null`; rename a name with `{ newName: "old_value" }`. A cell that isn't its attribute's type (a number in an ISO `datetime`, text in an `integer`) fails the load with a `TypeError` naming the attribute: correct the override, don't catch it.
16
16
  - Start queries and new records from the Model, as in Rails: `User.find(id)`, `User.where(…)`, `User.build(…)`. Each Model queries the binding named in the generated schema its base class holds, during a request. For a D1 Session, wrap the handler in `withSession(request, env.DB, fn)`. For per-request `onQuery`, or tests and scripts outside a Worker, wrap the code once in `withDatabase(connect(env.DB, { … }), fn)`. Records keep the database they came from.
17
- - Never pass a request's whole body, form or query string to a Model: name the fields, with destructuring or `User.permit(await request.json(), "email", "name")` (it reads `FormData` and `URLSearchParams` too). Assigned values are checked against the attribute's type, but that doesn't stop a user setting `role` or `isAdmin`. Check a request value's type before querying with it: `findBy({ token: null })` matches rows whose token is NULL.
17
+ - Never pass a request's whole body, form or query string to a Model: name the fields, with destructuring or `User.permit(await request.json(), "email", "name")` (it reads `FormData` and `URLSearchParams` too). Assigned values are checked against the attribute's type, but that doesn't stop a user setting `role` or `isAdmin`. Check a request value's type before querying with it: `findBy({ token: null })` matches rows whose token is NULL, and a list matches any of its values. `findOrCreateBy`, `findOrInitializeBy` and `createOrFindBy` throw `TypeError` for a list, a comparison or a `sql` fragment.
18
18
  - Name attributes in camelCase everywhere: `where`, `order`, `pluck`, `foreignKey`. Column names (snake_case) appear only inside `sql` fragments.
19
19
  - Write custom SQL as an `sql` tagged template, which binds every value: ``where(sql`lower(${column("email")}) = ${email}`)``. Interpolate an attribute's value with `column("publishedAt").value(date)`, not the bare `Date`, when the attribute is stored as a Unix time: a bare `Date` is ISO text, and it throws `TypeError` when it's compared directly with that column.
20
20
  - For a raw `env.DB.prepare(…).bind(…)` statement, bind `Post.typeForAttribute("publishedAt").serialize(date)`, which writes the value as the attribute stores it, and read a cell with `.deserialize(cell)`. A value the attribute can't hold throws `TypeError`.
21
- - Bulk writes run when called: `await posts.deleteAll()` and `updateAll(…)` resolve to how many rows; `insert(…)`, `insertAll`, `upsert` and `upsertAll` to `{ rowsAffected, rows }`, where `rows` holds each written row's primary key, or the attributes `returning: [...]` names (`returning: false` for none). Make several writes atomic with one `batch([...])` of their `to…` forms (`toInsert`, `toUpdateAll`, `toDeleteAll`, …) and records' `toSave()`/`toDestroy()`. D1 has no interactive transactions, so a read-then-write can't be atomic.
22
- - Keep the generators' `TEXT` keys, generated in code, for records saved together (`--id integer` gives a key D1 generates instead). An owner whose key is known before its INSERT (generated in code, or already saved) is written in one atomic batch with the records built through it. A key D1 generates exists only after its own write, so each level is then written in a separate batch.
21
+ - Bulk writes run when called, without callbacks: `await posts.deleteAll()`, `deleteBy({…})` and `updateAll(…)` resolve to how many rows; `insert(…)`, `insertAll`, `upsert` and `upsertAll` to `{ rowsAffected, rows }`, where `rows` holds each written row's primary key, or the attributes `returning: [...]` names (`returning: false` for none). Through a Relation they write its equality values and `createWith` over the attributes given (`Post.where({ userId: 1 }).insert({ userId: 2, … })` writes `userId: 1`), where `build` and `create` keep the given ones. Make several writes atomic by preparing them in one batch's callback: `batch((b) => [b.insert(Post, {…}), b.updateAll(Post.where(…), {…}), b.save(user), b.destroy(post)])`. The callback can't await, so load what the writes need first. D1 has no interactive transactions, so a read-then-write can't be atomic.
22
+ - Count with the database, not in memory: `post.incrementColumn("viewCount")` or `Post.updateCounters(id, { viewCount: 1 })` add to the row atomically, where `post.viewCount++` then `save()` loses another request's increment. The counter statics (`Post.updateCounters(ids, …)`, `incrementCounter`) skip the default scope, so with a key from a request, and a default scope that separates tenants or hides deleted rows, write `Post.where({ id }).updateCounters({ … })`, which keeps it. The `…Column` methods and `updateColumns` skip validations, callbacks and `updatedAt`, so use `update` for a change those should see; `increment` and `toggle` only change the record in memory. In an after-callback, `record.isPreviouslyNewRecord()` says whether the save created it.
23
+ - To show how many records an association has, keep a counter cache rather than counting on each read: `article = belongsTo(Article, { counterCache: true })` with a `commentsCount` attribute, which `article.comments().size()` reads. Saves, destroys and the association's `delete`/`clear`/`deleteAll()` keep it; bulk writes (`insertAll`, `updateAll`, a Relation's `deleteAll`) don't, so follow them with `Article.resetCounters(id, "comments")`. Add one to existing rows with `{ active: false }`, reset each, then drop `active: false`.
24
+ - To work through more records than a request should hold (a backfill, an export, a cleanup), iterate in batches rather than `toArray()` or `offset` pages: `for await (const user of User.where(…).findEach())`, `findInBatches()` for arrays, and `inBatches()` for a Relation per batch to `updateAll`, `deleteAll` or `destroyAll`. Batches go in primary-key order, so `reorder()` a Relation that has an order (a default scope's too), and bound them with `start` and `finish`, not `offset`. On D1 a Worker invocation sends at most 1,000 queries (50 on Free), and each batch sends one (`inBatches` reads its keys, then sends the write, and a `destroyAll` adds a load and each record's dependent reads; a `db.batch` counts as one): split a larger job across invocations by `start` and `finish`.
25
+ - To destroy many records with their callbacks and `dependent:` strategies, use `posts.destroyAll()`, `Post.destroyBy({…})` or `Post.destroy(ids)`: they load the records and destroy them in one write, all or none (`RecordNotDestroyed` if one refuses). They hold every record in memory, so destroy a large set a batch at a time: `for await (const batch of posts.inBatches({ batchSize: 100 })) await batch.destroyAll()`.
26
+ - Keep the generators' `TEXT` keys, generated in code, for records saved together (`--id integer` gives a key D1 generates instead). An owner whose key is known before its INSERT (generated in code, or already saved) is written in one atomic batch with the records built through it on its database. A key D1 generates exists only after its own write, so each level is then written in a separate batch. Records on another database are always a separate write there, and a batch refuses them.
23
27
  - To change how those keys are made (UUIDv7, ULID, a prefix), override `static generateId` once on the app's base class; don't give each Model's key a `default`. `generateId` sees only the attribute's name, so a value made from other attributes (a slug) goes in a callback.
24
- - Declare associations as fields, passing the target class: `posts = hasMany(Post, { dependent: "destroy" })`, `author = belongsTo(User)`. The field's name is the association's name.
25
- - Change the copy of validation messages with `this.errorMessages({...})` in the `static {}` block of the app's base class (every Model) or a Model (`attributes: { email: { taken: "…" } }` for one attribute), and attribute names with `this.humanAttributeNames({...})`, rather than a `message` on every `validates`. For a custom error, `errors.add("endsAt", { type: "afterStart" })` and give `afterStart` a message there.
26
- - Check what writes return. `save()` and `update()` resolve to `false` when validation fails (reasons in `record.errors`) or a callback aborts (`record.abortReason`). `destroy()` resolves to `false` when a callback aborts, or a `restrictWithError` association refuses (reason in `record.errors`). The `…OrThrow` methods throw instead. Constraint errors, such as `RecordNotUnique`, always throw.
28
+ - Declare associations as fields, passing the target class: `posts = hasMany(Post, { dependent: "destroy" })`, `author = belongsTo(User)`. The field's name is the association's name. Add and remove a `hasMany`'s records through it: `user.posts().push(post)`, `delete(post)` (by its `dependent:`, nullifying by default), `destroy(post)` and `clear()`, rather than writing the foreign key yourself, so a loaded collection stays in step. Saving requires a `belongsTo`'s record ("must exist"), so pass `optional: true` when its foreign key may be `null`. Its target may be on another database (a Model on another base class): reading, preloading (one more round trip), and writing through it go to the target's database, and a save or destroy writes each database separately, not atomically. A `hasOne`'s new record, through `set`, `build` or `create`, replaces the old one, which its `dependent:` strategy removes (without one, its foreign key is set to `null`). Await `user.profile.set(profile)`: on a saved owner it saves at once, unlike a `belongsTo`'s `set`. To save changes to associated records with their owner, declare the association `autosave: true` and change the records it loaded (`await user.posts().toArray()`), not ones found with a query of their own. `record.markForDestruction()` then destroys a record when its owner is saved. For a record that can belong to one of several Models, list them: `commentable = belongsTo([Post, Photo])`, with `commentableType` and `commentableId` attributes, and `comments = hasMany(Comment, { as: "commentable" })` on each listed Model. Point it with `comment.commentable.set(post)`, not by writing the type yourself: the type holds each Model's `modelName`, so set `static modelName` on the listed Models if a bundler renames classes. Reach records through a join Model with `through`: `projects = hasMany(Project, { through: "assignments" })` (`source:` names the join Model's association when it isn't `project`). It reads and preloads as any association, each record once. Write through it to make and remove join records: `user.projects().push(project)`, `build`, `create`, `delete(project)` and `clear()` (`destroy(project)` destroys the join records too, not the project). A built project is linked when the owner is saved, not the project. Don't narrow before `deleteAll` (`user.projects().where(…).deleteAll()`), which deletes the projects themselves. Only a join Model is written through (a `hasMany` to a `belongsTo`); `insert` and `upsert` through it throw. An upsert through a `hasMany` only updates the owner's records, and leaves another owner's clashing row as it is.
29
+ - Change the copy of validation messages with `this.errorMessages({...})` in the `static {}` block of the app's base class (every Model) or a Model (`attributes: { email: { taken: "…" } }` for one attribute), and attribute names with `this.humanAttributeNames({...})`, rather than a `message` on every `validates`. Compare one attribute with another with `comparison: { greaterThan: (event) => event.startsAt }`, not a callback. Validate an association's loaded records with `this.validatesAssociated("posts")`, not a callback. Run a rule only when creating or updating with `on: "create"` or `on: "update"` (or skip one with `exceptOn`), not `if: (record) => record.isNewRecord()`. For a step of the app's own, list its name in the Model's `static validationContexts = ["signup"] as const` and validate in it with `isValid("signup")` or `save({ context: "signup" })`; that replaces `"create"`, so pass `["create", "signup"]` to run both. For a custom error, `errors.add("startsAt", { type: "onTheHour" })` and give `onTheHour` a message there.
30
+ - Check what writes return. `save()` and `update()` resolve to `false` when validation fails (reasons in `record.errors`) or a callback aborts (`record.abortReason`). `destroy()` resolves to `false` when a callback aborts, or a `restrictWithError` association refuses (reason in `record.errors`). The `…OrThrow` methods throw instead. Constraint errors, such as `RecordNotUnique`, always throw, and so does a rule declared `strict: true` (`StrictValidationFailed`), meant for values only a bug could set.
27
31
 
28
32
  <!-- #endregion rules -->
29
33
 
30
34
  ## Shapes to follow
31
35
 
32
- Generated Models extend `ApplicationRecord`, with their attributes from the schema. Associations are fields, scopes are statics, and validations and callbacks go in the `static {}` block:
36
+ Generated Models extend `ApplicationRecord`, with their attributes from the schema. Associations are fields, scopes are statics, and validations, callbacks and a `this.defaultScope((q) => …)` go in the `static {}` block:
33
37
 
34
38
  ```ts
35
39
  import { belongsTo, hasMany } from "@forestfuture/active-record";
@@ -77,12 +81,16 @@ export default {
77
81
  ## Where code goes wrong
78
82
 
79
83
  - **`onQuery` listeners see filtered attributes' values as `"[FILTERED]"`**: passwords, tokens, keys and emails, by Rails' default list. Add names to `static filterAttributes` on the app's base class for other secrets. Values inside `sql` fragments aren't filtered.
80
- - **`relation.toSql()` and `statement.toSql()` show a query's `{ sql, params }` without sending it**, to inspect it while debugging. The params are real values, filtered attributes included, so don't log them where `onQuery` wouldn't. A record's `toSave()`/`toDestroy()` have no `toSql()`.
84
+ - **`relation.toSql()` shows a query's `{ sql, params }` without sending it**, to inspect it while debugging. The params are real values, filtered attributes included, so don't log them where `onQuery` wouldn't. Bulk writes and batches have no `toSql()`; `onQuery` shows what they sent.
81
85
  - **`toJSON()` sends every loaded attribute**, so `Response.json(user)` includes `passwordDigest`. List the names to leave out in `static hiddenAttributes` on the app's base class (exact names; a Model's own list replaces it). `attributes()` still has them.
82
- - **Uniqueness validation is a friendly check, not a guarantee.** Two requests can pass it at once; the table's UNIQUE index decides, and the save then throws `RecordNotUnique`. Declare both.
86
+ - **Uniqueness validation is a friendly check, not a guarantee.** Two requests can pass it at once; the table's UNIQUE index decides, and the save then throws `RecordNotUnique`. Declare both. To create a row once where requests race, use `createOrFindBy(attrs)` (insert, then find on `RecordNotUnique`) with the index alone: a `uniqueness` validation refuses first, so it finds nothing. `findOrCreateBy` races.
83
87
  - **`record.loaded("posts")` reads what was preloaded or already read**, synchronously, and throws `AssociationNotLoaded` otherwise. `await user.posts().toArray()` loads when needed.
84
- - **Page a list with `paginate()`, not a hand-built `limit` and `offset`**: `Post.published().paginate({ page: url.searchParams.get("page") })` casts the untrusted page, caps its size at `static maxPerPage`, and sends the count with the page in one round trip. `{ count: false }` skips the `COUNT`, which reads (and bills) every matching row.
85
- - **`find(id)` throws `RecordNotFound`**; `findBy(conditions)` resolves to `null`.
86
- - **After-callbacks run once D1 has committed the write.** An error there reaches the caller with the record already saved: nothing rolls back.
88
+ - **Page a list with `paginate()`, not a hand-built `limit` and `offset`**: `Post.published().paginate({ page: url.searchParams.get("page") })` casts the untrusted page, caps its size at `static maxPerPage`, and on D1 sends the count with the page in one round trip. `{ count: false }` skips the `COUNT`, which reads (and bills) every matching row.
89
+ - **Total, average or find the extremes of a column with `sum`, `average`, `minimum` and `maximum`**, not by loading records and adding them up in JavaScript: `Order.where({ status: "paid" }).sum("total")` sends one query. A sum of no rows is 0; the others are `null`. A `limit` picks the rows calculated, and an `sql` fragment calculates an expression: ``LineItem.sum(sql`${column("price")} * ${column("quantity")}`)``.
90
+ - **Calculate per category with `group`**, not with one query per category: `Order.group("status").count()` resolves to a `Map` such as `Map { "paid" => 3, "open" => 1 }`, and `sum`, `average`, `minimum` and `maximum` work the same way. ``having(sql`COUNT(*) > ${1}`)`` keeps some groups. Several attributes key each group by an array, which a `Map` finds only by identity, so loop over it. A grouped Relation has no records, and can only be ordered by grouped attributes or an `sql` fragment such as ``sql`COUNT(*) DESC` ``.
91
+ - **Filter by an associated Model with `joins` and `merge`**, not by loading its ids first: `Post.joins("author").merge(User.where({ role: "admin" }))` sends one query, and `leftJoins` keeps records with no linked record. A `hasMany` join repeats a record for each linked one: add `distinct()`. Join a Model before merging its Relation, and merge only its conditions, scopes and order. A polymorphic `belongsTo` can't be joined: join each listed Model's `as:` association instead. `includes` is still how to load associated records.
92
+ - **Replace a condition with `rewhere({ role: "admin" })`, and drop parts of a query with `unscope("order")` or `unscope({ where: "role" })`**, rather than rebuilding a scope's query by hand. Both widen a query, so never pass them request data. An association's link to its owner always stays: `user.posts().unscope("where")` is still the user's posts. Order by a list of values with `inOrderOf("status", ["open", "paid"])`, not a `CASE` fragment, and leave records out with `excluding(record)`.
93
+ - **`find(id)` throws `RecordNotFound`**; `findBy(conditions)` resolves to `null`. `firstOrThrow()`, `lastOrThrow()`, `takeOrThrow()` and `findByOrThrow()` throw `RecordNotFound` instead. When exactly one record must match, use `sole()` or `findSoleBy(conditions)`: none throws `RecordNotFound`, more than one `SoleRecordExceeded`. Read one value with `pick("email")`, not `(await first())?.email`, and the primary keys with `ids()`.
94
+ - **After-callbacks run once D1 has committed the write.** An error there reaches the caller with the record already saved: nothing rolls back. `afterCommit` (and `afterCreateCommit`, `afterUpdateCommit`, `afterSaveCommit`, `afterDestroyCommit`) runs after every after-callback, including those of every record in a batch; `afterRollback` runs only when the database refuses a write it was sent.
87
95
  - **Read replicas:** wrap the handler in `withSession(request, env.DB, fn)`. Every query in `fn` goes through one D1 Session, and its bookmark is set on `fn`'s Response as a `d1-bookmark` cookie, so the user's next request reads at least as new as their last write. For APIs, pass `{ header: "x-d1-bookmark" }` before `fn`; `start: "first-primary"` starts a request with no bookmark on the primary. Don't read or set the bookmark by hand.
88
- - **Outside a Worker** (tests, scripts) there's no binding to find: run the code in `withDatabase(connect(binding), fn)`, or a query throws `NoDatabase` saying so. With several databases, `withDatabase` can't tell them apart outside a Worker: mock `cloudflare:workers` with the bindings instead (Vitest needs `test.server.deps.inline: ["@forestfuture/d1-record"]`), assigning them onto the mocked `env` object. A query at a module's top level fails too: Workers only allow D1 calls during a request.
96
+ - **Outside a Worker** (tests, scripts) there's no binding to find: run the code in `withDatabase(connect(binding), fn)`, or a query throws `NoDatabase` saying so. With several databases on one adapter, `withDatabase` can't tell them apart outside a Worker (one D1 and one Postgres database each serve their own Models): mock `cloudflare:workers` with the bindings instead (Vitest needs `test.server.deps.inline: ["@forestfuture/active-record"]`), assigning them onto the mocked `env` object. A query at a module's top level fails too: Workers only allow D1 calls during a request.