@forestfuture/active-record 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/llms-full.txt CHANGED
@@ -412,12 +412,13 @@ Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for
412
412
  - Start queries and new records from the Model, as in Rails: `User.find(id)`, `User.where(…)`, `User.build(…)`. Each Model queries the binding named in the generated schema its base class holds, during a request. For a D1 Session, wrap the handler in `withSession(request, env.DB, fn)`. For per-request `onQuery`, or tests and scripts outside a Worker, wrap the code once in `withDatabase(connect(env.DB, { … }), fn)`. Records keep the database they came from.
413
413
  - Never pass a request's whole body, form or query string to a Model: name the fields, with destructuring or `User.permit(await request.json(), "email", "name")` (it reads `FormData` and `URLSearchParams` too). Assigned values are checked against the attribute's type, but that doesn't stop a user setting `role` or `isAdmin`. Check a request value's type before querying with it: `findBy({ token: null })` matches rows whose token is NULL, and a list matches any of its values. `findOrCreateBy`, `findOrInitializeBy` and `createOrFindBy` throw `TypeError` for a list, a comparison or a `sql` fragment.
414
414
  - Name attributes in camelCase everywhere: `where`, `order`, `pluck`, `foreignKey`. Column names (snake_case) appear only inside `sql` fragments.
415
- - Write custom SQL as an `sql` tagged template, which binds every value: ``where(sql`lower(${column("email")}) = ${email}`)``. Interpolate an attribute's value with `column("publishedAt").value(date)`, not the bare `Date`, when the attribute is stored as a Unix time: a bare `Date` is ISO text, and it throws `TypeError` when it's compared directly with that column.
415
+ - Write custom SQL as an `sql` tagged template, which binds every value: ``where(sql`lower(${column("email")}) = ${email}`)``. Interpolate an attribute's value with `column("publishedAt").value(date)`, not the bare `Date`, when the attribute is stored as a Unix time: a bare `Date` is ISO text, and it throws `TypeError` when it's compared directly with that column. `column()` works only inside a fragment: `where({ views: column("likes") })` and `updateAll({ views: column("likes") })` throw, as do one nested in a json value and one given as `find`'s id, so write ``where(sql`${column("views")} = ${column("likes")}`)``.
416
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`.
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.
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). `upsert(…, { uniqueBy: "email", updateOnly: ["name"] })` updates only `name` on a clash; ``upsertAll(rows, { uniqueBy: "name", onDuplicate: { count: sql`${column("count")} + ${incoming("count")}` } })`` sets each named attribute to a fragment (`column()` the clashing row's value, `incoming()` the new row's) or a value. 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.
418
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
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.
420
420
  - To stop two edits of one record from overwriting each other, add a `lock_version INTEGER NOT NULL DEFAULT 0` column: every save, destroy and `touch()` then checks the row still has the record's `lockVersion`, and a stale copy's throws `StaleRecord` (from `save()` too, not `false`) and writes nothing in its batch (a destroy's dependents on another database are already gone). For edits across requests, put `lockVersion` in the form as a hidden field and permit it with the other fields, and answer `StaleRecord` with a 409; to retry in code, `await record.reload()` and make the change again. A child's `touch` on a locked parent raises the parent's version, so a parent its children touch often gets conflicts: drop the `touch` or write the children inside `noTouching`.
421
+ - For records a request reads but must not write (a public page, a report), load them with `readonly()` (`Article.readonly().where(…)`) or call `record.markReadonly()`: a save, update, destroy, `touch()` or column write then throws `ReadonlyRecord` before anything runs. Bulk writes (`updateAll`, `deleteAll`) ignore the mark. For an attribute set once on create, such as a slug, declare `slug: { readonly: true }` in the Model's `static attributes`: changing it on a saved record throws `ReadonlyAttribute`, and posting back the value it holds is fine, so an edit form needn't leave it out.
421
422
  - 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`.
422
423
  - 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`.
423
424
  - 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()`.
@@ -780,7 +781,7 @@ Declare each association as a field, passing the target Model’s class, as the
780
781
  - Models can refer to each other in any order.
781
782
  - A subclass inherits its parent’s associations, and can redeclare one to change it.
782
783
 
783
- ## belongsTo
784
+ ## Using `belongsTo`
784
785
 
785
786
  Use `belongsTo` on the Model whose table holds the foreign key, as an article belongs to its author:
786
787
 
@@ -808,7 +809,7 @@ await article.save();
808
809
  | `scope` | Narrows the target, `(q) => q.where(…)`. See [Scoping associations](#scoping-associations) |
809
810
  | `optional` | Lets the record point at nothing. See [Requiring the record](#requiring-the-record) |
810
811
  | `autosave` | `true` saves the record’s changes with this record. See [Saving changed records](/autosaving#saving-changed-records) |
811
- | `inverseOf` | The target’s `hasOne` that points back, or `false`. See [Inverse associations](#inverse-associations) |
812
+ | `inverseOf` | The target’s `hasOne` that points back, or `false`. See [Inverse associations](#using-inverse-associations) |
812
813
 
813
814
  ## Requiring the record
814
815
 
@@ -818,7 +819,7 @@ Saving a record checks that each `belongsTo` points at a record that exists, unl
818
819
  - A saved record whose foreign key hasn’t changed isn’t checked again.
819
820
  - A record built through a `hasMany` or `hasOne` already points at its owner, so it passes the check before either is saved. See [Autosaving](/autosaving#saving-a-graph).
820
821
 
821
- ## hasMany
822
+ ## Using `hasMany`
822
823
 
823
824
  Use `hasMany` on the Model the other table’s foreign key points at, as an author has many articles:
824
825
 
@@ -850,9 +851,9 @@ await author.articles().where({ title: "Untitled" }).deleteAll(); // scoped to t
850
851
  | `scope` | Narrows or orders the records, `(q) => q.order(…)`. See [Scoping associations](#scoping-associations) |
851
852
  | `dependent` | What destroying the owner does to the records. See [Destroying dependent records](#destroying-dependent-records) |
852
853
  | `autosave` | `true` saves the records’ changes with the owner. See [Saving changed records](/autosaving#saving-changed-records) |
853
- | `inverseOf` | The target’s `belongsTo` that points back, or `false`. See [Inverse associations](#inverse-associations) |
854
+ | `inverseOf` | The target’s `belongsTo` that points back, or `false`. See [Inverse associations](#using-inverse-associations) |
854
855
 
855
- ## hasOne
856
+ ## Using `hasOne`
856
857
 
857
858
  Use `hasOne` like `hasMany`, when there’s at most one record, as an author has one profile:
858
859
 
@@ -893,7 +894,7 @@ await author.profile.set(Profile.build({ bio: "Novelist" })); // and deletes the
893
894
  - If the old record can’t be saved with a `NULL` foreign key, the write throws `RecordNotSaved`, and nothing is written.
894
895
  - If the new record doesn’t save, the old one stays. `set` throws `RecordNotSaved` and leaves the association as it was. `create` returns the unsaved record, and saving the owner tries again.
895
896
 
896
- ## Polymorphic associations
897
+ ## Using a polymorphic `belongsTo`
897
898
 
898
899
  A polymorphic `belongsTo` points at a record of any of several Models, listed in an array, as a like belongs to a photo or a video:
899
900
 
@@ -962,7 +963,7 @@ const again = await article.author(); // none: it's cached on the article
962
963
  - A write made another way, such as `Article.where({ authorId: author.id }).deleteAll()`, doesn’t touch a loaded collection: reload the association to see it.
963
964
  - A `belongsTo` whose foreign key is `null`, or an association on an unsaved owner, reads without a query.
964
965
 
965
- ## Inverse associations
966
+ ## Using inverse associations
966
967
 
967
968
  A record loaded through its owner’s `hasMany` or `hasOne` has the owner loaded already, so reading it back sends no query:
968
969
 
@@ -1768,6 +1769,8 @@ Source: https://active-record.forestfuture.dev/batches
1768
1769
  | update or delete every row a Relation finds | `updateAll({ … })`, `deleteAll()`, `deleteBy({ … })` |
1769
1770
  | insert rows without loading records | `insert({ … })`, `insertAll([…])` |
1770
1771
  | insert, or update a row that clashes | `upsert({ … }, { uniqueBy: "email" })`, `upsertAll([…])` |
1772
+ | update only some attributes on a clash | `upsertAll([…], { updateOnly: ["name"] })` |
1773
+ | update a clashing row with your own SQL | ``upsertAll([…], { onDuplicate: { name: sql`…` } })`` |
1771
1774
  | get attributes back from an insert | `{ returning: ["id", "body"] }` |
1772
1775
  | write several statements atomically | `batch((b) => [b.insert(…), b.updateAll(…)])` |
1773
1776
  | save or destroy records in that batch | `b.save(record)`, `b.destroy(record)` |
@@ -1931,6 +1934,7 @@ To run each record’s callbacks, destroy the records with [`destroyAll`](/persi
1931
1934
  Insert many rows at once with `insertAll`:
1932
1935
 
1933
1936
  ```ts
1937
+ import { column, incoming, sql } from "@forestfuture/active-record";
1934
1938
  import { Article } from "./models/article";
1935
1939
  import { Author } from "./models/author";
1936
1940
  import { Comment } from "./models/comment";
@@ -1941,12 +1945,25 @@ await Comment.insertAll([
1941
1945
  { articleId: article.id, body: "Two" },
1942
1946
  ]);
1943
1947
  await Author.upsert({ name: "Jane Doe", email: "jane@example.com" }, { uniqueBy: "email" }); // renames Jane
1948
+ await Author.upsert(
1949
+ { id: crypto.randomUUID(), name: "Jane Smith", email: "jane@example.com" },
1950
+ { uniqueBy: "email", updateOnly: "name" },
1951
+ ); // renames Jane, keeping her id
1952
+ await Author.upsert(
1953
+ { name: "J. Smith", email: "jane@example.com" },
1954
+ {
1955
+ uniqueBy: "email",
1956
+ onDuplicate: { name: sql`${column("name")} || ' / ' || ${incoming("name")}` },
1957
+ },
1958
+ ); // Jane Smith / J. Smith
1944
1959
  await Author.insert({ name: "Jane", email: "jane@example.com" }, { onDuplicate: "skip" }); // writes nothing
1945
1960
  ```
1946
1961
 
1947
1962
  - **`insertAll(rows)`** inserts every row, however many. Every row must have the same attributes. A duplicate throws and writes nothing.
1948
1963
  - **`{ onDuplicate: "skip" }`** skips rows that clash with a unique index.
1949
- - **`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.
1964
+ - **`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 when a value changes. A row with nothing to update is left alone, and isn’t counted or returned.
1965
+ - **`{ updateOnly: ["name"] }`** updates only the attributes it names when a row clashes. The others keep their values. Each row must give every attribute it names. A row’s own `updatedAt` is written only when it’s named, or when a named attribute changes.
1966
+ - **``{ onDuplicate: { name: sql`…` } }``** sets each attribute it names to an `sql` fragment or a value when a row clashes. In a fragment, `column("name")` is the clashing row’s value and `incoming("name")` is the new row’s. The others keep their values. `updatedAt` is set when a value changes. To see whether a value changes, each fragment runs twice. Name `updatedAt` yourself to run a fragment with side effects once. You can’t give `updateOnly` with it.
1950
1967
  - **Through a Relation**, `insertAll`, `upsert`, and `upsertAll` write its equality conditions over each row’s values, as `insert` does.
1951
1968
  - **Through a `hasMany`**, an upsert only updates the owner’s records. A row that clashes with another owner’s record isn’t written, counted, or returned. See [Writing many rows](/associations#writing-many-rows).
1952
1969
 
@@ -1976,7 +1993,7 @@ await Comment.insert({ articleId: article.id, body: "Three" }, { returning: fals
1976
1993
 
1977
1994
  > **Compared with Rails**
1978
1995
  >
1979
- > These are Rails’ `insert_all`, `upsert_all`, `update_all`, and `delete_all`, with two differences. Declared defaults fill what an insert isn’t given, since on D1 defaults are where keys are generated. And skipping duplicates is something you opt in to, so an insert’s duplicate is never silently lost. The `returning` option works as Rails’ does.
1996
+ > These are Rails’ `insert_all`, `upsert_all`, `update_all`, and `delete_all`, with two differences. Declared defaults fill what an insert isn’t given, since on D1 defaults are where keys are generated. And skipping duplicates is something you opt in to, so an insert’s duplicate is never silently lost. The `returning` option works as Rails’ does, `updateOnly` is Rails’ `update_only`, and `onDuplicate` is Rails’ `on_duplicate`, given for each attribute rather than as one SQL string.
1980
1997
 
1981
1998
  ## Batching writes
1982
1999
 
@@ -3042,6 +3059,7 @@ The generators follow `rails generate model` and `rails generate migration`. A c
3042
3059
  - `dependent:` strategies run after the owner’s `beforeDestroy` callbacks, wherever they’re declared, so an `abort()` always protects the records.
3043
3060
  - Records in a batch run all their before-callbacks before any write, and their after-callbacks after all of them.
3044
3061
  - Scopes preloaded with `limit` throw, where Rails silently gives wrong results.
3062
+ - The query cache is on only inside `withDatabase`, and a Model’s queries on the binding alone are never cached. `db.clearRequestCache()` is `clear_query_cache`, and `connect(env.DB, { cache: { request: false } })` turns it off. See [Caching identical reads](/connecting#caching-identical-reads).
3045
3063
 
3046
3064
  ## Not built yet
3047
3065
 
@@ -3564,6 +3582,8 @@ const email = "Jane@Example.com";
3564
3582
  const user = await User.findBy(sql`lower(${column("email")}) = lower(${email})`);
3565
3583
  ```
3566
3584
 
3585
+ To compare two columns, write both in a fragment: ``where(sql`${column("updatedAt")} > ${column("createdAt")}`)``.
3586
+
3567
3587
  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)`:
3568
3588
 
3569
3589
  ```ts
@@ -3642,11 +3662,11 @@ Source: https://active-record.forestfuture.dev/connecting
3642
3662
 
3643
3663
  Most apps only use the binding.
3644
3664
 
3645
- | | How | Use it for |
3646
- | -------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------- |
3647
- | **The binding** | `User.find(id)`, with nothing to set up | Everyday queries |
3648
- | **The request’s database** | `withDatabase(connect(env.DB, …), fn)`, once per request | Read replicas with a Session, per-request `onQuery` logging, tests, and scripts |
3649
- | **An explicit database** | `connect(env.DB).model(User).find(id)` | Code that passes its database around, or uses two at once |
3665
+ | | How | Use it for |
3666
+ | -------------------------- | -------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
3667
+ | **The binding** | `User.find(id)`, with nothing to set up | Everyday queries |
3668
+ | **The request’s database** | `withDatabase(connect(env.DB, …), fn)`, once per request | Caching identical reads, read replicas with a Session, per-request `onQuery` logging, tests, and scripts |
3669
+ | **An explicit database** | `connect(env.DB).model(User).find(id)` | Code that passes its database around, or uses two at once |
3650
3670
 
3651
3671
  [Database resolution](/query-databases) explains why there are three, and [which one you need](/query-databases#which-do-i-need).
3652
3672
 
@@ -3803,6 +3823,69 @@ These pages use a request’s database:
3803
3823
  - **[Testing](/testing):** a database for Models outside a Worker.
3804
3824
  - **[Multiple databases](/several-databases):** `withDatabase([...])`, matched to each Model’s binding.
3805
3825
 
3826
+ ## Caching identical reads
3827
+
3828
+ Inside `withDatabase`, a read you’ve already sent is answered from memory, with no round trip:
3829
+
3830
+ ```ts
3831
+ import { withDatabase } from "@forestfuture/active-record";
3832
+ import { connect } from "@forestfuture/active-record/d1";
3833
+ import { User } from "./models/user";
3834
+
3835
+ export async function findTwice(env: Env) {
3836
+ return withDatabase(connect(env.DB), async () => {
3837
+ const user = await User.findByOrThrow({ email: "jane@example.com" }); // sent
3838
+ const again = await User.findByOrThrow({ email: "jane@example.com" }); // answered from memory
3839
+ return [user, again] as const;
3840
+ });
3841
+ }
3842
+ ```
3843
+
3844
+ - Each answer is new records, so changing one changes no other.
3845
+ - Any write Active Record sends inside the call clears the cache: a save, a destroy, a bulk write, or a batch, through any database handle. So a request always reads its own writes.
3846
+ - `reload()` always reads the database, and clears the cache too.
3847
+ - The cache ends with the `withDatabase` call. Requests never share it.
3848
+ - It keeps the 100 answers used last. [Batch iteration](/batch-iteration) doesn’t keep its batches, so walking a big table doesn’t fill it.
3849
+ - [`onQuery`](/logging#seeing-a-cached-answer) hears each cached answer, with `cached: true`.
3850
+
3851
+ :::note[Caching needs `withDatabase`]
3852
+ A Model’s queries outside `withDatabase` use the binding, which every request running at once shares, so they’re never cached. To cache a request’s reads, run it inside `withDatabase`, as the example does.
3853
+ :::
3854
+
3855
+ To send every read, turn the cache off:
3856
+
3857
+ ```ts
3858
+ import { connect } from "@forestfuture/active-record/d1";
3859
+
3860
+ export function uncachedDatabase(env: Env) {
3861
+ return connect(env.DB, { cache: { request: false } }); // every read is sent
3862
+ }
3863
+ ```
3864
+
3865
+ ### Clearing the cache
3866
+
3867
+ Active Record only sees the writes it sends. After SQL you send on the binding yourself, clear the cache with `clearRequestCache()`:
3868
+
3869
+ ```ts
3870
+ import { withDatabase } from "@forestfuture/active-record";
3871
+ import { connect } from "@forestfuture/active-record/d1";
3872
+ import { Post } from "./models/post";
3873
+
3874
+ export async function renamePost(env: Env, id: string) {
3875
+ const db = connect(env.DB);
3876
+ return withDatabase(db, async () => {
3877
+ const post = await Post.find(id);
3878
+ await env.DB.prepare("UPDATE posts SET title = ? WHERE id = ?").bind("Hello again", id).run();
3879
+ db.clearRequestCache(); // the UPDATE didn't go through Active Record
3880
+ return Post.find(post.id); // sent, so it reads "Hello again"
3881
+ });
3882
+ }
3883
+ ```
3884
+
3885
+ > **Compared with Rails**
3886
+ >
3887
+ > This is Rails’ query cache. Rails turns it on for each request with its executor; here `withDatabase` does. `clearRequestCache()` is `clear_query_cache`, and `cache: { request: false }` stands in for `uncached`. Like Rails, it keeps 100 answers, dropping the least recently used.
3888
+
3806
3889
  ## Using an explicit database
3807
3890
 
3808
3891
  Start a query from a database you hold with `db.model`. It ignores `withDatabase`:
@@ -3830,7 +3913,7 @@ export async function listPosts(env: Env) {
3830
3913
  }
3831
3914
  ```
3832
3915
 
3833
- `connect(env.DB, { session, onQuery })` takes the same options as a request’s database.
3916
+ `connect(env.DB, { session, onQuery, cache })` takes the same options as a request’s database.
3834
3917
 
3835
3918
  ## Batching writes
3836
3919
 
@@ -3880,7 +3963,7 @@ local> const admins = await User.where({ role: "admin" }).toArray()
3880
3963
 
3881
3964
  Leave with `quit`, `exit`, or Ctrl-D. Ctrl-C stops a line that’s still running. `.help` lists the console’s own commands, and `npx active-record c` is the short form.
3882
3965
 
3883
- ## What you can use
3966
+ ## Using your Models and `db`
3884
3967
 
3885
3968
  - **Your Models,** by class name, from every file in `src/models`. They query your database, local unless you pass `--remote`, with no `db` to pass.
3886
3969
  - **`db`,** your connected database, for `db.batch(...)` and `db.model(...)`.
@@ -3939,7 +4022,7 @@ The SQL comes from the database’s own `onQuery`, so a listener you set on your
3939
4022
  | `--yes` | With `--remote`, don’t ask first. It’s also how to open it without a terminal. |
3940
4023
  | `--history` | Keep what you type in a remote session, which isn’t kept unless you ask. |
3941
4024
 
3942
- ## Where your data lives
4025
+ ## Finding your local data
3943
4026
 
3944
4027
  The console opens the local database in `.wrangler/state`, beside your Wrangler config. It’s the same one `wrangler dev` and `wrangler d1 migrations apply --local` use, so apply your migrations first, and what you change in the console is what your dev server sees. With [`wranglerConfig`](/command-line#declaring-your-databases), it’s beside the config that setting names.
3945
4028
 
@@ -5088,17 +5171,19 @@ export async function showUser(id: string): Promise<Response> {
5088
5171
 
5089
5172
  ## Lifecycle errors
5090
5173
 
5091
- | Error | When |
5092
- | ----------------------- | ------------------------------------------------------------------------- |
5093
- | `RecordNotFound` | `find`, `sole`, an `OrThrow` finder, or `reload` found nothing |
5094
- | `SoleRecordExceeded` | `sole` or `findSoleBy` found more than one record |
5095
- | `RecordInvalid` | an `OrThrow` save found the record invalid; the record is on `.record` |
5096
- | `RecordNotSaved` | a save was aborted by a callback, or needs an owner that isn’t saved |
5097
- | `RecordNotDestroyed` | a destroy was aborted, or restricted by `restrictWithError` |
5098
- | `RecordDestroyed` | writing to a record that’s already destroyed |
5099
- | `StaleRecord` | a [locked](/optimistic-locking) record’s row changed since it was loaded |
5100
- | `CallbackAbort` | what `abort()` makes; caught by the lifecycle |
5101
- | `AbortAfterPersistence` | `abort()` in an after-callback, too late to stop the write (`.callback`) |
5174
+ | Error | When |
5175
+ | ----------------------- | ------------------------------------------------------------------------------------------- |
5176
+ | `RecordNotFound` | `find`, `sole`, an `OrThrow` finder, or `reload` found nothing |
5177
+ | `SoleRecordExceeded` | `sole` or `findSoleBy` found more than one record |
5178
+ | `RecordInvalid` | an `OrThrow` save found the record invalid; the record is on `.record` |
5179
+ | `RecordNotSaved` | a save was aborted by a callback, or needs an owner that isn’t saved |
5180
+ | `RecordNotDestroyed` | a destroy was aborted, or restricted by `restrictWithError` |
5181
+ | `RecordDestroyed` | writing to a record that’s already destroyed |
5182
+ | `StaleRecord` | a [locked](/optimistic-locking) record’s row changed since it was loaded |
5183
+ | `ReadonlyRecord` | writing a [read-only](/read-only) record; what was refused is on `.action` |
5184
+ | `ReadonlyAttribute` | changing a saved record’s [read-only](/read-only#declaring-read-only-attributes) attribute |
5185
+ | `CallbackAbort` | what `abort()` makes; caught by the lifecycle |
5186
+ | `AbortAfterPersistence` | `abort()` in an after-callback, too late to stop the write (`.callback`) |
5102
5187
 
5103
5188
  ## Usage errors
5104
5189
 
@@ -5759,6 +5844,7 @@ Source: https://active-record.forestfuture.dev/logging
5759
5844
  | log one request’s queries, with its ID | `withDatabase(connect(env.DB, { onQuery }), …)` |
5760
5845
  | send the database time to the browser | add up `durationMs` into a `Server-Timing` header |
5761
5846
  | keep more attributes out of the logs | `static override filterAttributes = [...Model.filterAttributes, "iban"]` |
5847
+ | tell a cached read from a sent one | `event.cached` |
5762
5848
 
5763
5849
  ## The Models
5764
5850
 
@@ -5858,6 +5944,7 @@ An `onQuery` listener is called once for every statement, writes and batches inc
5858
5944
  | `durationMs` | How long it took; in a D1 batch, D1’s own timing for each statement |
5859
5945
  | `meta` | The database’s result metadata, such as D1’s rows read and written |
5860
5946
  | `error` | The database’s error, when it failed |
5947
+ | `cached` | `true` when the read was answered from memory |
5861
5948
 
5862
5949
  Send these wherever you like. A listener never changes a query’s outcome: one that throws is logged with `console.error`, and the query’s result stands.
5863
5950
 
@@ -5870,6 +5957,10 @@ Set a listener in one of two places:
5870
5957
 
5871
5958
  If both are set, the request’s listener runs first, then the base class’s.
5872
5959
 
5960
+ ### Seeing a cached answer
5961
+
5962
+ Inside `withDatabase`, a read you’ve already sent is answered from the [request cache](/connecting#caching-identical-reads), and your listener still hears it. Its event has `cached: true`, a `durationMs` of 0, and no `meta`, since nothing reached the database.
5963
+
5873
5964
  ## Logging every query
5874
5965
 
5875
5966
  Set `onQuery` on your app’s base class, in `application-record.ts`, to see every statement of every Model:
@@ -9005,6 +9096,10 @@ export async function paidSince(db: D1Database, since: Date) {
9005
9096
 
9006
9097
  For a cache key, or the value a test expects of a raw row, `serialize` gives the stored form too.
9007
9098
 
9099
+ :::warning[Your writes don’t clear the request cache]
9100
+ Inside `withDatabase`, Active Record answers a read it has already sent from memory. It can’t see SQL you send yourself, so after a raw write, call `db.clearRequestCache()` before reading again. See [Clearing the cache](/connecting#clearing-the-cache).
9101
+ :::
9102
+
9008
9103
  ## Reading cells
9009
9104
 
9010
9105
  Turn a cell from a raw query into the attribute’s value with `deserialize`:
@@ -9040,6 +9135,212 @@ export async function paidAt(db: D1Database, id: number) {
9040
9135
 
9041
9136
  ---
9042
9137
 
9138
+ # Read-only records
9139
+ Source: https://active-record.forestfuture.dev/read-only
9140
+
9141
+ ## At a glance
9142
+
9143
+ | To | Write |
9144
+ | --------------------------------------- | ---------------------------------------------------------- |
9145
+ | load records that can’t be saved | `Article.readonly().toArray()` |
9146
+ | make one record read-only | `article.markReadonly()` |
9147
+ | ask whether a record is read-only | `article.isReadonly()` |
9148
+ | catch a refused write | `catch (error) { if (error instanceof ReadonlyRecord) … }` |
9149
+ | set an attribute only when it’s created | `slug: { readonly: true }` in the Model’s `attributes` |
9150
+
9151
+ ## The Model
9152
+
9153
+ The examples use this Model, whose attributes come from its table through the schema `active-record schema` generates:
9154
+
9155
+ ```ts article.ts
9156
+ import { ApplicationRecord } from "./application-record";
9157
+
9158
+ export class Article extends ApplicationRecord {
9159
+ static override attributes = {
9160
+ slug: { readonly: true }, // set when the article is created, never changed after
9161
+ } as const;
9162
+ }
9163
+ ```
9164
+
9165
+ ```ts schema.ts
9166
+ // Generated by `active-record schema` from migrations/ — don't edit.
9167
+ // schema: df347ceeec61
9168
+
9169
+ import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
9170
+ import { d1 } from "@forestfuture/active-record/d1";
9171
+
9172
+ /** articles — last changed by 0001_create_articles.sql */
9173
+ export const articles = {
9174
+ id: { type: "string", null: false, generateId: true },
9175
+ title: { type: "string", null: false },
9176
+ slug: { type: "string", null: false },
9177
+ body: "string",
9178
+ updatedAt: "datetime",
9179
+ } as const;
9180
+
9181
+ /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
9182
+ export const schema = defineSchema({
9183
+ adapter: d1({ binding: "DB" }),
9184
+ tables: {
9185
+ articles: { attributes: articles, primaryKey: "id" },
9186
+ },
9187
+ models: { Article: "articles" },
9188
+ });
9189
+
9190
+ declare module "../models/article" {
9191
+ interface Article extends TableAttributes<typeof articles, (typeof Article)["attributes"]> {}
9192
+ }
9193
+ ```
9194
+
9195
+ ```sql D1
9196
+ CREATE TABLE articles (
9197
+ id TEXT PRIMARY KEY NOT NULL,
9198
+ title TEXT NOT NULL,
9199
+ slug TEXT NOT NULL UNIQUE,
9200
+ body TEXT,
9201
+ updated_at DATETIME
9202
+ );
9203
+ ```
9204
+
9205
+ ```sql Postgres
9206
+ CREATE TABLE articles (
9207
+ id UUID PRIMARY KEY,
9208
+ title TEXT NOT NULL,
9209
+ slug TEXT NOT NULL UNIQUE,
9210
+ body TEXT,
9211
+ updated_at TIMESTAMPTZ
9212
+ );
9213
+ ```
9214
+
9215
+ ## Loading read-only records
9216
+
9217
+ Call `readonly()` on a query, and the records it loads can’t be saved:
9218
+
9219
+ ```ts
9220
+ import { Article } from "./models/article";
9221
+
9222
+ const articles = await Article.readonly().order({ title: "asc" }).toArray();
9223
+ console.log(articles[0]?.isReadonly()); // true
9224
+
9225
+ const article = await Article.readonly().findByOrThrow({ slug: "hello" });
9226
+ article.title = "Hello, world";
9227
+ await article.save(); // throws ReadonlyRecord, and sends nothing
9228
+ ```
9229
+
9230
+ - Every way a query loads records marks them: `toArray()`, `find`, `findBy`, `first`, `sole`, `findEach`, and the rest.
9231
+ - Chaining keeps it, and so does `merge`. A scope, a default scope, or an association’s `scope` can call it too. `readonly(false)` undoes it.
9232
+ - The records `includes` preloads aren’t read-only, unless an association’s `scope` calls `readonly()`. Records the query builds or creates aren’t read-only either.
9233
+
9234
+ ## Marking one record
9235
+
9236
+ `markReadonly()` makes a record you already have read-only:
9237
+
9238
+ ```ts
9239
+ import { Article } from "./models/article";
9240
+
9241
+ const article = await Article.findByOrThrow({ slug: "hello" });
9242
+ article.markReadonly();
9243
+
9244
+ console.log(article.isReadonly()); // true
9245
+ await article.destroy(); // throws ReadonlyRecord, and the article stays
9246
+ ```
9247
+
9248
+ A read-only record can still change in memory, and `reload()` still reads its row. It stays read-only.
9249
+
9250
+ ## Refusing writes
9251
+
9252
+ Saving, updating, destroying, or touching a read-only record throws `ReadonlyRecord`, and so do `updateColumns`, `updateColumn`, `incrementColumn`, `decrementColumn`, and `toggleColumn`:
9253
+
9254
+ ```ts
9255
+ import { ReadonlyRecord } from "@forestfuture/active-record";
9256
+ import { Article } from "./models/article";
9257
+
9258
+ const article = await Article.findByOrThrow({ slug: "hello" });
9259
+ article.markReadonly();
9260
+ try {
9261
+ await article.touch();
9262
+ } catch (error) {
9263
+ if (!(error instanceof ReadonlyRecord)) throw error;
9264
+ console.log(error.action); // "touch"
9265
+ }
9266
+ ```
9267
+
9268
+ - It throws before validation or any callback runs, and sends nothing.
9269
+ - `save()` throws too, rather than returning `false`.
9270
+ - The error’s `record` is the refused record, and its `action` names what was refused: `"save"`, `"destroy"`, `"touch"`, or the column method.
9271
+ - A write that would reach a read-only record through another throws too, and writes nothing. Saving an owner that [autosaves](/autosaving) a changed read-only record, a [batch](/batches) holding one, and a has-many’s `push` throw before any callback runs. So does a write that would [touch](/touching) a loaded read-only record.
9272
+ - Some records are only loaded partway through a write: the record a has-one’s new record replaces, and a `dependent: "destroy"` association’s records. A read-only one throws once it’s loaded, after the owner’s before-callbacks, and nothing is written.
9273
+
9274
+ ## Writing past it
9275
+
9276
+ Bulk writes don’t load records, so `readonly()` doesn’t stop them:
9277
+
9278
+ ```ts
9279
+ import { Article } from "./models/article";
9280
+
9281
+ const updated = await Article.readonly().where({ slug: "hello" }).updateAll({ body: "" });
9282
+ console.log(updated); // 1: a bulk write doesn't load records, so it isn't refused
9283
+ ```
9284
+
9285
+ `updateAll`, `deleteAll`, `insert`, and `upsert` all write as usual. So do the removals that work like them: `dependent: "delete"`, a has-one replacement whose `dependent` is `"delete"`, and a has-many’s `delete()` and `clear()`.
9286
+
9287
+ ## Declaring read-only attributes
9288
+
9289
+ Give an attribute `readonly: true`, and it’s written when its record is created, then never changed by it:
9290
+
9291
+ ```ts
9292
+ import { Article } from "./models/article";
9293
+
9294
+ const article = await Article.create({ title: "Getting started", slug: "getting-started" });
9295
+ console.log(article.slug); // "getting-started"
9296
+
9297
+ article.slug = "first-steps"; // throws ReadonlyAttribute: it's set when it's created
9298
+ ```
9299
+
9300
+ - Assigning a saved record a new value throws `ReadonlyAttribute` straight away, whether you assign it, `update()` it, or write it with `updateColumns`. The error’s `attribute` names it.
9301
+ - Pointing a belongs-to at another record throws `ReadonlyAttribute` when its read-only foreign key would change. So does saving a record whose read-only foreign key a new record would fill once it’s inserted.
9302
+ - Changing a JSON value or a `Date` in place makes the save throw before anything runs. `touch()` refuses a read-only datetime the same way.
9303
+ - A new record can change it until it’s saved.
9304
+ - A [counter cache](/counter-caches) still counts a read-only column, so a save can’t overwrite the count. `Model.updateCounters` and `touchAll` write rows without loading them, as `updateAll` does, so they write a read-only column too.
9305
+ - An `upsert` leaves the value of a row it updates alone. `updateAll` still writes it.
9306
+ - A virtual attribute, a secure password, and a secure token can’t be read-only. Neither can `updatedAt` or `lockVersion`, which every save writes.
9307
+
9308
+ ## Posting it back from a form
9309
+
9310
+ Assigning the value an attribute already holds isn’t a change, so a form that sends every field back still saves:
9311
+
9312
+ ```ts
9313
+ import { ReadonlyAttribute } from "@forestfuture/active-record";
9314
+ import { Article } from "./models/article";
9315
+
9316
+ export async function updateArticle(request: Request): Promise<Response> {
9317
+ const id = new URL(request.url).searchParams.get("id") ?? "";
9318
+ const article = await Article.find(id);
9319
+ const form = await request.formData();
9320
+ const changes = Article.permit(form, "title", "slug");
9321
+ try {
9322
+ // A form that posts the slug back unchanged saves; one that changes it doesn't
9323
+ await article.updateOrThrow(changes);
9324
+ } catch (error) {
9325
+ if (!(error instanceof ReadonlyAttribute)) throw error;
9326
+ return new Response(`An article's ${error.attribute} can't be changed.`, { status: 422 });
9327
+ }
9328
+ return new Response("Saved");
9329
+ }
9330
+ ```
9331
+
9332
+ The value is compared after it’s cast and normalized, so `" Hello "` matches `"hello"` when a [normalization](/models#normalizing-attributes) trims and lowercases it.
9333
+
9334
+ > **Compared with Rails**
9335
+ >
9336
+ > Rails names the error `ActiveRecord::ReadOnlyRecord`, and its record method is `readonly!`. Here it’s `markReadonly()`.
9337
+ >
9338
+ > Rails runs a read-only record’s own save and destroy callbacks, `dependent: :destroy` included, before it raises. Here they don’t run.
9339
+ >
9340
+ > With Rails 7.1’s defaults, `attr_readonly` raises `ActiveRecord::ReadonlyAttributeError` on any assignment to a saved record. Here assigning the value it holds is allowed.
9341
+
9342
+ ---
9343
+
9043
9344
  # Read replicas
9044
9345
  Source: https://active-record.forestfuture.dev/read-your-own-writes
9045
9346
 
@@ -10279,6 +10580,10 @@ test("emails are saved in lowercase", async () => {
10279
10580
 
10280
10581
  Outside a Worker, the database given to `withDatabase` serves every Model on its adapter, whatever binding its base class names. For code that takes a database explicitly, pass it one: `connect(database.binding).model(User)`.
10281
10582
 
10583
+ :::note[Reads are cached for the whole call]
10584
+ Inside `withDatabase`, a read you’ve already sent is [answered from memory](/connecting#caching-identical-reads) until Active Record writes. A test that changes rows with raw SQL, or a long script that checks a row again and again, would read the first answer. Give each test its own `withDatabase` call, call `db.clearRequestCache()` after a raw write, or open the database with `connect(binding, { cache: { request: false } })`.
10585
+ :::
10586
+
10282
10587
  ## Testing your Worker
10283
10588
 
10284
10589
  Call your Worker’s `fetch` handler inside `withDatabase` too, and its queries use the test’s database. This calls the Worker in `src/index.ts`:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forestfuture/active-record",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "A Rails-inspired Active Record for Cloudflare Workers, with an adapter per database.",
5
5
  "keywords": [
6
6
  "active-record",
@@ -46,7 +46,7 @@
46
46
  "jiti": "^2.7.0"
47
47
  },
48
48
  "devDependencies": {
49
- "@electric-sql/pglite": "^0.5.14",
49
+ "@electric-sql/pglite": "^0.5.16",
50
50
  "pg": "^8.23.1"
51
51
  },
52
52
  "peerDependencies": {
@@ -16,12 +16,13 @@ Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for
16
16
  - Start queries and new records from the Model, as in Rails: `User.find(id)`, `User.where(…)`, `User.build(…)`. Each Model queries the binding named in the generated schema its base class holds, during a request. For a D1 Session, wrap the handler in `withSession(request, env.DB, fn)`. For per-request `onQuery`, or tests and scripts outside a Worker, wrap the code once in `withDatabase(connect(env.DB, { … }), fn)`. Records keep the database they came from.
17
17
  - Never pass a request's whole body, form or query string to a Model: name the fields, with destructuring or `User.permit(await request.json(), "email", "name")` (it reads `FormData` and `URLSearchParams` too). Assigned values are checked against the attribute's type, but that doesn't stop a user setting `role` or `isAdmin`. Check a request value's type before querying with it: `findBy({ token: null })` matches rows whose token is NULL, and a list matches any of its values. `findOrCreateBy`, `findOrInitializeBy` and `createOrFindBy` throw `TypeError` for a list, a comparison or a `sql` fragment.
18
18
  - Name attributes in camelCase everywhere: `where`, `order`, `pluck`, `foreignKey`. Column names (snake_case) appear only inside `sql` fragments.
19
- - Write custom SQL as an `sql` tagged template, which binds every value: ``where(sql`lower(${column("email")}) = ${email}`)``. Interpolate an attribute's value with `column("publishedAt").value(date)`, not the bare `Date`, when the attribute is stored as a Unix time: a bare `Date` is ISO text, and it throws `TypeError` when it's compared directly with that column.
19
+ - Write custom SQL as an `sql` tagged template, which binds every value: ``where(sql`lower(${column("email")}) = ${email}`)``. Interpolate an attribute's value with `column("publishedAt").value(date)`, not the bare `Date`, when the attribute is stored as a Unix time: a bare `Date` is ISO text, and it throws `TypeError` when it's compared directly with that column. `column()` works only inside a fragment: `where({ views: column("likes") })` and `updateAll({ views: column("likes") })` throw, as do one nested in a json value and one given as `find`'s id, so write ``where(sql`${column("views")} = ${column("likes")}`)``.
20
20
  - For a raw `env.DB.prepare(…).bind(…)` statement, bind `Post.typeForAttribute("publishedAt").serialize(date)`, which writes the value as the attribute stores it, and read a cell with `.deserialize(cell)`. A value the attribute can't hold throws `TypeError`.
21
- - Bulk writes run when called, 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.
21
+ - Bulk writes run when called, without callbacks: `await posts.deleteAll()`, `deleteBy({…})` and `updateAll(…)` resolve to how many rows; `insert(…)`, `insertAll`, `upsert` and `upsertAll` to `{ rowsAffected, rows }`, where `rows` holds each written row's primary key, or the attributes `returning: [...]` names (`returning: false` for none). `upsert(…, { uniqueBy: "email", updateOnly: ["name"] })` updates only `name` on a clash; ``upsertAll(rows, { uniqueBy: "name", onDuplicate: { count: sql`${column("count")} + ${incoming("count")}` } })`` sets each named attribute to a fragment (`column()` the clashing row's value, `incoming()` the new row's) or a value. Through a Relation they write its equality values and `createWith` over the attributes given (`Post.where({ userId: 1 }).insert({ userId: 2, … })` writes `userId: 1`), where `build` and `create` keep the given ones. Make several writes atomic by preparing them in one batch's callback: `batch((b) => [b.insert(Post, {…}), b.updateAll(Post.where(…), {…}), b.save(user), b.destroy(post)])`. The callback can't await, so load what the writes need first. D1 has no interactive transactions, so a read-then-write can't be atomic.
22
22
  - Count with the database, not in memory: `post.incrementColumn("viewCount")` or `Post.updateCounters(id, { viewCount: 1 })` add to the row atomically, where `post.viewCount++` then `save()` loses another request's increment. The counter statics (`Post.updateCounters(ids, …)`, `incrementCounter`) skip the default scope, so with a key from a request, and a default scope that separates tenants or hides deleted rows, write `Post.where({ id }).updateCounters({ … })`, which keeps it. The `…Column` methods and `updateColumns` skip validations, callbacks and `updatedAt`, so use `update` for a change those should see; `increment` and `toggle` only change the record in memory. In an after-callback, `record.isPreviouslyNewRecord()` says whether the save created it.
23
23
  - 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.
24
24
  - To stop two edits of one record from overwriting each other, add a `lock_version INTEGER NOT NULL DEFAULT 0` column: every save, destroy and `touch()` then checks the row still has the record's `lockVersion`, and a stale copy's throws `StaleRecord` (from `save()` too, not `false`) and writes nothing in its batch (a destroy's dependents on another database are already gone). For edits across requests, put `lockVersion` in the form as a hidden field and permit it with the other fields, and answer `StaleRecord` with a 409; to retry in code, `await record.reload()` and make the change again. A child's `touch` on a locked parent raises the parent's version, so a parent its children touch often gets conflicts: drop the `touch` or write the children inside `noTouching`.
25
+ - For records a request reads but must not write (a public page, a report), load them with `readonly()` (`Article.readonly().where(…)`) or call `record.markReadonly()`: a save, update, destroy, `touch()` or column write then throws `ReadonlyRecord` before anything runs. Bulk writes (`updateAll`, `deleteAll`) ignore the mark. For an attribute set once on create, such as a slug, declare `slug: { readonly: true }` in the Model's `static attributes`: changing it on a saved record throws `ReadonlyAttribute`, and posting back the value it holds is fine, so an edit form needn't leave it out.
25
26
  - 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`.
26
27
  - 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`.
27
28
  - 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()`.
@@ -83,6 +84,7 @@ export default {
83
84
  ## Where code goes wrong
84
85
 
85
86
  - **`onQuery` listeners see filtered attributes' values as `"[FILTERED]"`**: passwords, tokens, keys and emails, by Rails' default list. Add names to `static filterAttributes` on the app's base class for other secrets. Values inside `sql` fragments aren't filtered.
87
+ - **Inside `withDatabase`, an identical read is answered from memory** (the request cache), until a write the library sends inside the call, through any Database handle, clears it. After SQL you send on the binding or a `pg` client yourself, call `db.clearRequestCache()` before reading again. `reload()` always reads the database. `connect(env.DB, { cache: { request: false } })` turns it off.
86
88
  - **`relation.toSql()` shows a query's `{ sql, params }` without sending it**, to inspect it while debugging. The params are real values, filtered attributes included, so don't log them where `onQuery` wouldn't. Bulk writes and batches have no `toSql()`; `onQuery` shows what they sent.
87
89
  - **`toJSON()` sends every loaded attribute**, so `Response.json(user)` includes an `apiKey` column. List the names to leave out in `static hiddenAttributes` on the app's base class (exact names; a Model's own list replaces it). `attributes()` still has them. A secure password, its confirmation, challenge and digest, and a secure token, are left out already; send a token on purpose, as `Response.json({ token: user.authToken })`.
88
90
  - **Uniqueness validation is a friendly check, not a guarantee.** Two requests can pass it at once; the table's UNIQUE index decides, and the save then throws `RecordNotUnique`. Declare both. To create a row once where requests race, use `createOrFindBy(attrs)` (insert, then find on `RecordNotUnique`) with the index alone: a `uniqueness` validation refuses first, so it finds nothing. `findOrCreateBy` races.