@forestfuture/active-record 0.8.1 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forestfuture/active-record",
3
- "version": "0.8.1",
3
+ "version": "0.8.2",
4
4
  "description": "A Rails-inspired Active Record for Cloudflare Workers, with an adapter per database.",
5
5
  "keywords": [
6
6
  "active-record",
@@ -20,7 +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
+ - 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 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`.
25
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`.
26
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()`.
@@ -92,6 +92,6 @@ export default {
92
92
  - **Filter by an associated Model with `joins` and `merge`**, not by loading its ids first: `Post.joins("author").merge(User.where({ role: "admin" }))` sends one query, and `leftJoins` keeps records with no linked record. A `hasMany` join repeats a record for each linked one: add `distinct()`. Join a Model before merging its Relation, and merge only its conditions, scopes and order. A polymorphic `belongsTo` can't be joined: join each listed Model's `as:` association instead. `includes` is still how to load associated records.
93
93
  - **Replace a condition with `rewhere({ role: "admin" })`, and drop parts of a query with `unscope("order")` or `unscope({ where: "role" })`**, rather than rebuilding a scope's query by hand. Both widen a query, so never pass them request data. An association's link to its owner always stays: `user.posts().unscope("where")` is still the user's posts. Order by a list of values with `inOrderOf("status", ["open", "paid"])`, not a `CASE` fragment, and leave records out with `excluding(record)`.
94
94
  - **`find(id)` throws `RecordNotFound`**; `findBy(conditions)` resolves to `null`. `firstOrThrow()`, `lastOrThrow()`, `takeOrThrow()` and `findByOrThrow()` throw `RecordNotFound` instead. When exactly one record must match, use `sole()` or `findSoleBy(conditions)`: none throws `RecordNotFound`, more than one `SoleRecordExceeded`. Read one value with `pick("email")`, not `(await first())?.email`, and the primary keys with `ids()`.
95
- - **After-callbacks run once D1 has committed the write.** An error there reaches the caller with the record already saved: nothing rolls back. `afterCommit` (and `afterCreateCommit`, `afterUpdateCommit`, `afterSaveCommit`, `afterDestroyCommit`) runs after every after-callback, including those of every record in a batch; `afterRollback` runs only when the database refuses a write it was sent.
95
+ - **After-callbacks run once D1 has committed the write.** An error there reaches the caller with the record already saved: nothing rolls back. `afterCommit` (and `afterCreateCommit`, `afterUpdateCommit`, `afterSaveCommit`, `afterDestroyCommit`) runs after every after-callback, including those of every record in a batch; `afterRollback` runs only when the database refuses a write it was sent. `aroundSave`, `aroundCreate`, `aroundUpdate` and `aroundDestroy` take `(record, next)` and must `await next()` (not calling it stops the save, as `abort()` does); `next()` waits for the whole save's or batch's write, so put cleanup in a `finally` around it. `afterFind` (every record loaded) and `afterInitialize` (every record built or loaded) run synchronously, so they can't be `async`; a record from `select(...)` runs them too, so check `record.hasAttribute("total")` before reading an attribute there.
96
96
  - **Read replicas:** wrap the handler in `withSession(request, env.DB, fn)`. Every query in `fn` goes through one D1 Session, and its bookmark is set on `fn`'s Response as a `d1-bookmark` cookie, so the user's next request reads at least as new as their last write. For APIs, pass `{ header: "x-d1-bookmark" }` before `fn`; `start: "first-primary"` starts a request with no bookmark on the primary. Don't read or set the bookmark by hand.
97
97
  - **Outside a Worker** (tests, scripts) there's no binding to find: run the code in `withDatabase(connect(binding), fn)`, or a query throws `NoDatabase` saying so. With several databases on one adapter, `withDatabase` can't tell them apart outside a Worker (one D1 and one Postgres database each serve their own Models): mock `cloudflare:workers` with the bindings instead (Vitest needs `test.server.deps.inline: ["@forestfuture/active-record"]`), assigning them onto the mocked `env` object. A query at a module's top level fails too: Workers only allow D1 calls during a request.