@forestfuture/active-record 0.8.0 → 0.8.1
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/dist/adapter.d.mts +2 -2
- package/dist/adapter.mjs +4 -4
- package/dist/{batch-ReqVoCfa.mjs → batch-Ms5p9lKq.mjs} +8114 -7896
- package/dist/cli.mjs +3 -3
- package/dist/command.mjs +5 -5
- package/dist/d1.d.mts +2 -2
- package/dist/d1.mjs +4 -4
- package/dist/{for-adapters-B0xMP6Dq.d.mts → for-adapters-BT2GDjIA.d.mts} +1 -1
- package/dist/{for-adapters-DhNV1mWf.mjs → for-adapters-BbIMUNcz.mjs} +2 -2
- package/dist/{for-adapters-CfXMGeOu.mjs → for-adapters-C-MQxaIx.mjs} +1 -1
- package/dist/{generated-model-g5oWsDKE.mjs → generated-model-DJA8vmNE.mjs} +220 -211
- package/dist/{epoch-storage-CDlQZcBB.mjs → identifiers-Dh5DFACX.mjs} +86 -85
- package/dist/{index-BATasvJa.d.mts → index-D5getfHx.d.mts} +4 -3
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +4 -4
- package/dist/{plugin-wOSILvSB.mjs → plugin-CZPDqguF.mjs} +3 -3
- package/dist/{plugin-x5-d3TSN.mjs → plugin-Cf-5Z0_h.mjs} +3 -3
- package/dist/postgresql.d.mts +1 -1
- package/dist/postgresql.mjs +4 -4
- package/dist/{src-D56_3odT.mjs → src-BAVZKQ7J.mjs} +2 -2
- package/dist/{storage-override-n4w1cS_M.mjs → storage-override-0ZgeP2sc.mjs} +1 -1
- package/dist/{validations-DHDVV8hB.d.mts → validations-BSZ5gVeI.d.mts} +35 -7
- package/llms-full.txt +109 -3
- package/package.json +1 -1
- package/skills/active-record/SKILL.md +2 -1
package/llms-full.txt
CHANGED
|
@@ -373,6 +373,7 @@ Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for
|
|
|
373
373
|
- 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
374
|
- 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
375
|
- 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.
|
|
376
|
+
- 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`.
|
|
376
377
|
- 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
378
|
- 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
379
|
- 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()`.
|
|
@@ -456,6 +457,7 @@ await article.save();
|
|
|
456
457
|
| `scope` | Narrows the target, `(q) => q.where(…)`. See [Scoping associations](#scoping-associations) |
|
|
457
458
|
| `optional` | Lets the record point at nothing. See [Requiring the record](#requiring-the-record) |
|
|
458
459
|
| `autosave` | `true` saves the record’s changes with this record. See [Saving changed records](#saving-changed-records) |
|
|
460
|
+
| `inverseOf` | The target’s `hasOne` that points back, or `false`. See [Inverse associations](#inverse-associations) |
|
|
459
461
|
|
|
460
462
|
### Requiring the record
|
|
461
463
|
|
|
@@ -510,6 +512,7 @@ await author.articles().where({ title: "Untitled" }).deleteAll(); // bulk writes
|
|
|
510
512
|
| `scope` | Narrows or orders the records, `(q) => q.order(…)`. See [Scoping associations](#scoping-associations) |
|
|
511
513
|
| `dependent` | What destroying the owner does to the records. See [Destroying dependent records](#destroying-dependent-records) |
|
|
512
514
|
| `autosave` | `true` saves the records’ changes with the owner. See [Saving changed records](#saving-changed-records) |
|
|
515
|
+
| `inverseOf` | The target’s `belongsTo` that points back, or `false`. See [Inverse associations](#inverse-associations) |
|
|
513
516
|
|
|
514
517
|
## hasOne
|
|
515
518
|
|
|
@@ -686,6 +689,60 @@ const latest = await author?.articles().first();
|
|
|
686
689
|
A `belongsTo` whose foreign key is `null`, or an association on an unsaved owner, reads without a query.
|
|
687
690
|
:::
|
|
688
691
|
|
|
692
|
+
## Inverse associations
|
|
693
|
+
|
|
694
|
+
A record loaded through its owner’s `hasMany` or `hasOne` has the owner loaded already. Reading it back doesn’t send a query:
|
|
695
|
+
|
|
696
|
+
```ts
|
|
697
|
+
const author = await Author.find(authorId);
|
|
698
|
+
const [article] = await author.articles().toArray();
|
|
699
|
+
const sameAuthor = await article?.author(); // `author` itself, with no query
|
|
700
|
+
```
|
|
701
|
+
|
|
702
|
+
- 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).
|
|
703
|
+
- Records built or created through the association point back too, before either is saved.
|
|
704
|
+
- 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.
|
|
705
|
+
- The owner is the same object on both sides, so a change to it shows from either one.
|
|
706
|
+
- 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).
|
|
707
|
+
|
|
708
|
+
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).
|
|
709
|
+
|
|
710
|
+
If you want another inverse, or one for an association with a `scope`, name it with `inverseOf`:
|
|
711
|
+
|
|
712
|
+
```ts
|
|
713
|
+
import { belongsTo, hasMany, Model } from "@forestfuture/active-record";
|
|
714
|
+
|
|
715
|
+
export class Editor extends Model.define({
|
|
716
|
+
id: { type: "string", null: false, generateId: true },
|
|
717
|
+
name: { type: "string", null: false },
|
|
718
|
+
}) {
|
|
719
|
+
static table = "authors";
|
|
720
|
+
|
|
721
|
+
// A scope turns inference off, so name the inverse.
|
|
722
|
+
drafts = hasMany(Draft, {
|
|
723
|
+
foreignKey: "authorId",
|
|
724
|
+
scope: (q) => q.where({ title: "Untitled" }),
|
|
725
|
+
inverseOf: "editor",
|
|
726
|
+
});
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
export class Draft extends Model.define({
|
|
730
|
+
id: { type: "string", null: false, generateId: true },
|
|
731
|
+
authorId: { type: "string", null: false },
|
|
732
|
+
title: { type: "string", null: false },
|
|
733
|
+
}) {
|
|
734
|
+
static table = "articles";
|
|
735
|
+
|
|
736
|
+
editor = belongsTo(Editor, { foreignKey: "authorId" });
|
|
737
|
+
}
|
|
738
|
+
```
|
|
739
|
+
|
|
740
|
+
`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`.
|
|
741
|
+
|
|
742
|
+
> **Beyond Rails**
|
|
743
|
+
>
|
|
744
|
+
> 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`.
|
|
745
|
+
|
|
689
746
|
## Preloading associations
|
|
690
747
|
|
|
691
748
|
Load an association for every record at once with `includes`, with one query per association however many records there are:
|
|
@@ -1148,7 +1205,6 @@ These features aren’t in Active Record yet. The code shows the shape they’re
|
|
|
1148
1205
|
- **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
1206
|
- **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
1207
|
- **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.
|
|
1152
1208
|
|
|
1153
1209
|
---
|
|
1154
1210
|
|
|
@@ -1399,6 +1455,12 @@ Once a Model has been used, registering another callback throws `InvalidModel`,
|
|
|
1399
1455
|
| 2 | `afterDestroy` | After the record is destroyed | Too late: `AbortAfterPersistence` |
|
|
1400
1456
|
| 3 | `afterCommit` | Last, after every after-callback | Too late: `AbortAfterPersistence` |
|
|
1401
1457
|
| 3 | `afterDestroyCommit` | Last, after the record is destroyed | Too late: `AbortAfterPersistence` |
|
|
1458
|
+
| **Touching** | | | |
|
|
1459
|
+
| | _The write to D1_ | `updatedAt`, and any attributes named | |
|
|
1460
|
+
| 1 | `afterTouch` | After `touch()` writes the record’s timestamps | Too late: `AbortAfterPersistence` |
|
|
1461
|
+
| 2 | `afterCommit` | Last, when `touch()` wrote a row | Too late: `AbortAfterPersistence` |
|
|
1462
|
+
| 2 | `afterUpdateCommit` | Last, when `touch()` wrote a row | Too late: `AbortAfterPersistence` |
|
|
1463
|
+
| 2 | `afterSaveCommit` | Last, when `touch()` wrote a row | Too late: `AbortAfterPersistence` |
|
|
1402
1464
|
| **Refused** | | | |
|
|
1403
1465
|
| 1 | `afterRollback` | When the database refuses the save or destroy | Nothing to stop |
|
|
1404
1466
|
|
|
@@ -1430,6 +1492,27 @@ this.afterCreateCommit(async (user) => {
|
|
|
1430
1492
|
Destroying a record that was never saved runs no commit callback, since there was no row to delete.
|
|
1431
1493
|
:::
|
|
1432
1494
|
|
|
1495
|
+
## Running code after a touch
|
|
1496
|
+
|
|
1497
|
+
`afterTouch` runs after [`touch()`](/persistence#touching-a-record) writes a record’s timestamps:
|
|
1498
|
+
|
|
1499
|
+
```ts
|
|
1500
|
+
this.afterTouch(async (article) => {
|
|
1501
|
+
await purgeCachedPage(article.id);
|
|
1502
|
+
});
|
|
1503
|
+
```
|
|
1504
|
+
|
|
1505
|
+
- **No validation or save callback runs** for a touch.
|
|
1506
|
+
- **The commit callbacks for an update** run after `afterTouch`: `afterCommit`, `afterUpdateCommit`, and `afterSaveCommit`. When the row is gone, only `afterTouch` runs.
|
|
1507
|
+
- **`savedChanges()`** holds only the touched attributes, so `hasSavedChangeTo("email")` is `false` in a touch’s callbacks.
|
|
1508
|
+
- **A refused touch** runs `afterRollback`, and the record stays as it was.
|
|
1509
|
+
|
|
1510
|
+
`touchAll` and the counters’ `touch` option run no callbacks.
|
|
1511
|
+
|
|
1512
|
+
:::warning[A touch runs the update commit callbacks]
|
|
1513
|
+
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.
|
|
1514
|
+
:::
|
|
1515
|
+
|
|
1433
1516
|
## Handling a refused write
|
|
1434
1517
|
|
|
1435
1518
|
`afterRollback` runs when the database refuses a record’s save or destroy:
|
|
@@ -1478,12 +1561,13 @@ These callbacks aren’t in Active Record yet. The code shows the shape they’r
|
|
|
1478
1561
|
|
|
1479
1562
|
- **Around callbacks** ([#48](https://github.com/forestfuture/active-record/issues/48)): `this.aroundSave(async (record, proceed) => { …; await proceed(); … })`, and `aroundCreate`, `aroundUpdate`, and `aroundDestroy`.
|
|
1480
1563
|
- **`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
1564
|
|
|
1483
1565
|
> **Compared with Rails**
|
|
1484
1566
|
>
|
|
1485
1567
|
> `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
1568
|
>
|
|
1569
|
+
> `after_touch` is `afterTouch`. As in Rails, `touch` runs the commit callbacks too.
|
|
1570
|
+
>
|
|
1487
1571
|
> `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
1572
|
>
|
|
1489
1573
|
> Rails’ `if:` and `unless:` options for callbacks aren’t needed: write the condition inside the callback.
|
|
@@ -4351,12 +4435,31 @@ await article.toggleColumn("isPinned");
|
|
|
4351
4435
|
await article.updateColumns({ title: "Renamed" }); // no validations, callbacks, or updatedAt
|
|
4352
4436
|
```
|
|
4353
4437
|
|
|
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.
|
|
4438
|
+
- **`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
4439
|
- **`toggleColumn`** writes the flipped value.
|
|
4356
4440
|
- **`updateColumns(attrs)`** writes the attributes you give. `updateColumn(name, value)` writes one.
|
|
4357
4441
|
|
|
4358
4442
|
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
4443
|
|
|
4444
|
+
### Touching a record
|
|
4445
|
+
|
|
4446
|
+
To mark a record as changed without saving it, call `touch`. It sets `updatedAt` to the current time in the row:
|
|
4447
|
+
|
|
4448
|
+
```ts
|
|
4449
|
+
await article.touch(); // sets updatedAt to now
|
|
4450
|
+
await article.touch("viewedAt"); // sets viewedAt and updatedAt
|
|
4451
|
+
await article.touch({ time: new Date("2026-01-01T00:00:00Z") });
|
|
4452
|
+
await Article.where({ isPinned: true }).touchAll(); // every pinned article, in one statement
|
|
4453
|
+
```
|
|
4454
|
+
|
|
4455
|
+
- **Name datetime attributes** to set them as well as `updatedAt`.
|
|
4456
|
+
- **Pass `{ time }` last** to set a time other than now.
|
|
4457
|
+
- **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.
|
|
4458
|
+
|
|
4459
|
+
`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).
|
|
4460
|
+
|
|
4461
|
+
`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.
|
|
4462
|
+
|
|
4360
4463
|
### Updating counters
|
|
4361
4464
|
|
|
4362
4465
|
To add to a number without loading the record, pass its primary key to `updateCounters`:
|
|
@@ -4395,6 +4498,8 @@ await Article.where({ id }).updateCounters({ viewCount: 1 }); // keeps the defau
|
|
|
4395
4498
|
> 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
4499
|
>
|
|
4397
4500
|
> Rails’ `increment!` keeps the value it worked out. `incrementColumn` reads the row’s new value back, so it includes other requests’ increments.
|
|
4501
|
+
>
|
|
4502
|
+
> `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
4503
|
|
|
4399
4504
|
## Finding or creating a record
|
|
4400
4505
|
|
|
@@ -4536,6 +4641,7 @@ export class Article extends Model.define({
|
|
|
4536
4641
|
title: { type: "string", null: false },
|
|
4537
4642
|
viewCount: { type: "integer", null: false },
|
|
4538
4643
|
isPinned: { type: "boolean", null: false },
|
|
4644
|
+
viewedAt: "datetime",
|
|
4539
4645
|
updatedAt: "datetime",
|
|
4540
4646
|
}) {
|
|
4541
4647
|
static {
|
package/package.json
CHANGED
|
@@ -20,6 +20,7 @@ Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for
|
|
|
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
21
|
- Bulk writes run when called, without callbacks: `await posts.deleteAll()`, `deleteBy({…})` and `updateAll(…)` resolve to how many rows; `insert(…)`, `insertAll`, `upsert` and `upsertAll` to `{ rowsAffected, rows }`, where `rows` holds each written row's primary key, or the attributes `returning: [...]` names (`returning: false` for none). Through a Relation they write its equality values and `createWith` over the attributes given (`Post.where({ userId: 1 }).insert({ userId: 2, … })` writes `userId: 1`), where `build` and `create` keep the given ones. Make several writes atomic by preparing them in one batch's callback: `batch((b) => [b.insert(Post, {…}), b.updateAll(Post.where(…), {…}), b.save(user), b.destroy(post)])`. The callback can't await, so load what the writes need first. D1 has no interactive transactions, so a read-then-write can't be atomic.
|
|
22
22
|
- Count with the database, not in memory: `post.incrementColumn("viewCount")` or `Post.updateCounters(id, { viewCount: 1 })` add to the row atomically, where `post.viewCount++` then `save()` loses another request's increment. The counter statics (`Post.updateCounters(ids, …)`, `incrementCounter`) skip the default scope, so with a key from a request, and a default scope that separates tenants or hides deleted rows, write `Post.where({ id }).updateCounters({ … })`, which keeps it. The `…Column` methods and `updateColumns` skip validations, callbacks and `updatedAt`, so use `update` for a change those should see; `increment` and `toggle` only change the record in memory. In an after-callback, `record.isPreviouslyNewRecord()` says whether the save created it.
|
|
23
|
+
- To 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`.
|
|
23
24
|
- To show how many records an association has, keep a counter cache rather than counting on each read: `article = belongsTo(Article, { counterCache: true })` with a `commentsCount` attribute, which `article.comments().size()` reads. Saves, destroys and the association's `delete`/`clear`/`deleteAll()` keep it; bulk writes (`insertAll`, `updateAll`, a Relation's `deleteAll`) don't, so follow them with `Article.resetCounters(id, "comments")`. Add one to existing rows with `{ active: false }`, reset each, then drop `active: false`.
|
|
24
25
|
- To work through more records than a request should hold (a backfill, an export, a cleanup), iterate in batches rather than `toArray()` or `offset` pages: `for await (const user of User.where(…).findEach())`, `findInBatches()` for arrays, and `inBatches()` for a Relation per batch to `updateAll`, `deleteAll` or `destroyAll`. Batches go in primary-key order, so `reorder()` a Relation that has an order (a default scope's too), and bound them with `start` and `finish`, not `offset`. On D1 a Worker invocation sends at most 1,000 queries (50 on Free), and each batch sends one (`inBatches` reads its keys, then sends the write, and a `destroyAll` adds a load and each record's dependent reads; a `db.batch` counts as one): split a larger job across invocations by `start` and `finish`.
|
|
25
26
|
- 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()`.
|
|
@@ -84,7 +85,7 @@ export default {
|
|
|
84
85
|
- **`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.
|
|
85
86
|
- **`toJSON()` sends every loaded attribute**, so `Response.json(user)` includes `passwordDigest`. List the names to leave out in `static hiddenAttributes` on the app's base class (exact names; a Model's own list replaces it). `attributes()` still has them.
|
|
86
87
|
- **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.
|
|
87
|
-
- **`record.loaded("posts")` reads what was preloaded or already read**, synchronously, and throws `AssociationNotLoaded` otherwise. `await user.posts().toArray()` loads when needed.
|
|
88
|
+
- **`record.loaded("posts")` reads what was preloaded or already read**, synchronously, and throws `AssociationNotLoaded` otherwise. `await user.posts().toArray()` loads when needed. A record loaded or built through `user.posts()` already has `user` loaded as its `author` (its inverse association), so don't preload or re-read the owner from a child; with a `scope:` on either side, name the inverse with `inverseOf: "author"`.
|
|
88
89
|
- **Page a list with `paginate()`, not a hand-built `limit` and `offset`**: `Post.published().paginate({ page: url.searchParams.get("page") })` casts the untrusted page, caps its size at `static maxPerPage`, and on D1 sends the count with the page in one round trip. `{ count: false }` skips the `COUNT`, which reads (and bills) every matching row.
|
|
89
90
|
- **Total, average or find the extremes of a column with `sum`, `average`, `minimum` and `maximum`**, not by loading records and adding them up in JavaScript: `Order.where({ status: "paid" }).sum("total")` sends one query. A sum of no rows is 0; the others are `null`. A `limit` picks the rows calculated, and an `sql` fragment calculates an expression: ``LineItem.sum(sql`${column("price")} * ${column("quantity")}`)``.
|
|
90
91
|
- **Calculate per category with `group`**, not with one query per category: `Order.group("status").count()` resolves to a `Map` such as `Map { "paid" => 3, "open" => 1 }`, and `sum`, `average`, `minimum` and `maximum` work the same way. ``having(sql`COUNT(*) > ${1}`)`` keeps some groups. Several attributes key each group by an array, which a `Map` finds only by identity, so loop over it. A grouped Relation has no records, and can only be ordered by grouped attributes or an `sql` fragment such as ``sql`COUNT(*) DESC` ``.
|