@forestfuture/active-record 0.8.0 → 0.8.2

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/llms-full.txt CHANGED
@@ -9,8 +9,6 @@ Source: https://active-record.forestfuture.dev/
9
9
  npm install @forestfuture/active-record
10
10
  ```
11
11
 
12
- The same Models and queries run on D1 and on Postgres. See the [PostgreSQL adapter](/postgresql).
13
-
14
12
  **[Get started](/getting-started)**
15
13
 
16
14
  From an empty Worker to two related Models in about ten minutes.
@@ -25,6 +23,37 @@ See what’s different
25
23
 
26
24
  ## A Model and its queries
27
25
 
26
+ Use a Model in your Worker with no connection setup. It finds its database from its binding:
27
+
28
+ ```ts Worker
29
+ import { User } from "./models/user";
30
+
31
+ export default {
32
+ async fetch(request: Request): Promise<Response> {
33
+ // GET: the 20 newest active users, each with their posts.
34
+ if (request.method === "GET") {
35
+ const users = await User.active()
36
+ .includes("posts") // loaded in one extra query, not one per user
37
+ .order({ createdAt: "desc" })
38
+ .limit(20)
39
+ .toArray();
40
+ return Response.json(users);
41
+ }
42
+
43
+ // POST: sign up a user with a first post, saved together.
44
+ const { email } = await request.json<{ email: string }>();
45
+ const user = User.build({ email });
46
+ user.posts().build({ title: "Hello, world" });
47
+
48
+ // save() validates and runs callbacks; false means it wasn't saved, and why is in errors.
49
+ if (!(await user.save())) {
50
+ return Response.json({ errors: user.errors.fullMessages() }, { status: 422 });
51
+ }
52
+ return Response.json(user, { status: 201 });
53
+ },
54
+ } satisfies ExportedHandler<Env>;
55
+ ```
56
+
28
57
  ```ts Model
29
58
  import { hasMany } from "@forestfuture/active-record";
30
59
  import { ApplicationRecord } from "./application-record";
@@ -92,6 +121,20 @@ CREATE TABLE posts (
92
121
  CREATE INDEX index_posts_on_user_id ON posts (user_id);
93
122
  ```
94
123
 
124
+ ## Choose your database
125
+
126
+ **[Cloudflare D1](/d1)**
127
+
128
+ Bind a D1 database, and read from nearby replicas with Sessions.
129
+
130
+ Use D1
131
+
132
+ **[Postgres](/postgresql)**
133
+
134
+ Connect through Hyperdrive in a Worker, or directly on Node.
135
+
136
+ Use Postgres
137
+
95
138
  ## What’s inside
96
139
 
97
140
  **[Models, declared once](/models)**
@@ -124,8 +167,6 @@ works differently on its database.
124
167
  # Existing databases
125
168
  Source: https://active-record.forestfuture.dev/adopt-a-database
126
169
 
127
- Active Record reads a database’s tables from its migrations. If your database already has migrations, from Drizzle, Prisma, or Wrangler, point Active Record at them. If it doesn’t, start from a snapshot of its schema.
128
-
129
170
  ## Using Drizzle’s migrations
130
171
 
131
172
  Drizzle writes its migrations to `drizzle/`, its `out` setting. Tell Wrangler where they are:
@@ -271,7 +312,7 @@ The column stays an `INTEGER`. `createdAt` and `updatedAt` declared this way are
271
312
  Under `unixSeconds`, a `Date` is stored to the second, so a condition such as `lt(date)` compares to the second too.
272
313
 
273
314
  :::warning[A Date in an sql fragment]
274
- A `Date` beside that column in a `sql` fragment throws `TypeError`: a fragment has no attribute, so it would bind as ISO text. Use `column("publishedAt").value(date)`, which writes it as the attribute stores it. See [Writing SQL fragments](/querying#writing-sql-fragments).
315
+ A `Date` beside that column in a `sql` fragment throws `TypeError`: a fragment has no attribute, so it would bind as ISO text. Use `column("publishedAt").value(date)`, which writes it as the attribute stores it. See [Writing SQL fragments](/conditions#writing-sql-fragments).
275
316
  :::
276
317
 
277
318
  :::note
@@ -316,7 +357,9 @@ SQLite converts a value to the column’s declared type only when it can: `'42'`
316
357
  # AI agents
317
358
  Source: https://active-record.forestfuture.dev/ai-agents
318
359
 
319
- Coding agents follow Active Record’s conventions best with its guide at hand and its rules in context. The agent skill brings both, and is what most projects need. The rest are for agents that can’t load a skill, or for a pointer that’s always in context.
360
+ :::tip
361
+ The agent skill gives your agent the guide and its rules, and is what most projects need. The rest are for agents that can’t load a skill, or for a pointer that’s always in context.
362
+ :::
320
363
 
321
364
  ## Giving your agent the docs
322
365
 
@@ -373,6 +416,7 @@ Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for
373
416
  - 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`.
374
417
  - 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.
375
418
  - 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.
419
+ - To mark a record changed without saving it (a cache key, a "last seen"), `await record.touch()` sets `updatedAt`, or `touch("lastSeenAt")` that attribute too, with no validation or save callback; `Post.where(…).touchAll()` touches many rows. A touch runs `afterTouch` and the update commit callbacks (`afterUpdateCommit` included), so code there that should run only on a save belongs in `afterUpdate` or `afterSave`. To keep a parent's `updatedAt` current as its children change (a cache key), declare `belongsTo(Article, { touch: true })` on the child rather than touching the parent in a callback: the parent is touched in the child's batch, runs its own touch callbacks, and touches its own parents in turn. A parent that isn't loaded costs one SELECT per level, so preload the chain (`includes({ article: "blog" })`) when saving many. `hasOne(Profile, { touch: true })` touches a user's profile the same way when the user is updated, destroyed or touched. For a bulk import, wrap it in `Article.noTouching(async () => { … })`, so no article is touched per comment, then touch each article once after it.
376
420
  - 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`.
377
421
  - 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`.
378
422
  - 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()`.
@@ -391,8 +435,6 @@ Copy it again after upgrading Active Record, since the rules can change.
391
435
  # Associations
392
436
  Source: https://active-record.forestfuture.dev/associations
393
437
 
394
- Associations connect Models: `belongsTo`, `hasMany`, and `hasOne`.
395
-
396
438
  ## Defining associations
397
439
 
398
440
  Declare each association as a field, passing the target Model’s class. The field’s name is the association’s name:
@@ -456,6 +498,7 @@ await article.save();
456
498
  | `scope` | Narrows the target, `(q) => q.where(…)`. See [Scoping associations](#scoping-associations) |
457
499
  | `optional` | Lets the record point at nothing. See [Requiring the record](#requiring-the-record) |
458
500
  | `autosave` | `true` saves the record’s changes with this record. See [Saving changed records](#saving-changed-records) |
501
+ | `inverseOf` | The target’s `hasOne` that points back, or `false`. See [Inverse associations](#inverse-associations) |
459
502
 
460
503
  ### Requiring the record
461
504
 
@@ -510,6 +553,7 @@ await author.articles().where({ title: "Untitled" }).deleteAll(); // bulk writes
510
553
  | `scope` | Narrows or orders the records, `(q) => q.order(…)`. See [Scoping associations](#scoping-associations) |
511
554
  | `dependent` | What destroying the owner does to the records. See [Destroying dependent records](#destroying-dependent-records) |
512
555
  | `autosave` | `true` saves the records’ changes with the owner. See [Saving changed records](#saving-changed-records) |
556
+ | `inverseOf` | The target’s `belongsTo` that points back, or `false`. See [Inverse associations](#inverse-associations) |
513
557
 
514
558
  ## hasOne
515
559
 
@@ -686,6 +730,60 @@ const latest = await author?.articles().first();
686
730
  A `belongsTo` whose foreign key is `null`, or an association on an unsaved owner, reads without a query.
687
731
  :::
688
732
 
733
+ ## Inverse associations
734
+
735
+ A record loaded through its owner’s `hasMany` or `hasOne` has the owner loaded already. Reading it back doesn’t send a query:
736
+
737
+ ```ts
738
+ const author = await Author.find(authorId);
739
+ const [article] = await author.articles().toArray();
740
+ const sameAuthor = await article?.author(); // `author` itself, with no query
741
+ ```
742
+
743
+ - Every record the association loads points back: from `toArray()`, `first()`, `find()`, `findBy()`, a Relation narrowed from it such as `author.articles().where(…)`, and [`includes`](#preloading-associations).
744
+ - Records built or created through the association point back too, before either is saved.
745
+ - A `belongsTo`’s record points back through its `hasOne`. After `await profile.author()`, the author’s `profile()` is that profile. A `hasMany` isn’t filled this way, because one record isn’t the whole collection.
746
+ - The owner is the same object on both sides, so a change to it shows from either one.
747
+ - If the `belongsTo` is declared `autosave: true`, saving one of those records also saves the owner’s unsaved changes. See [Saving changed records](#saving-changed-records).
748
+
749
+ The inverse is the target’s first `belongsTo` that points at the owner’s Model through the same foreign key. None is found when either association has a `scope`, or for an association [through another](#reaching-records-through-another-association).
750
+
751
+ If you want another inverse, or one for an association with a `scope`, name it with `inverseOf`:
752
+
753
+ ```ts
754
+ import { belongsTo, hasMany, Model } from "@forestfuture/active-record";
755
+
756
+ export class Editor extends Model.define({
757
+ id: { type: "string", null: false, generateId: true },
758
+ name: { type: "string", null: false },
759
+ }) {
760
+ static table = "authors";
761
+
762
+ // A scope turns inference off, so name the inverse.
763
+ drafts = hasMany(Draft, {
764
+ foreignKey: "authorId",
765
+ scope: (q) => q.where({ title: "Untitled" }),
766
+ inverseOf: "editor",
767
+ });
768
+ }
769
+
770
+ export class Draft extends Model.define({
771
+ id: { type: "string", null: false, generateId: true },
772
+ authorId: { type: "string", null: false },
773
+ title: { type: "string", null: false },
774
+ }) {
775
+ static table = "articles";
776
+
777
+ editor = belongsTo(Editor, { foreignKey: "authorId" });
778
+ }
779
+ ```
780
+
781
+ `inverseOf` on a `hasMany` or `hasOne` names a `belongsTo`, and on a `belongsTo` it names a `hasOne`. On a polymorphic `belongsTo`, each Model it lists needs that `hasOne`. `inverseOf: false` turns the inverse off. If the association you name doesn’t link back through the same keys, using the Model throws `InvalidModel`.
782
+
783
+ > **Beyond Rails**
784
+ >
785
+ > Rails finds an inverse by its name. `has_many :articles` on `Author` looks for `belongs_to :author` on `Article`. It finds none when you pass `foreign_key:`, or when the `belongs_to` has another name, such as `belongs_to :writer, class_name: "Author"`. Then you add `inverse_of` yourself. Active Record finds the inverse by its foreign key instead, so it finds `writer = belongsTo(Author, { foreignKey: "authorId" })` too. It also finds a polymorphic `belongsTo`’s `hasOne` without `inverseOf`, where Rails needs `inverse_of`.
786
+
689
787
  ## Preloading associations
690
788
 
691
789
  Load an association for every record at once with `includes`, with one query per association however many records there are:
@@ -844,142 +942,7 @@ export class Category extends Model.define({
844
942
 
845
943
  ## Reaching records through another association
846
944
 
847
- Reach records through another association with `through`. A tag has many articles through its taggings:
848
-
849
- ```ts
850
- import { belongsTo, hasMany, Model } from "@forestfuture/active-record";
851
-
852
- export class Tag extends Model.define({
853
- id: { type: "integer", null: false },
854
- name: { type: "string", null: false },
855
- }) {
856
- taggings = hasMany(Tagging);
857
- articles = hasMany(Article, { through: "taggings" }); // each tagging's article
858
- }
859
-
860
- export class Tagging extends Model.define({
861
- id: { type: "integer", null: false },
862
- articleId: { type: "string", null: false },
863
- tagId: { type: "integer", null: false },
864
- }) {
865
- article = belongsTo(Article);
866
- tag = belongsTo(Tag);
867
- }
868
- ```
869
-
870
- `through` names one of the Model’s own associations, here `taggings`. The join Model’s association with the same name, singular or plural, leads on to the records: `articles` follows each tagging’s `article`.
871
-
872
- | Option | Does |
873
- | --------- | ----------------------------------------------------------------------------------------------- |
874
- | `through` | The association to go through |
875
- | `source` | The join Model’s association to follow. Defaults to this association’s name, singular or plural |
876
- | `scope` | Narrows or orders the records. See [Scoping associations](#scoping-associations) |
877
-
878
- ### Naming the source
879
-
880
- If the join Model’s association has another name, pass it as `source`:
881
-
882
- ```ts
883
- import { hasMany } from "@forestfuture/active-record";
884
-
885
- writers = hasMany(Author, { through: "articles", source: "author" }); // each article's author
886
- ```
887
-
888
- ### Reading and preloading
889
-
890
- Read it as you would any `hasMany`:
891
-
892
- ```ts
893
- const tag = await Tag.find(tagId);
894
- const articles = await tag.articles().order({ title: "asc" }).toArray(); // one query
895
-
896
- const tags = await Tag.includes("articles").toArray(); // tags, taggings, and articles: one round trip
897
- for (const each of tags) console.log(each.name, each.loaded("articles").length);
898
- ```
899
-
900
- - **`tag.articles()`** is a Relation, with every Relation method, read in one query. Its writes go to the taggings, as [below](#writing-through-it).
901
- - **Each record comes back once**, however many join records point at it.
902
- - **`includes("articles")`** loads the join records and the articles with the tags’ own query, in one round trip on D1. The join records aren’t kept as `taggings` unless you include them too.
903
-
904
- The scopes of both associations it goes through apply, and so does its own `scope`.
905
-
906
- ### Going through a belongsTo or a hasOne
907
-
908
- `through` can name a `belongsTo`, a `hasMany`, or a `hasOne`, and the association it follows can be any of the three. A `hasOne` goes through a `belongsTo` or a `hasOne`:
909
-
910
- ```ts
911
- import { hasOne } from "@forestfuture/active-record";
912
-
913
- author = hasOne(Author, { through: "article" }); // the article's author
914
- ```
915
-
916
- An association can also go through one that goes through another, as `writers` does above through `articles`.
917
-
918
- ### Writing through it
919
-
920
- Add records through the association with `push`, `build`, and `create`. Each makes the join record that links the owner to the record:
921
-
922
- ```ts
923
- const tag = await Tag.find(tagId);
924
- const article = await Article.find(articleId);
925
-
926
- await tag.articles().push(article); // saves a tagging that links them
927
- const draft = await tag.articles().create({ authorId: article.authorId, title: "Draft" });
928
-
929
- await tag.articles().delete(article); // deletes the tagging; the article stays
930
- ```
931
-
932
- - **`push(article)`** saves a tagging for each article, in one write. A new article is saved first.
933
- - **`build(attributes)`** builds the article and its tagging. Saving the tag saves both. Saving the article on its own saves no tagging.
934
- - **`create(attributes)`** saves the article, then its tagging. An invalid article comes back unsaved, and nothing is written.
935
-
936
- On a tag that isn’t saved yet, `push` and `build` wait for the tag’s save. `create` throws `RecordNotSaved` there, as it does through a `hasMany`.
937
-
938
- Records built or created through it take the equality values of its `scope`, and their join records take those of the association it goes through.
939
-
940
- #### Removing records
941
-
942
- Removing records through the association removes their join records. The records themselves stay:
943
-
944
- | Method | Does |
945
- | ------------------ | --------------------------------------------------------------------------------------------------- |
946
- | `delete(article)` | Deletes the tag’s taggings to the article, without callbacks |
947
- | `destroy(article)` | Destroys those taggings, running their callbacks, in one write |
948
- | `clear()` | Deletes every tagging to the tag’s articles, without callbacks. The tag then has no articles loaded |
949
- | `deleteAll()` | Deletes the same taggings, and resolves to how many it deleted |
950
- | `destroyAll()` | Destroys the same taggings, running their callbacks, and resolves to the articles |
951
-
952
- An article the tag doesn’t reach removes nothing. To remove an article itself, destroy it: `await article.destroy()`.
953
-
954
- In a batch, pass the association to the write: `b.deleteAll(tag.articles())` deletes the tag’s taggings.
955
-
956
- :::warning[A narrowed deleteAll or destroyAll removes the records themselves]
957
- `updateAll`, and a narrowed `deleteAll` or `destroyAll`, act on the records, as any Relation’s do. `tag.articles().where({ title: "Draft" }).deleteAll()` deletes those articles for every tag, not the tag’s taggings.
958
- :::
959
-
960
- #### Removing join records with dependent
961
-
962
- A `hasMany` through a join Model takes `dependent: "destroy"` or `dependent: "deleteAll"`, which acts on its join records. With `"destroy"`, destroying the tag destroys its taggings, running their callbacks, and `delete` destroys them too. With `"deleteAll"`, destroying the tag deletes them without callbacks. `clear` and `deleteAll` always delete them without callbacks.
963
-
964
- #### Setting a hasOne through another
965
-
966
- A `hasOne` that goes through another `hasOne` has `set`. `await member.club.set(club)` points the member’s membership at the club, or creates a membership if there isn’t one, with the equality values of the membership association’s `scope`. `set(null)` destroys the membership. It has no `build` or `create`.
967
-
968
- #### Spotting read-only associations
969
-
970
- Writes need a join Model: the association has to go through a `hasMany` (a `hasOne`, for a `hasOne`), and follow a `belongsTo` from there, with neither going through another. Any other write throws `ReadonlyAssociation`, naming the association that stops it. `writers` above is read-only, since it goes through `articles`, which goes through `taggings`.
971
-
972
- `insert`, `insertAll`, `upsert`, and `upsertAll` throw `ReadonlyAssociation` on any association through another, since they write no join records.
973
-
974
- :::note
975
- Every association it goes through must be on one database. One that reaches [another database](/several-databases#associating-models-on-different-databases) is an `InvalidModel` for now ([#435](https://github.com/forestfuture/active-record/issues/435)).
976
- :::
977
-
978
- > **Compared with Rails**
979
- >
980
- > `through` and `source` work as Rails’ `has_many :through` and `has_one :through` options do. Rails reads through a SQL join, so a record two join records point at comes back twice unless the association is `distinct`. Here it comes back once.
981
- >
982
- > Writing through it works as in Rails: `destroy` destroys the join records rather than the records, `clear` deletes them whatever `dependent` is, and `insert_all` through it raises. Rails also writes through a `belongsTo` or `hasOne` hop by building or updating that hop’s record, which can change a record that other records share. Here that throws `ReadonlyAssociation`. Rails’ `disable_joins` has no counterpart yet.
945
+ Reach records through another association with `through`, such as a tag’s articles through its taggings. See [Through associations](/through-associations).
983
946
 
984
947
  ## Destroying dependent records
985
948
 
@@ -1119,86 +1082,261 @@ Writes keep the count up to date, while `size()` and the others count the rows.
1119
1082
  > In Rails, removing records through a scoped association leaves the count too high, and `reset_counters` on one writes the scope’s count into the counter. Here the removal counts its records out, and `resetCounters` refuses the scoped association.
1120
1083
  >
1121
1084
  > Rails counts a comment twice when two `belongs_to`s keep the same counter. Here that throws `InvalidModel`.
1122
- >
1123
- > Rails’ `belongs_to … touch: true` also touches the article when its count changes. That option isn’t built yet ([#353](https://github.com/forestfuture/active-record/issues/353)).
1124
1085
 
1125
- ## Writing many rows
1086
+ ## Touching the record it belongs to
1126
1087
 
1127
- `insert`, `updateAll`, and `deleteAll` work through a `hasMany`, scoped to the owner’s records:
1088
+ To set an article’s `updatedAt` whenever one of its comments changes, declare `touch: true` on the comment’s `belongsTo`:
1128
1089
 
1129
1090
  ```ts
1130
- await article.comments().deleteAll(); // one DELETE for the article's comments
1131
- ```
1091
+ import { belongsTo, Model } from "@forestfuture/active-record";
1132
1092
 
1133
- In a batch, pass the association to the write: `b.deleteAll(article.comments())`.
1093
+ export class Comment extends Model.define({
1094
+ id: { type: "integer", null: false },
1095
+ articleId: "integer",
1096
+ body: { type: "string", null: false },
1097
+ updatedAt: "datetime",
1098
+ }) {
1099
+ article = belongsTo(Article, { touch: true });
1100
+ }
1101
+ ```
1134
1102
 
1135
- `upsert` and `upsertAll` through a `hasMany` only update the owner’s records. When a row clashes with another owner’s record, that record stays as it is. The row isn’t written, counted, or returned. To find out whether a row was skipped, compare `rowsAffected` with the number of rows you gave.
1103
+ Creating, updating, or destroying a comment then touches its article. So does calling `touch()` on the comment:
1136
1104
 
1137
- > **Beyond Rails**
1138
- >
1139
- > In Rails, `upsert_all` through an association writes the owner’s key into a clashing row. So `current_user.posts.upsert_all(rows)`, given an id from a request, moves another user’s post to the current user. Here that row is skipped, as `onDuplicate: "skip"` skips a duplicate.
1105
+ ```ts
1106
+ const article = await Article.find(id);
1107
+ const comment = await article.comments().create({ body: "First!" }); // sets article.updatedAt
1108
+ await comment.update({ body: "Edited" }); // sets it again
1109
+ await comment.touch(); // and again
1110
+ ```
1140
1111
 
1141
- `deleteAll()` on the association follows its `dependent` strategy: it deletes the records for `"destroy"` or `"deleteAll"`, and otherwise sets their foreign keys to `NULL`. See [Bulk writes and batches](/batches).
1112
+ The article’s new time is written in the same atomic batch as the comment. A save with nothing to write doesn’t touch it. Changing a comment’s `articleId` touches both the old article and the new one.
1142
1113
 
1143
- ## Not built yet
1114
+ :::note
1115
+ `updateColumns`, `updateAll`, `insert`, and the other bulk writes don’t touch the article, since they run no callbacks.
1116
+ :::
1144
1117
 
1145
- These features aren’t in Active Record yet. The code shows the shape they’re likely to take.
1118
+ To set another datetime attribute too, name it. It’s set to the same time as `updatedAt`:
1146
1119
 
1147
- - **Autosaving through an association through another** ([#450](https://github.com/forestfuture/active-record/issues/450)): `articles = hasMany(Article, { through: "taggings", autosave: true })`, which saves the tag’s changed articles with it.
1148
- - **Associations through another across databases** ([#435](https://github.com/forestfuture/active-record/issues/435)): an association whose hops are on different databases, read with a query per database.
1149
- - **Never autosaving** ([#378](https://github.com/forestfuture/active-record/issues/378)): `articles = hasMany(Article, { autosave: false })`, which never saves the association’s records with the owner, not even new ones.
1150
- - **Numbered autosave errors** ([#379](https://github.com/forestfuture/active-record/issues/379)): `hasMany(Article, { autosave: true, indexErrors: true })`, which names a copied error by the record’s position, `articles[1].title`.
1151
- - **Inverse associations** ([#62](https://github.com/forestfuture/active-record/issues/62)): after `await post.comments().toArray()`, each `comment.post()` returns that same post, without a query.
1120
+ ```ts
1121
+ import { belongsTo, Model } from "@forestfuture/active-record";
1152
1122
 
1153
- ---
1123
+ export class Reply extends Model.define({
1124
+ id: { type: "integer", null: false },
1125
+ articleId: "integer",
1126
+ body: { type: "string", null: false },
1127
+ }) {
1128
+ static table = "comments";
1129
+ article = belongsTo(Article, { touch: "lastCommentedAt" }); // and updatedAt
1130
+ }
1131
+ ```
1154
1132
 
1155
- # Bulk writes and batches
1156
- Source: https://active-record.forestfuture.dev/batches
1133
+ To set several, list them: `touch: ["lastCommentedAt", "lastActivityAt"]`.
1157
1134
 
1158
- Bulk writes change many rows in one SQL statement. A batch sends several writes to D1 at once, and they’re all written, or none of them.
1135
+ :::note
1136
+ A Model without `updatedAt` needs a named attribute. Touching a Model on [another database](/several-databases) throws `InvalidModel`, since the touch couldn’t be written in the same batch.
1137
+ :::
1159
1138
 
1160
- ## Writing many rows
1139
+ ### Running the article’s callbacks
1161
1140
 
1162
- Call a bulk write on a Relation. It runs straight away, without validations or callbacks:
1141
+ The article is touched as `article.touch()` touches it. It runs its `afterTouch` callbacks, then its update commit callbacks. An article that declares `touch` on its own `belongsTo` touches that record too:
1163
1142
 
1164
1143
  ```ts
1165
- import { column, sql } from "@forestfuture/active-record";
1166
- import { Article, Comment } from "./models";
1144
+ import { belongsTo, hasMany, Model } from "@forestfuture/active-record";
1167
1145
 
1168
- const deleted = await Comment.where({ articleId }).deleteAll(); // how many
1169
- await Article.where({ id: articleId }).updateAll({ title: "Edited" });
1170
- await Article.where({ id: articleId }).updateAll(
1171
- sql`${column("title")} = upper(${column("title")})`,
1172
- );
1173
- const { rowsAffected, rows } = await Comment.insert({ articleId, body: "First!" });
1174
- console.log(deleted, rowsAffected, rows[0]?.id); // the new comment's key
1146
+ export class Blog extends Model.define({
1147
+ id: { type: "integer", null: false },
1148
+ updatedAt: "datetime",
1149
+ }) {}
1150
+
1151
+ export class Article extends Model.define({
1152
+ id: { type: "integer", null: false },
1153
+ blogId: "integer",
1154
+ title: { type: "string", null: false },
1155
+ updatedAt: "datetime",
1156
+ lastCommentedAt: "datetime",
1157
+ }) {
1158
+ blog = belongsTo(Blog, { touch: true }); // touching an article touches its blog
1159
+ comments = hasMany(Comment);
1160
+ }
1175
1161
  ```
1176
1162
 
1177
- - **`updateAll(changes)`** takes attributes or an `sql` fragment, and resolves to the number of rows updated. It leaves `updatedAt` alone. With a `limit` or `offset`, the Relation’s order picks which rows are written.
1178
- - **`deleteAll()`** resolves to the number of rows deleted. On `none()`, both send nothing and resolve to `0`.
1179
- - **`deleteBy(conditions)`** is `where(conditions).deleteAll()`. **`Comment.delete(id)`** deletes by primary key, and takes an array of keys too. Both resolve to the number of rows deleted.
1180
- - **`insert(attrs)`** writes one row. It resolves to `{ rowsAffected, rows }`, and `rows` holds the new row’s primary key. Declared defaults and timestamps fill what isn’t given. A Relation’s equality conditions are written over what is given. So `Post.where({ userId: 1 }).insert({ title: "Hi", userId: 2 })` writes `userId: 1`.
1163
+ An article the same save creates, such as one built with `comment.article.build()`, is touched after it’s inserted. It runs `afterTouch` and its create commit callbacks, but not the update ones.
1181
1164
 
1182
- :::note
1183
- To run each record’s callbacks, destroy the records with [`destroyAll`](/persistence#destroying-many-records) instead.
1184
- :::
1165
+ A write touches each record once, however many of its comments touch it.
1185
1166
 
1186
- ### Inserting many rows
1167
+ ### Loading the article
1187
1168
 
1188
- Insert many rows at once with `insertAll`:
1169
+ The article is loaded before the comment is written, so its callbacks can run. A loaded article sends no query, such as one reached through `article.comments()`. Each level of the chain that isn’t loaded takes one query, and each one waits for the one before it. Preload the chain to skip them:
1189
1170
 
1190
1171
  ```ts
1191
- import { Author, Comment } from "./models";
1192
-
1193
- await Comment.insertAll([
1194
- { articleId, body: "One" },
1195
- { articleId, body: "Two" },
1196
- ]);
1197
- await Author.upsert({ id: "author-1", name: "Ada" }); // insert, or update the name
1198
- await Author.insert({ id: "author-1", name: "Ada" }, { onDuplicate: "skip" });
1172
+ const comments = await Comment.includes({ article: "blog" }).toArray();
1173
+ for (const each of comments) await each.touch(); // no query to load an article or blog
1199
1174
  ```
1200
1175
 
1201
- - **`insertAll(rows)`** inserts every row, however many. Every row must have the same attributes. A duplicate throws and writes nothing.
1176
+ Inside [`noTouching`](#turning-touches-off), the touch doesn’t load the article.
1177
+
1178
+ The article is found through the association, so the association’s scope and Article’s default scope apply. An article they hide isn’t touched.
1179
+
1180
+ ### Touching with a counter cache
1181
+
1182
+ A comment that also keeps a [counter cache](#counting-records-with-a-counter-cache) on the article touches it the same way, in the same batch as the count. An article the default scope hides is counted, but isn’t touched.
1183
+
1184
+ ### Turning touches off
1185
+
1186
+ To import many comments without touching their article for each one, run the import in `Article.noTouching`:
1187
+
1188
+ ```ts
1189
+ await Article.noTouching(async () => {
1190
+ for (const body of bodies) {
1191
+ await Comment.create({ articleId, body }); // doesn't touch the article
1192
+ }
1193
+ });
1194
+ const article = await Article.find(articleId);
1195
+ await article.touch(); // touch it once, after the import
1196
+ ```
1197
+
1198
+ Inside the block, no article is touched. A comment’s `belongsTo` leaves its article alone, and `article.touch()` writes nothing and resolves to `false`. Once the block ends, articles are touched again.
1199
+
1200
+ `noTouching` covers the Model you call it on and the Models that extend it. To turn off touches for every Model, call `ApplicationRecord.noTouching`. It covers only the code the block runs and what that code awaits, so other requests still touch.
1201
+
1202
+ :::note
1203
+ The comments still set their own `updatedAt` when they’re saved. `Article.touchAll()` and `Article.updateCounters(id, counters, { touch: true })` still set the articles’ `updatedAt`. A comment whose `belongsTo` also keeps a counter cache still counts, but doesn’t touch the article.
1204
+ :::
1205
+
1206
+ :::note
1207
+ Like `withDatabase`, `noTouching` needs [Node.js compatibility](/connecting#using-the-requests-database).
1208
+ :::
1209
+
1210
+ > **Compared with Rails**
1211
+ >
1212
+ > Rails’ `touch:` takes `true` or one column. Here it also takes a list of attributes.
1213
+ >
1214
+ > Rails does nothing when the article has no `updated_at`, and writes the time to any column you name. Here both throw `InvalidModel` when the Model is first used.
1215
+ >
1216
+ > With a counter cache, Rails sets the time in the counter’s `UPDATE` and runs none of the article’s callbacks. Here the article is touched as it is without one, so its `afterTouch` and commit callbacks run.
1217
+ >
1218
+ > When a comment moves to another article, Rails finds the old one without the association’s scope. Here the scope applies to both.
1219
+ >
1220
+ > When a comment’s `belongs_to` has both `counter_cache:` and `touch:`, Rails’ `no_touching` still touches the article, since the time is set in the counter’s `UPDATE`. Here the article is only counted. Inside the block, Rails’ `touch` returns `nil`, and here it resolves to `false`. Rails also loads each comment’s article for its touch, then leaves it alone. Here the touch doesn’t load it, though a required `belongsTo` still checks that its article exists.
1221
+
1222
+ ## Touching the record it has
1223
+
1224
+ To set a profile’s `updatedAt` whenever its user changes, declare `touch: true` on the user’s `hasOne`:
1225
+
1226
+ ```ts
1227
+ import { hasOne, Model } from "@forestfuture/active-record";
1228
+
1229
+ export class User extends Model.define({
1230
+ id: { type: "integer", null: false },
1231
+ name: { type: "string", null: false },
1232
+ updatedAt: "datetime",
1233
+ }) {
1234
+ profile = hasOne(Profile, { touch: true });
1235
+ }
1236
+ ```
1237
+
1238
+ Updating or destroying a user then touches its profile, in the same atomic batch as the user. So does calling `touch()` on the user:
1239
+
1240
+ ```ts
1241
+ const user = await User.find(id);
1242
+ await user.update({ name: "Ada" }); // sets the profile's updatedAt
1243
+ await user.touch(); // and again
1244
+ ```
1245
+
1246
+ A save with nothing to write doesn’t touch the profile. A `hasOne` through another touches the record it reaches.
1247
+
1248
+ The profile is touched as [a `belongsTo`’s record is](#running-the-articles-callbacks). It takes the names of datetime attributes to set, runs its `afterTouch` and update commit callbacks, and touches its own records in turn. It’s found through the association, so a profile the association’s scope or Profile’s default scope hides isn’t touched. Inside [`Profile.noTouching`](#turning-touches-off), it isn’t loaded or touched.
1249
+
1250
+ The profile isn’t touched when:
1251
+
1252
+ - **The user is new.** A profile built with `user.profile.build()` is inserted with the user, and its insert sets its `updatedAt`.
1253
+ - **The user’s own save writes it**, such as a profile built through the user, or a changed one with `autosave: true`. Its own save sets its `updatedAt`.
1254
+ - **The user’s `dependent` removes it**, with `"destroy"` or `"delete"`. With `"nullify"`, it’s touched once it no longer points at the user.
1255
+
1256
+ A profile saved as its own entry in the user’s batch is still touched, whether it comes before or after the user.
1257
+
1258
+ > **Compared with Rails**
1259
+ >
1260
+ > Rails’ `has_one … touch:` takes `true` or one column. Here it also takes a list of attributes.
1261
+ >
1262
+ > Rails touches a changed profile before its autosave saves it, so its `after_touch` runs too. Here only its save writes it.
1263
+ >
1264
+ > After a user is created, Rails finds and touches a profile that already points at the new user’s key. Here a new user touches nothing, so a create sends no query for it.
1265
+
1266
+ ## Writing many rows
1267
+
1268
+ `insert`, `updateAll`, and `deleteAll` work through a `hasMany`, scoped to the owner’s records:
1269
+
1270
+ ```ts
1271
+ await article.comments().deleteAll(); // one DELETE for the article's comments
1272
+ ```
1273
+
1274
+ In a batch, pass the association to the write: `b.deleteAll(article.comments())`.
1275
+
1276
+ `upsert` and `upsertAll` through a `hasMany` only update the owner’s records. When a row clashes with another owner’s record, that record stays as it is. The row isn’t written, counted, or returned. To find out whether a row was skipped, compare `rowsAffected` with the number of rows you gave.
1277
+
1278
+ > **Beyond Rails**
1279
+ >
1280
+ > In Rails, `upsert_all` through an association writes the owner’s key into a clashing row. So `current_user.posts.upsert_all(rows)`, given an id from a request, moves another user’s post to the current user. Here that row is skipped, as `onDuplicate: "skip"` skips a duplicate.
1281
+
1282
+ `deleteAll()` on the association follows its `dependent` strategy: it deletes the records for `"destroy"` or `"deleteAll"`, and otherwise sets their foreign keys to `NULL`. See [Bulk writes and batches](/batches).
1283
+
1284
+ ## Not built yet
1285
+
1286
+ These features aren’t in Active Record yet. The code shows the shape they’re likely to take.
1287
+
1288
+ - **Autosaving through an association through another** ([#450](https://github.com/forestfuture/active-record/issues/450)): `articles = hasMany(Article, { through: "taggings", autosave: true })`, which saves the tag’s changed articles with it.
1289
+ - **Associations through another across databases** ([#435](https://github.com/forestfuture/active-record/issues/435)): an association whose hops are on different databases, read with a query per database.
1290
+ - **Never autosaving** ([#378](https://github.com/forestfuture/active-record/issues/378)): `articles = hasMany(Article, { autosave: false })`, which never saves the association’s records with the owner, not even new ones.
1291
+ - **Numbered autosave errors** ([#379](https://github.com/forestfuture/active-record/issues/379)): `hasMany(Article, { autosave: true, indexErrors: true })`, which names a copied error by the record’s position, `articles[1].title`.
1292
+
1293
+ ---
1294
+
1295
+ # Bulk writes and batches
1296
+ Source: https://active-record.forestfuture.dev/batches
1297
+
1298
+ ## Writing many rows
1299
+
1300
+ Call a bulk write on a Relation. It runs straight away, without validations or callbacks:
1301
+
1302
+ ```ts
1303
+ import { column, sql } from "@forestfuture/active-record";
1304
+ import { Article, Comment } from "./models";
1305
+
1306
+ const deleted = await Comment.where({ articleId }).deleteAll(); // how many
1307
+ await Article.where({ id: articleId }).updateAll({ title: "Edited" });
1308
+ await Article.where({ id: articleId }).updateAll(
1309
+ sql`${column("title")} = upper(${column("title")})`,
1310
+ );
1311
+ const { rowsAffected, rows } = await Comment.insert({ articleId, body: "First!" });
1312
+ console.log(deleted, rowsAffected, rows[0]?.id); // the new comment's key
1313
+ ```
1314
+
1315
+ - **`updateAll(changes)`** takes attributes or an `sql` fragment, and resolves to the number of rows updated. It leaves `updatedAt` alone. With a `limit` or `offset`, the Relation’s order picks which rows are written.
1316
+ - **`deleteAll()`** resolves to the number of rows deleted. On `none()`, both send nothing and resolve to `0`.
1317
+ - **`deleteBy(conditions)`** is `where(conditions).deleteAll()`. **`Comment.delete(id)`** deletes by primary key, and takes an array of keys too. Both resolve to the number of rows deleted.
1318
+ - **`insert(attrs)`** writes one row. It resolves to `{ rowsAffected, rows }`, and `rows` holds the new row’s primary key. Declared defaults and timestamps fill what isn’t given. A Relation’s equality conditions are written over what is given. So `Post.where({ userId: 1 }).insert({ title: "Hi", userId: 2 })` writes `userId: 1`.
1319
+
1320
+ :::note
1321
+ To run each record’s callbacks, destroy the records with [`destroyAll`](/persistence#destroying-many-records) instead.
1322
+ :::
1323
+
1324
+ ### Inserting many rows
1325
+
1326
+ Insert many rows at once with `insertAll`:
1327
+
1328
+ ```ts
1329
+ import { Author, Comment } from "./models";
1330
+
1331
+ await Comment.insertAll([
1332
+ { articleId, body: "One" },
1333
+ { articleId, body: "Two" },
1334
+ ]);
1335
+ await Author.upsert({ id: "author-1", name: "Ada" }); // insert, or update the name
1336
+ await Author.insert({ id: "author-1", name: "Ada" }, { onDuplicate: "skip" });
1337
+ ```
1338
+
1339
+ - **`insertAll(rows)`** inserts every row, however many. Every row must have the same attributes. A duplicate throws and writes nothing.
1202
1340
  - **`{ onDuplicate: "skip" }`** skips rows that clash with a unique index.
1203
1341
  - **`upsert(attrs)`** and **`upsertAll(rows)`** update a row that clashes with the primary key, or with the unique index named by `uniqueBy`. The attributes you give are updated. So are the values a Relation adds to each row, from its equality conditions, its default scope, and `createWith`. Defaults filled in for you aren’t updated. `updatedAt` is set.
1204
1342
  - **Through a Relation**, `insertAll`, `upsert`, and `upsertAll` write its equality conditions over each row’s values, as `insert` does.
@@ -1322,11 +1460,9 @@ await batch((b) => [
1322
1460
  # Callbacks
1323
1461
  Source: https://active-record.forestfuture.dev/callbacks
1324
1462
 
1325
- Callbacks run your code at points in a record’s lifecycle, such as before it’s validated or after it’s saved.
1326
-
1327
1463
  ## Registering callbacks
1328
1464
 
1329
- Register callbacks in a Model’s `static {}` block. Each receives the record, and may be async:
1465
+ Register callbacks in a Model’s `static {}` block. Each receives the record, and may be async, except the [callbacks for a record built or loaded](#running-code-when-a-record-is-built-or-loaded):
1330
1466
 
1331
1467
  ```ts
1332
1468
  import { abort, Model } from "@forestfuture/active-record";
@@ -1383,24 +1519,41 @@ Once a Model has been used, registering another callback throws `InvalidModel`,
1383
1519
  | 1 | `beforeValidation` | Before the validators, on every save, and on `isValid()` | Stops the save |
1384
1520
  | 2 | `afterValidation` | After the validators | Stops the save |
1385
1521
  | 3 | `beforeSave` | Before every write, new or persisted | Stops the save |
1386
- | 4 | `beforeCreate` | Before inserting a new record | Stops the save |
1387
- | 4 | `beforeUpdate` | Before updating a persisted record | Stops the save |
1522
+ | 4 | `aroundSave` | Its first part, before `next()` | Stops the save |
1523
+ | 5 | `beforeCreate` | Before inserting a new record | Stops the save |
1524
+ | 5 | `beforeUpdate` | Before updating a persisted record | Stops the save |
1525
+ | 6 | `aroundCreate` | Its first part, before `next()` | Stops the save |
1526
+ | 6 | `aroundUpdate` | Its first part, before `next()` | Stops the save |
1388
1527
  | | _The write to D1_ | Skipped when a persisted record has no changes | |
1389
- | 5 | `afterCreate` | After inserting a new record | Too late: `AbortAfterPersistence` |
1390
- | 5 | `afterUpdate` | After updating a persisted record | Too late: `AbortAfterPersistence` |
1391
- | 6 | `afterSave` | After every successful save | Too late: `AbortAfterPersistence` |
1392
- | 7 | `afterCommit` | Last, after every after-callback | Too late: `AbortAfterPersistence` |
1393
- | 7 | `afterCreateCommit` | Last, after inserting a new record | Too late: `AbortAfterPersistence` |
1394
- | 7 | `afterUpdateCommit` | Last, after updating a persisted record | Too late: `AbortAfterPersistence` |
1395
- | 7 | `afterSaveCommit` | Last, after every successful save | Too late: `AbortAfterPersistence` |
1528
+ | 7 | `aroundCreate` | Its last part, once `next()` resolves | Too late: `AbortAfterPersistence` |
1529
+ | 7 | `aroundUpdate` | Its last part, once `next()` resolves | Too late: `AbortAfterPersistence` |
1530
+ | 8 | `afterCreate` | After inserting a new record | Too late: `AbortAfterPersistence` |
1531
+ | 8 | `afterUpdate` | After updating a persisted record | Too late: `AbortAfterPersistence` |
1532
+ | 9 | `aroundSave` | Its last part, once `next()` resolves | Too late: `AbortAfterPersistence` |
1533
+ | 10 | `afterSave` | After every successful save | Too late: `AbortAfterPersistence` |
1534
+ | 11 | `afterCommit` | Last, after every after-callback | Too late: `AbortAfterPersistence` |
1535
+ | 11 | `afterCreateCommit` | Last, after inserting a new record | Too late: `AbortAfterPersistence` |
1536
+ | 11 | `afterUpdateCommit` | Last, after updating a persisted record | Too late: `AbortAfterPersistence` |
1537
+ | 11 | `afterSaveCommit` | Last, after every successful save | Too late: `AbortAfterPersistence` |
1396
1538
  | **Destroying** | | | |
1397
1539
  | 1 | `beforeDestroy` | Before the `dependent` strategies and the DELETE | Stops the destroy |
1540
+ | 2 | `aroundDestroy` | Its first part, before `next()` | Stops the destroy |
1398
1541
  | | _The delete in D1_ | With the dependents, in one batch | |
1399
- | 2 | `afterDestroy` | After the record is destroyed | Too late: `AbortAfterPersistence` |
1400
- | 3 | `afterCommit` | Last, after every after-callback | Too late: `AbortAfterPersistence` |
1401
- | 3 | `afterDestroyCommit` | Last, after the record is destroyed | Too late: `AbortAfterPersistence` |
1542
+ | 3 | `aroundDestroy` | Its last part, once `next()` resolves | Too late: `AbortAfterPersistence` |
1543
+ | 4 | `afterDestroy` | After the record is destroyed | Too late: `AbortAfterPersistence` |
1544
+ | 5 | `afterCommit` | Last, after every after-callback | Too late: `AbortAfterPersistence` |
1545
+ | 5 | `afterDestroyCommit` | Last, after the record is destroyed | Too late: `AbortAfterPersistence` |
1546
+ | **Touching** | | | |
1547
+ | | _The write to D1_ | `updatedAt`, and any attributes named | |
1548
+ | 1 | `afterTouch` | After `touch()` writes the record’s timestamps | Too late: `AbortAfterPersistence` |
1549
+ | 2 | `afterCommit` | Last, when `touch()` wrote a row | Too late: `AbortAfterPersistence` |
1550
+ | 2 | `afterUpdateCommit` | Last, when `touch()` wrote a row | Too late: `AbortAfterPersistence` |
1551
+ | 2 | `afterSaveCommit` | Last, when `touch()` wrote a row | Too late: `AbortAfterPersistence` |
1402
1552
  | **Refused** | | | |
1403
1553
  | 1 | `afterRollback` | When the database refuses the save or destroy | Nothing to stop |
1554
+ | **Loading** | | | |
1555
+ | 1 | `afterFind` | After a record is loaded | Nothing to stop |
1556
+ | 2 | `afterInitialize` | After a record is loaded, or built | Nothing to stop |
1404
1557
 
1405
1558
  A save runs either the create pair or the update pair, never both.
1406
1559
 
@@ -1412,6 +1565,34 @@ A save runs either the create pair or the update pair, never both.
1412
1565
  The database has kept a save’s writes before any after-callback runs. An error thrown by an after-callback or a commit callback reaches the caller, but the record stays saved. The callbacks after it don’t run. In a batch, that includes the other records’ callbacks.
1413
1566
  :::
1414
1567
 
1568
+ ## Wrapping a save or destroy
1569
+
1570
+ An around callback runs code on both sides of a write. Call `next()` to run the rest of the save, and await it:
1571
+
1572
+ ```ts
1573
+ this.aroundSave(async (order, next) => {
1574
+ const started = Date.now();
1575
+ await next();
1576
+ console.info(`Saved order ${order.id} in ${Date.now() - started} ms`);
1577
+ });
1578
+ ```
1579
+
1580
+ - **`aroundSave`** runs after `beforeSave`. Its `next()` runs `beforeCreate` or `beforeUpdate`, the write, and `afterCreate` or `afterUpdate`. `afterSave` runs once the callback finishes.
1581
+ - **`aroundCreate`**, **`aroundUpdate`**, and **`aroundDestroy`** wrap only the write, between the matching before- and after-callbacks.
1582
+ - **Several around callbacks of one kind** nest. The first one declared is the outermost.
1583
+
1584
+ `next()` returns a promise with no value. It resolves once the database has kept the write. A save sends its writes together, so in a [batch](/batches#batching-records), every record’s first part runs before the batch is written. Then each record’s last part runs in turn.
1585
+
1586
+ ### Stopping a wrapped write
1587
+
1588
+ - **Not calling `next()`** stops the save, as `abort()` does. `save()` resolves to `false`, and nothing is written.
1589
+ - **An `abort()` before `next()`** stops the save. After `next()`, the write has happened, so `abort()` throws `AbortAfterPersistence`.
1590
+ - **When the database refuses the write**, `afterRollback` runs, then `next()` rejects with the database’s error. The save throws it even if you catch it.
1591
+ - **When the save ends without sending the write**, `next()` rejects with the error the save ends with. That happens when another record in the save or batch is refused before the write is sent.
1592
+ - **When an earlier record’s after-callback throws**, the write is kept. This record’s after-callbacks are skipped, and `next()` rejects with that error.
1593
+
1594
+ To release something you hold during the write, put `await next()` in a `try` block, and release it in `finally`.
1595
+
1415
1596
  ## Running code after the commit
1416
1597
 
1417
1598
  Commit callbacks run last, after every after-callback of the save. In a [batch](/batches#batching-records), they wait for every record’s after-callbacks. Register one to run code once everything is written:
@@ -1430,6 +1611,29 @@ this.afterCreateCommit(async (user) => {
1430
1611
  Destroying a record that was never saved runs no commit callback, since there was no row to delete.
1431
1612
  :::
1432
1613
 
1614
+ ## Running code after a touch
1615
+
1616
+ `afterTouch` runs after [`touch()`](/persistence#touching-a-record) writes a record’s timestamps:
1617
+
1618
+ ```ts
1619
+ this.afterTouch(async (article) => {
1620
+ await purgeCachedPage(article.id);
1621
+ });
1622
+ ```
1623
+
1624
+ - **No validation or save callback runs** for a touch.
1625
+ - **The commit callbacks for an update** run after `afterTouch`: `afterCommit`, `afterUpdateCommit`, and `afterSaveCommit`. When the row is gone, only `afterTouch` runs.
1626
+ - **`savedChanges()`** holds only the touched attributes, so `hasSavedChangeTo("email")` is `false` in a touch’s callbacks.
1627
+ - **A refused touch** runs `afterRollback`, and the record stays as it was.
1628
+
1629
+ A `belongsTo` declared with [`touch`](/associations#touching-the-record-it-belongs-to) touches its record the same way. Saving a comment can run its article’s `afterTouch` and commit callbacks.
1630
+
1631
+ `touchAll` and the counters’ `touch` option run no callbacks.
1632
+
1633
+ :::warning[A touch runs the update commit callbacks]
1634
+ A `touch()` that writes a row runs `afterUpdateCommit`. To send an email only when a record is saved, register it with `afterUpdate` instead. It runs once the database has kept the save.
1635
+ :::
1636
+
1433
1637
  ## Handling a refused write
1434
1638
 
1435
1639
  `afterRollback` runs when the database refuses a record’s save or destroy:
@@ -1450,6 +1654,34 @@ The record keeps its unsaved state, and no after-callback or commit callback run
1450
1654
  An error thrown by an `afterRollback` reaches the caller in place of the constraint error, which becomes its `cause`. The `afterRollback` callbacks after it don’t run.
1451
1655
  :::
1452
1656
 
1657
+ ## Running code when a record is built or loaded
1658
+
1659
+ `afterInitialize` runs for every record you build and every record you load. `afterFind` runs for every record you load, just before `afterInitialize`:
1660
+
1661
+ ```ts
1662
+ this.afterInitialize((invoice) => {
1663
+ if (invoice.isNewRecord()) invoice.currency ??= currencyFor(invoice.country);
1664
+ });
1665
+ ```
1666
+
1667
+ - **`build` and `create`** run `afterInitialize` after their `init` function, so it sees what `init` set. Building through a `hasMany` or `hasOne` runs it once the record points at its owner. Building through a `through` association runs the join record’s `afterInitialize` once it points at the record.
1668
+ - **Every load** runs `afterFind`, then `afterInitialize`: a query, an association read, a preload, and `reload()`. Preloaded associations aren’t attached yet when they run.
1669
+ - **Saving a record** runs neither, and neither does `new Invoice()`.
1670
+
1671
+ Both callbacks run synchronously, since `build` can’t wait for them. An `async` one is a type error. An error thrown by either reaches the caller, and the query returns no records.
1672
+
1673
+ ### Handling partial records
1674
+
1675
+ A record loaded with [`select`](/querying#selecting-attributes) runs both callbacks too, and reading an attribute it left out throws `MissingAttribute`. Check with `hasAttribute` first:
1676
+
1677
+ ```ts
1678
+ this.afterFind((invoice) => {
1679
+ if (invoice.hasAttribute("total") && invoice.total > 10_000) {
1680
+ console.info(`Large invoice ${invoice.id} loaded`);
1681
+ }
1682
+ });
1683
+ ```
1684
+
1453
1685
  ## Stopping a save
1454
1686
 
1455
1687
  Throw `abort(reason)` from a before-callback to stop a save or destroy:
@@ -1472,20 +1704,18 @@ Only `abort()` stops a save. Returning `false` does nothing, and any other error
1472
1704
  In an after-callback, the write has already happened, so `abort()` throws `AbortAfterPersistence`, naming the callback.
1473
1705
  :::
1474
1706
 
1475
- ## Not built yet
1476
-
1477
- These callbacks aren’t in Active Record yet. The code shows the shape they’re likely to take.
1478
-
1479
- - **Around callbacks** ([#48](https://github.com/forestfuture/active-record/issues/48)): `this.aroundSave(async (record, proceed) => { …; await proceed(); … })`, and `aroundCreate`, `aroundUpdate`, and `aroundDestroy`.
1480
- - **`afterInitialize` and `afterFind`** ([#49](https://github.com/forestfuture/active-record/issues/49)): for every record built or loaded, and every record loaded.
1481
- - **`record.touch()` and `afterTouch`** ([#50](https://github.com/forestfuture/active-record/issues/50)): sets `updatedAt` without a full save.
1482
-
1483
1707
  > **Compared with Rails**
1484
1708
  >
1485
1709
  > `after_commit` and its `on:` forms are `afterCommit`, `afterCreateCommit`, `afterUpdateCommit`, `afterSaveCommit`, and `afterDestroyCommit`, run in the order declared, as Rails 7.1 runs them. In Rails, `after_save` runs before the save’s transaction commits. Here, the database has already kept the write before any after-callback runs, so every after-callback is already “after commit”. An error in `afterSave` rolls a Rails save back; here the record stays saved, and its commit callbacks don’t run.
1486
1710
  >
1711
+ > `after_touch` is `afterTouch`. As in Rails, `touch` runs the commit callbacks too.
1712
+ >
1487
1713
  > `after_rollback` is `afterRollback`. Rails also runs it for a save that fails inside a transaction. Here it runs only when the database refuses a write, since validation and the before-callbacks run before anything is sent.
1488
1714
  >
1715
+ > `around_save`, `around_create`, `around_update`, and `around_destroy` are `aroundSave`, `aroundCreate`, `aroundUpdate`, and `aroundDestroy`, and `yield` is `await next()`. Rails wraps each record’s own SQL in its transaction. Here, `next()` waits for the whole save’s batch. A Rails `around_save` can rescue the database’s error and carry on; here the save still throws it. Rails saves a `has_many`’s autosaved records inside the owner’s `around_save`. Here, the owner’s `aroundSave` finishes before their after-callbacks run. When an inner `around_save` doesn’t `yield`, Rails resumes the outer one after its `yield`. Here, the outer one’s `next()` rejects, and nothing is saved.
1716
+ >
1717
+ > `after_initialize` and `after_find` are `afterInitialize` and `afterFind`, and run in the same order. Here they can’t be async. `new Invoice()` doesn’t run `afterInitialize`, where Rails’ `new` does: build records through the Model instead, with `Invoice.build()`. `reload()` runs both on the record itself, where Rails runs them on a fresh copy and takes its attributes. `has_attribute?` is `hasAttribute`.
1718
+ >
1489
1719
  > Rails’ `if:` and `unless:` options for callbacks aren’t needed: write the condition inside the callback.
1490
1720
 
1491
1721
  ---
@@ -1493,7 +1723,9 @@ These callbacks aren’t in Active Record yet. The code shows the shape they’r
1493
1723
  # Schema changes
1494
1724
  Source: https://active-record.forestfuture.dev/change-a-table
1495
1725
 
1496
- Change a table with a new migration. Wrangler applies each migration once, in order. The schema is regenerated after each change, so a Model’s attributes follow its table.
1726
+ :::note
1727
+ Wrangler applies each migration once, in order. The schema is regenerated after each change, so a Model’s attributes follow its table.
1728
+ :::
1497
1729
 
1498
1730
  ## Adding a column
1499
1731
 
@@ -1586,7 +1818,9 @@ Wrangler backs up the database before applying migrations to it.
1586
1818
  # Coming from Rails
1587
1819
  Source: https://active-record.forestfuture.dev/coming-from-rails
1588
1820
 
1589
- Models, validations, callbacks, associations, scopes, and dirty tracking all follow Active Record, down to the default error messages. Here’s what’s different.
1821
+ :::tip
1822
+ Models, validations, callbacks, associations, scopes, and dirty tracking all follow Rails’ Active Record, down to the default error messages.
1823
+ :::
1590
1824
 
1591
1825
  ## Querying from the Model
1592
1826
 
@@ -1689,7 +1923,9 @@ The generators follow `rails generate model` and `rails generate migration`. A c
1689
1923
  # Command line
1690
1924
  Source: https://active-record.forestfuture.dev/command-line
1691
1925
 
1692
- The `active-record` command generates `src/db/schema.ts` from your migrations, writes new migrations and Models, and applies migrations. It comes with `@forestfuture/active-record`, and `ffar` is its short name. Run it from your project’s folder:
1926
+ ## Running the command
1927
+
1928
+ The `active-record` command comes with `@forestfuture/active-record`, and `ffar` is its short name. Run it from your project’s folder:
1693
1929
 
1694
1930
  ```sh
1695
1931
  npx active-record --help
@@ -2040,75 +2276,415 @@ Every command exits with `0` on success, and `1` when anything was refused or fa
2040
2276
 
2041
2277
  ---
2042
2278
 
2043
- # Connections
2044
- Source: https://active-record.forestfuture.dev/connecting
2045
-
2046
- A query finds its database in one of three ways. Most apps only use the first.
2279
+ # Conditions
2280
+ Source: https://active-record.forestfuture.dev/conditions
2047
2281
 
2048
- | | How | Use it for |
2049
- | -------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------- |
2050
- | **The binding** | `User.find(id)`, with nothing to set up | Everyday queries |
2051
- | **The request’s database** | `withDatabase(connect(env.DB, …), fn)`, once per request | Read replicas with a Session, per-request `onQuery` logging, tests, and scripts |
2052
- | **An explicit database** | `connect(env.DB).model(User).find(id)` | Code that passes its database around, or uses two at once |
2282
+ ## At a glance
2053
2283
 
2054
- [Database resolution](/query-databases) explains why there are three, and [which one you need](/query-databases#which-do-i-need).
2284
+ | To match | Write | SQL |
2285
+ | ----------------------------- | -------------------------------------- | --------------------------- |
2286
+ | equal values | `where({ role: "admin" })` | `role = ?` |
2287
+ | NULL | `where({ role: null })` | `role IS NULL` |
2288
+ | any value in a list | `where({ role: ["admin", "editor"] })` | `role IN (…)` |
2289
+ | anything but a value | `whereNot({ role: "admin" })` | `NOT (role = ?)` |
2290
+ | either of two queries | `where(a).or(User.where(b))` | `(…) OR (…)` |
2291
+ | a comparison | `where({ createdAt: gte(date) })` | `created_at >= ?` |
2292
+ | a range | `where({ createdAt: between(a, b) })` | both ends included |
2293
+ | anything else | ``where(sql`…`)`` | your SQL, with values bound |
2294
+ | a replacement for a condition | `rewhere({ role: "admin" })` | drops the old `role = ?` |
2295
+ | fewer parts of a query | `unscope("order")`, `only("where")` | drops the parts named |
2296
+ | all but some records | `excluding(record)` | leaves those records out |
2055
2297
 
2056
- :::note
2057
- The examples use D1’s `connect`, from `@forestfuture/active-record/d1`. On Postgres, `connect` comes from `@forestfuture/active-record/postgresql` and takes your Hyperdrive binding. See [PostgreSQL](/postgresql#connecting).
2058
- :::
2298
+ ## The Model
2059
2299
 
2060
- ## Using the binding
2300
+ The examples use this Model and table:
2061
2301
 
2062
- Each Model names the binding it queries, so a Model queries by itself during any request:
2302
+ **Model**
2063
2303
 
2064
2304
  ```ts
2065
- import { Post, User } from "./models";
2305
+ import { Model } from "@forestfuture/active-record";
2066
2306
 
2067
- // No setup: each Model queries the binding its generated schema names during the request.
2068
- const user = await User.findByOrThrow({ email: "ada@example.com" });
2069
- const posts = await Post.where({ userId: user.id }).order({ id: "desc" }).toArray();
2307
+ export class User extends Model.define({
2308
+ id: { type: "string", null: false, generateId: true },
2309
+ email: { type: "string", null: false },
2310
+ role: "string",
2311
+ isActive: "boolean",
2312
+ createdAt: { type: "datetime", null: false },
2313
+ updatedAt: { type: "datetime", null: false },
2314
+ }) {}
2070
2315
  ```
2071
2316
 
2072
- `active-record schema` writes the binding into the generated schema your app’s base class holds. On D1 it comes from your Wrangler config’s `d1_databases`, and on Postgres from your `active-record.jsonc`.
2317
+ **D1**
2073
2318
 
2074
- Records remember their database, so `user.save()` and `user.posts()` use the same one later. Build records with `User.build(…)`: a record made with `new User()` has no database, and throws `NoDatabase` when it needs one.
2319
+ ```sql
2320
+ CREATE TABLE users (
2321
+ id TEXT PRIMARY KEY NOT NULL,
2322
+ email TEXT NOT NULL,
2323
+ role TEXT,
2324
+ is_active BOOLEAN,
2325
+ created_at DATETIME NOT NULL,
2326
+ updated_at DATETIME NOT NULL
2327
+ );
2328
+ ```
2075
2329
 
2076
- :::note
2077
- The binding is only there during a request, inside a Worker. Tests and scripts that run in Node get their database from `withDatabase`. See [Testing](/testing).
2078
- :::
2330
+ **Postgres**
2079
2331
 
2080
- ## Using the request’s database
2332
+ ```sql
2333
+ CREATE TABLE users (
2334
+ id UUID PRIMARY KEY,
2335
+ email TEXT NOT NULL,
2336
+ role TEXT,
2337
+ is_active BOOLEAN,
2338
+ created_at TIMESTAMPTZ NOT NULL,
2339
+ updated_at TIMESTAMPTZ NOT NULL
2340
+ );
2341
+ ```
2081
2342
 
2082
- Some things belong to one request, such as a D1 Session that reads its own writes, or logging tagged with the request’s ID. Open a database for the request, and run its code inside `withDatabase`:
2343
+ ## Matching values
2083
2344
 
2084
- ```ts
2085
- import { withDatabase } from "@forestfuture/active-record";
2086
- import { connect } from "@forestfuture/active-record/d1";
2345
+ Pass `where` an object of attributes that must all match:
2087
2346
 
2088
- export default {
2089
- fetch(request, env) {
2090
- const db = connect(env.DB, { onQuery: log });
2091
- return withDatabase(db, () => app.fetch(request, env));
2092
- },
2093
- };
2094
- ```
2347
+ ```ts twoslash
2348
+ // @filename: models.ts
2349
+ import { Model } from "@forestfuture/active-record";
2095
2350
 
2096
- Every query started from a Model inside it, and everything it awaits, uses that database instead of the binding.
2351
+ export class User extends Model.define({
2352
+ id: { type: "string", null: false, generateId: true },
2353
+ email: { type: "string", null: false },
2354
+ role: "string",
2355
+ isActive: "boolean",
2356
+ createdAt: { type: "datetime", null: false },
2357
+ updatedAt: { type: "datetime", null: false },
2358
+ }) {}
2097
2359
 
2098
- :::warning[Node.js compatibility]
2099
- `withDatabase` uses Workers’ `AsyncLocalStorage`. It’s on by default for compatibility dates from 2026-08-04. For an earlier date, add `"compatibility_flags": ["nodejs_compat"]` to your Wrangler config, or `withDatabase` throws `NoDatabase`. Nothing else on D1 needs it. On Postgres, `pg` needs it too.
2100
- :::
2360
+ // @filename: example.ts
2361
+ // ---cut---
2362
+ import { User } from "./models";
2101
2363
 
2102
- These pages use a request’s database:
2364
+ const admins = await User.where({ role: "admin", isActive: true }).toArray();
2103
2365
 
2104
- - **[Read replicas](/read-your-own-writes):** a D1 Session per request.
2105
- - **[Logging](/logging):** one request’s queries, tagged with its ID.
2106
- - **[Testing](/testing):** a database for Models outside a Worker.
2107
- - **[Multiple databases](/several-databases):** `withDatabase([...])`, matched to each Model’s binding.
2366
+ User.where({ role: null }); // role IS NULL
2367
+ User.where({ role: ["admin", "editor"] }); // role IN (…), any number of values
2368
+ ```
2108
2369
 
2109
- ## Using an explicit database
2370
+ - `null` matches NULL. An array matches any of its values, and is bound as one value, so it can be any length.
2371
+ - Values are [cast to the attribute’s type](/models#casting-assigned-values), so text from a query string works as it is: `where({ isActive: "false" })` finds inactive users. A value that can’t be cast matches nothing: `findBy` resolves to `null`, and `find` throws `RecordNotFound`.
2372
+ - `undefined` throws `TypeError`. Leave the key out, or use `null`.
2110
2373
 
2111
- Start a query from a database you hold with `db.model`. It ignores `withDatabase`:
2374
+ Attribute names are checked when you compile, and a misspelled one that gets past the compiler throws `UnknownAttribute`:
2375
+
2376
+ ```ts twoslash
2377
+ // @noErrorValidation
2378
+ // @filename: models.ts
2379
+ import { Model } from "@forestfuture/active-record";
2380
+
2381
+ export class User extends Model.define({
2382
+ id: { type: "string", null: false, generateId: true },
2383
+ email: { type: "string", null: false },
2384
+ role: "string",
2385
+ isActive: "boolean",
2386
+ createdAt: { type: "datetime", null: false },
2387
+ updatedAt: { type: "datetime", null: false },
2388
+ }) {}
2389
+
2390
+ // @filename: example.ts
2391
+ // ---cut---
2392
+ import { User } from "./models";
2393
+
2394
+ User.where({ rol: "admin" });
2395
+ ```
2396
+
2397
+ ## Negating conditions
2398
+
2399
+ Negate a condition with `whereNot`, or combine two queries with `or`:
2400
+
2401
+ ```ts twoslash
2402
+ // @filename: models.ts
2403
+ import { Model } from "@forestfuture/active-record";
2404
+
2405
+ export class User extends Model.define({
2406
+ id: { type: "string", null: false, generateId: true },
2407
+ email: { type: "string", null: false },
2408
+ role: "string",
2409
+ isActive: "boolean",
2410
+ createdAt: { type: "datetime", null: false },
2411
+ updatedAt: { type: "datetime", null: false },
2412
+ }) {}
2413
+
2414
+ // @filename: example.ts
2415
+ // ---cut---
2416
+ import { User } from "./models";
2417
+
2418
+ const others = await User.whereNot({ role: "admin" }).toArray();
2419
+ const either = await User.where({ role: "admin" })
2420
+ .or(User.where({ isActive: false }))
2421
+ .toArray();
2422
+ ```
2423
+
2424
+ - `whereNot` negates the whole condition. As in SQL, `whereNot({ role: "admin" })` also leaves out users whose role is NULL.
2425
+ - `or` combines two Relations of the same Model that differ only in their conditions.
2426
+
2427
+ :::note
2428
+ In a list, values that can’t be cast are left out. So `whereNot({ id: "abc" })` on an integer key excludes nothing.
2429
+ :::
2430
+
2431
+ ## Comparing values
2432
+
2433
+ Pass a comparison helper as a value:
2434
+
2435
+ ```ts twoslash
2436
+ // @filename: models.ts
2437
+ import { Model } from "@forestfuture/active-record";
2438
+
2439
+ export class User extends Model.define({
2440
+ id: { type: "string", null: false, generateId: true },
2441
+ email: { type: "string", null: false },
2442
+ role: "string",
2443
+ isActive: "boolean",
2444
+ createdAt: { type: "datetime", null: false },
2445
+ updatedAt: { type: "datetime", null: false },
2446
+ }) {}
2447
+
2448
+ // @filename: example.ts
2449
+ // ---cut---
2450
+ import { between, gte, lt } from "@forestfuture/active-record";
2451
+ import { User } from "./models";
2452
+
2453
+ const since = new Date("2026-01-01");
2454
+ const until = new Date("2026-02-01");
2455
+
2456
+ User.where({ createdAt: gte(since) }); // created_at >= ?
2457
+ User.where({ createdAt: lt(since) }); // created_at < ?
2458
+ User.where({ createdAt: between(since, until) }); // both ends included
2459
+ User.where({ createdAt: between(since, until, { excludeEnd: true }) });
2460
+ ```
2461
+
2462
+ `gt`, `gte`, `lt`, `lte`, and `between` work on number, string, and datetime attributes, and dates compare by time. `between` includes both ends, unless you pass `{ excludeEnd: true }`.
2463
+
2464
+ ## Writing SQL fragments
2465
+
2466
+ Write anything else as an `sql` tagged template, with `column()` for an attribute’s column:
2467
+
2468
+ ```ts twoslash
2469
+ // @filename: models.ts
2470
+ import { Model } from "@forestfuture/active-record";
2471
+
2472
+ export class User extends Model.define({
2473
+ id: { type: "string", null: false, generateId: true },
2474
+ email: { type: "string", null: false },
2475
+ role: "string",
2476
+ isActive: "boolean",
2477
+ createdAt: { type: "datetime", null: false },
2478
+ updatedAt: { type: "datetime", null: false },
2479
+ }) {}
2480
+
2481
+ // @filename: example.ts
2482
+ // ---cut---
2483
+ import { column, sql } from "@forestfuture/active-record";
2484
+ import { User } from "./models";
2485
+
2486
+ const email = "Ada@Example.com";
2487
+ const ada = await User.findBy(sql`lower(${column("email")}) = lower(${email})`);
2488
+ ```
2489
+
2490
+ Values are always bound, as they are, so a `Date` is ISO text. To write a value the way its attribute stores it, use `column(name).value(v)`:
2491
+
2492
+ ```ts twoslash
2493
+ // @filename: models.ts
2494
+ import { Model } from "@forestfuture/active-record";
2495
+
2496
+ export class User extends Model.define({
2497
+ id: { type: "string", null: false, generateId: true },
2498
+ email: { type: "string", null: false },
2499
+ role: "string",
2500
+ isActive: "boolean",
2501
+ createdAt: { type: "datetime", null: false },
2502
+ updatedAt: { type: "datetime", null: false },
2503
+ }) {}
2504
+
2505
+ // @filename: example.ts
2506
+ // ---cut---
2507
+ import { column, sql } from "@forestfuture/active-record";
2508
+ import { User } from "./models";
2509
+
2510
+ const createdAt = column("createdAt");
2511
+ const newcomers = await User.where(
2512
+ sql`${createdAt} >= ${createdAt.value(new Date("2026-01-01"))}`,
2513
+ ).toArray();
2514
+ ```
2515
+
2516
+ `value` works for any attribute, and writes a boolean as 0 or 1 and a JSON value as text. It casts as assigning would, so a value the attribute can’t hold throws `TypeError` naming the attribute, when `where` is given the fragment. A filtered attribute’s value is hidden from `onQuery`, as it is anywhere else.
2517
+
2518
+ :::warning[Datetimes stored as Unix time]
2519
+ For a datetime [stored as a Unix time](/adopt-a-database#reading-unix-timestamps), a bare `Date`, or an ISO datetime string, beside its column throws `TypeError`. Inside an expression, such as `abs(${column("publishedAt")} - ${date})`, or an `IN` list, nothing can tell, and the integer is compared with text: `>` matches nothing and `<` matches every row. Use `value` there.
2520
+ :::
2521
+
2522
+ ## Replacing conditions
2523
+
2524
+ Replace the conditions on some attributes with `rewhere`:
2525
+
2526
+ ```ts twoslash
2527
+ // @filename: models.ts
2528
+ import { Model } from "@forestfuture/active-record";
2529
+
2530
+ export class User extends Model.define({
2531
+ id: { type: "string", null: false, generateId: true },
2532
+ email: { type: "string", null: false },
2533
+ role: "string",
2534
+ isActive: "boolean",
2535
+ createdAt: { type: "datetime", null: false },
2536
+ updatedAt: { type: "datetime", null: false },
2537
+ }) {}
2538
+
2539
+ // @filename: example.ts
2540
+ // ---cut---
2541
+ import { User } from "./models";
2542
+
2543
+ const members = User.where({ role: "member", isActive: true });
2544
+ const activeAdmins = await members.rewhere({ role: "admin" }).toArray(); // is_active = ? AND role = ?
2545
+ ```
2546
+
2547
+ Conditions on other attributes stay, and so do `sql` fragments. A default scope’s condition on the attribute is replaced too. A `whereNot` or `or` is replaced only if it names no other attributes.
2548
+
2549
+ Drop parts of a query with `unscope`, or keep only some with `only`:
2550
+
2551
+ ```ts twoslash
2552
+ // @filename: models.ts
2553
+ import { Model } from "@forestfuture/active-record";
2554
+
2555
+ export class User extends Model.define({
2556
+ id: { type: "string", null: false, generateId: true },
2557
+ email: { type: "string", null: false },
2558
+ role: "string",
2559
+ isActive: "boolean",
2560
+ createdAt: { type: "datetime", null: false },
2561
+ updatedAt: { type: "datetime", null: false },
2562
+ }) {}
2563
+
2564
+ // @filename: example.ts
2565
+ // ---cut---
2566
+ import { User } from "./models";
2567
+
2568
+ const recent = User.where({ role: "admin" }).order({ createdAt: "desc" }).limit(10);
2569
+ recent.unscope("order", "limit"); // every admin, unordered
2570
+ recent.unscope({ where: "role" }); // the 10 newest users
2571
+ recent.only("where"); // every admin
2572
+ ```
2573
+
2574
+ - The parts are `"where"`, `"order"`, `"limit"`, `"offset"`, `"select"`, `"distinct"`, `"includes"`, `"joins"`, `"leftJoins"`, and `"createWith"`. `{ where: "role" }` drops only the conditions on those attributes.
2575
+ - A default scope’s parts are dropped too. To start without the default scope, use [`unscoped()`](/querying#defining-a-default-scope).
2576
+ - On an association, the link to its owner stays: `user.posts().unscope("where")` is still the user’s posts, and so is `rewhere({ userId })`. Start from `Post` to read past the owner.
2577
+ - Merging a Relation built with `unscope` drops those parts from the Relation it’s merged into.
2578
+ - A join can’t be dropped while a merged condition or order uses it. That throws `IncompatibleRelation`.
2579
+
2580
+ ## Leaving records out
2581
+
2582
+ Leave out records you already have with `excluding`:
2583
+
2584
+ ```ts twoslash
2585
+ // @filename: models.ts
2586
+ import { Model } from "@forestfuture/active-record";
2587
+
2588
+ export class User extends Model.define({
2589
+ id: { type: "string", null: false, generateId: true },
2590
+ email: { type: "string", null: false },
2591
+ role: "string",
2592
+ isActive: "boolean",
2593
+ createdAt: { type: "datetime", null: false },
2594
+ updatedAt: { type: "datetime", null: false },
2595
+ }) {}
2596
+
2597
+ // @filename: example.ts
2598
+ // ---cut---
2599
+ import { User } from "./models";
2600
+
2601
+ const me = await User.findByOrThrow({ email: "ada@example.com" });
2602
+ const everyoneElse = await User.excluding(me).toArray();
2603
+ ```
2604
+
2605
+ It takes records of the Relation’s Model, or arrays of them. A record that isn’t saved yet leaves nothing out.
2606
+
2607
+ > **Compared with Rails**
2608
+ >
2609
+ > `rewhere`, `unscope`, `only`, and `excluding` work as Rails’ do, with the parts named as strings. `group` and `having` aren’t parts, since a grouped Relation is a type of its own. `invert_where` and `without` aren’t offered, and scopes cover `extending`.
2610
+
2611
+ > **Beyond Rails**
2612
+ >
2613
+ > On an association, Rails’ `unscope(:where)` drops the link to its owner, so a read can reach records that `create` wouldn’t link to it. Here no rewrite drops the link, so reads and writes agree.
2614
+
2615
+ ---
2616
+
2617
+ # Connections
2618
+ Source: https://active-record.forestfuture.dev/connecting
2619
+
2620
+ ## At a glance
2621
+
2622
+ Most apps only use the binding.
2623
+
2624
+ | | How | Use it for |
2625
+ | -------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------- |
2626
+ | **The binding** | `User.find(id)`, with nothing to set up | Everyday queries |
2627
+ | **The request’s database** | `withDatabase(connect(env.DB, …), fn)`, once per request | Read replicas with a Session, per-request `onQuery` logging, tests, and scripts |
2628
+ | **An explicit database** | `connect(env.DB).model(User).find(id)` | Code that passes its database around, or uses two at once |
2629
+
2630
+ [Database resolution](/query-databases) explains why there are three, and [which one you need](/query-databases#which-do-i-need).
2631
+
2632
+ :::note
2633
+ The examples use D1’s `connect`, from `@forestfuture/active-record/d1`. On Postgres, `connect` comes from `@forestfuture/active-record/postgresql` and takes your Hyperdrive binding. See [PostgreSQL](/postgresql#connecting).
2634
+ :::
2635
+
2636
+ ## Using the binding
2637
+
2638
+ Each Model names the binding it queries, so a Model queries by itself during any request:
2639
+
2640
+ ```ts
2641
+ import { Post, User } from "./models";
2642
+
2643
+ // No setup: each Model queries the binding its generated schema names during the request.
2644
+ const user = await User.findByOrThrow({ email: "ada@example.com" });
2645
+ const posts = await Post.where({ userId: user.id }).order({ id: "desc" }).toArray();
2646
+ ```
2647
+
2648
+ `active-record schema` writes the binding into the generated schema your app’s base class holds. On D1 it comes from your Wrangler config’s `d1_databases`, and on Postgres from your `active-record.jsonc`.
2649
+
2650
+ Records remember their database, so `user.save()` and `user.posts()` use the same one later. Build records with `User.build(…)`: a record made with `new User()` has no database, and throws `NoDatabase` when it needs one.
2651
+
2652
+ :::note
2653
+ The binding is only there during a request, inside a Worker. Tests and scripts that run in Node get their database from `withDatabase`. See [Testing](/testing).
2654
+ :::
2655
+
2656
+ ## Using the request’s database
2657
+
2658
+ Some things belong to one request, such as a D1 Session that reads its own writes, or logging tagged with the request’s ID. Open a database for the request, and run its code inside `withDatabase`:
2659
+
2660
+ ```ts
2661
+ import { withDatabase } from "@forestfuture/active-record";
2662
+ import { connect } from "@forestfuture/active-record/d1";
2663
+
2664
+ export default {
2665
+ fetch(request, env) {
2666
+ const db = connect(env.DB, { onQuery: log });
2667
+ return withDatabase(db, () => app.fetch(request, env));
2668
+ },
2669
+ };
2670
+ ```
2671
+
2672
+ Every query started from a Model inside it, and everything it awaits, uses that database instead of the binding.
2673
+
2674
+ :::warning[Node.js compatibility]
2675
+ `withDatabase` uses Workers’ `AsyncLocalStorage`. It’s on by default for compatibility dates from 2026-08-04. For an earlier date, add `"compatibility_flags": ["nodejs_compat"]` to your Wrangler config, or `withDatabase` throws `NoDatabase`. On D1, only `withDatabase` and [`noTouching`](/associations#turning-touches-off) need it. On Postgres, `pg` needs it too.
2676
+ :::
2677
+
2678
+ These pages use a request’s database:
2679
+
2680
+ - **[Read replicas](/read-your-own-writes):** a D1 Session per request.
2681
+ - **[Logging](/logging):** one request’s queries, tagged with its ID.
2682
+ - **[Testing](/testing):** a database for Models outside a Worker.
2683
+ - **[Multiple databases](/several-databases):** `withDatabase([...])`, matched to each Model’s binding.
2684
+
2685
+ ## Using an explicit database
2686
+
2687
+ Start a query from a database you hold with `db.model`. It ignores `withDatabase`:
2112
2688
 
2113
2689
  ```ts
2114
2690
  import { connect } from "@forestfuture/active-record/d1";
@@ -2151,7 +2727,9 @@ await batch((b) => [b.save(user), b.save(post), b.deleteAll(Post.where({ userId:
2151
2727
  # Console
2152
2728
  Source: https://active-record.forestfuture.dev/console
2153
2729
 
2154
- Open a console on your local database, with your Models loaded, to try a query or fix a record by hand, or on your remote one with [`--remote`](#opening-your-remote-database). Run it from your project’s folder:
2730
+ ## Opening the console
2731
+
2732
+ Run the console from your project’s folder. It opens your local database, or your remote one with [`--remote`](#opening-your-remote-database):
2155
2733
 
2156
2734
  ```sh
2157
2735
  npx active-record console
@@ -2351,8 +2929,6 @@ The console runs your project’s code: your Models, and the `wrangler` and `@fo
2351
2929
  # Custom types
2352
2930
  Source: https://active-record.forestfuture.dev/custom-types
2353
2931
 
2354
- A custom type holds a value the built-in types don’t, such as money or a list of sizes. Its values are stored in their column as one of the built-in types.
2355
-
2356
2932
  ## Defining a type
2357
2933
 
2358
2934
  Define a type with `defineType`, naming the built-in type it’s stored as. This one keeps money as whole cents in an integer column:
@@ -2491,7 +3067,9 @@ An equal value in another object, such as a new `Money` of the same cents, isn
2491
3067
  # D1
2492
3068
  Source: https://active-record.forestfuture.dev/d1
2493
3069
 
2494
- The D1 adapter runs your Models on [Cloudflare D1](https://developers.cloudflare.com/d1/). It comes with `@forestfuture/active-record`, as its `/d1` entry:
3070
+ ## Installing
3071
+
3072
+ The D1 adapter comes with `@forestfuture/active-record`, as its `/d1` entry:
2495
3073
 
2496
3074
  ```sh
2497
3075
  npm install @forestfuture/active-record
@@ -2570,6 +3148,8 @@ SQLite stores a [`decimal`](/models#storing-exact-numbers-days-and-times) as a n
2570
3148
  # Errors
2571
3149
  Source: https://active-record.forestfuture.dev/errors
2572
3150
 
3151
+ ## Checking for Active Record’s errors
3152
+
2573
3153
  Every error Active Record throws extends `ActiveRecordError`, so one check separates them from anything else:
2574
3154
 
2575
3155
  ```ts
@@ -2659,7 +3239,9 @@ Every method throws them, `save()` as well as `saveOrThrow()`. The record keeps
2659
3239
  # Generators
2660
3240
  Source: https://active-record.forestfuture.dev/generators
2661
3241
 
2662
- Generators write a table’s migration and its Model from a short description, then regenerate `src/db/schema.ts`. Each migration is written in your database’s own SQL: the [Command line](/command-line#column-syntax) reference lists the types on D1 and on Postgres, and every option.
3242
+ :::note
3243
+ Each migration is written in your database’s own SQL. [Command line](/command-line#column-syntax) lists the types on D1 and on Postgres, and every option.
3244
+ :::
2663
3245
 
2664
3246
  ## Adding a table
2665
3247
 
@@ -2788,8 +3370,6 @@ npx active-record schema
2788
3370
  # Getting started
2789
3371
  Source: https://active-record.forestfuture.dev/getting-started
2790
3372
 
2791
- Active Record turns each table in your [D1](https://developers.cloudflare.com/d1/) database into a Model, so your [Worker](https://developers.cloudflare.com/workers/) works with records instead of rows. In this tutorial you’ll build the start of a small blog: users, and the posts they write.
2792
-
2793
3373
  :::warning[Version 0.x]
2794
3374
  Active Record is before 1.0. Its behavior is tested against real D1, but the API may still change. A breaking change ships in a new minor version, so `^0.7.0` never takes one.
2795
3375
  :::
@@ -3005,7 +3585,9 @@ The list includes Ada, with her email lowercased by `beforeSave`. Sign her up ag
3005
3585
  # Logging
3006
3586
  Source: https://active-record.forestfuture.dev/logging
3007
3587
 
3008
- Log the SQL your Worker sends to D1 with an `onQuery` listener. It’s called once for every statement, writes and batches included, with:
3588
+ ## Receiving each query
3589
+
3590
+ An `onQuery` listener is called once for every statement, writes and batches included, with:
3009
3591
 
3010
3592
  | Field | |
3011
3593
  | --------------- | ---------------------------------------------------------------- |
@@ -3198,8 +3780,6 @@ A bare value inside an `sql` fragment has no attribute, so it’s logged as give
3198
3780
  # Models
3199
3781
  Source: https://active-record.forestfuture.dev/models
3200
3782
 
3201
- A Model describes one table. Its attributes come from your migrations, through the generated schema, so the Model only declares behavior.
3202
-
3203
3783
  ## Defining Models
3204
3784
 
3205
3785
  ### Generating `ApplicationRecord`
@@ -3859,7 +4439,7 @@ import { column, sql } from "@forestfuture/active-record";
3859
4439
  const recent = await User.where(sql`${column("createdAt")} > ${since}`).toArray();
3860
4440
  ```
3861
4441
 
3862
- A plain string is rejected. To write a `Date`, boolean, or JSON value the way an attribute stores it, see [Writing SQL fragments](/querying#writing-sql-fragments).
4442
+ A plain string is rejected. To write a `Date`, boolean, or JSON value the way an attribute stores it, see [Writing SQL fragments](/conditions#writing-sql-fragments).
3863
4443
 
3864
4444
  ## Serializing records
3865
4445
 
@@ -3996,7 +4576,9 @@ After that, a Model’s declarations are fixed, so request code can’t change t
3996
4576
  # Moving to Postgres
3997
4577
  Source: https://active-record.forestfuture.dev/move-to-postgres
3998
4578
 
3999
- Move your app from D1 to Postgres by changing its migrations, its schema, its config, and its data. Your Models and the code that uses them stay as they are. The examples move the app from [Getting started](/getting-started).
4579
+ ## Planning the move
4580
+
4581
+ The examples move the app from [Getting started](/getting-started).
4000
4582
 
4001
4583
  | What changes | How |
4002
4584
  | --------------------- | -------------------------------------------------------- |
@@ -4250,8 +4832,6 @@ Your queries, validations, callbacks, and associations work the same on Postgres
4250
4832
  # Persistence
4251
4833
  Source: https://active-record.forestfuture.dev/persistence
4252
4834
 
4253
- Records are saved, updated, and destroyed with `save`, `create`, `update`, and `destroy`.
4254
-
4255
4835
  ## Saving records
4256
4836
 
4257
4837
  Save a record with `save`. It validates the record, runs its callbacks, and resolves to `true` or `false`:
@@ -4351,12 +4931,33 @@ await article.toggleColumn("isPinned");
4351
4931
  await article.updateColumns({ title: "Renamed" }); // no validations, callbacks, or updatedAt
4352
4932
  ```
4353
4933
 
4354
- - **`incrementColumn` and `decrementColumn`** add to the value in the row, not the one the record loaded. When two requests increment the same row, both count. The record then holds the row’s new value.
4934
+ - **`incrementColumn` and `decrementColumn`** add to the value in the row, not the one the record loaded. When two requests increment the same row, both count. The record then holds the row’s new value. To set `updatedAt` in the same write, pass `{ touch: true }` after the amount.
4355
4935
  - **`toggleColumn`** writes the flipped value.
4356
4936
  - **`updateColumns(attrs)`** writes the attributes you give. `updateColumn(name, value)` writes one.
4357
4937
 
4358
4938
  Each resolves to `true`, or `false` when the row is gone. The record’s other unsaved changes stay unsaved. A record that was never saved has no row, so these methods throw `RecordNotSaved`.
4359
4939
 
4940
+ ### Touching a record
4941
+
4942
+ To mark a record as changed without saving it, call `touch`. It sets `updatedAt` to the current time in the row:
4943
+
4944
+ ```ts
4945
+ await article.touch(); // sets updatedAt to now
4946
+ await article.touch("viewedAt"); // sets viewedAt and updatedAt
4947
+ await article.touch({ time: new Date("2026-01-01T00:00:00Z") });
4948
+ await Article.where({ isPinned: true }).touchAll(); // every pinned article, in one statement
4949
+ ```
4950
+
4951
+ - **Name datetime attributes** to set them as well as `updatedAt`.
4952
+ - **Pass `{ time }` last** to set a time other than now.
4953
+ - **A Relation’s `touchAll`** sets them in every row it matches, in one statement. Like `updateAll`, it keeps the default scope and runs no callbacks.
4954
+
4955
+ `touch` skips validations and the save callbacks, and the record’s other unsaved changes stay unsaved. It runs `afterTouch`, then the commit callbacks for an update. See [Running code after a touch](/callbacks#running-code-after-a-touch).
4956
+
4957
+ `touch` resolves to `true`, or `false` when the row is gone. A record that was never saved throws `RecordNotSaved`. On a Model with no `updatedAt`, name at least one attribute. Inside a [`noTouching` block](/associations#turning-touches-off) for its Model, `touch` writes nothing and resolves to `false`.
4958
+
4959
+ To touch the record a record belongs to whenever it changes, declare `touch` on its `belongsTo`. See [Touching the record it belongs to](/associations#touching-the-record-it-belongs-to).
4960
+
4360
4961
  ### Updating counters
4361
4962
 
4362
4963
  To add to a number without loading the record, pass its primary key to `updateCounters`:
@@ -4395,6 +4996,8 @@ await Article.where({ id }).updateCounters({ viewCount: 1 }); // keeps the defau
4395
4996
  > Rails’ `toggle!` runs the save callbacks and saves the record’s other changes. `toggleColumn` runs no callbacks and writes only the one attribute. For callbacks, call `toggle`, then `save`.
4396
4997
  >
4397
4998
  > Rails’ `increment!` keeps the value it worked out. `incrementColumn` reads the row’s new value back, so it includes other requests’ increments.
4999
+ >
5000
+ > `touch` and `touchAll` are Rails’ `touch` and `touch_all`. Rails writes the time to any column you name, and touching a Model with no `updated_at` does nothing. Here, an attribute that isn’t a datetime, or nothing to touch, throws a `TypeError`.
4398
5001
 
4399
5002
  ## Finding or creating a record
4400
5003
 
@@ -4447,7 +5050,7 @@ const news = await Label.createOrFindBy({ name: "news" }); // created, or found
4447
5050
 
4448
5051
  - **Leave out a `uniqueness` validation on those attributes.** It refuses the duplicate before the insert, so `createOrFindBy` resolves to the invalid record, not the existing one. The UNIQUE index alone keeps the column unique.
4449
5052
  - **Save the record alone.** When `init` builds or sets records through its associations, a refusal may be theirs, so `createOrFindBy` throws the `RecordNotUnique` instead of finding.
4450
- - **It throws `RecordNotFound` when there’s nothing to find:** when the index refused a value in an attribute you didn’t pass, when the existing row isn’t linked to the owner of an [association through another](/associations#reaching-records-through-another-association), or when a [D1 Session](/read-your-own-writes) reads from a replica that the other request’s row hasn’t reached yet.
5053
+ - **It throws `RecordNotFound` when there’s nothing to find:** when the index refused a value in an attribute you didn’t pass, when the existing row isn’t linked to the owner of an [association through another](/through-associations), or when a [D1 Session](/read-your-own-writes) reads from a replica that the other request’s row hasn’t reached yet.
4451
5054
 
4452
5055
  :::
4453
5056
 
@@ -4536,6 +5139,7 @@ export class Article extends Model.define({
4536
5139
  title: { type: "string", null: false },
4537
5140
  viewCount: { type: "integer", null: false },
4538
5141
  isPinned: { type: "boolean", null: false },
5142
+ viewedAt: "datetime",
4539
5143
  updatedAt: "datetime",
4540
5144
  }) {
4541
5145
  static {
@@ -4573,7 +5177,9 @@ To insert, update, or delete many rows at once, without validations and callback
4573
5177
  # PostgreSQL
4574
5178
  Source: https://active-record.forestfuture.dev/postgresql
4575
5179
 
4576
- The PostgreSQL adapter runs your Models on Postgres, in a Worker through [Hyperdrive](https://developers.cloudflare.com/hyperdrive/) or on Node. It comes with `@forestfuture/active-record`, as its `/postgresql` entry. Install the library with `pg`, and PGlite for reading your schema:
5180
+ ## Installing
5181
+
5182
+ The PostgreSQL adapter comes with `@forestfuture/active-record`, as its `/postgresql` entry. Install the library with `pg`, and PGlite for reading your schema:
4577
5183
 
4578
5184
  ```sh
4579
5185
  npm install @forestfuture/active-record pg
@@ -4723,8 +5329,6 @@ A `jsonb` column keeps a JSON value, not the text you wrote. A raw query reads i
4723
5329
  # Database resolution
4724
5330
  Source: https://active-record.forestfuture.dev/query-databases
4725
5331
 
4726
- `Product.find(id)` works with no setup, because a Model knows its binding. But a Worker isn’t a long-running server, and that shapes how a query finds its database.
4727
-
4728
5332
  ## One isolate, many requests
4729
5333
 
4730
5334
  A Worker runs in an **isolate** that serves many requests at the same time, and a Model class is shared by all of them. So anything stored on a class is shared by every request in flight. That rules out storing a connection on a class: some of what a connection carries belongs to one request only.
@@ -4768,6 +5372,8 @@ For the options themselves, see [Connections](/connecting).
4768
5372
  # Querying
4769
5373
  Source: https://active-record.forestfuture.dev/querying
4770
5374
 
5375
+ ## Building a Relation
5376
+
4771
5377
  A query is a **Relation**. Each method that narrows, orders, or pages it returns a new Relation, and nothing runs until you ask for results:
4772
5378
 
4773
5379
  ```ts
@@ -4790,132 +5396,9 @@ A query runs on the current database: the request’s, if it was opened with `wi
4790
5396
 
4791
5397
  ## Adding conditions
4792
5398
 
4793
- Pass `where` an object of attributes that must all match:
5399
+ Narrow a query with `where`, `whereNot`, `or`, comparisons such as `gte` and `between`, and `sql` fragments. Replace them with `rewhere`, drop parts with `unscope`, and leave records out with `excluding`. See [Conditions](/conditions).
4794
5400
 
4795
- ```ts
4796
- import { User } from "./models";
4797
-
4798
- User.where({ role: "admin", isActive: true }); // role = ? AND is_active = ?
4799
- User.where({ role: null }); // role IS NULL
4800
- User.where({ role: ["admin", "editor"] }); // role IN (…), any number of values
4801
- User.whereNot({ role: "admin" }); // NOT (role = ?)
4802
- User.where({ role: "admin" }).or(User.where({ isActive: false }));
4803
- ```
4804
-
4805
- - `null` matches NULL, and an array matches any of its values. The list is bound as one value, so it can be any length.
4806
- - `whereNot` negates the whole condition. As in SQL, `whereNot({ role: "admin" })` also leaves out users whose role is NULL.
4807
- - `or` combines two Relations of the same Model that differ only in their conditions.
4808
- - `undefined` throws `TypeError`. Leave the key out, or use `null`.
4809
-
4810
- Values are [cast to the attribute’s type](/models#casting-assigned-values), so `where({ quantity: "42" })` finds 42. A value that can’t be cast matches nothing: `findBy` resolves to `null`, and `find` throws `RecordNotFound`.
4811
-
4812
- :::note
4813
- In a list, values that can’t be cast are left out. So `whereNot({ id: "abc" })` on an integer key excludes nothing.
4814
- :::
4815
-
4816
- ### Comparing values
4817
-
4818
- Pass a comparison helper as a value:
4819
-
4820
- ```ts
4821
- import { between, gte, lt } from "@forestfuture/active-record";
4822
- import { Post, User } from "./models";
4823
-
4824
- Post.where({ publishedAt: gte(since) }); // published_at >= since
4825
- User.where({ createdAt: lt(since) }); // created_at < since
4826
- User.where({ createdAt: between(since, until) }); // both ends included
4827
- User.where({ createdAt: between(since, until, { excludeEnd: true }) });
4828
- ```
4829
-
4830
- `gt`, `gte`, `lt`, `lte`, and `between` work on number, string, and datetime attributes, and dates compare by time. `between` includes both ends. Pass `{ excludeEnd: true }` to leave out the end.
4831
-
4832
- ### Writing SQL fragments
4833
-
4834
- For anything else, write an `sql` tagged template. Values are always bound, and `column()` looks up an attribute’s column:
4835
-
4836
- ```ts
4837
- import { column, sql } from "@forestfuture/active-record";
4838
- import { User } from "./models";
4839
-
4840
- const email = "Ada@Example.com";
4841
- User.where(sql`lower(${column("email")}) = lower(${email})`);
4842
- ```
4843
-
4844
- :::warning[Integer datetimes]
4845
- A value in a fragment is bound as it is, so a `Date` is ISO text. If the attribute is a datetime [stored as a Unix time](/adopt-a-database#reading-unix-timestamps), compare it with `column("publishedAt").value(date)`, which writes the `Date` as the attribute stores it. A bare `Date` (or an ISO datetime string) beside that column in a comparison throws `TypeError`. In an expression, such as `abs(${column("publishedAt")} - ${date})`, or in an `IN` list, Active Record can’t tell what you meant: you’re comparing an integer with text, which SQLite always orders the same way, so `>` matches nothing and `<` matches every row. Check which form the expression needs, and use `value` when it needs the stored one.
4846
- :::
4847
-
4848
- ```ts
4849
- import { column, sql } from "@forestfuture/active-record";
4850
-
4851
- export function publishedBefore(before: Date) {
4852
- const publishedAt = column("publishedAt");
4853
- return Article.where(sql`${publishedAt} < ${publishedAt.value(before)}`);
4854
- }
4855
- ```
4856
-
4857
- `value` works for any attribute, and writes a boolean as 0 or 1 and a JSON value as text. The value is cast as an assigned one, so a value the attribute can’t hold throws `TypeError` naming the attribute, when `where` is given the fragment. A filtered attribute’s value is hidden from `onQuery`, as it is anywhere else.
4858
-
4859
- ### Replacing conditions
4860
-
4861
- Replace the conditions on some attributes with `rewhere`:
4862
-
4863
- ```ts
4864
- import { User } from "./models";
4865
-
4866
- const members = User.where({ role: "member", isActive: true });
4867
- members.rewhere({ role: "admin" }); // is_active = ? AND role = ?
4868
- ```
4869
-
4870
- Conditions on other attributes stay, and so do `sql` fragments. A default scope’s condition on the attribute is replaced too.
4871
-
4872
- :::note
4873
- A `whereNot` or `or` that names only those attributes is replaced. One that names other attributes too stays.
4874
- :::
4875
-
4876
- Drop parts of a query with `unscope`, or keep only some with `only`:
4877
-
4878
- ```ts
4879
- import { User } from "./models";
4880
-
4881
- const recent = User.where({ role: "admin" }).order({ createdAt: "desc" }).limit(10);
4882
- recent.unscope("order", "limit"); // every admin, unordered
4883
- recent.unscope({ where: "role" }); // the 10 newest users
4884
- recent.only("where"); // every admin
4885
- ```
4886
-
4887
- - The parts are `"where"`, `"order"`, `"limit"`, `"offset"`, `"select"`, `"distinct"`, `"includes"`, `"joins"`, `"leftJoins"`, and `"createWith"`. `{ where: "role" }` drops only the conditions on those attributes.
4888
- - A default scope’s parts are dropped too. To start without the default scope, use [`unscoped()`](#defining-a-default-scope).
4889
- - On an association, the link to its owner stays. `user.posts().unscope("where")` is still the user’s posts, and so is `rewhere({ userId })`. Start from `Post` to read past the owner.
4890
- - Merging a Relation built with `unscope` drops those parts from the Relation it’s merged into.
4891
- - A join can’t be dropped while conditions or an order merged onto it use it. That throws `IncompatibleRelation`.
4892
-
4893
- > **Compared with Rails**
4894
- >
4895
- > `rewhere`, `unscope`, and `only` work as Rails’ do, with the parts named as strings. `group` and `having` aren’t parts, since a grouped Relation is a type of its own. Rails’ `invert_where` and `extending` aren’t offered. Scopes cover `extending`.
4896
-
4897
- > **Beyond Rails**
4898
- >
4899
- > On an association, Rails’ `unscope(:where)` drops the link to its owner, so a read can reach records that `create` wouldn’t link to it. Here no rewrite drops the link, so reads and writes agree.
4900
-
4901
- ## Leaving records out
4902
-
4903
- Leave out records you already have with `excluding`:
4904
-
4905
- ```ts
4906
- import { User } from "./models";
4907
-
4908
- const current = await User.firstOrThrow();
4909
- const others = await User.where({ role: "admin" }).excluding(current).toArray();
4910
- ```
4911
-
4912
- It takes records of the Relation’s Model, or arrays of them. A record that isn’t saved yet leaves nothing out.
4913
-
4914
- > **Compared with Rails**
4915
- >
4916
- > `excluding` is Rails’ `excluding`. Its alias `without` isn’t offered.
4917
-
4918
- ## Using raw statements
5401
+ ## Using raw statements
4919
5402
 
4920
5403
  Bind what `serialize` gives when you send SQL to D1 yourself. `typeForAttribute` returns an attribute’s conversions:
4921
5404
 
@@ -5303,7 +5786,7 @@ console.log(partial[0]?.id); // the primary key is always loaded too
5303
5786
  const roles = await User.select("role").distinct().pluck("role");
5304
5787
  ```
5305
5788
 
5306
- - Reading an attribute that wasn’t loaded throws `MissingAttribute`, including from a validator or callback.
5789
+ - Reading an attribute that wasn’t loaded throws `MissingAttribute`, including from a validator or callback. `record.hasAttribute("email")` says whether it was loaded.
5307
5790
  - Saving a partial record writes only what changed. `reload()` loads the whole row.
5308
5791
  - After `distinct()`, the primary key isn’t added, since it would make every row distinct, so those records can’t be saved.
5309
5792
 
@@ -5415,7 +5898,7 @@ const draft = Product.build({ name: "Pen" }); // available: 1, from the default
5415
5898
  - `insert`, `insertAll`, `upsert`, and `upsertAll` write its conditions’ values over the values you give. `build` and `create` use the values you give.
5416
5899
  - Several default scopes all apply. A subclass adds its own to its parent’s.
5417
5900
  - An order in a default scope is the Relation’s order. `reorder` replaces it.
5418
- - `rewhere` replaces its condition on an attribute, and [`unscope`](#replacing-conditions) drops its parts.
5901
+ - `rewhere` replaces its condition on an attribute, and [`unscope`](/conditions#replacing-conditions) drops its parts.
5419
5902
 
5420
5903
  To leave the default scope out, start from `unscoped()`:
5421
5904
 
@@ -5531,7 +6014,9 @@ A polymorphic `belongsTo` can’t be joined, because its records may be in sever
5531
6014
  # Read replicas
5532
6015
  Source: https://active-record.forestfuture.dev/read-your-own-writes
5533
6016
 
5534
- With [D1 read replication](https://developers.cloudflare.com/d1/best-practices/read-replication/), reads can come from a nearby replica that may be a moment behind. A D1 **Session** keeps each user’s reads at least as new as their own writes.
6017
+ :::note
6018
+ [D1 read replication](https://developers.cloudflare.com/d1/best-practices/read-replication/) serves reads from a nearby replica, which may be a moment behind. A D1 **Session** keeps each user’s reads at least as new as their own writes.
6019
+ :::
5535
6020
 
5536
6021
  ## Opening a Session for each request
5537
6022
 
@@ -5606,8 +6091,6 @@ After the first query, each query reads data at least as new as the one before,
5606
6091
  # Schema and ApplicationRecord
5607
6092
  Source: https://active-record.forestfuture.dev/schema
5608
6093
 
5609
- In Rails, a migration describes a table, and the model never repeats it: Rails reads the columns from the database when the app runs. Active Record keeps that idea, with one change TypeScript requires: it reads the columns when you **generate** the schema, not when your Worker runs.
5610
-
5611
6094
  ## Migrations are the source of truth
5612
6095
 
5613
6096
  Tables are created and changed by **migrations**: numbered SQL files that Wrangler applies in order, recording each one in the database (in a `d1_migrations` table), so each runs once. Cloudflare’s [D1 migrations](https://developers.cloudflare.com/d1/reference/migrations/) guide covers Wrangler’s side. Active Record’s generators write migrations for you, but any migration Wrangler can apply works, however it was written.
@@ -5647,10 +6130,6 @@ A Model can still declare its attributes itself, with `define`, for a view or a
5647
6130
  # Security
5648
6131
  Source: https://active-record.forestfuture.dev/security
5649
6132
 
5650
- Whatever a request sends can reach a query or a record through Active Record, so a mistake in it is a mistake in every app that uses it. Here’s what it protects against, what it leaves to your app, the tests that check each guarantee, how releases are built, and the security reviews it has had.
5651
-
5652
- These are the project’s own reviews, not an independent audit. Each says what it covered and what it didn’t.
5653
-
5654
6133
  ## What Active Record protects against
5655
6134
 
5656
6135
  - **SQL injection.** Every value is bound as a parameter, never written into SQL text. Identifiers come only from a Model’s declared attributes, and are quoted. Raw SQL is only possible through the `sql` tagged template, which binds every value it’s given.
@@ -5697,7 +6176,7 @@ The library’s guarantees are tested against a real D1 database (through Minifl
5697
6176
 
5698
6177
  ## Review log
5699
6178
 
5700
- Each security review adds an entry here: what it covered, how, what it found, and what it didn’t cover.
6179
+ Each security review adds an entry here: what it covered, how, what it found, and what it didn’t cover. These are the project’s own reviews, not an independent audit.
5701
6180
 
5702
6181
  ### 2026-10-04: the library, its command line, and CI
5703
6182
 
@@ -5771,8 +6250,6 @@ Please report a security problem privately, as the [security policy](https://git
5771
6250
  # Multiple databases
5772
6251
  Source: https://active-record.forestfuture.dev/several-databases
5773
6252
 
5774
- A Worker can bind several D1 databases, or a D1 database and a Postgres one. Each gets its own schema file and base class, and each Model queries the database its base class names.
5775
-
5776
6253
  ## Binding the databases
5777
6254
 
5778
6255
  Add each database to your Wrangler config, with its own `migrations_dir`:
@@ -6048,8 +6525,6 @@ npx active-record migrate --database HYPERDRIVE
6048
6525
  # Shared behavior
6049
6526
  Source: https://active-record.forestfuture.dev/shared-behavior
6050
6527
 
6051
- Every Model extends your app’s `ApplicationRecord`, so whatever you write on it, every Model has.
6052
-
6053
6528
  ## Sharing methods, callbacks, and scopes
6054
6529
 
6055
6530
  Write them on `ApplicationRecord`, in `src/models/application-record.ts`:
@@ -6153,7 +6628,9 @@ See [Multiple databases](/several-databases).
6153
6628
  # Testing
6154
6629
  Source: https://active-record.forestfuture.dev/testing
6155
6630
 
6156
- Test your Models and Worker against a real D1 database, with your migrations applied. [Miniflare](https://developers.cloudflare.com/workers/testing/miniflare/) runs Cloudflare’s runtime, D1 included, inside Node:
6631
+ ## Installing
6632
+
6633
+ [Miniflare](https://developers.cloudflare.com/workers/testing/miniflare/) runs Cloudflare’s runtime, D1 included, inside Node:
6157
6634
 
6158
6635
  ```sh
6159
6636
  npm install --save-dev vitest miniflare@4
@@ -6244,11 +6721,466 @@ To run tests inside the Workers runtime itself, use Cloudflare’s [Vitest integ
6244
6721
 
6245
6722
  ---
6246
6723
 
6724
+ # Through associations
6725
+ Source: https://active-record.forestfuture.dev/through-associations
6726
+
6727
+ ## At a glance
6728
+
6729
+ | To | Write |
6730
+ | --------------------------------------- | ------------------------------------------------------------ |
6731
+ | declare a many-to-many association | `hasMany(Article, { through: "taggings" })` |
6732
+ | follow an association with another name | `hasMany(Author, { through: "articles", source: "author" })` |
6733
+ | reach one record | `hasOne(Author, { through: "article" })` |
6734
+ | read the records | `tag.articles()`, a Relation |
6735
+ | preload them | `Tag.includes("articles")` |
6736
+ | link a record | `tag.articles().push(article)` |
6737
+ | create a record and link it | `tag.articles().create({ … })` |
6738
+ | unlink a record | `tag.articles().delete(article)` |
6739
+
6740
+ ### Options
6741
+
6742
+ | Prop | Type | Default | Description |
6743
+ | - | - | - | - |
6744
+ | `through` | `string` | - | The association to go through. |
6745
+ | `source?` | `string` | - | The join Model’s association to follow. Defaults to this association’s name, singular or plural. |
6746
+ | `scope?` | `(q) => Relation` | - | Narrows or orders the records, as on any association. |
6747
+ | `dependent?` | `"destroy" \| "deleteAll"` | - | What destroying the owner does to the join records. hasMany only. |
6748
+
6749
+ `scope` works as it does on any association. See [Scoping associations](/associations#scoping-associations).
6750
+
6751
+ ## The Models
6752
+
6753
+ The examples use these Models and tables:
6754
+
6755
+ **Models**
6756
+
6757
+ ```ts
6758
+ import { belongsTo, hasMany, hasOne, Model } from "@forestfuture/active-record";
6759
+
6760
+ export class Author extends Model.define({
6761
+ id: { type: "string", null: false, generateId: true },
6762
+ name: { type: "string", null: false },
6763
+ }) {
6764
+ articles = hasMany(Article);
6765
+ }
6766
+
6767
+ export class Article extends Model.define({
6768
+ id: { type: "string", null: false, generateId: true },
6769
+ authorId: { type: "string", null: false },
6770
+ title: { type: "string", null: false },
6771
+ }) {
6772
+ author = belongsTo(Author);
6773
+ taggings = hasMany(Tagging);
6774
+ tags = hasMany(Tag, { through: "taggings" }); // each tagging's tag
6775
+ }
6776
+
6777
+ export class Tag extends Model.define({
6778
+ id: { type: "integer", null: false },
6779
+ name: { type: "string", null: false },
6780
+ }) {
6781
+ taggings = hasMany(Tagging);
6782
+ articles = hasMany(Article, { through: "taggings" }); // each tagging's article
6783
+ writers = hasMany(Author, { through: "articles", source: "author" }); // each article's author
6784
+ }
6785
+
6786
+ export class Tagging extends Model.define({
6787
+ id: { type: "integer", null: false },
6788
+ articleId: { type: "string", null: false },
6789
+ tagId: { type: "integer", null: false },
6790
+ }) {
6791
+ article = belongsTo(Article);
6792
+ tag = belongsTo(Tag);
6793
+ author = hasOne(Author, { through: "article" }); // the article's author
6794
+ }
6795
+ ```
6796
+
6797
+ **D1**
6798
+
6799
+ ```sql
6800
+ CREATE TABLE authors (
6801
+ id TEXT PRIMARY KEY NOT NULL,
6802
+ name TEXT NOT NULL
6803
+ );
6804
+ CREATE TABLE articles (
6805
+ id TEXT PRIMARY KEY NOT NULL,
6806
+ author_id TEXT NOT NULL REFERENCES authors (id),
6807
+ title TEXT NOT NULL
6808
+ );
6809
+ CREATE TABLE tags (
6810
+ id INTEGER PRIMARY KEY,
6811
+ name TEXT NOT NULL
6812
+ );
6813
+ CREATE TABLE taggings (
6814
+ id INTEGER PRIMARY KEY,
6815
+ article_id TEXT NOT NULL REFERENCES articles (id),
6816
+ tag_id INTEGER NOT NULL REFERENCES tags (id)
6817
+ );
6818
+ ```
6819
+
6820
+ **Postgres**
6821
+
6822
+ ```sql
6823
+ CREATE TABLE authors (
6824
+ id UUID PRIMARY KEY,
6825
+ name TEXT NOT NULL
6826
+ );
6827
+ CREATE TABLE articles (
6828
+ id UUID PRIMARY KEY,
6829
+ author_id UUID NOT NULL REFERENCES authors (id),
6830
+ title TEXT NOT NULL
6831
+ );
6832
+ CREATE TABLE tags (
6833
+ id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
6834
+ name TEXT NOT NULL
6835
+ );
6836
+ CREATE TABLE taggings (
6837
+ id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
6838
+ article_id UUID NOT NULL REFERENCES articles (id),
6839
+ tag_id BIGINT NOT NULL REFERENCES tags (id)
6840
+ );
6841
+ ```
6842
+
6843
+ ## Reading records
6844
+
6845
+ Read a through association as you would any `hasMany`:
6846
+
6847
+ ```ts twoslash
6848
+ // @filename: models.ts
6849
+ import { belongsTo, hasMany, hasOne, Model } from "@forestfuture/active-record";
6850
+
6851
+ export class Author extends Model.define({
6852
+ id: { type: "string", null: false, generateId: true },
6853
+ name: { type: "string", null: false },
6854
+ }) {
6855
+ articles = hasMany(Article);
6856
+ }
6857
+
6858
+ export class Article extends Model.define({
6859
+ id: { type: "string", null: false, generateId: true },
6860
+ authorId: { type: "string", null: false },
6861
+ title: { type: "string", null: false },
6862
+ }) {
6863
+ author = belongsTo(Author);
6864
+ taggings = hasMany(Tagging);
6865
+ tags = hasMany(Tag, { through: "taggings" }); // each tagging's tag
6866
+ }
6867
+
6868
+ export class Tag extends Model.define({
6869
+ id: { type: "integer", null: false },
6870
+ name: { type: "string", null: false },
6871
+ }) {
6872
+ taggings = hasMany(Tagging);
6873
+ articles = hasMany(Article, { through: "taggings" }); // each tagging's article
6874
+ writers = hasMany(Author, { through: "articles", source: "author" }); // each article's author
6875
+ }
6876
+
6877
+ export class Tagging extends Model.define({
6878
+ id: { type: "integer", null: false },
6879
+ articleId: { type: "string", null: false },
6880
+ tagId: { type: "integer", null: false },
6881
+ }) {
6882
+ article = belongsTo(Article);
6883
+ tag = belongsTo(Tag);
6884
+ author = hasOne(Author, { through: "article" }); // the article's author
6885
+ }
6886
+
6887
+ // @filename: example.ts
6888
+ // ---cut---
6889
+ import { Article, Tag } from "./models";
6890
+
6891
+ const tag = await Tag.findByOrThrow({ name: "essays" });
6892
+ const articles = await tag.articles().order({ title: "asc" }).toArray(); // one query
6893
+
6894
+ const article = await Article.findByOrThrow({ title: "Engines" });
6895
+ const tags = await article.tags().toArray(); // the other way, through the same taggings
6896
+ ```
6897
+
6898
+ - `through` names one of the Model’s own associations, here `taggings`. The join Model’s association with the same name, singular or plural, leads on to the records: `articles` follows each tagging’s `article`.
6899
+ - `tag.articles()` is a Relation, with every Relation method, read in one query. Its writes go to the taggings, as [below](#writing-through-it).
6900
+ - Each record comes back once, however many join records point at it.
6901
+ - The scopes of both associations it goes through apply, and so does its own `scope`.
6902
+
6903
+ ## Preloading records
6904
+
6905
+ Preload the records for every tag with `includes`:
6906
+
6907
+ ```ts twoslash
6908
+ // @filename: models.ts
6909
+ import { belongsTo, hasMany, hasOne, Model } from "@forestfuture/active-record";
6910
+
6911
+ export class Author extends Model.define({
6912
+ id: { type: "string", null: false, generateId: true },
6913
+ name: { type: "string", null: false },
6914
+ }) {
6915
+ articles = hasMany(Article);
6916
+ }
6917
+
6918
+ export class Article extends Model.define({
6919
+ id: { type: "string", null: false, generateId: true },
6920
+ authorId: { type: "string", null: false },
6921
+ title: { type: "string", null: false },
6922
+ }) {
6923
+ author = belongsTo(Author);
6924
+ taggings = hasMany(Tagging);
6925
+ tags = hasMany(Tag, { through: "taggings" }); // each tagging's tag
6926
+ }
6927
+
6928
+ export class Tag extends Model.define({
6929
+ id: { type: "integer", null: false },
6930
+ name: { type: "string", null: false },
6931
+ }) {
6932
+ taggings = hasMany(Tagging);
6933
+ articles = hasMany(Article, { through: "taggings" }); // each tagging's article
6934
+ writers = hasMany(Author, { through: "articles", source: "author" }); // each article's author
6935
+ }
6936
+
6937
+ export class Tagging extends Model.define({
6938
+ id: { type: "integer", null: false },
6939
+ articleId: { type: "string", null: false },
6940
+ tagId: { type: "integer", null: false },
6941
+ }) {
6942
+ article = belongsTo(Article);
6943
+ tag = belongsTo(Tag);
6944
+ author = hasOne(Author, { through: "article" }); // the article's author
6945
+ }
6946
+
6947
+ // @filename: example.ts
6948
+ // ---cut---
6949
+ import { Tag } from "./models";
6950
+
6951
+ const everyTag = await Tag.includes("articles").toArray(); // tags, taggings, and articles
6952
+ for (const each of everyTag) console.log(each.name, each.loaded("articles").length);
6953
+ ```
6954
+
6955
+ The join records and the articles load with the tags’ own query, in one round trip on D1. The join records aren’t kept as `taggings` unless you include them too.
6956
+
6957
+ ## Naming the source
6958
+
6959
+ If the join Model’s association has another name, pass it as `source`, as `writers` does to follow each article’s `author`:
6960
+
6961
+ ```ts twoslash
6962
+ // @filename: models.ts
6963
+ import { belongsTo, hasMany, hasOne, Model } from "@forestfuture/active-record";
6964
+
6965
+ export class Author extends Model.define({
6966
+ id: { type: "string", null: false, generateId: true },
6967
+ name: { type: "string", null: false },
6968
+ }) {
6969
+ articles = hasMany(Article);
6970
+ }
6971
+
6972
+ export class Article extends Model.define({
6973
+ id: { type: "string", null: false, generateId: true },
6974
+ authorId: { type: "string", null: false },
6975
+ title: { type: "string", null: false },
6976
+ }) {
6977
+ author = belongsTo(Author);
6978
+ taggings = hasMany(Tagging);
6979
+ tags = hasMany(Tag, { through: "taggings" }); // each tagging's tag
6980
+ }
6981
+
6982
+ export class Tag extends Model.define({
6983
+ id: { type: "integer", null: false },
6984
+ name: { type: "string", null: false },
6985
+ }) {
6986
+ taggings = hasMany(Tagging);
6987
+ articles = hasMany(Article, { through: "taggings" }); // each tagging's article
6988
+ writers = hasMany(Author, { through: "articles", source: "author" }); // each article's author
6989
+ }
6990
+
6991
+ export class Tagging extends Model.define({
6992
+ id: { type: "integer", null: false },
6993
+ articleId: { type: "string", null: false },
6994
+ tagId: { type: "integer", null: false },
6995
+ }) {
6996
+ article = belongsTo(Article);
6997
+ tag = belongsTo(Tag);
6998
+ author = hasOne(Author, { through: "article" }); // the article's author
6999
+ }
7000
+
7001
+ // @filename: example.ts
7002
+ // ---cut---
7003
+ import { Tag } from "./models";
7004
+
7005
+ const tag = await Tag.findByOrThrow({ name: "essays" });
7006
+ const writers = await tag.writers().toArray(); // each author once
7007
+ ```
7008
+
7009
+ `writers` goes through `articles`, which goes through `taggings`. An association can go through any number of others this way.
7010
+
7011
+ ## Going through a belongsTo or a hasOne
7012
+
7013
+ A `hasOne` can go through a `belongsTo`, as a tagging’s `author` does through its `article`:
7014
+
7015
+ ```ts twoslash
7016
+ // @filename: models.ts
7017
+ import { belongsTo, hasMany, hasOne, Model } from "@forestfuture/active-record";
7018
+
7019
+ export class Author extends Model.define({
7020
+ id: { type: "string", null: false, generateId: true },
7021
+ name: { type: "string", null: false },
7022
+ }) {
7023
+ articles = hasMany(Article);
7024
+ }
7025
+
7026
+ export class Article extends Model.define({
7027
+ id: { type: "string", null: false, generateId: true },
7028
+ authorId: { type: "string", null: false },
7029
+ title: { type: "string", null: false },
7030
+ }) {
7031
+ author = belongsTo(Author);
7032
+ taggings = hasMany(Tagging);
7033
+ tags = hasMany(Tag, { through: "taggings" }); // each tagging's tag
7034
+ }
7035
+
7036
+ export class Tag extends Model.define({
7037
+ id: { type: "integer", null: false },
7038
+ name: { type: "string", null: false },
7039
+ }) {
7040
+ taggings = hasMany(Tagging);
7041
+ articles = hasMany(Article, { through: "taggings" }); // each tagging's article
7042
+ writers = hasMany(Author, { through: "articles", source: "author" }); // each article's author
7043
+ }
7044
+
7045
+ export class Tagging extends Model.define({
7046
+ id: { type: "integer", null: false },
7047
+ articleId: { type: "string", null: false },
7048
+ tagId: { type: "integer", null: false },
7049
+ }) {
7050
+ article = belongsTo(Article);
7051
+ tag = belongsTo(Tag);
7052
+ author = hasOne(Author, { through: "article" }); // the article's author
7053
+ }
7054
+
7055
+ // @filename: example.ts
7056
+ // ---cut---
7057
+ import { Tagging } from "./models";
7058
+
7059
+ const tagging = await Tagging.firstOrThrow();
7060
+ const author = await tagging.author();
7061
+ ```
7062
+
7063
+ `through` can name a `belongsTo`, a `hasMany`, or a `hasOne`, and the association it follows can be any of the three. A `hasOne` goes through a `belongsTo` or a `hasOne`.
7064
+
7065
+ ## Writing through it
7066
+
7067
+ Add records with `push`, `build`, and `create`, which each make the join record that links the owner to the record:
7068
+
7069
+ ```ts twoslash
7070
+ // @filename: models.ts
7071
+ import { belongsTo, hasMany, hasOne, Model } from "@forestfuture/active-record";
7072
+
7073
+ export class Author extends Model.define({
7074
+ id: { type: "string", null: false, generateId: true },
7075
+ name: { type: "string", null: false },
7076
+ }) {
7077
+ articles = hasMany(Article);
7078
+ }
7079
+
7080
+ export class Article extends Model.define({
7081
+ id: { type: "string", null: false, generateId: true },
7082
+ authorId: { type: "string", null: false },
7083
+ title: { type: "string", null: false },
7084
+ }) {
7085
+ author = belongsTo(Author);
7086
+ taggings = hasMany(Tagging);
7087
+ tags = hasMany(Tag, { through: "taggings" }); // each tagging's tag
7088
+ }
7089
+
7090
+ export class Tag extends Model.define({
7091
+ id: { type: "integer", null: false },
7092
+ name: { type: "string", null: false },
7093
+ }) {
7094
+ taggings = hasMany(Tagging);
7095
+ articles = hasMany(Article, { through: "taggings" }); // each tagging's article
7096
+ writers = hasMany(Author, { through: "articles", source: "author" }); // each article's author
7097
+ }
7098
+
7099
+ export class Tagging extends Model.define({
7100
+ id: { type: "integer", null: false },
7101
+ articleId: { type: "string", null: false },
7102
+ tagId: { type: "integer", null: false },
7103
+ }) {
7104
+ article = belongsTo(Article);
7105
+ tag = belongsTo(Tag);
7106
+ author = hasOne(Author, { through: "article" }); // the article's author
7107
+ }
7108
+
7109
+ // @filename: example.ts
7110
+ // ---cut---
7111
+ import { Article, Tag } from "./models";
7112
+
7113
+ const tag = await Tag.findByOrThrow({ name: "essays" });
7114
+ const article = await Article.findByOrThrow({ title: "Engines" });
7115
+
7116
+ await tag.articles().push(article); // saves a tagging that links them
7117
+ const draft = await tag.articles().create({ authorId: article.authorId, title: "Draft" });
7118
+
7119
+ await tag.articles().delete(article); // deletes the tagging; the article stays
7120
+ ```
7121
+
7122
+ - `push(article)` saves a tagging for each article, in one write. A new article is saved first.
7123
+ - `build(attributes)` builds the article and its tagging. Saving the tag saves both. Saving the article on its own saves no tagging.
7124
+ - `create(attributes)` saves the article, then its tagging. An invalid article comes back unsaved, and nothing is written.
7125
+
7126
+ On a tag that isn’t saved yet, `push` and `build` wait for the tag’s save. `create` throws `RecordNotSaved` there, as it does through a `hasMany`.
7127
+
7128
+ Records built or created through it take the equality values of its `scope`, and their join records take those of the association it goes through.
7129
+
7130
+ ## Removing records
7131
+
7132
+ Removing records through the association removes their join records. The records themselves stay:
7133
+
7134
+ | Method | Does |
7135
+ | ------------------ | --------------------------------------------------------------------------------------------------- |
7136
+ | `delete(article)` | Deletes the tag’s taggings to the article, without callbacks |
7137
+ | `destroy(article)` | Destroys those taggings, running their callbacks, in one write |
7138
+ | `clear()` | Deletes every tagging to the tag’s articles, without callbacks. The tag then has no articles loaded |
7139
+ | `deleteAll()` | Deletes the same taggings, and resolves to how many it deleted |
7140
+ | `destroyAll()` | Destroys the same taggings, running their callbacks, and resolves to the articles |
7141
+
7142
+ An article the tag doesn’t reach removes nothing. To remove an article itself, destroy it: `await article.destroy()`. In a batch, pass the association to the write: `b.deleteAll(tag.articles())` deletes the tag’s taggings.
7143
+
7144
+ :::warning[A narrowed deleteAll or destroyAll removes the records themselves]
7145
+ `updateAll`, and a narrowed `deleteAll` or `destroyAll`, act on the records, as any Relation’s do. `tag.articles().where({ title: "Draft" }).deleteAll()` deletes those articles for every tag, not the tag’s taggings.
7146
+ :::
7147
+
7148
+ ### Removing join records with dependent
7149
+
7150
+ A `hasMany` through a join Model takes `dependent: "destroy"` or `dependent: "deleteAll"`, which acts on its join records:
7151
+
7152
+ - With `"destroy"`, destroying the tag destroys its taggings, running their callbacks, and `delete` destroys them too.
7153
+ - With `"deleteAll"`, destroying the tag deletes them without callbacks.
7154
+ - `clear` and `deleteAll` always delete them without callbacks.
7155
+
7156
+ ## Setting a hasOne through another
7157
+
7158
+ A `hasOne` that goes through another `hasOne` has `set`, and no `build` or `create`:
7159
+
7160
+ - `set(record)` points the owner’s join record at the record, or creates the join record if there isn’t one, with the equality values of the join association’s `scope`.
7161
+ - `set(null)` destroys the join record.
7162
+
7163
+ ## Spotting read-only associations
7164
+
7165
+ Writes need a join Model: the association has to go through a `hasMany` (a `hasOne`, for a `hasOne`), and follow a `belongsTo` from there, with neither going through another. Any other write throws `ReadonlyAssociation`, naming the association that stops it. `writers` is read-only, since it goes through `articles`, which goes through `taggings`.
7166
+
7167
+ `insert`, `insertAll`, `upsert`, and `upsertAll` throw `ReadonlyAssociation` on any association through another, since they write no join records.
7168
+
7169
+ :::note
7170
+ Every association it goes through must be on one database. One that reaches [another database](/several-databases#associating-models-on-different-databases) is an `InvalidModel` for now ([#435](https://github.com/forestfuture/active-record/issues/435)).
7171
+ :::
7172
+
7173
+ > **Compared with Rails**
7174
+ >
7175
+ > `through` and `source` work as Rails’ `has_many :through` and `has_one :through` options do. Rails reads through a SQL join, so a record two join records point at comes back twice unless the association is `distinct`. Here it comes back once.
7176
+ >
7177
+ > Writing through it works as in Rails: `destroy` destroys the join records rather than the records, `clear` deletes them whatever `dependent` is, and `insert_all` through it raises. Rails also writes through a `belongsTo` or `hasOne` hop by building or updating that hop’s record, which can change a record that other records share. Here that throws `ReadonlyAssociation`. Rails’ `disable_joins` has no counterpart yet.
7178
+
7179
+ ---
7180
+
6247
7181
  # Untrusted input
6248
7182
  Source: https://active-record.forestfuture.dev/untrusted-input
6249
7183
 
6250
- A request can send any fields it likes. Pick the ones you want before they reach a Model.
6251
-
6252
7184
  ## Permitting fields
6253
7185
 
6254
7186
  Only permit the fields you want from a request:
@@ -6346,8 +7278,6 @@ An association’s link to its owner always stays. `user.posts().rewhere({ userI
6346
7278
  # Upgrading
6347
7279
  Source: https://active-record.forestfuture.dev/upgrading
6348
7280
 
6349
- Each section moves an app up one release. Start from the release you’re on.
6350
-
6351
7281
  ## Upgrading from 0.7 to 0.8
6352
7282
 
6353
7283
  In 0.8, a `belongsTo` requires its record, a batch prepares its writes in a callback, a new record’s changes run from its defaults, a `hasOne`’s new record replaces its old one, a `hasMany` gives its records its own key, a bulk write gives its Relation’s values over yours, the generated schema is a `defineSchema` call and reads a `DATE` column as a `date`, and `serialize` can give bytes. Upgrade in nine steps.
@@ -6563,8 +7493,6 @@ It also applies migrations through your project’s Wrangler, with `npx active-r
6563
7493
  # Validations
6564
7494
  Source: https://active-record.forestfuture.dev/validations
6565
7495
 
6566
- Validations check a record before it’s saved. An invalid record isn’t saved, and its `errors` say why.
6567
-
6568
7496
  ## Declaring validations
6569
7497
 
6570
7498
  Declare validations in a Model’s `static {}` block with `this.validates`:
@@ -6947,6 +7875,8 @@ export class Product extends ApplicationRecord {
6947
7875
  Each message is looked up when you read it:
6948
7876
 
6949
7877
  ```ts
7878
+ import { Product } from "./models";
7879
+
6950
7880
  const product = Product.build({ name: "", priceCents: 0 });
6951
7881
  await product.isValid(); // false
6952
7882