@forestfuture/active-record 0.7.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/config-schema.json +6 -2
- package/dist/adapter.d.mts +3 -3
- package/dist/adapter.mjs +5 -4
- package/dist/batch-Ms5p9lKq.mjs +9777 -0
- package/dist/cli.d.mts +55 -33
- package/dist/cli.mjs +4 -4
- package/dist/command.mjs +530 -271
- package/dist/d1.d.mts +2 -10
- package/dist/d1.mjs +0 -0
- package/dist/{for-adapters-t3-LukJQ.d.mts → for-adapters-BT2GDjIA.d.mts} +8 -6
- package/dist/{for-adapters-Ch6CoHD4.mjs → for-adapters-BbIMUNcz.mjs} +46 -10
- package/dist/{for-adapters-D_Iu0gS_.mjs → for-adapters-C-MQxaIx.mjs} +3 -5
- package/dist/{generated-model-Cnt0Ot9q.mjs → generated-model-DJA8vmNE.mjs} +705 -508
- package/dist/identifiers-Dh5DFACX.mjs +989 -0
- package/dist/index-D5getfHx.d.mts +242 -0
- package/dist/index.d.mts +4 -3
- package/dist/index.mjs +5 -4
- package/dist/metadata-CzntpYzC.d.mts +182 -0
- package/dist/{plugin-Cyoej7qV.mjs → plugin-CZPDqguF.mjs} +211 -112
- package/dist/{plugin-XOHYndhP.mjs → plugin-Cf-5Z0_h.mjs} +148 -52
- package/dist/postgresql.d.mts +1 -9
- package/dist/postgresql.mjs +42 -26
- package/dist/src-BAVZKQ7J.mjs +46 -0
- package/dist/{storage-override-CpbkdIqE.mjs → storage-override-0ZgeP2sc.mjs} +61 -28
- package/dist/validations-BSZ5gVeI.d.mts +2024 -0
- package/llms-full.txt +2326 -229
- package/package.json +1 -1
- package/skills/active-record/SKILL.md +24 -15
- package/dist/adapter-AGKp6wfO.d.mts +0 -1326
- package/dist/batch-BS_WseLf.mjs +0 -4255
- package/dist/epoch-storage-o2aoOH7H.mjs +0 -112
- package/dist/index-CyCJuM96.d.mts +0 -149
- package/dist/src-la_KkjCS.mjs +0 -1
package/llms-full.txt
CHANGED
|
@@ -73,10 +73,10 @@ import { batch } from "@forestfuture/active-record";
|
|
|
73
73
|
import { Article, Author } from "./models";
|
|
74
74
|
|
|
75
75
|
const authorId = crypto.randomUUID(); // generated in code, so rows can point at it
|
|
76
|
-
await batch([
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
Article.where({ authorId: "author-1" })
|
|
76
|
+
await batch((b) => [
|
|
77
|
+
b.insert(Author, { id: authorId, name: "Grace" }),
|
|
78
|
+
b.insert(Article, { authorId, title: "Hello" }),
|
|
79
|
+
b.deleteAll(Article.where({ authorId: "author-1" })),
|
|
80
80
|
]);
|
|
81
81
|
```
|
|
82
82
|
|
|
@@ -240,6 +240,8 @@ export class Post extends ApplicationRecord {
|
|
|
240
240
|
}
|
|
241
241
|
```
|
|
242
242
|
|
|
243
|
+
A Postgres enum type or a `CHECK (column IN (…))` makes its column an enum of the names it lists. Its type and its checks come from the database. Its methods stay off until you turn them on with `enum: true`. See [Reading enums from the database](/models#reading-enums-from-the-database).
|
|
244
|
+
|
|
243
245
|
## Reading Unix timestamps
|
|
244
246
|
|
|
245
247
|
Read a Unix timestamp column as a `Date` by overriding it as a `datetime` with the matching `storage`. Drizzle’s `integer({ mode: "timestamp" })` stores seconds, and `"timestamp_ms"` stores milliseconds:
|
|
@@ -360,21 +362,26 @@ Skip this section if you’ve installed the skill: the block below is the skill
|
|
|
360
362
|
|
|
361
363
|
```md
|
|
362
364
|
|
|
363
|
-
Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for Cloudflare Workers, with an adapter per database inside it: `@forestfuture/active-record/d1` for D1, and `@forestfuture/active-record/postgresql` for Postgres, which needs the app's own `pg`. Import Models, Relations, and errors from the core, and what opens a database from its adapter's entry: `connect`, `withSession`, `NoSession`, and `d1` from `/d1`; `connect` and `postgresql` from `/postgresql`. Every `active-record` command reads `active-record.jsonc`, which names each database's adapter: run `npx active-record init` to write it, never `--adapter
|
|
365
|
+
Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for Cloudflare Workers, with an adapter per database inside it: `@forestfuture/active-record/d1` for D1, and `@forestfuture/active-record/postgresql` for Postgres, which needs the app's own `pg`. Import Models, Relations, and errors from the core, and what opens a database from its adapter's entry: `connect`, `withSession`, `NoSession`, and `d1` from `/d1`; `connect` and `postgresql` from `/postgresql`. Every `active-record` command reads `active-record.jsonc`, which names each database's adapter, so one project can hold a D1 database and a Postgres one: run `npx active-record init` to write it, never `--adapter` on another command (`init --adapter postgresql` adds Hyperdrive bindings to a file that names only D1 databases). Its guide for the installed version is `node_modules/@forestfuture/active-record/llms-full.txt`, one Markdown file with a `#` heading per page: read the part for the task before writing code with it.
|
|
364
366
|
|
|
365
367
|
- Create tables with the generators, never by hand-declaring attributes: `npx active-record g model Post user:references 'title:string!'` writes the migration and the Model; `npx active-record g migration AddSlugToPosts slug:string:unique` writes a change. Apply them with `npx active-record migrate`. After a hand-written migration, run `npx active-record schema`. Never edit the generated `src/db/schema.ts`.
|
|
366
|
-
- A Model extends the app's base class: `class Post extends ApplicationRecord {}`. Its table comes from its class name (`Post` → `posts`), or `static override table = "…"`, and its attributes from the schema, so it declares only behavior. Run `npx active-record schema` after adding or renaming a Model, as after a migration: a Model it hasn't seen throws `InvalidModel`. Change how a column is read with an override in the class, `static override attributes = { metadata: "json" } as const`, never by editing the schema. An `INTEGER` holding a Unix time (Drizzle's `timestamp` modes) is `{ type: "datetime", storage: "unixSeconds" }` or `"unixMilliseconds"`. A cell that isn't its attribute's type (a number in an ISO `datetime`, text in an `integer`) fails the load with a `TypeError` naming the attribute: correct the override, don't catch it.
|
|
368
|
+
- A Model extends the app's base class: `class Post extends ApplicationRecord {}`. Its table comes from its class name (`Post` → `posts`), or `static override table = "…"`, and its attributes from the schema, so it declares only behavior. With a bundler that renames classes (Wrangler keeps them by default), set `static override modelName = "Post"` on each Model, so its table, foreign keys and schema entry keep the name. Run `npx active-record schema` after adding or renaming a Model, as after a migration: a Model it hasn't seen throws `InvalidModel`. Change how a column is read with an override in the class, `static override attributes = { metadata: "json" } as const`, never by editing the schema. An `INTEGER` holding a Unix time (Drizzle's `timestamp` modes) is `{ type: "datetime", storage: "unixSeconds" }` or `"unixMilliseconds"`. Bytes are a `binary` attribute (a `Uint8Array`, in a `BLOB` or `bytea` column): assign a form's file as `new Uint8Array(await file.arrayBuffer())`. An exact number (a price, a quantity with a fraction) is a `decimal` attribute, held as text (`"12.5"`) in a `NUMERIC` or `DECIMAL` column, never a `real`, with `precision` and `scale` to round it as `NUMERIC(10, 2)` does; a day with no time is a `date` (`"2026-01-02"`) and a time of day a `time` (`"09:30:00"`), assigned as text, not a `Date`. A value no built-in type holds (money, a value object, a list kept as text) is a custom type: `const money = defineType({ storedAs: "integer", cast, serialize, deserialize })`, given as `priceCents: money` in the override or in `define`, rather than converting in getters, setters or callbacks; its `cast` throws for a value it can't hold. A column with a fixed set of values is an enum: `status: { enum: ["draft", "published"] }` (names stored as text) or `{ enum: { low: 0, high: 1 } }` (an integer column), which gives `post.isDraft()`, `await post.saveAsPublished()`, `Post.published()`, `Post.notPublished()` and `Post.enumValues("status")`; use those and `where({ status: "published" })` rather than a hand-written scope or a `declare status: …` narrowing. Run `npx active-record schema` after adding an enum, so its scopes are typed. A column the database restricts to a list (a Postgres enum type, `CHECK (state IN ('open', 'done'))`) already has the names in the schema, typed and checked but without methods: turn them on with `state: { enum: true }`, rather than listing the names again, or drop it with `enum: false`. An unlisted stored value reads as `null`; rename a name with `{ newName: "old_value" }`. A cell that isn't its attribute's type (a number in an ISO `datetime`, text in an `integer`) fails the load with a `TypeError` naming the attribute: correct the override, don't catch it.
|
|
367
369
|
- 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.
|
|
368
|
-
- 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.
|
|
370
|
+
- 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.
|
|
369
371
|
- Name attributes in camelCase everywhere: `where`, `order`, `pluck`, `foreignKey`. Column names (snake_case) appear only inside `sql` fragments.
|
|
370
372
|
- 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.
|
|
371
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`.
|
|
372
|
-
- Bulk writes run when called: `await posts.deleteAll()` and `updateAll(…)` resolve to how many rows; `insert(…)`, `insertAll`, `upsert` and `upsertAll` to `{ rowsAffected, rows }`, where `rows` holds each written row's primary key, or the attributes `returning: [...]` names (`returning: false` for none).
|
|
373
|
-
-
|
|
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
|
+
- 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`.
|
|
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`.
|
|
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`.
|
|
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()`.
|
|
380
|
+
- Keep the generators' `TEXT` keys, generated in code, for records saved together (`--id integer` gives a key D1 generates instead). An owner whose key is known before its INSERT (generated in code, or already saved) is written in one atomic batch with the records built through it on its database. A key D1 generates exists only after its own write, so each level is then written in a separate batch. Records on another database are always a separate write there, and a batch refuses them.
|
|
374
381
|
- To change how those keys are made (UUIDv7, ULID, a prefix), override `static generateId` once on the app's base class; don't give each Model's key a `default`. `generateId` sees only the attribute's name, so a value made from other attributes (a slug) goes in a callback.
|
|
375
|
-
- Declare associations as fields, passing the target class: `posts = hasMany(Post, { dependent: "destroy" })`, `author = belongsTo(User)`. The field's name is the association's name.
|
|
376
|
-
- Change the copy of validation messages with `this.errorMessages({...})` in the `static {}` block of the app's base class (every Model) or a Model (`attributes: { email: { taken: "…" } }` for one attribute), and attribute names with `this.humanAttributeNames({...})`, rather than a `message` on every `validates`. For a custom error, `errors.add("
|
|
377
|
-
- Check what writes return. `save()` and `update()` resolve to `false` when validation fails (reasons in `record.errors`) or a callback aborts (`record.abortReason`). `destroy()` resolves to `false` when a callback aborts, or a `restrictWithError` association refuses (reason in `record.errors`). The `…OrThrow` methods throw instead. Constraint errors, such as `RecordNotUnique`, always throw.
|
|
382
|
+
- Declare associations as fields, passing the target class: `posts = hasMany(Post, { dependent: "destroy" })`, `author = belongsTo(User)`. The field's name is the association's name. Add and remove a `hasMany`'s records through it: `user.posts().push(post)`, `delete(post)` (by its `dependent:`, nullifying by default), `destroy(post)` and `clear()`, rather than writing the foreign key yourself, so a loaded collection stays in step. Saving requires a `belongsTo`'s record ("must exist"), so pass `optional: true` when its foreign key may be `null`. Its target may be on another database (a Model on another base class): reading, preloading (one more round trip), and writing through it go to the target's database, and a save or destroy writes each database separately, not atomically. A `hasOne`'s new record, through `set`, `build` or `create`, replaces the old one, which its `dependent:` strategy removes (without one, its foreign key is set to `null`). Await `user.profile.set(profile)`: on a saved owner it saves at once, unlike a `belongsTo`'s `set`. To save changes to associated records with their owner, declare the association `autosave: true` and change the records it loaded (`await user.posts().toArray()`), not ones found with a query of their own. `record.markForDestruction()` then destroys a record when its owner is saved. For a record that can belong to one of several Models, list them: `commentable = belongsTo([Post, Photo])`, with `commentableType` and `commentableId` attributes, and `comments = hasMany(Comment, { as: "commentable" })` on each listed Model. Point it with `comment.commentable.set(post)`, not by writing the type yourself: the type holds each Model's `modelName`, so set `static modelName` on the listed Models if a bundler renames classes. Reach records through a join Model with `through`: `projects = hasMany(Project, { through: "assignments" })` (`source:` names the join Model's association when it isn't `project`). It reads and preloads as any association, each record once. Write through it to make and remove join records: `user.projects().push(project)`, `build`, `create`, `delete(project)` and `clear()` (`destroy(project)` destroys the join records too, not the project). A built project is linked when the owner is saved, not the project. Don't narrow before `deleteAll` (`user.projects().where(…).deleteAll()`), which deletes the projects themselves. Only a join Model is written through (a `hasMany` to a `belongsTo`); `insert` and `upsert` through it throw. An upsert through a `hasMany` only updates the owner's records, and leaves another owner's clashing row as it is.
|
|
383
|
+
- Change the copy of validation messages with `this.errorMessages({...})` in the `static {}` block of the app's base class (every Model) or a Model (`attributes: { email: { taken: "…" } }` for one attribute), and attribute names with `this.humanAttributeNames({...})`, rather than a `message` on every `validates`. Compare one attribute with another with `comparison: { greaterThan: (event) => event.startsAt }`, not a callback. Validate an association's loaded records with `this.validatesAssociated("posts")`, not a callback. Run a rule only when creating or updating with `on: "create"` or `on: "update"` (or skip one with `exceptOn`), not `if: (record) => record.isNewRecord()`. For a step of the app's own, list its name in the Model's `static validationContexts = ["signup"] as const` and validate in it with `isValid("signup")` or `save({ context: "signup" })`; that replaces `"create"`, so pass `["create", "signup"]` to run both. For a custom error, `errors.add("startsAt", { type: "onTheHour" })` and give `onTheHour` a message there.
|
|
384
|
+
- Check what writes return. `save()` and `update()` resolve to `false` when validation fails (reasons in `record.errors`) or a callback aborts (`record.abortReason`). `destroy()` resolves to `false` when a callback aborts, or a `restrictWithError` association refuses (reason in `record.errors`). The `…OrThrow` methods throw instead. Constraint errors, such as `RecordNotUnique`, always throw, and so does a rule declared `strict: true` (`StrictValidationFailed`), meant for values only a bug could set.
|
|
378
385
|
|
|
379
386
|
```
|
|
380
387
|
|
|
@@ -398,7 +405,7 @@ export class Author extends Model.define({
|
|
|
398
405
|
id: { type: "string", null: false, generateId: true },
|
|
399
406
|
name: { type: "string", null: false },
|
|
400
407
|
}) {
|
|
401
|
-
articles = hasMany(Article, { dependent: "destroy" }); // Article's authorId
|
|
408
|
+
articles = hasMany(Article, { dependent: "destroy", autosave: true }); // Article's authorId
|
|
402
409
|
profile = hasOne(Profile, { dependent: "delete" }); // Profile's authorId
|
|
403
410
|
}
|
|
404
411
|
|
|
@@ -443,11 +450,36 @@ await article.save();
|
|
|
443
450
|
- **`record.author.build(attrs)`** builds a record to point at. It’s validated with the record, and saved before it, so the foreign key can be filled in.
|
|
444
451
|
- **`record.author.create(attrs)`** and **`createOrThrow(attrs)`** save a new record at once, and point at it. The record itself isn’t saved.
|
|
445
452
|
|
|
446
|
-
| Option | Does
|
|
447
|
-
| ------------ |
|
|
448
|
-
| `foreignKey` | The attribute on this record that holds the link. Defaults to the association’s name + `Id`
|
|
449
|
-
| `primaryKey` | The attribute on the target it points at. Defaults to the target’s primary key
|
|
450
|
-
| `scope` | Narrows the target, `(q) => q.where(…)`. See [Scoping associations](#scoping-associations)
|
|
453
|
+
| Option | Does |
|
|
454
|
+
| ------------ | --------------------------------------------------------------------------------------------------------- |
|
|
455
|
+
| `foreignKey` | The attribute on this record that holds the link. Defaults to the association’s name + `Id` |
|
|
456
|
+
| `primaryKey` | The attribute on the target it points at. Defaults to the target’s primary key |
|
|
457
|
+
| `scope` | Narrows the target, `(q) => q.where(…)`. See [Scoping associations](#scoping-associations) |
|
|
458
|
+
| `optional` | Lets the record point at nothing. See [Requiring the record](#requiring-the-record) |
|
|
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) |
|
|
461
|
+
|
|
462
|
+
### Requiring the record
|
|
463
|
+
|
|
464
|
+
Saving a record checks that each `belongsTo` points at a record that exists. If the foreign key is `null`, or no row has that key, the save fails with “must exist” on the association, such as `author`. The record it finds stays loaded. A saved record whose foreign key hasn’t changed isn’t checked again.
|
|
465
|
+
|
|
466
|
+
If a record may point at nothing, pass `optional: true`. A top-level category has no parent:
|
|
467
|
+
|
|
468
|
+
```ts
|
|
469
|
+
import { belongsTo, hasMany } from "@forestfuture/active-record";
|
|
470
|
+
|
|
471
|
+
export class Category extends ApplicationRecord {
|
|
472
|
+
// foreign key: parentId, from the association's name; optional, since a top-level category has none
|
|
473
|
+
parent = belongsTo(Category, { optional: true });
|
|
474
|
+
children = hasMany(Category, { foreignKey: "parentId" }); // not the default, categoryId
|
|
475
|
+
}
|
|
476
|
+
```
|
|
477
|
+
|
|
478
|
+
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).
|
|
479
|
+
|
|
480
|
+
> **Compared with Rails**
|
|
481
|
+
>
|
|
482
|
+
> Rails requires a `belongs_to` record by default too, and `optional: true` works the same. As in Rails 7.1, an unchanged foreign key isn’t checked. There’s no setting to turn the check off for every association, like Rails’ `belongs_to_required_by_default`.
|
|
451
483
|
|
|
452
484
|
## hasMany
|
|
453
485
|
|
|
@@ -466,7 +498,12 @@ await author.articles().where({ title: "Untitled" }).deleteAll(); // bulk writes
|
|
|
466
498
|
- **`record.posts()`** is a Relation of the associated records, with every Relation method and the target’s scopes.
|
|
467
499
|
- **`record.posts().build(attrs)`** builds a record with the owner’s key, saved with the owner. See [Autosaving](#autosaving).
|
|
468
500
|
- **`record.posts().create(attrs)`** and **`createOrThrow(attrs)`** save a new record at once. The owner must already be saved.
|
|
469
|
-
- **`
|
|
501
|
+
- **`record.posts().push(...records)`** adds records. It sets their foreign key and saves them in one write, or resolves to `false` and saves none if one can’t be saved. On an unsaved owner, they’re saved with it.
|
|
502
|
+
- **`record.posts().delete(...records)`** removes records by the `dependent` strategy. It destroys them for `"destroy"`, deletes them for `"deleteAll"`, and otherwise sets their foreign key to `NULL`.
|
|
503
|
+
- **`record.posts().destroy(...records)`** destroys records with their callbacks, whatever the strategy.
|
|
504
|
+
- **`record.posts().clear()`** removes every record, as `deleteAll()` does.
|
|
505
|
+
- **`record.posts().destroyAll()`** destroys every record with its callbacks, whatever the strategy, and leaves the association empty.
|
|
506
|
+
- **`insert`, `upsert`, `updateAll`, and `deleteAll`** write to the owner’s records. See [Writing many rows](#writing-many-rows).
|
|
470
507
|
|
|
471
508
|
| Option | Does |
|
|
472
509
|
| ------------ | ---------------------------------------------------------------------------------------------------------------- |
|
|
@@ -474,6 +511,8 @@ await author.articles().where({ title: "Untitled" }).deleteAll(); // bulk writes
|
|
|
474
511
|
| `primaryKey` | The attribute on this record the foreign key points at. Defaults to the primary key |
|
|
475
512
|
| `scope` | Narrows or orders the records, `(q) => q.order(…)`. See [Scoping associations](#scoping-associations) |
|
|
476
513
|
| `dependent` | What destroying the owner does to the records. See [Destroying dependent records](#destroying-dependent-records) |
|
|
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) |
|
|
477
516
|
|
|
478
517
|
## hasOne
|
|
479
518
|
|
|
@@ -487,17 +526,128 @@ if (profile === null) await author.profile.create({ bio: "Writer" }); // saved a
|
|
|
487
526
|
```
|
|
488
527
|
|
|
489
528
|
- **`await record.profile()`** reads the associated record, or `null`. If several records point at the owner, it’s the first by the scope’s order, then the primary key.
|
|
529
|
+
- **`await record.profile.set(profile)`** gives the owner another record, and `set(null)` removes it. On a saved owner, the record is saved at once, so await it. On an unsaved owner, it’s saved with the owner.
|
|
490
530
|
- **`record.profile.build(attrs)`** builds a record with the owner’s key, saved with the owner.
|
|
491
531
|
- **`record.profile.create(attrs)`** and **`createOrThrow(attrs)`** save a new record at once. The owner must already be saved.
|
|
492
532
|
|
|
493
533
|
`hasOne` takes the same options as `hasMany`.
|
|
494
534
|
|
|
535
|
+
### Replacing the record
|
|
536
|
+
|
|
537
|
+
Giving a saved owner a new record removes its old one, by the association’s `dependent` strategy:
|
|
538
|
+
|
|
539
|
+
```ts
|
|
540
|
+
const author = await Author.find(authorId);
|
|
541
|
+
const profile = Profile.build({ bio: "Novelist" });
|
|
542
|
+
|
|
543
|
+
await author.profile.set(profile); // saves it, and deletes the old profile in the same batch
|
|
544
|
+
```
|
|
545
|
+
|
|
546
|
+
| `dependent` | What happens to the old record |
|
|
547
|
+
| ----------------------------------------- | ------------------------------------------------ |
|
|
548
|
+
| `"destroy"` | It’s destroyed, with its own callbacks |
|
|
549
|
+
| `"delete"` | It’s deleted, without callbacks |
|
|
550
|
+
| `"nullify"`, a restrict strategy, or none | Its foreign key is set to `NULL`, and it’s saved |
|
|
551
|
+
|
|
552
|
+
The old record is removed in the same atomic batch that writes the new one. That’s at once for `set` and `create`, and when the owner is saved for `build`.
|
|
553
|
+
|
|
554
|
+
If the old record can’t be saved with a `NULL` foreign key, the write throws `RecordNotSaved`, and nothing is written. 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.
|
|
555
|
+
|
|
556
|
+
> **Compared with Rails**
|
|
557
|
+
>
|
|
558
|
+
> `await user.profile.set(profile)` is Rails’ `user.profile = profile`. Rails removes the old record as soon as you build a new one, so a build that’s never saved still loses it. Here, `build` waits for the owner’s save.
|
|
559
|
+
|
|
560
|
+
## Polymorphic associations
|
|
561
|
+
|
|
562
|
+
A polymorphic `belongsTo` points at a record of any of several Models, listed in an array. A like can belong to a photo or a video:
|
|
563
|
+
|
|
564
|
+
```ts
|
|
565
|
+
import { belongsTo, hasMany, Model } from "@forestfuture/active-record";
|
|
566
|
+
|
|
567
|
+
export class Photo extends Model.define({
|
|
568
|
+
id: { type: "integer", null: false },
|
|
569
|
+
title: { type: "string", null: false },
|
|
570
|
+
}) {
|
|
571
|
+
likes = hasMany(Like, { as: "likeable" }); // Like's likeableType is "Photo"
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
export class Video extends Model.define({
|
|
575
|
+
id: { type: "integer", null: false },
|
|
576
|
+
title: { type: "string", null: false },
|
|
577
|
+
}) {
|
|
578
|
+
likes = hasMany(Like, { as: "likeable" }); // Like's likeableType is "Video"
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
export class Like extends Model.define({
|
|
582
|
+
id: { type: "integer", null: false },
|
|
583
|
+
likeableType: { type: "string", null: false },
|
|
584
|
+
likeableId: { type: "integer", null: false },
|
|
585
|
+
}) {
|
|
586
|
+
likeable = belongsTo([Photo, Video]); // its own likeableType and likeableId
|
|
587
|
+
}
|
|
588
|
+
```
|
|
589
|
+
|
|
590
|
+
The record holds the link in two attributes: a type, which names the Model, and a foreign key. They’re the association’s name with `Type` and `Id`, so `likeable` uses `likeableType` and `likeableId`. On each listed Model, a `hasMany` or `hasOne` names the `belongsTo` with `as`, and reads the records whose type is that Model.
|
|
591
|
+
|
|
592
|
+
- **`await like.likeable()`** reads the record of the Model the type names, or `null`.
|
|
593
|
+
- **`like.likeable.set(video)`** sets both the type and the foreign key, and `set(null)` clears both. It’s written when the record is saved.
|
|
594
|
+
- **`video.likes()`** works like any `hasMany`. Records built, created, or pushed through it get the video’s type and key. Removing records through it, or by a `"nullify"` strategy, clears both.
|
|
595
|
+
|
|
596
|
+
Here’s each of them at work:
|
|
597
|
+
|
|
598
|
+
```ts
|
|
599
|
+
const like = await Like.find(likeId);
|
|
600
|
+
const liked = await like.likeable(); // a Photo, a Video, or null
|
|
601
|
+
|
|
602
|
+
like.likeable.set(video); // likeableType "Video", likeableId video.id
|
|
603
|
+
await like.save();
|
|
604
|
+
|
|
605
|
+
const likes = await video.likes().toArray(); // the likes whose type is "Video"
|
|
606
|
+
```
|
|
607
|
+
|
|
608
|
+
| Option | Does |
|
|
609
|
+
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
|
|
610
|
+
| `foreignType` | The attribute that holds the type. Defaults to the association’s name + `Type`, or on a `hasMany` or `hasOne`, the `as` name + `Type` |
|
|
611
|
+
| `as` | On a `hasMany` or `hasOne`: the name of the target’s polymorphic `belongsTo`. Its foreign key defaults to that name + `Id` |
|
|
612
|
+
|
|
613
|
+
The polymorphic `belongsTo` also takes `foreignKey`, `primaryKey`, `optional`, and `autosave`, as any `belongsTo` does.
|
|
614
|
+
|
|
615
|
+
:::note
|
|
616
|
+
The polymorphic side has no `build` or `create`, since it can’t tell which Model to make, and no `scope`. Neither D1 nor Postgres can enforce a foreign key that points at a different table in each row.
|
|
617
|
+
:::
|
|
618
|
+
|
|
619
|
+
### Storing the type
|
|
620
|
+
|
|
621
|
+
The type holds the listed Model’s `modelName`, such as `"Photo"`. A subclass of a listed Model is stored as the Model whose table it shares. If a stored type names none of the listed Models, reading the association throws `UnknownModelName`.
|
|
622
|
+
|
|
623
|
+
:::warning[Set modelName if your bundler renames classes]
|
|
624
|
+
The type is saved in your rows. A Model’s name is its class name unless it sets `static modelName`, so a bundler that renames `Photo` to `e` saves `"e"`, and a later build can’t read those rows. Wrangler keeps class names by default. With any other bundler, set `static modelName` on each listed Model. See [Naming Models](/models#naming-models).
|
|
625
|
+
:::
|
|
626
|
+
|
|
627
|
+
### Preloading polymorphic records
|
|
628
|
+
|
|
629
|
+
`includes` preloads a polymorphic association with one query for each listed Model:
|
|
630
|
+
|
|
631
|
+
```ts
|
|
632
|
+
const likes = await Like.includes("likeable").toArray(); // likes, photos and videos, in one round trip
|
|
633
|
+
|
|
634
|
+
for (const like of likes) {
|
|
635
|
+
console.log(like.loaded("likeable")?.title); // no query: already loaded
|
|
636
|
+
}
|
|
637
|
+
```
|
|
638
|
+
|
|
639
|
+
Each query runs the likes’ query again to find their keys, even for a Model no like points at. Index what that query filters and sorts by. A nested include can name an association that only some listed Models have: `includes({ likeable: "album" })` loads the photos’ albums and skips the videos.
|
|
640
|
+
|
|
641
|
+
> **Compared with Rails**
|
|
642
|
+
>
|
|
643
|
+
> Rails declares `belongs_to :likeable, polymorphic: true` without a list, and finds the class from the stored name. Here you list the Models, so `await like.likeable()` is typed `Photo | Video | null`. Rails preloads a polymorphic association after the likes load, with one query per type it finds. Here every listed Model’s query goes with the likes’ own, in one round trip. The cost is that each of them reads the likes’ query again, even for a Model no like points at. Records built through `video.likes()` point back at the video without a query, which Rails doesn’t do for a polymorphic association.
|
|
644
|
+
|
|
495
645
|
## Naming foreign keys
|
|
496
646
|
|
|
497
647
|
A foreign key names an attribute, such as `authorId`, rather than a column. By default, it’s inferred:
|
|
498
648
|
|
|
499
649
|
- **`belongsTo`** uses the association’s name + `Id`. `author = belongsTo(Author)` uses the record’s own `authorId`.
|
|
500
|
-
- **`hasMany` and `hasOne`** use the Model’s
|
|
650
|
+
- **`hasMany` and `hasOne`** use the Model’s name + `Id`, on the target. `Author`’s associations use `authorId`, `BlogPost`’s use `blogPostId`, and `APIKey`’s use `apiKeyId`.
|
|
501
651
|
|
|
502
652
|
If the name doesn’t follow the convention, pass `foreignKey`:
|
|
503
653
|
|
|
@@ -513,7 +663,7 @@ Keys are checked the first time a Model is used, and a missing attribute throws
|
|
|
513
663
|
|
|
514
664
|
**Bundlers and class names**
|
|
515
665
|
|
|
516
|
-
Wrangler keeps class names by default, even when minifying. If a bundler renames `Author` to `e`, the inferred `eId` doesn’t exist, and the first use of the Model throws `InvalidModel`, saying where the key came from.
|
|
666
|
+
A Model’s name is its class name, unless it sets `static modelName`. Wrangler keeps class names by default, even when minifying. If a bundler renames `Author` to `e`, the inferred `eId` doesn’t exist, and the first use of the Model throws `InvalidModel`, saying where the key came from. Set `static modelName = "Author"` (see [Naming Models](/models#naming-models)), pass `foreignKey`, or keep class names in your bundler’s settings.
|
|
517
667
|
|
|
518
668
|
## Caching loaded records
|
|
519
669
|
|
|
@@ -528,7 +678,7 @@ const latest = await author?.articles().first();
|
|
|
528
678
|
|
|
529
679
|
- Changing a foreign key makes the next read query again.
|
|
530
680
|
- `reload()` clears the cache, and `await record.reloadAssociation("articles")` reloads one association.
|
|
531
|
-
- A write through a `hasMany` clears its loaded collection: `insert`, `upsert`, `updateAll` and `deleteAll`, alone or in `db.batch`, even after `where` or `order`, or with the association joined by `or()`, `merge()` or a scope. `create`
|
|
681
|
+
- A write through a `hasMany` clears its loaded collection: `insert`, `upsert`, `updateAll` and `deleteAll`, alone or in `db.batch`, even after `where` or `order`, or with the association joined by `or()`, `merge()` or a scope. `create`, `push`, `delete`, `destroy`, and `clear` on the association itself update it instead, so the next read still doesn’t query.
|
|
532
682
|
- 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.
|
|
533
683
|
|
|
534
684
|
> **Beyond Rails**
|
|
@@ -539,6 +689,60 @@ const latest = await author?.articles().first();
|
|
|
539
689
|
A `belongsTo` whose foreign key is `null`, or an association on an unsaved owner, reads without a query.
|
|
540
690
|
:::
|
|
541
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
|
+
|
|
542
746
|
## Preloading associations
|
|
543
747
|
|
|
544
748
|
Load an association for every record at once with `includes`, with one query per association however many records there are:
|
|
@@ -555,7 +759,7 @@ for (const each of authors) {
|
|
|
555
759
|
|
|
556
760
|
Nest with an object: `includes({ articles: "comments" })` or `includes({ articles: ["comments", "tags"] })`.
|
|
557
761
|
|
|
558
|
-
The example above sends four queries, however many authors there are. On D1, the whole tree goes [in one round trip](/d1#sending-queries-in-one-round-trip) with the authors’ own query.
|
|
762
|
+
The example above sends four queries, however many authors there are. On D1, the whole tree goes [in one round trip](/d1#sending-queries-in-one-round-trip) with the authors’ own query. An association to [another database](/several-databases#associating-models-on-different-databases) takes one more.
|
|
559
763
|
|
|
560
764
|
:::note
|
|
561
765
|
With a `limit` or `offset`, `includes` ends the order with the primary key, so the preloads find the same records the query loads.
|
|
@@ -563,7 +767,7 @@ With a `limit` or `offset`, `includes` ends the order with the primary key, so t
|
|
|
563
767
|
|
|
564
768
|
> **Beyond Rails**
|
|
565
769
|
>
|
|
566
|
-
> Rails sends each association’s preload query on its own, so every association adds a round trip. On D1, the whole tree takes one.
|
|
770
|
+
> Rails sends each association’s preload query on its own, so every association adds a round trip. On D1, the whole tree on one database takes one.
|
|
567
771
|
|
|
568
772
|
:::note
|
|
569
773
|
`hasMany` and `hasOne` find their records by the foreign key, both with `includes` and when you read one record’s association, such as `author.articles()`. Add an index to the foreign key column. Otherwise D1 reads every row of the table for each lookup, and bills you for each row it reads. A `references` column from the [generators](/generators) is indexed already, and you can add an index to any other foreign key yourself:
|
|
@@ -598,9 +802,55 @@ ada.profile.build({ bio: "Mathematician" });
|
|
|
598
802
|
await ada.saveOrThrow(); // the author, both articles and the profile, in one batch
|
|
599
803
|
```
|
|
600
804
|
|
|
601
|
-
The built records are validated with the owner. An invalid article makes the author invalid (“Articles is invalid”), with its own errors on the article.
|
|
805
|
+
The built records are validated with the owner. An invalid article makes the author invalid (“Articles is invalid”), with its own errors on the article. To validate the records an association loaded too, use [`validatesAssociated`](/validations#validating-associated-records). Each built article’s `author` is the owner, without a query, even before either is saved.
|
|
806
|
+
|
|
807
|
+
When the owner’s key is generated in code, as here, everything is written in one atomic batch. Records on [another database](/several-databases#associating-models-on-different-databases) are written there separately.
|
|
808
|
+
|
|
809
|
+
#### Saving changed records
|
|
602
810
|
|
|
603
|
-
|
|
811
|
+
By default, only new records are saved with their owner. Declare an association with `autosave: true` to save the changes to its loaded records too, as `Author`’s `articles` does above:
|
|
812
|
+
|
|
813
|
+
```ts
|
|
814
|
+
const author = await Author.find(authorId);
|
|
815
|
+
const articles = await author.articles().toArray();
|
|
816
|
+
|
|
817
|
+
for (const article of articles) article.title = article.title.toUpperCase();
|
|
818
|
+
await author.saveOrThrow(); // every article that changed, in one batch
|
|
819
|
+
```
|
|
820
|
+
|
|
821
|
+
Saving the author saves each article that changed, in the same atomic batch. Unchanged articles aren’t validated or written. Only the records the association holds count: those it loaded, and those built through it. A record you found with a query of its own isn’t saved.
|
|
822
|
+
|
|
823
|
+
The changed records are validated with the owner. An invalid one’s errors are copied to the owner under the association’s name: an article with a blank title gives the author an `articles.title` error, “Articles title can’t be blank”.
|
|
824
|
+
|
|
825
|
+
`autosave: true` works on a `hasOne` and a `belongsTo` too. A `belongsTo`’s record is saved before its owner.
|
|
826
|
+
|
|
827
|
+
#### Removing records on save
|
|
828
|
+
|
|
829
|
+
Mark a record with `markForDestruction()` to destroy it when its owner is saved:
|
|
830
|
+
|
|
831
|
+
```ts
|
|
832
|
+
const author = await Author.find(authorId);
|
|
833
|
+
const articles = await author.articles().toArray();
|
|
834
|
+
|
|
835
|
+
for (const article of articles) {
|
|
836
|
+
if (article.title.startsWith("Draft")) article.markForDestruction();
|
|
837
|
+
}
|
|
838
|
+
await author.saveOrThrow(); // destroys the drafts, with their comments
|
|
839
|
+
```
|
|
840
|
+
|
|
841
|
+
Marking writes nothing, and the marked articles stay in `author.articles()` until the author is saved. Then each is destroyed with its callbacks and `dependent` strategies, in the same batch as the author, and leaves the association. Changed articles are saved after the destroys.
|
|
842
|
+
|
|
843
|
+
`isMarkedForDestruction()` reads the mark, and `reload()` clears it. A marked record that was never saved is dropped from the association, and nothing is written for it. Through a `belongsTo`, the owner’s foreign key is set to `null`, and the owner is written before its record is destroyed.
|
|
844
|
+
|
|
845
|
+
If a marked record refuses to be destroyed, because its `beforeDestroy` aborts or a `restrictWithError` strategy stops it, nothing is written. `save()` returns `false`, and `saveOrThrow()` throws `RecordNotDestroyed`. The marked record holds the reason, in `abortReason` or `errors`.
|
|
846
|
+
|
|
847
|
+
:::note
|
|
848
|
+
A mark only counts through an association declared `autosave: true`.
|
|
849
|
+
:::
|
|
850
|
+
|
|
851
|
+
> **Compared with Rails**
|
|
852
|
+
>
|
|
853
|
+
> `autosave: true`, `markForDestruction`, and the copied errors work as in Rails. Rails destroys a marked `belongs_to` record before it saves the owner. Here the owner is written first, so a foreign key constraint doesn’t refuse the delete. When a marked record refuses to be destroyed, Rails raises from `save` for a `has_many`, and saves the owner anyway for a `has_one` or `belongs_to`. Here the save is refused the same way for every association.
|
|
604
854
|
|
|
605
855
|
:::warning[Keys D1 generates]
|
|
606
856
|
When D1 generates the key, with an `INTEGER PRIMARY KEY`, the key doesn’t exist until the owner is written. So the owner is written first, and its records follow in the next batch, a level at a time. The batches aren’t atomic together: if a record fails at the second level, the save throws with the owner already saved. Generate keys in code wherever a graph must save all at once.
|
|
@@ -621,7 +871,7 @@ export class Blog extends Model.define({ id: { type: "integer", null: false } })
|
|
|
621
871
|
}
|
|
622
872
|
```
|
|
623
873
|
|
|
624
|
-
The scope applies to reads and preloads alike, and records created through the association take its equality values. `q` is the target’s Relation, with its attributes and scopes.
|
|
874
|
+
The scope applies to reads and preloads alike, and records created through the association take its equality values. `q` is the target’s Relation, with its attributes and scopes. The target’s [default scope](/querying#defining-a-default-scope) applies too.
|
|
625
875
|
|
|
626
876
|
:::note
|
|
627
877
|
A scope that uses `limit`, `offset`, or `distinct` can’t be preloaded, since it would apply to every owner’s records together. `includes` throws `IncompatibleRelation` before it sends any preload.
|
|
@@ -645,10 +895,149 @@ export class Category extends Model.define({
|
|
|
645
895
|
foreignKey: "parentId",
|
|
646
896
|
scope: (q) => q.top(),
|
|
647
897
|
});
|
|
648
|
-
parent = belongsTo(Category, { foreignKey: "parentId" });
|
|
898
|
+
parent = belongsTo(Category, { foreignKey: "parentId", optional: true });
|
|
649
899
|
}
|
|
650
900
|
```
|
|
651
901
|
|
|
902
|
+
## Reaching records through another association
|
|
903
|
+
|
|
904
|
+
Reach records through another association with `through`. A tag has many articles through its taggings:
|
|
905
|
+
|
|
906
|
+
```ts
|
|
907
|
+
import { belongsTo, hasMany, Model } from "@forestfuture/active-record";
|
|
908
|
+
|
|
909
|
+
export class Tag extends Model.define({
|
|
910
|
+
id: { type: "integer", null: false },
|
|
911
|
+
name: { type: "string", null: false },
|
|
912
|
+
}) {
|
|
913
|
+
taggings = hasMany(Tagging);
|
|
914
|
+
articles = hasMany(Article, { through: "taggings" }); // each tagging's article
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
export class Tagging extends Model.define({
|
|
918
|
+
id: { type: "integer", null: false },
|
|
919
|
+
articleId: { type: "string", null: false },
|
|
920
|
+
tagId: { type: "integer", null: false },
|
|
921
|
+
}) {
|
|
922
|
+
article = belongsTo(Article);
|
|
923
|
+
tag = belongsTo(Tag);
|
|
924
|
+
}
|
|
925
|
+
```
|
|
926
|
+
|
|
927
|
+
`through` names one of the Model’s own associations, here `taggings`. The join Model’s association with the same name, singular or plural, leads on to the records: `articles` follows each tagging’s `article`.
|
|
928
|
+
|
|
929
|
+
| Option | Does |
|
|
930
|
+
| --------- | ----------------------------------------------------------------------------------------------- |
|
|
931
|
+
| `through` | The association to go through |
|
|
932
|
+
| `source` | The join Model’s association to follow. Defaults to this association’s name, singular or plural |
|
|
933
|
+
| `scope` | Narrows or orders the records. See [Scoping associations](#scoping-associations) |
|
|
934
|
+
|
|
935
|
+
### Naming the source
|
|
936
|
+
|
|
937
|
+
If the join Model’s association has another name, pass it as `source`:
|
|
938
|
+
|
|
939
|
+
```ts
|
|
940
|
+
import { hasMany } from "@forestfuture/active-record";
|
|
941
|
+
|
|
942
|
+
writers = hasMany(Author, { through: "articles", source: "author" }); // each article's author
|
|
943
|
+
```
|
|
944
|
+
|
|
945
|
+
### Reading and preloading
|
|
946
|
+
|
|
947
|
+
Read it as you would any `hasMany`:
|
|
948
|
+
|
|
949
|
+
```ts
|
|
950
|
+
const tag = await Tag.find(tagId);
|
|
951
|
+
const articles = await tag.articles().order({ title: "asc" }).toArray(); // one query
|
|
952
|
+
|
|
953
|
+
const tags = await Tag.includes("articles").toArray(); // tags, taggings, and articles: one round trip
|
|
954
|
+
for (const each of tags) console.log(each.name, each.loaded("articles").length);
|
|
955
|
+
```
|
|
956
|
+
|
|
957
|
+
- **`tag.articles()`** is a Relation, with every Relation method, read in one query. Its writes go to the taggings, as [below](#writing-through-it).
|
|
958
|
+
- **Each record comes back once**, however many join records point at it.
|
|
959
|
+
- **`includes("articles")`** loads the join records and the articles with the tags’ own query, in one round trip on D1. The join records aren’t kept as `taggings` unless you include them too.
|
|
960
|
+
|
|
961
|
+
The scopes of both associations it goes through apply, and so does its own `scope`.
|
|
962
|
+
|
|
963
|
+
### Going through a belongsTo or a hasOne
|
|
964
|
+
|
|
965
|
+
`through` can name a `belongsTo`, a `hasMany`, or a `hasOne`, and the association it follows can be any of the three. A `hasOne` goes through a `belongsTo` or a `hasOne`:
|
|
966
|
+
|
|
967
|
+
```ts
|
|
968
|
+
import { hasOne } from "@forestfuture/active-record";
|
|
969
|
+
|
|
970
|
+
author = hasOne(Author, { through: "article" }); // the article's author
|
|
971
|
+
```
|
|
972
|
+
|
|
973
|
+
An association can also go through one that goes through another, as `writers` does above through `articles`.
|
|
974
|
+
|
|
975
|
+
### Writing through it
|
|
976
|
+
|
|
977
|
+
Add records through the association with `push`, `build`, and `create`. Each makes the join record that links the owner to the record:
|
|
978
|
+
|
|
979
|
+
```ts
|
|
980
|
+
const tag = await Tag.find(tagId);
|
|
981
|
+
const article = await Article.find(articleId);
|
|
982
|
+
|
|
983
|
+
await tag.articles().push(article); // saves a tagging that links them
|
|
984
|
+
const draft = await tag.articles().create({ authorId: article.authorId, title: "Draft" });
|
|
985
|
+
|
|
986
|
+
await tag.articles().delete(article); // deletes the tagging; the article stays
|
|
987
|
+
```
|
|
988
|
+
|
|
989
|
+
- **`push(article)`** saves a tagging for each article, in one write. A new article is saved first.
|
|
990
|
+
- **`build(attributes)`** builds the article and its tagging. Saving the tag saves both. Saving the article on its own saves no tagging.
|
|
991
|
+
- **`create(attributes)`** saves the article, then its tagging. An invalid article comes back unsaved, and nothing is written.
|
|
992
|
+
|
|
993
|
+
On a tag that isn’t saved yet, `push` and `build` wait for the tag’s save. `create` throws `RecordNotSaved` there, as it does through a `hasMany`.
|
|
994
|
+
|
|
995
|
+
Records built or created through it take the equality values of its `scope`, and their join records take those of the association it goes through.
|
|
996
|
+
|
|
997
|
+
#### Removing records
|
|
998
|
+
|
|
999
|
+
Removing records through the association removes their join records. The records themselves stay:
|
|
1000
|
+
|
|
1001
|
+
| Method | Does |
|
|
1002
|
+
| ------------------ | --------------------------------------------------------------------------------------------------- |
|
|
1003
|
+
| `delete(article)` | Deletes the tag’s taggings to the article, without callbacks |
|
|
1004
|
+
| `destroy(article)` | Destroys those taggings, running their callbacks, in one write |
|
|
1005
|
+
| `clear()` | Deletes every tagging to the tag’s articles, without callbacks. The tag then has no articles loaded |
|
|
1006
|
+
| `deleteAll()` | Deletes the same taggings, and resolves to how many it deleted |
|
|
1007
|
+
| `destroyAll()` | Destroys the same taggings, running their callbacks, and resolves to the articles |
|
|
1008
|
+
|
|
1009
|
+
An article the tag doesn’t reach removes nothing. To remove an article itself, destroy it: `await article.destroy()`.
|
|
1010
|
+
|
|
1011
|
+
In a batch, pass the association to the write: `b.deleteAll(tag.articles())` deletes the tag’s taggings.
|
|
1012
|
+
|
|
1013
|
+
:::warning[A narrowed deleteAll or destroyAll removes the records themselves]
|
|
1014
|
+
`updateAll`, and a narrowed `deleteAll` or `destroyAll`, act on the records, as any Relation’s do. `tag.articles().where({ title: "Draft" }).deleteAll()` deletes those articles for every tag, not the tag’s taggings.
|
|
1015
|
+
:::
|
|
1016
|
+
|
|
1017
|
+
#### Removing join records with dependent
|
|
1018
|
+
|
|
1019
|
+
A `hasMany` through a join Model takes `dependent: "destroy"` or `dependent: "deleteAll"`, which acts on its join records. With `"destroy"`, destroying the tag destroys its taggings, running their callbacks, and `delete` destroys them too. With `"deleteAll"`, destroying the tag deletes them without callbacks. `clear` and `deleteAll` always delete them without callbacks.
|
|
1020
|
+
|
|
1021
|
+
#### Setting a hasOne through another
|
|
1022
|
+
|
|
1023
|
+
A `hasOne` that goes through another `hasOne` has `set`. `await member.club.set(club)` points the member’s membership at the club, or creates a membership if there isn’t one, with the equality values of the membership association’s `scope`. `set(null)` destroys the membership. It has no `build` or `create`.
|
|
1024
|
+
|
|
1025
|
+
#### Spotting read-only associations
|
|
1026
|
+
|
|
1027
|
+
Writes need a join Model: the association has to go through a `hasMany` (a `hasOne`, for a `hasOne`), and follow a `belongsTo` from there, with neither going through another. Any other write throws `ReadonlyAssociation`, naming the association that stops it. `writers` above is read-only, since it goes through `articles`, which goes through `taggings`.
|
|
1028
|
+
|
|
1029
|
+
`insert`, `insertAll`, `upsert`, and `upsertAll` throw `ReadonlyAssociation` on any association through another, since they write no join records.
|
|
1030
|
+
|
|
1031
|
+
:::note
|
|
1032
|
+
Every association it goes through must be on one database. One that reaches [another database](/several-databases#associating-models-on-different-databases) is an `InvalidModel` for now ([#435](https://github.com/forestfuture/active-record/issues/435)).
|
|
1033
|
+
:::
|
|
1034
|
+
|
|
1035
|
+
> **Compared with Rails**
|
|
1036
|
+
>
|
|
1037
|
+
> `through` and `source` work as Rails’ `has_many :through` and `has_one :through` options do. Rails reads through a SQL join, so a record two join records point at comes back twice unless the association is `distinct`. Here it comes back once.
|
|
1038
|
+
>
|
|
1039
|
+
> Writing through it works as in Rails: `destroy` destroys the join records rather than the records, `clear` deletes them whatever `dependent` is, and `insert_all` through it raises. Rails also writes through a `belongsTo` or `hasOne` hop by building or updating that hop’s record, which can change a record that other records share. Here that throws `ReadonlyAssociation`. Rails’ `disable_joins` has no counterpart yet.
|
|
1040
|
+
|
|
652
1041
|
## Destroying dependent records
|
|
653
1042
|
|
|
654
1043
|
Set what destroying the owner does to its records with `dependent`:
|
|
@@ -661,30 +1050,161 @@ Set what destroying the owner does to its records with `dependent`:
|
|
|
661
1050
|
| `"restrictWithException"` | The destroy throws `DeleteRestriction` while there are records |
|
|
662
1051
|
| `"restrictWithError"` | The destroy returns `false`, with an error on the owner’s `base` |
|
|
663
1052
|
|
|
664
|
-
Everything a destroy does
|
|
1053
|
+
Everything a destroy does on the owner’s database, its DELETE included, is written in one atomic batch. Records on [another database](/several-databases#associating-models-on-different-databases) are written there separately. Strategies run after the owner’s `beforeDestroy` callbacks, so an `abort()` leaves the records alone.
|
|
665
1054
|
|
|
666
1055
|
:::note
|
|
667
1056
|
Without a strategy, it’s up to the database. If the table declares the foreign key with `REFERENCES`, destroying an owner whose records still point at it throws `InvalidForeignKey`.
|
|
668
1057
|
:::
|
|
669
1058
|
|
|
1059
|
+
## Counting records with a counter cache
|
|
1060
|
+
|
|
1061
|
+
To keep a count of an article’s comments on the article itself, declare `counterCache` on the comment’s `belongsTo`:
|
|
1062
|
+
|
|
1063
|
+
```ts
|
|
1064
|
+
import { belongsTo, hasMany, Model } from "@forestfuture/active-record";
|
|
1065
|
+
|
|
1066
|
+
export class Article extends Model.define({
|
|
1067
|
+
id: { type: "integer", null: false },
|
|
1068
|
+
title: { type: "string", null: false },
|
|
1069
|
+
commentsCount: { type: "integer", null: false },
|
|
1070
|
+
updatedAt: "datetime",
|
|
1071
|
+
}) {
|
|
1072
|
+
comments = hasMany(Comment);
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
export class Comment extends Model.define({
|
|
1076
|
+
id: { type: "integer", null: false },
|
|
1077
|
+
articleId: "integer",
|
|
1078
|
+
body: { type: "string", null: false },
|
|
1079
|
+
}) {
|
|
1080
|
+
article = belongsTo(Article, { counterCache: true }); // keeps Article's commentsCount
|
|
1081
|
+
}
|
|
1082
|
+
```
|
|
1083
|
+
|
|
1084
|
+
The article needs an attribute for the count, named for the counted Model: `commentsCount` for comments. To keep it in another attribute, name it: `counterCache: "replyCount"`.
|
|
1085
|
+
|
|
1086
|
+
Creating a comment adds one to its article’s count, and destroying it takes one away:
|
|
1087
|
+
|
|
1088
|
+
```ts
|
|
1089
|
+
const article = await Article.find(id);
|
|
1090
|
+
const comment = await article.comments().create({ body: "First!" }); // commentsCount + 1
|
|
1091
|
+
await comment.destroy(); // commentsCount - 1
|
|
1092
|
+
```
|
|
1093
|
+
|
|
1094
|
+
Changing a comment’s `articleId` moves the count to the other article. An article you’ve loaded takes the new count too, without a save.
|
|
1095
|
+
|
|
1096
|
+
:::tip
|
|
1097
|
+
Each change is written in the same atomic batch as the comment, so the count can’t drift from the rows.
|
|
1098
|
+
:::
|
|
1099
|
+
|
|
1100
|
+
Removing comments through the article’s association counts them out: `delete`, `clear`, and `deleteAll()` on `article.comments()`. Removing records through an association through another counts out its join records the same way. Bulk writes leave the count alone: `insert`, `insertAll`, `upsert`, `updateAll`, and `deleteAll()` on any other Relation.
|
|
1101
|
+
|
|
1102
|
+
:::note
|
|
1103
|
+
A polymorphic `belongsTo` counts a record on whichever listed Model its type names, so each of them declares the attribute. A counter cache on a Model on [another database](/several-databases) throws `InvalidModel`, since its count couldn’t be written in the same batch. So do two `belongsTo`s on one foreign key that keep the same attribute, since each comment would count twice.
|
|
1104
|
+
:::
|
|
1105
|
+
|
|
1106
|
+
### Reading the count
|
|
1107
|
+
|
|
1108
|
+
`size()`, `isEmpty()`, and `hasAny()` on the association read the count, without a query:
|
|
1109
|
+
|
|
1110
|
+
```ts
|
|
1111
|
+
await article.comments().create({ body: "Hello" });
|
|
1112
|
+
const count = await article.comments().size(); // reads commentsCount, no query
|
|
1113
|
+
```
|
|
1114
|
+
|
|
1115
|
+
An association reads the counter named for it: `comments` reads `commentsCount`. If its counter has another name, name it on the `hasMany` too:
|
|
1116
|
+
|
|
1117
|
+
```ts
|
|
1118
|
+
import { belongsTo, hasMany, Model } from "@forestfuture/active-record";
|
|
1119
|
+
|
|
1120
|
+
export class Forum extends Model.define({
|
|
1121
|
+
id: { type: "integer", null: false },
|
|
1122
|
+
replyCount: { type: "integer", null: false },
|
|
1123
|
+
}) {
|
|
1124
|
+
replies = hasMany(Reply, { counterCache: "replyCount" }); // not repliesCount
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
export class Reply extends Model.define({
|
|
1128
|
+
id: { type: "integer", null: false },
|
|
1129
|
+
forumId: "integer",
|
|
1130
|
+
}) {
|
|
1131
|
+
forum = belongsTo(Forum, { counterCache: "replyCount" });
|
|
1132
|
+
}
|
|
1133
|
+
```
|
|
1134
|
+
|
|
1135
|
+
An association with any other name counts its rows, so one narrowed by a scope counts only its own records.
|
|
1136
|
+
|
|
1137
|
+
:::note
|
|
1138
|
+
`count()` always counts the rows.
|
|
1139
|
+
:::
|
|
1140
|
+
|
|
1141
|
+
### Resetting a count
|
|
1142
|
+
|
|
1143
|
+
To set a count from the rows, after a bulk write for example, use `resetCounters`:
|
|
1144
|
+
|
|
1145
|
+
```ts
|
|
1146
|
+
await Article.resetCounters(id, "comments", { touch: true });
|
|
1147
|
+
```
|
|
1148
|
+
|
|
1149
|
+
It takes one association’s name or a list of them. It sets every counter the association’s records keep on the article. `touch: true` also sets `updatedAt`. An association with a scope can’t reset a counter, since its records aren’t all the ones counted.
|
|
1150
|
+
|
|
1151
|
+
### Adding a counter to existing records
|
|
1152
|
+
|
|
1153
|
+
A new counter starts at zero, even for an article that already has comments. To fill it in before anything reads it, declare it with `active: false`:
|
|
1154
|
+
|
|
1155
|
+
```ts
|
|
1156
|
+
import { belongsTo, Model } from "@forestfuture/active-record";
|
|
1157
|
+
|
|
1158
|
+
export class ImportedComment extends Model.define({
|
|
1159
|
+
id: { type: "integer", null: false },
|
|
1160
|
+
articleId: "integer",
|
|
1161
|
+
}) {
|
|
1162
|
+
static table = "comments";
|
|
1163
|
+
// Writes keep commentsCount, but nothing reads it until active: false goes.
|
|
1164
|
+
article = belongsTo(Article, { counterCache: { attribute: "commentsCount", active: false } });
|
|
1165
|
+
}
|
|
1166
|
+
```
|
|
1167
|
+
|
|
1168
|
+
Writes keep the count up to date, while `size()` and the others count the rows. Run `resetCounters` for each article, then remove `active: false`.
|
|
1169
|
+
|
|
1170
|
+
> **Compared with Rails**
|
|
1171
|
+
>
|
|
1172
|
+
> Rails takes one from the article the comment’s key pointed at when it was loaded. Here the count is taken from the article the comment’s row points at as it’s deleted, so a comment that’s already gone, or that another request moved, doesn’t throw the count off.
|
|
1173
|
+
>
|
|
1174
|
+
> `counterCache` names an attribute, where Rails’ `counter_cache` names a column. Rails also makes the counter read-only. Here it’s an ordinary attribute.
|
|
1175
|
+
>
|
|
1176
|
+
> In Rails, removing records through a scoped association leaves the count too high, and `reset_counters` on one writes the scope’s count into the counter. Here the removal counts its records out, and `resetCounters` refuses the scoped association.
|
|
1177
|
+
>
|
|
1178
|
+
> Rails counts a comment twice when two `belongs_to`s keep the same counter. Here that throws `InvalidModel`.
|
|
1179
|
+
>
|
|
1180
|
+
> Rails’ `belongs_to … touch: true` also touches the article when its count changes. That option isn’t built yet ([#353](https://github.com/forestfuture/active-record/issues/353)).
|
|
1181
|
+
|
|
670
1182
|
## Writing many rows
|
|
671
1183
|
|
|
672
|
-
`insert`, `updateAll`, and `deleteAll` work through a `hasMany`, scoped to the owner’s records
|
|
1184
|
+
`insert`, `updateAll`, and `deleteAll` work through a `hasMany`, scoped to the owner’s records:
|
|
673
1185
|
|
|
674
1186
|
```ts
|
|
675
1187
|
await article.comments().deleteAll(); // one DELETE for the article's comments
|
|
676
1188
|
```
|
|
677
1189
|
|
|
1190
|
+
In a batch, pass the association to the write: `b.deleteAll(article.comments())`.
|
|
1191
|
+
|
|
1192
|
+
`upsert` and `upsertAll` through a `hasMany` only update the owner’s records. When a row clashes with another owner’s record, that record stays as it is. The row isn’t written, counted, or returned. To find out whether a row was skipped, compare `rowsAffected` with the number of rows you gave.
|
|
1193
|
+
|
|
1194
|
+
> **Beyond Rails**
|
|
1195
|
+
>
|
|
1196
|
+
> In Rails, `upsert_all` through an association writes the owner’s key into a clashing row. So `current_user.posts.upsert_all(rows)`, given an id from a request, moves another user’s post to the current user. Here that row is skipped, as `onDuplicate: "skip"` skips a duplicate.
|
|
1197
|
+
|
|
678
1198
|
`deleteAll()` on the association follows its `dependent` strategy: it deletes the records for `"destroy"` or `"deleteAll"`, and otherwise sets their foreign keys to `NULL`. See [Bulk writes and batches](/batches).
|
|
679
1199
|
|
|
680
1200
|
## Not built yet
|
|
681
1201
|
|
|
682
1202
|
These features aren’t in Active Record yet. The code shows the shape they’re likely to take.
|
|
683
1203
|
|
|
684
|
-
- **
|
|
685
|
-
- **
|
|
686
|
-
- **
|
|
687
|
-
- **
|
|
1204
|
+
- **Autosaving through an association through another** ([#450](https://github.com/forestfuture/active-record/issues/450)): `articles = hasMany(Article, { through: "taggings", autosave: true })`, which saves the tag’s changed articles with it.
|
|
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.
|
|
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.
|
|
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`.
|
|
688
1208
|
|
|
689
1209
|
---
|
|
690
1210
|
|
|
@@ -712,11 +1232,16 @@ console.log(deleted, rowsAffected, rows[0]?.id); // the new comment's key
|
|
|
712
1232
|
|
|
713
1233
|
- **`updateAll(changes)`** takes attributes or an `sql` fragment, and resolves to the number of rows updated. It leaves `updatedAt` alone. With a `limit` or `offset`, the Relation’s order picks which rows are written.
|
|
714
1234
|
- **`deleteAll()`** resolves to the number of rows deleted. On `none()`, both send nothing and resolve to `0`.
|
|
715
|
-
- **`
|
|
1235
|
+
- **`deleteBy(conditions)`** is `where(conditions).deleteAll()`. **`Comment.delete(id)`** deletes by primary key, and takes an array of keys too. Both resolve to the number of rows deleted.
|
|
1236
|
+
- **`insert(attrs)`** writes one row. It resolves to `{ rowsAffected, rows }`, and `rows` holds the new row’s primary key. Declared defaults and timestamps fill what isn’t given. A Relation’s equality conditions are written over what is given. So `Post.where({ userId: 1 }).insert({ title: "Hi", userId: 2 })` writes `userId: 1`.
|
|
1237
|
+
|
|
1238
|
+
:::note
|
|
1239
|
+
To run each record’s callbacks, destroy the records with [`destroyAll`](/persistence#destroying-many-records) instead.
|
|
1240
|
+
:::
|
|
716
1241
|
|
|
717
1242
|
### Inserting many rows
|
|
718
1243
|
|
|
719
|
-
Insert many rows
|
|
1244
|
+
Insert many rows at once with `insertAll`:
|
|
720
1245
|
|
|
721
1246
|
```ts
|
|
722
1247
|
import { Author, Comment } from "./models";
|
|
@@ -729,9 +1254,11 @@ await Author.upsert({ id: "author-1", name: "Ada" }); // insert, or update the n
|
|
|
729
1254
|
await Author.insert({ id: "author-1", name: "Ada" }, { onDuplicate: "skip" });
|
|
730
1255
|
```
|
|
731
1256
|
|
|
732
|
-
- **`insertAll(rows)`** inserts every row, however many
|
|
1257
|
+
- **`insertAll(rows)`** inserts every row, however many. Every row must have the same attributes. A duplicate throws and writes nothing.
|
|
733
1258
|
- **`{ onDuplicate: "skip" }`** skips rows that clash with a unique index.
|
|
734
|
-
- **`upsert(attrs)`** and **`upsertAll(rows)`** update a row that clashes with the primary key, or with the unique index named by `uniqueBy`.
|
|
1259
|
+
- **`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.
|
|
1260
|
+
- **Through a Relation**, `insertAll`, `upsert`, and `upsertAll` write its equality conditions over each row’s values, as `insert` does.
|
|
1261
|
+
- **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).
|
|
735
1262
|
|
|
736
1263
|
### Returning attributes
|
|
737
1264
|
|
|
@@ -757,37 +1284,44 @@ await Comment.insert({ articleId, body: "Three" }, { returning: false });
|
|
|
757
1284
|
|
|
758
1285
|
> **Compared with Rails**
|
|
759
1286
|
>
|
|
760
|
-
> 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
|
|
1287
|
+
> 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.
|
|
761
1288
|
|
|
762
1289
|
## Batching writes
|
|
763
1290
|
|
|
764
|
-
|
|
1291
|
+
Prepare several writes in `batch`’s callback to write them atomically:
|
|
765
1292
|
|
|
766
1293
|
```ts
|
|
767
1294
|
import { batch } from "@forestfuture/active-record";
|
|
768
1295
|
import { Article, Author } from "./models";
|
|
769
1296
|
|
|
770
1297
|
const authorId = crypto.randomUUID(); // generated in code, so rows can point at it
|
|
771
|
-
await batch([
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
Article.where({ authorId: "author-1" })
|
|
1298
|
+
await batch((b) => [
|
|
1299
|
+
b.insert(Author, { id: authorId, name: "Grace" }),
|
|
1300
|
+
b.insert(Article, { authorId, title: "Hello" }),
|
|
1301
|
+
b.deleteAll(Article.where({ authorId: "author-1" })),
|
|
775
1302
|
]);
|
|
776
1303
|
```
|
|
777
1304
|
|
|
778
|
-
|
|
1305
|
+
The callback gets `b`, with a method for each bulk write: `insert`, `insertAll`, `upsert`, `upsertAll`, `updateAll`, `updateCounters`, and `deleteAll`. Each takes what it writes to, then the same arguments as the write itself. Pass a Model to write to its table, or a Relation to write to its rows, such as `Article.where(…)` or `author.articles()`.
|
|
1306
|
+
|
|
1307
|
+
`batch` resolves to each write’s result, in order. A bulk write gives the same `{ rowsAffected, rows }` it resolves to when it runs alone, and `rows` is empty for `updateAll` and `deleteAll`.
|
|
779
1308
|
|
|
780
1309
|
- **Keys:** rows in one batch can only point at each other through keys that exist before it’s sent, so generate keys in code, with [`generateId`](/models#generating-ids).
|
|
781
|
-
- **
|
|
782
|
-
- **Databases:** a
|
|
1310
|
+
- **Errors:** a write that can’t be prepared, such as one with an unknown attribute, rejects the batch before anything is sent.
|
|
1311
|
+
- **Databases:** `batch` writes a Model’s rows on the current database, and `db.batch` on `db`. A Relation or a record writes on the database it came from. Writes on two databases throw `IncompatibleRelation`.
|
|
1312
|
+
- **Relations in `db.batch`:** `Article.where(…)` uses the current database. Build it with `db.model(Article).where(…)` to write on `db`.
|
|
783
1313
|
|
|
784
1314
|
:::note
|
|
785
|
-
D1 can’t keep a transaction open across `await`s, so
|
|
1315
|
+
The callback returns its writes without awaiting anything, since the batch is sent to D1 as one. Load what the writes need before you call `batch`. D1 can’t keep a transaction open across `await`s, so a batch is how you make writes atomic.
|
|
786
1316
|
:::
|
|
787
1317
|
|
|
1318
|
+
> **Compared with Rails**
|
|
1319
|
+
>
|
|
1320
|
+
> A batch reads like a `transaction do … end` block, but its callback only prepares writes. They’re sent together when it returns, so it can’t read in between.
|
|
1321
|
+
|
|
788
1322
|
## Batching records
|
|
789
1323
|
|
|
790
|
-
Add a record’s save or destroy to a batch with `
|
|
1324
|
+
Add a record’s save or destroy to a batch with `b.save(record)` and `b.destroy(record)`. Its validations and callbacks still run:
|
|
791
1325
|
|
|
792
1326
|
```ts
|
|
793
1327
|
import { batch } from "@forestfuture/active-record";
|
|
@@ -798,35 +1332,44 @@ article.title = "Final";
|
|
|
798
1332
|
const author = Author.build({ name: "Hedy" });
|
|
799
1333
|
const old = await Author.find(oldAuthorId);
|
|
800
1334
|
|
|
801
|
-
const [savedArticle, savedAuthor] = await batch([
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
Comment.where({ articleId })
|
|
1335
|
+
const [savedArticle, savedAuthor] = await batch((b) => [
|
|
1336
|
+
b.save(article),
|
|
1337
|
+
b.save(author),
|
|
1338
|
+
b.destroy(old), // with its dependents
|
|
1339
|
+
b.deleteAll(Comment.where({ articleId })),
|
|
806
1340
|
]);
|
|
807
1341
|
```
|
|
808
1342
|
|
|
809
1343
|
When the batch runs:
|
|
810
1344
|
|
|
811
1345
|
1. Each record, in order, is validated and runs its before-callbacks. The first that’s invalid or aborts throws `RecordInvalid`, `RecordNotSaved`, or `RecordNotDestroyed`, and nothing is sent.
|
|
812
|
-
2. Every write goes to D1 as one atomic batch. If D1 refuses it with a constraint error, nothing is written,
|
|
1346
|
+
2. Every write goes to D1 as one atomic batch. If D1 refuses it with a constraint error, nothing is written, every record keeps its unsaved state, and each record’s `afterRollback` runs.
|
|
813
1347
|
3. Each record takes its saved state, then its after-callbacks run.
|
|
1348
|
+
4. Every record’s [commit callbacks](/callbacks#running-code-after-the-commit) run, in the same order.
|
|
814
1349
|
|
|
815
1350
|
A record’s autosaved associations and `dependent` strategies join the same batch. A record listed twice, or already saved by its owner’s autosave, is written once.
|
|
816
1351
|
|
|
1352
|
+
To validate a record in a context of your own, such as the `"signup"` context of [`Member`](/validations#naming-your-own-contexts), pass the context to `b.save`:
|
|
1353
|
+
|
|
1354
|
+
```ts
|
|
1355
|
+
import { batch } from "@forestfuture/active-record";
|
|
1356
|
+
|
|
1357
|
+
await batch((b) => [b.save(member, { context: "signup" })]);
|
|
1358
|
+
```
|
|
1359
|
+
|
|
817
1360
|
> **Compared with Rails**
|
|
818
1361
|
>
|
|
819
1362
|
> In a Rails transaction, one record’s `after_save` runs before the next record’s `before_save`. In a batch, every before-callback runs first.
|
|
820
1363
|
|
|
821
|
-
|
|
1364
|
+
Bulk writes and records mix in one batch. From the [Getting started](/getting-started) project, this publishes every draft and destroys a user with their posts:
|
|
822
1365
|
|
|
823
1366
|
```ts
|
|
824
1367
|
import { batch } from "@forestfuture/active-record";
|
|
825
1368
|
import { Post } from "./models";
|
|
826
1369
|
|
|
827
|
-
await batch([
|
|
828
|
-
Post.where({ publishedAt: null })
|
|
829
|
-
|
|
1370
|
+
await batch((b) => [
|
|
1371
|
+
b.updateAll(Post.where({ publishedAt: null }), { publishedAt: new Date() }),
|
|
1372
|
+
b.destroy(user), // and the user's posts, since posts are dependent: "destroy"
|
|
830
1373
|
]);
|
|
831
1374
|
```
|
|
832
1375
|
|
|
@@ -873,28 +1416,53 @@ export class Order extends Model.define({
|
|
|
873
1416
|
|
|
874
1417
|
Callbacks of one kind run in the order declared. A subclass runs its parent’s callbacks, then its own.
|
|
875
1418
|
|
|
1419
|
+
To run a validation callback only in some [validation contexts](/validations#validating-only-when-creating-or-updating), pass `on` to `beforeValidation` or `afterValidation`:
|
|
1420
|
+
|
|
1421
|
+
```ts
|
|
1422
|
+
this.beforeValidation(
|
|
1423
|
+
(order) => {
|
|
1424
|
+
order.placedAt = new Date();
|
|
1425
|
+
},
|
|
1426
|
+
{ on: "create" },
|
|
1427
|
+
);
|
|
1428
|
+
```
|
|
1429
|
+
|
|
876
1430
|
:::note
|
|
877
1431
|
Once a Model has been used, registering another callback throws `InvalidModel`, so request code can’t add one that leaks into later requests.
|
|
878
1432
|
:::
|
|
879
1433
|
|
|
880
1434
|
## Callback order
|
|
881
1435
|
|
|
882
|
-
| Order | Callback
|
|
883
|
-
| -------------- |
|
|
884
|
-
| **Saving** |
|
|
885
|
-
| 1 | `beforeValidation`
|
|
886
|
-
| 2 | `afterValidation`
|
|
887
|
-
| 3 | `beforeSave`
|
|
888
|
-
| 4 | `beforeCreate`
|
|
889
|
-
| 4 | `beforeUpdate`
|
|
890
|
-
| | _The write to D1_
|
|
891
|
-
| 5 | `afterCreate`
|
|
892
|
-
| 5 | `afterUpdate`
|
|
893
|
-
| 6 | `afterSave`
|
|
894
|
-
|
|
|
895
|
-
|
|
|
896
|
-
|
|
|
897
|
-
|
|
|
1436
|
+
| Order | Callback | Runs | `abort()` |
|
|
1437
|
+
| -------------- | -------------------- | -------------------------------------------------------- | --------------------------------- |
|
|
1438
|
+
| **Saving** | | | |
|
|
1439
|
+
| 1 | `beforeValidation` | Before the validators, on every save, and on `isValid()` | Stops the save |
|
|
1440
|
+
| 2 | `afterValidation` | After the validators | Stops the save |
|
|
1441
|
+
| 3 | `beforeSave` | Before every write, new or persisted | Stops the save |
|
|
1442
|
+
| 4 | `beforeCreate` | Before inserting a new record | Stops the save |
|
|
1443
|
+
| 4 | `beforeUpdate` | Before updating a persisted record | Stops the save |
|
|
1444
|
+
| | _The write to D1_ | Skipped when a persisted record has no changes | |
|
|
1445
|
+
| 5 | `afterCreate` | After inserting a new record | Too late: `AbortAfterPersistence` |
|
|
1446
|
+
| 5 | `afterUpdate` | After updating a persisted record | Too late: `AbortAfterPersistence` |
|
|
1447
|
+
| 6 | `afterSave` | After every successful save | Too late: `AbortAfterPersistence` |
|
|
1448
|
+
| 7 | `afterCommit` | Last, after every after-callback | Too late: `AbortAfterPersistence` |
|
|
1449
|
+
| 7 | `afterCreateCommit` | Last, after inserting a new record | Too late: `AbortAfterPersistence` |
|
|
1450
|
+
| 7 | `afterUpdateCommit` | Last, after updating a persisted record | Too late: `AbortAfterPersistence` |
|
|
1451
|
+
| 7 | `afterSaveCommit` | Last, after every successful save | Too late: `AbortAfterPersistence` |
|
|
1452
|
+
| **Destroying** | | | |
|
|
1453
|
+
| 1 | `beforeDestroy` | Before the `dependent` strategies and the DELETE | Stops the destroy |
|
|
1454
|
+
| | _The delete in D1_ | With the dependents, in one batch | |
|
|
1455
|
+
| 2 | `afterDestroy` | After the record is destroyed | Too late: `AbortAfterPersistence` |
|
|
1456
|
+
| 3 | `afterCommit` | Last, after every after-callback | Too late: `AbortAfterPersistence` |
|
|
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` |
|
|
1464
|
+
| **Refused** | | | |
|
|
1465
|
+
| 1 | `afterRollback` | When the database refuses the save or destroy | Nothing to stop |
|
|
898
1466
|
|
|
899
1467
|
A save runs either the create pair or the update pair, never both.
|
|
900
1468
|
|
|
@@ -903,7 +1471,66 @@ A save runs either the create pair or the update pair, never both.
|
|
|
903
1471
|
- **An after-callback that changes an attribute** leaves the record dirty. Nothing is written again.
|
|
904
1472
|
|
|
905
1473
|
:::warning[Nothing is rolled back]
|
|
906
|
-
|
|
1474
|
+
The database has kept a save’s writes before any after-callback runs. An error thrown by an after-callback or a commit callback reaches the caller, but the record stays saved. The callbacks after it don’t run. In a batch, that includes the other records’ callbacks.
|
|
1475
|
+
:::
|
|
1476
|
+
|
|
1477
|
+
## Running code after the commit
|
|
1478
|
+
|
|
1479
|
+
Commit callbacks run last, after every after-callback of the save. In a [batch](/batches#batching-records), they wait for every record’s after-callbacks. Register one to run code once everything is written:
|
|
1480
|
+
|
|
1481
|
+
```ts
|
|
1482
|
+
this.afterCreateCommit(async (user) => {
|
|
1483
|
+
await sendWelcomeEmail(user.email);
|
|
1484
|
+
});
|
|
1485
|
+
```
|
|
1486
|
+
|
|
1487
|
+
- **`afterCommit`** runs after a create, an update, or a destroy.
|
|
1488
|
+
- **`afterCreateCommit`**, **`afterUpdateCommit`**, and **`afterDestroyCommit`** run after one kind of write. **`afterSaveCommit`** runs after a create or an update.
|
|
1489
|
+
- **Commit callbacks of every kind** run in the order you declared them.
|
|
1490
|
+
|
|
1491
|
+
:::note
|
|
1492
|
+
Destroying a record that was never saved runs no commit callback, since there was no row to delete.
|
|
1493
|
+
:::
|
|
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
|
+
|
|
1516
|
+
## Handling a refused write
|
|
1517
|
+
|
|
1518
|
+
`afterRollback` runs when the database refuses a record’s save or destroy:
|
|
1519
|
+
|
|
1520
|
+
```ts
|
|
1521
|
+
this.afterRollback((order) => {
|
|
1522
|
+
console.warn(`Order ${order.id} wasn’t saved`);
|
|
1523
|
+
});
|
|
1524
|
+
```
|
|
1525
|
+
|
|
1526
|
+
- **A constraint error** refuses the record’s write, and the save then throws the [constraint error](/errors#constraint-errors).
|
|
1527
|
+
- **In a batch**, one refused write refuses them all, so `afterRollback` runs for every record in it.
|
|
1528
|
+
- **A failed validation or an `abort()`** sends nothing, so `afterRollback` doesn’t run.
|
|
1529
|
+
|
|
1530
|
+
The record keeps its unsaved state, and no after-callback or commit callback runs for it.
|
|
1531
|
+
|
|
1532
|
+
:::note
|
|
1533
|
+
An error thrown by an `afterRollback` reaches the caller in place of the constraint error, which becomes its `cause`. The `afterRollback` callbacks after it don’t run.
|
|
907
1534
|
:::
|
|
908
1535
|
|
|
909
1536
|
## Stopping a save
|
|
@@ -934,12 +1561,14 @@ These callbacks aren’t in Active Record yet. The code shows the shape they’r
|
|
|
934
1561
|
|
|
935
1562
|
- **Around callbacks** ([#48](https://github.com/forestfuture/active-record/issues/48)): `this.aroundSave(async (record, proceed) => { …; await proceed(); … })`, and `aroundCreate`, `aroundUpdate`, and `aroundDestroy`.
|
|
936
1563
|
- **`afterInitialize` and `afterFind`** ([#49](https://github.com/forestfuture/active-record/issues/49)): for every record built or loaded, and every record loaded.
|
|
937
|
-
- **`record.touch()` and `afterTouch`** ([#50](https://github.com/forestfuture/active-record/issues/50)): sets `updatedAt` without a full save.
|
|
938
|
-
- **`on: "create"` and `on: "update"`** ([#51](https://github.com/forestfuture/active-record/issues/51)): `this.validates("password", { presence: true, on: "create" })`. Until then, check `record.isNewRecord()` in an `if` option or a callback.
|
|
939
1564
|
|
|
940
1565
|
> **Compared with Rails**
|
|
941
1566
|
>
|
|
942
|
-
>
|
|
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.
|
|
1568
|
+
>
|
|
1569
|
+
> `after_touch` is `afterTouch`. As in Rails, `touch` runs the commit callbacks too.
|
|
1570
|
+
>
|
|
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.
|
|
943
1572
|
>
|
|
944
1573
|
> Rails’ `if:` and `unless:` options for callbacks aren’t needed: write the condition inside the callback.
|
|
945
1574
|
|
|
@@ -1064,7 +1693,10 @@ Most names are Rails’ own, in camelCase:
|
|
|
1064
1693
|
| `foreign_key: :user_id` | `foreignKey: "userId"` |
|
|
1065
1694
|
| `save!`, `create!`, `find_by!` | `saveOrThrow`, `createOrThrow`, `findByOrThrow` |
|
|
1066
1695
|
| `new_record?`, `persisted?` | `isNewRecord()`, `isPersisted()` |
|
|
1696
|
+
| `find_or_create_by(name:) do … end` | `findOrCreateBy({ name }, (tag) => …)` |
|
|
1067
1697
|
| `empty?`, `any?` | `isEmpty()`, `hasAny()` |
|
|
1698
|
+
| `many?`, `one?` | `hasMoreThanOne()`, `hasExactlyOne()` |
|
|
1699
|
+
| `unscope(:order, where: :role)` | `unscope("order", { where: "role" })` |
|
|
1068
1700
|
| `changed?`, `saved_change_to_email?` | `isChanged()`, `hasSavedChangeTo("email")` |
|
|
1069
1701
|
| `rails generate model Post title:string` | `npx active-record g model Post title:string` |
|
|
1070
1702
|
| `db/schema.rb`, `rails db:schema:dump` | `src/db/schema.ts`, `npx active-record schema` |
|
|
@@ -1073,6 +1705,7 @@ Most names are Rails’ own, in camelCase:
|
|
|
1073
1705
|
| `has_many :posts, dependent: :destroy` | `posts = hasMany(Post, { dependent: "destroy" })` |
|
|
1074
1706
|
| `post.author = user` | `post.author.set(user)` |
|
|
1075
1707
|
| `build_profile` | `user.profile.build()` |
|
|
1708
|
+
| `user.profile = profile` | `await user.profile.set(profile)` |
|
|
1076
1709
|
| `reload_author` | `post.reloadAssociation("author")` |
|
|
1077
1710
|
| `throw :abort` | `throw abort("reason")` |
|
|
1078
1711
|
| `to_json` | `toJSON()` |
|
|
@@ -1105,7 +1738,7 @@ export class Product extends ApplicationRecord {
|
|
|
1105
1738
|
|
|
1106
1739
|
## Writing atomically
|
|
1107
1740
|
|
|
1108
|
-
There’s no `transaction do … end`, since D1 can’t keep a transaction open across awaits.
|
|
1741
|
+
There’s no `transaction do … end`, since D1 can’t keep a transaction open across awaits. Use [`batch((b) => [...])`](/batches) instead. In its callback, `b.save(user)`, `b.destroy(post)`, and bulk writes like `b.updateAll(…)` prepare writes. They’re sent atomically once the callback returns. Generating keys in code makes whole graphs of new records atomic too. See [D1’s limits](/d1).
|
|
1109
1742
|
|
|
1110
1743
|
## Primary keys
|
|
1111
1744
|
|
|
@@ -1122,6 +1755,9 @@ The generators follow `rails generate model` and `rails generate migration`. A c
|
|
|
1122
1755
|
- `insert` and `insertAll` raise on duplicates. Skipping them is opt-in, with `{ onDuplicate: "skip" }`.
|
|
1123
1756
|
- `insert` fills in declared defaults, since that’s where keys are generated.
|
|
1124
1757
|
- `merge` replaces the order rather than appending to it.
|
|
1758
|
+
- `merge` of another Model needs a join to it, and takes only its conditions and order. Anything else throws `IncompatibleRelation` when you write the query.
|
|
1759
|
+
- `find(1, 2)` on a `hasMany` join returns each record once.
|
|
1760
|
+
- `distinct()` with an order on a joined Model throws `IncompatibleRelation` on every database. Rails leaves it to the database, and only Postgres refuses it.
|
|
1125
1761
|
- `last()` can’t reverse an `sql` fragment order, and throws `IrreversibleOrder`, rather than trying to parse SQL.
|
|
1126
1762
|
- `find(1, 1)` always returns an array, so its return type follows its arguments.
|
|
1127
1763
|
- `dependent:` strategies run after the owner’s `beforeDestroy` callbacks, wherever they’re declared, so an `abort()` always protects the records.
|
|
@@ -1130,7 +1766,7 @@ The generators follow `rails generate model` and `rails generate migration`. A c
|
|
|
1130
1766
|
|
|
1131
1767
|
## Not built yet
|
|
1132
1768
|
|
|
1133
|
-
|
|
1769
|
+
`has_many :through`, `where` keyed by an association, `where.missing`, `eager_load`, single-table inheritance, `destroy_async`, and error messages in other languages.
|
|
1134
1770
|
|
|
1135
1771
|
---
|
|
1136
1772
|
|
|
@@ -1163,10 +1799,12 @@ Run it again after you add a database to your Wrangler config. It adds each data
|
|
|
1163
1799
|
Added LOGS to active-record.jsonc (on d1)
|
|
1164
1800
|
```
|
|
1165
1801
|
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
|
1169
|
-
|
|
|
1802
|
+
It adds only databases on the adapters the file already uses. To add another adapter’s databases, name it with `--adapter`.
|
|
1803
|
+
|
|
1804
|
+
| Option | |
|
|
1805
|
+
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1806
|
+
| `--adapter <name>` | The adapter, `d1` or `postgresql`, when your Wrangler config has both, or neither. With the file there, it adds that adapter’s databases. |
|
|
1807
|
+
| `--config <file>` | Write this file, in place of `active-record.jsonc`. |
|
|
1170
1808
|
|
|
1171
1809
|
With `--adapter postgresql` and no Hyperdrive binding, it writes a `DATABASE_URL` entry, with a guess at your local database’s `url` for you to correct.
|
|
1172
1810
|
|
|
@@ -1183,9 +1821,23 @@ With `--adapter postgresql` and no Hyperdrive binding, it writes a `DATABASE_URL
|
|
|
1183
1821
|
}
|
|
1184
1822
|
```
|
|
1185
1823
|
|
|
1186
|
-
Your generated schema names each database by its binding. The `$schema` line lets your editor complete and check the file.
|
|
1824
|
+
Your generated schema names each database by its binding. The `$schema` line lets your editor complete and check the file. Each database names its own adapter, so one project can use D1 and Postgres together, as [Multiple databases](/several-databases#using-databases-on-different-adapters) shows.
|
|
1825
|
+
|
|
1826
|
+
On D1, the rest of a database’s settings stay in your Wrangler config’s `d1_databases`, which must have its binding. A D1 database there that the file doesn’t name is left out, and every command notes it.
|
|
1827
|
+
|
|
1828
|
+
By default, that’s the Wrangler config beside the file. If your Worker’s config is in another folder, name it with `wranglerConfig`. The path is relative to `active-record.jsonc`:
|
|
1829
|
+
|
|
1830
|
+
```jsonc
|
|
1831
|
+
{
|
|
1832
|
+
"databases": {
|
|
1833
|
+
"DB": { "adapter": "d1", "wranglerConfig": "../worker/wrangler.jsonc" },
|
|
1834
|
+
},
|
|
1835
|
+
}
|
|
1836
|
+
```
|
|
1837
|
+
|
|
1838
|
+
The database’s migrations folder and its local data in `.wrangler/state` are then beside that config, where `wrangler dev` finds them. `migrate` and the console run the `wrangler` installed there, or else your project’s.
|
|
1187
1839
|
|
|
1188
|
-
On
|
|
1840
|
+
On Postgres, the file holds a database’s settings:
|
|
1189
1841
|
|
|
1190
1842
|
```jsonc
|
|
1191
1843
|
{
|
|
@@ -1318,18 +1970,20 @@ On D1, each column becomes an attribute by the first of these that applies:
|
|
|
1318
1970
|
1. **An override in the Model:** `static override attributes = { available: "boolean" } as const`.
|
|
1319
1971
|
2. **The column’s declared type:**
|
|
1320
1972
|
|
|
1321
|
-
| Declared as | Attribute
|
|
1322
|
-
| --------------------------------------------------- |
|
|
1323
|
-
| `INTEGER`, `INT`, `BIGINT`, … (anything with `INT`) | `integer`
|
|
1324
|
-
| `TEXT`, `VARCHAR(…)`, `CHAR(…)`, `CLOB` | `string`
|
|
1325
|
-
| `REAL`, `FLOAT`, `DOUBLE` | `real`
|
|
1326
|
-
| `
|
|
1327
|
-
| `
|
|
1328
|
-
| `
|
|
1329
|
-
| `
|
|
1330
|
-
| `
|
|
1331
|
-
| `
|
|
1332
|
-
|
|
|
1973
|
+
| Declared as | Attribute |
|
|
1974
|
+
| --------------------------------------------------- | ------------------------------------------------ |
|
|
1975
|
+
| `INTEGER`, `INT`, `BIGINT`, … (anything with `INT`) | `integer` |
|
|
1976
|
+
| `TEXT`, `VARCHAR(…)`, `CHAR(…)`, `CLOB` | `string` |
|
|
1977
|
+
| `REAL`, `FLOAT`, `DOUBLE` | `real` |
|
|
1978
|
+
| `NUMERIC`, `DECIMAL` | `decimal`, with a size’s `precision` and `scale` |
|
|
1979
|
+
| `BOOLEAN` | `boolean` |
|
|
1980
|
+
| `DATETIME`, `TIMESTAMP` | `datetime` |
|
|
1981
|
+
| `DATE` | `date` |
|
|
1982
|
+
| `TIME` | `time` |
|
|
1983
|
+
| `TEXT` with `CHECK (json_valid(column))` | `json` |
|
|
1984
|
+
| `JSON` | `json` |
|
|
1985
|
+
| `BLOB` | `binary` |
|
|
1986
|
+
| anything else | `string` |
|
|
1333
1987
|
|
|
1334
1988
|
3. **The column’s name**, only for a column declared exactly `TEXT` or `INTEGER`: `…_at` `TEXT` is a `datetime`, and `is_…` or `has_…` `INTEGER` is a `boolean` (with a note, since it’s a guess).
|
|
1335
1989
|
|
|
@@ -1338,8 +1992,9 @@ Also:
|
|
|
1338
1992
|
- **Names:** `price_cents` becomes `priceCents`. A column whose name doesn’t come back the same from camelCase gets `column: "…"`.
|
|
1339
1993
|
- **`NOT NULL`** becomes `null: false`. A primary key is never null.
|
|
1340
1994
|
- **Primary keys:** the key column is the Model’s `primaryKey`. A `TEXT` key gets `generateId: true`, so the Model’s [`generateId`](/models#generating-ids) makes it; an `INTEGER PRIMARY KEY` is left to D1. A table with no key, or a key of several columns, is an error.
|
|
1341
|
-
- **Defaults:** literal defaults (numbers, strings, `TRUE`/`FALSE`, JSON) are copied, so a new record shows them before it’s saved. Expressions such as `CURRENT_TIMESTAMP` are left to D1.
|
|
1995
|
+
- **Defaults:** literal defaults (numbers, strings, `TRUE`/`FALSE`, JSON) are copied, so a new record shows them before it’s saved. A decimal’s, a date’s, or a time’s is copied in its type’s form (`1.50` as `"1.5"`). Expressions such as `CURRENT_TIMESTAMP` are left to D1.
|
|
1342
1996
|
- **Foreign keys** take the referenced column’s type. They don’t create associations, which are behavior you declare.
|
|
1997
|
+
- **Enums:** a `TEXT` column with `CHECK (column IN ('open', 'done'))` gets `enum: ["open", "done"]`, with its methods off until the Model turns them on. See [Reading enums from the database](/models#reading-enums-from-the-database).
|
|
1343
1998
|
- **Left out:** SQLite’s own tables, Cloudflare’s (`_cf_…`), the migrations table, and virtual tables.
|
|
1344
1999
|
|
|
1345
2000
|
**Notes it prints** when the schema is written:
|
|
@@ -1354,19 +2009,23 @@ Also:
|
|
|
1354
2009
|
|
|
1355
2010
|
On Postgres, an override in the Model still comes first. Otherwise each column’s type decides, since Postgres’s types are real:
|
|
1356
2011
|
|
|
1357
|
-
| Type
|
|
1358
|
-
|
|
|
1359
|
-
| `smallint`, `integer`, `bigint`
|
|
1360
|
-
| `real`, `double precision`
|
|
1361
|
-
| `
|
|
1362
|
-
| `
|
|
1363
|
-
| `
|
|
1364
|
-
| `
|
|
1365
|
-
| `
|
|
1366
|
-
| `
|
|
1367
|
-
|
|
|
1368
|
-
|
|
1369
|
-
|
|
2012
|
+
| Type | Attribute |
|
|
2013
|
+
| -------------------------------------------- | ---------------------------------------------- |
|
|
2014
|
+
| `smallint`, `integer`, `bigint` | `integer` |
|
|
2015
|
+
| `real`, `double precision` | `real` |
|
|
2016
|
+
| `numeric` | `decimal`, with its `precision` and `scale` |
|
|
2017
|
+
| `boolean` | `boolean` |
|
|
2018
|
+
| `timestamptz`, `timestamp` | `datetime` |
|
|
2019
|
+
| `date` | `date` |
|
|
2020
|
+
| `time` | `time` |
|
|
2021
|
+
| `json`, `jsonb` | `json` |
|
|
2022
|
+
| `bytea` | `binary` |
|
|
2023
|
+
| `text`, `varchar`, `char`, `citext`, `uuid` | `string` |
|
|
2024
|
+
| an enum type | `string`, with the enum’s labels as its `enum` |
|
|
2025
|
+
| an array | An error: not supported |
|
|
2026
|
+
| anything else (`inet`, `interval`, `timetz`) | `string`, with a note |
|
|
2027
|
+
|
|
2028
|
+
A domain maps as the type it’s built on. Names, `NOT NULL`, keys, and `CHECK (column IN (…))` work as on D1, and an enum type’s labels keep their order. A string key gets `generateId: true` unless it has a literal default, even when Postgres has a default such as `gen_random_uuid()`. Literal defaults (`'draft'`, `0`, `true`, `'{}'::jsonb`) are copied, and functions such as `now()` are left to Postgres. Views, other schemas, and `schema_migrations` are left out.
|
|
1370
2029
|
|
|
1371
2030
|
**Extensions:** a migration can `CREATE EXTENSION` any of the extensions PGlite has its own build of, such as `citext`, `uuid-ossp`, `pg_trgm`, `pgcrypto`, `hstore`, and `ltree`. For any other, such as PostGIS, set `schemaUrl` to a Postgres server that has it, such as a local one. The schema is then read there, in a database of its own:
|
|
1372
2031
|
|
|
@@ -1405,9 +2064,13 @@ npx active-record g migration <Name> [columns] [options]
|
|
|
1405
2064
|
| `string` (the default) | `TEXT` | `TEXT` |
|
|
1406
2065
|
| `integer` | `INTEGER` | `BIGINT` |
|
|
1407
2066
|
| `real` | `REAL` | `DOUBLE PRECISION` |
|
|
2067
|
+
| `decimal` | `DECIMAL` | `NUMERIC` |
|
|
1408
2068
|
| `boolean` | `BOOLEAN` | `BOOLEAN` |
|
|
1409
2069
|
| `datetime` | `DATETIME` | `TIMESTAMPTZ` |
|
|
2070
|
+
| `date` | `DATE` | `DATE` |
|
|
2071
|
+
| `time` | `TIME` | `TIME` |
|
|
1410
2072
|
| `json` | `TEXT CHECK (json_valid(column))` | `JSONB` |
|
|
2073
|
+
| `binary` | `BLOB` | `BYTEA` |
|
|
1411
2074
|
|
|
1412
2075
|
A `references` column is `<name>_id`, typed like the referenced table’s key, with `REFERENCES <plural> (id)` and an index.
|
|
1413
2076
|
|
|
@@ -1421,7 +2084,8 @@ The key `g model` writes:
|
|
|
1421
2084
|
Timestamps are `created_at` and `updated_at`, `NOT NULL`, as `DATETIME` on D1 and `TIMESTAMPTZ` on Postgres.
|
|
1422
2085
|
|
|
1423
2086
|
- **`!`** makes the column `NOT NULL`. A `references` column is `NOT NULL` in a new table, and can be `NULL` when added to an existing one.
|
|
1424
|
-
- **`=value`** is a literal default, for `string`, `integer`, `real`,
|
|
2087
|
+
- **`=value`** is a literal default, for `string`, `integer`, `real`, `decimal`, `boolean`, `date`, and `time` columns (`=draft`, `=0`, `=1.5`, `=true`, `=2026-01-02`, `=09:00`).
|
|
2088
|
+
- **`{precision,scale}`** after `decimal` gives a decimal’s size: `'price:decimal{10,2}'` writes `DECIMAL(10, 2)` on D1 and `NUMERIC(10, 2)` on Postgres, and `decimal{6}` a precision alone. Quote it, so the shell doesn’t expand the braces.
|
|
1425
2089
|
- **`:unique`** adds a unique index, and **`:index`** an index, named like `index_products_on_sku`.
|
|
1426
2090
|
- **Names** can be written `priceCents` or `price_cents`; columns are always snake_case. Names the database reserves (`order`, `group`, and on Postgres `user`) are quoted.
|
|
1427
2091
|
|
|
@@ -1551,7 +2215,7 @@ const posts = await models.Post.where({ userId: user.id }).toArray();
|
|
|
1551
2215
|
|
|
1552
2216
|
## Batching writes
|
|
1553
2217
|
|
|
1554
|
-
`batch`
|
|
2218
|
+
`batch` saves and destroys records and runs bulk writes atomically:
|
|
1555
2219
|
|
|
1556
2220
|
```ts
|
|
1557
2221
|
import { batch } from "@forestfuture/active-record";
|
|
@@ -1561,10 +2225,10 @@ const user = User.build({ email: "grace@example.com" });
|
|
|
1561
2225
|
const post = Post.build({ userId: user.id, title: "Hello" });
|
|
1562
2226
|
|
|
1563
2227
|
// Atomic: all written, or none.
|
|
1564
|
-
await batch([
|
|
2228
|
+
await batch((b) => [b.save(user), b.save(post), b.deleteAll(Post.where({ userId: "old" }))]);
|
|
1565
2229
|
```
|
|
1566
2230
|
|
|
1567
|
-
|
|
2231
|
+
`batch` writes a Model’s rows on the current database. `db.batch` uses an explicit one. See [Bulk writes and batches](/batches).
|
|
1568
2232
|
|
|
1569
2233
|
---
|
|
1570
2234
|
|
|
@@ -1600,7 +2264,7 @@ Leave with `quit`, `exit`, or Ctrl-D. Ctrl-C stops a line that’s still running
|
|
|
1600
2264
|
## What you can use
|
|
1601
2265
|
|
|
1602
2266
|
- **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.
|
|
1603
|
-
- **`db`,** your connected database, for `db.batch(
|
|
2267
|
+
- **`db`,** your connected database, for `db.batch(...)` and `db.model(...)`.
|
|
1604
2268
|
- **Top-level `await`,** and `const` and `let`, which last until you leave.
|
|
1605
2269
|
|
|
1606
2270
|
A record prints as it does in a log: its class and attributes, with a filtered attribute as `[FILTERED]` and an unsaved change next to the value it had. [Printing records](/models#printing-records) has the details.
|
|
@@ -1646,9 +2310,9 @@ The SQL comes from the database’s own `onQuery`, so a listener you set on your
|
|
|
1646
2310
|
|
|
1647
2311
|
| Option | |
|
|
1648
2312
|
| ------------------- | ------------------------------------------------------------------------------------------------------- |
|
|
1649
|
-
| `--database <name>` | The
|
|
2313
|
+
| `--database <name>` | The database to open, when `active-record.jsonc` names several. |
|
|
1650
2314
|
| `--models <path>` | Where your Models are: a folder (`src/models` by default) or one file (`src/models.ts`). |
|
|
1651
|
-
| `--config <file>` | Use this
|
|
2315
|
+
| `--config <file>` | Use this config file, in place of `active-record.jsonc`. |
|
|
1652
2316
|
| `--no-history` | Don’t keep what you type in the history file. |
|
|
1653
2317
|
| `--verbose` | Print each statement a line runs, to begin with. `.verbose` turns it on and off. |
|
|
1654
2318
|
| `-e, --eval <code>` | Run this code, print its result, and exit. See [Running one piece of code](#running-one-piece-of-code). |
|
|
@@ -1658,7 +2322,7 @@ The SQL comes from the database’s own `onQuery`, so a listener you set on your
|
|
|
1658
2322
|
|
|
1659
2323
|
## Where your data lives
|
|
1660
2324
|
|
|
1661
|
-
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.
|
|
2325
|
+
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.
|
|
1662
2326
|
|
|
1663
2327
|
It opens your remote database only when you ask with `--remote`, and never for a binding your config marks `remote: true` by itself.
|
|
1664
2328
|
|
|
@@ -1768,6 +2432,146 @@ The console runs your project’s code: your Models, and the `wrangler` and `@fo
|
|
|
1768
2432
|
|
|
1769
2433
|
---
|
|
1770
2434
|
|
|
2435
|
+
# Custom types
|
|
2436
|
+
Source: https://active-record.forestfuture.dev/custom-types
|
|
2437
|
+
|
|
2438
|
+
A custom type holds a value the built-in types don’t, such as money or a list of sizes. Its values are stored in their column as one of the built-in types.
|
|
2439
|
+
|
|
2440
|
+
## Defining a type
|
|
2441
|
+
|
|
2442
|
+
Define a type with `defineType`, naming the built-in type it’s stored as. This one keeps money as whole cents in an integer column:
|
|
2443
|
+
|
|
2444
|
+
```ts
|
|
2445
|
+
import { defineType } from "@forestfuture/active-record";
|
|
2446
|
+
|
|
2447
|
+
export class Money {
|
|
2448
|
+
readonly cents: number;
|
|
2449
|
+
|
|
2450
|
+
constructor(cents: number) {
|
|
2451
|
+
this.cents = cents;
|
|
2452
|
+
}
|
|
2453
|
+
|
|
2454
|
+
toString() {
|
|
2455
|
+
return `$${(this.cents / 100).toFixed(2)}`;
|
|
2456
|
+
}
|
|
2457
|
+
}
|
|
2458
|
+
|
|
2459
|
+
export const money = defineType({
|
|
2460
|
+
storedAs: "integer",
|
|
2461
|
+
cast(input) {
|
|
2462
|
+
if (input instanceof Money) return input;
|
|
2463
|
+
if (Number.isSafeInteger(input)) return new Money(input as number);
|
|
2464
|
+
throw new TypeError("money is a Money or a whole number of cents");
|
|
2465
|
+
},
|
|
2466
|
+
serialize: (value) => value.cents,
|
|
2467
|
+
deserialize: (cents) => new Money(cents),
|
|
2468
|
+
});
|
|
2469
|
+
```
|
|
2470
|
+
|
|
2471
|
+
A type has three functions:
|
|
2472
|
+
|
|
2473
|
+
| Function | Takes | Returns |
|
|
2474
|
+
| ------------- | ---------------------------------- | ---------------------------------- |
|
|
2475
|
+
| `cast` | a value given to the attribute | the type’s value, or throws |
|
|
2476
|
+
| `serialize` | the type’s value | a value of the type it’s stored as |
|
|
2477
|
+
| `deserialize` | a value of the type it’s stored as | the type’s value |
|
|
2478
|
+
|
|
2479
|
+
The attribute’s TypeScript type is what `cast` returns, so `Money` here.
|
|
2480
|
+
|
|
2481
|
+
:::note
|
|
2482
|
+
None of them is called with `null`, which is always NULL.
|
|
2483
|
+
:::
|
|
2484
|
+
|
|
2485
|
+
## Using a type
|
|
2486
|
+
|
|
2487
|
+
Give the type to a generated attribute in `static attributes`:
|
|
2488
|
+
|
|
2489
|
+
```ts
|
|
2490
|
+
import { ApplicationRecord } from "./application-record";
|
|
2491
|
+
|
|
2492
|
+
export class Product extends ApplicationRecord {
|
|
2493
|
+
static override attributes = {
|
|
2494
|
+
priceCents: money,
|
|
2495
|
+
} as const;
|
|
2496
|
+
}
|
|
2497
|
+
```
|
|
2498
|
+
|
|
2499
|
+
Changing an attribute’s type drops its generated default, as any [override](/models#overriding-attributes) of a type does. Give it a `default` if it needs one.
|
|
2500
|
+
|
|
2501
|
+
A Model that declares its attributes itself takes the type in place of a type’s name:
|
|
2502
|
+
|
|
2503
|
+
```ts
|
|
2504
|
+
import { Model } from "@forestfuture/active-record";
|
|
2505
|
+
|
|
2506
|
+
export class Invoice extends Model.define({
|
|
2507
|
+
id: { type: "integer", null: false },
|
|
2508
|
+
total: { type: money, null: false },
|
|
2509
|
+
}) {}
|
|
2510
|
+
```
|
|
2511
|
+
|
|
2512
|
+
## Refusing values
|
|
2513
|
+
|
|
2514
|
+
Throw from `cast` for a value the type can’t hold. Assigning or permitting that value then throws a `TypeError` naming the Model and attribute, with your error as its `cause`:
|
|
2515
|
+
|
|
2516
|
+
```ts
|
|
2517
|
+
import { Product } from "./models/product";
|
|
2518
|
+
|
|
2519
|
+
Product.permit({ priceCents: "abc" }, "priceCents");
|
|
2520
|
+
// TypeError: Product: "abc" isn't a valid value for "priceCents"
|
|
2521
|
+
```
|
|
2522
|
+
|
|
2523
|
+
The same happens when `deserialize` throws for a stored value, and when `serialize` returns a value its stored type can’t hold. For a [filtered attribute](/models#filtering-attributes), the error has no `cause`, since yours may show the value.
|
|
2524
|
+
|
|
2525
|
+
## Querying by a type
|
|
2526
|
+
|
|
2527
|
+
Conditions take the type’s values, and anything `cast` takes:
|
|
2528
|
+
|
|
2529
|
+
```ts
|
|
2530
|
+
import { gte } from "@forestfuture/active-record";
|
|
2531
|
+
|
|
2532
|
+
const cheap = await Product.where({ priceCents: new Money(500) }).toArray();
|
|
2533
|
+
const pricey = await Product.where({ priceCents: gte(new Money(10_000)) })
|
|
2534
|
+
.order({ priceCents: "desc" })
|
|
2535
|
+
.toArray();
|
|
2536
|
+
```
|
|
2537
|
+
|
|
2538
|
+
Values compare and sort as their stored values do, so money sorts by cents. A value `cast` throws for matches nothing.
|
|
2539
|
+
|
|
2540
|
+
## Changing values in place
|
|
2541
|
+
|
|
2542
|
+
A type can hold a value you change in place. This one keeps a list of sizes as text:
|
|
2543
|
+
|
|
2544
|
+
```ts
|
|
2545
|
+
import { defineType } from "@forestfuture/active-record";
|
|
2546
|
+
|
|
2547
|
+
export const sizes = defineType({
|
|
2548
|
+
storedAs: "string",
|
|
2549
|
+
cast(input) {
|
|
2550
|
+
if (Array.isArray(input) && input.every((size) => typeof size === "string")) {
|
|
2551
|
+
return input as string[];
|
|
2552
|
+
}
|
|
2553
|
+
throw new TypeError("sizes are a list of strings");
|
|
2554
|
+
},
|
|
2555
|
+
serialize: (list) => list.join(","),
|
|
2556
|
+
deserialize: (text) => (text === "" ? [] : text.split(",")),
|
|
2557
|
+
});
|
|
2558
|
+
```
|
|
2559
|
+
|
|
2560
|
+
Changes are found by comparing what `serialize` returns, so a size pushed onto the list is a change, and `save()` writes it:
|
|
2561
|
+
|
|
2562
|
+
```ts
|
|
2563
|
+
shirt.sizes.push("XL");
|
|
2564
|
+
shirt.isChanged(); // true
|
|
2565
|
+
```
|
|
2566
|
+
|
|
2567
|
+
An equal value in another object, such as a new `Money` of the same cents, isn’t a change.
|
|
2568
|
+
|
|
2569
|
+
> **Compared with Rails**
|
|
2570
|
+
>
|
|
2571
|
+
> Rails registers a type by name, with `ActiveRecord::Type.register(:money, MoneyType)`, and a Model writes `attribute :price, :money`. Here you pass the type itself, so TypeScript knows the attribute’s type. Rails’ types read the database’s values directly. Here a type is always stored as a built-in type, which reads and compares its values the same way on every database.
|
|
2572
|
+
|
|
2573
|
+
---
|
|
2574
|
+
|
|
1771
2575
|
# D1
|
|
1772
2576
|
Source: https://active-record.forestfuture.dev/d1
|
|
1773
2577
|
|
|
@@ -1789,13 +2593,15 @@ Bind your D1 database in your Wrangler config:
|
|
|
1789
2593
|
|
|
1790
2594
|
Then run `npx active-record init`, which names it in your [`active-record.jsonc`](/command-line#declaring-your-databases) as a D1 database. `active-record schema` reads its migrations through your Wrangler config, and your generated schema names it with `adapter: d1({ binding: "DB" })`. Your Models then query it with nothing to set up. `connect(env.DB)` opens it yourself, for [a request’s database](/connecting#using-the-requests-database) or [an explicit one](/connecting#using-an-explicit-database). `active-record migrate` applies your migrations through Wrangler.
|
|
1791
2595
|
|
|
2596
|
+
If your Wrangler config is in another folder, name it in the database’s entry with [`wranglerConfig`](/command-line#declaring-your-databases).
|
|
2597
|
+
|
|
1792
2598
|
## Reading your own writes
|
|
1793
2599
|
|
|
1794
2600
|
With read replication, wrap each request in [`withSession`](/read-your-own-writes), from `@forestfuture/active-record/d1`. It opens a D1 Session, so the request reads its own writes, and carries its bookmark to the user’s next request.
|
|
1795
2601
|
|
|
1796
2602
|
## Sending queries in one round trip
|
|
1797
2603
|
|
|
1798
|
-
D1 sends a batch of queries in one round trip. A [preload](/associations#preloading-associations) sends its whole tree that way, with the records’ own query, so `includes({ articles: "comments" })` is three queries in one round trip. A [page](/querying#paginating) sends its `COUNT` and its records together, with their preloads.
|
|
2604
|
+
D1 sends a batch of queries in one round trip. A [preload](/associations#preloading-associations) sends its whole tree on one database that way, with the records’ own query, so `includes({ articles: "comments" })` is three queries in one round trip. A [page](/querying#paginating) sends its `COUNT` and its records together, with their preloads.
|
|
1799
2605
|
|
|
1800
2606
|
A batch runs as one transaction, so every query in it reads the same data. A preload’s nested query that would bind more than 100 values waits for the records above it, and takes one more round trip.
|
|
1801
2607
|
|
|
@@ -1805,29 +2611,31 @@ D1 also differs in these ways.
|
|
|
1805
2611
|
|
|
1806
2612
|
D1 can’t hold a transaction open while your Worker awaits, so there’s no `transaction(async (tx) => …)`. You can’t read, decide, then write atomically.
|
|
1807
2613
|
|
|
1808
|
-
What you can make atomic is a set of writes prepared in advance: [`batch
|
|
2614
|
+
What you can make atomic is a set of writes prepared in advance: [`batch`](/batches#batching-writes) sends bulk writes and records together, and D1 writes all of them or none. Active Record uses the same batches itself:
|
|
1809
2615
|
|
|
1810
|
-
- A destroy’s [`dependent` strategies](/associations#destroying-dependent-records) are written in one batch with
|
|
1811
|
-
- A record [autosaved](/associations#autosaving) with its owner joins the owner’s batch when the owner’s key is known in advance.
|
|
2616
|
+
- A destroy’s [`dependent` strategies](/associations#destroying-dependent-records) on the owner’s database are written in one batch with its DELETE.
|
|
2617
|
+
- A record [autosaved](/associations#autosaving) with its owner joins the owner’s batch when it’s on the owner’s database and the owner’s key is known in advance.
|
|
1812
2618
|
|
|
1813
2619
|
## Generating keys in code
|
|
1814
2620
|
|
|
1815
2621
|
Rows in a batch can only point at each other through keys that exist before it’s sent. Generated `TEXT` keys are made in code by [`generateId`](/models#generating-ids), so records have their key from `build()`. Then:
|
|
1816
2622
|
|
|
1817
|
-
- A graph of new records built through associations saves in one atomic batch.
|
|
2623
|
+
- A graph of new records built through associations on one database saves in one atomic batch.
|
|
1818
2624
|
- A batch can insert rows that point at each other.
|
|
1819
2625
|
|
|
1820
2626
|
When D1 generates the key (`INTEGER PRIMARY KEY`), it doesn’t exist until the row is written. An owner is written first, then the records built through it in the next batch, a level at a time, and the batches aren’t atomic together. See [Autosaving](/associations#autosaving).
|
|
1821
2627
|
|
|
1822
2628
|
## Uniqueness is checked twice
|
|
1823
2629
|
|
|
1824
|
-
The `uniqueness` validation asks D1 before saving, which gives a friendly error, but two requests can both pass it at once. Only a UNIQUE index guarantees uniqueness. Declare both, and handle [`RecordNotUnique`](/errors#constraint-errors) where a race matters.
|
|
2630
|
+
The `uniqueness` validation asks D1 before saving, which gives a friendly error, but two requests can both pass it at once. Only a UNIQUE index guarantees uniqueness. Declare both, and handle [`RecordNotUnique`](/errors#constraint-errors) where a race matters. To create such a row only once, use [`createOrFindBy`](/persistence#creating-records-from-concurrent-requests) with the index alone.
|
|
1825
2631
|
|
|
1826
2632
|
`caseSensitive: false` compares with SQLite’s `lower()`, which only lowercases ASCII letters, so `"Ä"` and `"ä"` are still different.
|
|
1827
2633
|
|
|
1828
2634
|
## Bound parameters
|
|
1829
2635
|
|
|
1830
|
-
D1 allows 100 bound values in one statement. The adapter binds lists as one JSON value (`json_each`), so `where({ id: [...] })`, `find([...])`, preloads, and `insertAll` work with any number of values.
|
|
2636
|
+
D1 allows 100 bound values in one statement. The adapter binds lists as one JSON value (`json_each`), so `where({ id: [...] })`, `find([...])`, preloads, and `insertAll` work with any number of values.
|
|
2637
|
+
|
|
2638
|
+
D1 takes at most 2 MB in one value. When a bulk write’s rows add up to more, the adapter sends them as several statements in one batch, which writes all of them or none. D1 counts the batch as one query.
|
|
1831
2639
|
|
|
1832
2640
|
## Foreign keys are enforced
|
|
1833
2641
|
|
|
@@ -1837,6 +2645,10 @@ D1 enforces the foreign keys a table declares with `REFERENCES`. Destroying a re
|
|
|
1837
2645
|
|
|
1838
2646
|
Once D1 has accepted a write, it’s done. An error thrown by an after-callback reaches the caller, but the record stays saved.
|
|
1839
2647
|
|
|
2648
|
+
## Decimals keep about 15 digits
|
|
2649
|
+
|
|
2650
|
+
SQLite stores a [`decimal`](/models#storing-exact-numbers-days-and-times) as a number, so D1 keeps about 15 significant digits of it and rounds the rest: `"1.2345678901234567891"` reads back as `"1.234567890123457"`. Postgres keeps every digit.
|
|
2651
|
+
|
|
1840
2652
|
---
|
|
1841
2653
|
|
|
1842
2654
|
# Errors
|
|
@@ -1856,7 +2668,8 @@ if (error instanceof ActiveRecordError) {
|
|
|
1856
2668
|
|
|
1857
2669
|
| Error | When |
|
|
1858
2670
|
| ----------------------- | ------------------------------------------------------------------------ |
|
|
1859
|
-
| `RecordNotFound` | `find`, `
|
|
2671
|
+
| `RecordNotFound` | `find`, `sole`, an `OrThrow` finder, or `reload` found nothing |
|
|
2672
|
+
| `SoleRecordExceeded` | `sole` or `findSoleBy` found more than one record |
|
|
1860
2673
|
| `RecordInvalid` | an `OrThrow` save found the record invalid; the record is on `.record` |
|
|
1861
2674
|
| `RecordNotSaved` | a save was aborted by a callback, or needs an owner that isn’t saved |
|
|
1862
2675
|
| `RecordNotDestroyed` | a destroy was aborted, or restricted by `restrictWithError` |
|
|
@@ -1875,6 +2688,7 @@ A usage error means the code needs to change:
|
|
|
1875
2688
|
| `MissingAttribute` | reading an attribute that `select` didn’t load |
|
|
1876
2689
|
| `UnknownAssociation` | an association that isn’t declared |
|
|
1877
2690
|
| `AssociationNotLoaded` | `loaded()` on an association that wasn’t loaded |
|
|
2691
|
+
| `UnknownModelName` | a polymorphic association’s stored type that names none of the Models it lists |
|
|
1878
2692
|
| `IncompatibleRelation` | two Relations or writes can’t be used together (below) |
|
|
1879
2693
|
| `IrreversibleOrder` | `last()` on a Relation ordered by an `sql` fragment |
|
|
1880
2694
|
| `DeleteRestriction` | destroying an owner whose `restrictWithException` association still has records |
|
|
@@ -1890,10 +2704,10 @@ A name from a request, such as `?include=` or a JSON key, only ever matches the
|
|
|
1890
2704
|
`IncompatibleRelation` is thrown for combinations that can’t make a correct query or write:
|
|
1891
2705
|
|
|
1892
2706
|
- **`or()`, `merge()`, or a scope** with a Relation of another Model, or one that resolves to another database when it runs. `or()` also needs both sides to have the same `select`, order, `limit`, `offset`, `distinct`, and `includes`, since only their conditions can be combined.
|
|
1893
|
-
- **`batch
|
|
2707
|
+
- **`batch`, `db.batch`, `save()`, or `destroy()`** with writes or records on two databases, such as a `belongsTo` target built on another `connect()`. A write runs on one database. The message names where each database came from. A batch also refuses a record whose autosave or `dependent` strategies reach an association to [another database](/several-databases#associating-models-on-different-databases).
|
|
1894
2708
|
- **`includes`** with `select(...).distinct()`. Preloading needs the keys, and adding them would undo the `distinct`.
|
|
1895
2709
|
- **Preloading an association scope** that uses `limit`, `offset`, or `distinct`. One preload query serves every owner, so the limit would apply to all of their records together.
|
|
1896
|
-
- **`updateAll` or `deleteAll`** after `distinct()`: they reject with it, and
|
|
2710
|
+
- **`updateAll` or `deleteAll`** after `distinct()`: they reject with it, and so does a batch preparing them.
|
|
1897
2711
|
|
|
1898
2712
|
## Constraint errors
|
|
1899
2713
|
|
|
@@ -2013,20 +2827,21 @@ SQLite can’t add a required column without a default, so the generator refuses
|
|
|
2013
2827
|
parent_id TEXT REFERENCES categories (id),
|
|
2014
2828
|
```
|
|
2015
2829
|
|
|
2016
|
-
2. In the Model, use `Category` itself, and add the other direction if you want it.
|
|
2830
|
+
2. In the Model, use `Category` itself, make it optional too, and add the other direction if you want it.
|
|
2017
2831
|
|
|
2018
2832
|
```ts
|
|
2019
2833
|
import { belongsTo, hasMany } from "@forestfuture/active-record";
|
|
2020
2834
|
|
|
2021
2835
|
export class Category extends ApplicationRecord {
|
|
2022
|
-
|
|
2836
|
+
// foreign key: parentId, from the association's name; optional, since a top-level category has none
|
|
2837
|
+
parent = belongsTo(Category, { optional: true });
|
|
2023
2838
|
children = hasMany(Category, { foreignKey: "parentId" }); // not the default, categoryId
|
|
2024
2839
|
}
|
|
2025
2840
|
```
|
|
2026
2841
|
|
|
2027
2842
|
> **Compared with Rails**
|
|
2028
2843
|
>
|
|
2029
|
-
> Rails writes `belongs_to :parent, class_name: "Category", optional: true`. Here the association takes the class itself, so there’s no `class_name
|
|
2844
|
+
> Rails writes `belongs_to :parent, class_name: "Category", optional: true`. Here the association takes the class itself, so there’s no `class_name`. `optional: true` is the same.
|
|
2030
2845
|
|
|
2031
2846
|
## Keeping Models in another folder
|
|
2032
2847
|
|
|
@@ -2438,7 +3253,7 @@ export class Base extends Model {
|
|
|
2438
3253
|
}
|
|
2439
3254
|
```
|
|
2440
3255
|
|
|
2441
|
-
A string matches any attribute whose snake_case name contains it, so `"iban"` also covers `ibanNumber`. Use a RegExp to match one name exactly.
|
|
3256
|
+
A string matches any attribute whose snake_case name contains it, so `"iban"` also covers `ibanNumber`. A string can be in camelCase or snake_case: `"ibanNumber"` and `"iban_number"` both match `ibanNumber`. Use a RegExp to match one name exactly.
|
|
2442
3257
|
|
|
2443
3258
|
### Seeing a filtered attribute
|
|
2444
3259
|
|
|
@@ -2536,11 +3351,14 @@ Write the object `as const`, so TypeScript keeps each type name. Without it, the
|
|
|
2536
3351
|
|
|
2537
3352
|
An override is one of these:
|
|
2538
3353
|
|
|
2539
|
-
| Override | Does
|
|
2540
|
-
| ----------------------------------------- |
|
|
2541
|
-
| `"boolean"` (a type name) | Reads and writes the attribute as that type
|
|
2542
|
-
| `
|
|
2543
|
-
| `
|
|
3354
|
+
| Override | Does |
|
|
3355
|
+
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------- |
|
|
3356
|
+
| `"boolean"` (a type name) | Reads and writes the attribute as that type |
|
|
3357
|
+
| `money` (a [custom type](/custom-types)) | Reads and writes the attribute as that type |
|
|
3358
|
+
| `{ type?, null?, default?, generateId? }` | Replaces those parts of the generated attribute; `null: false` makes it non-null in TypeScript |
|
|
3359
|
+
| `{ enum, prefix?, suffix?, … }` | Makes the attribute an [enum](#declaring-enums), of its column’s type |
|
|
3360
|
+
| `{ enum: true }`, `{ enum: false }` | Turns on the methods of an [enum read from the database](#reading-enums-from-the-database), or drops it |
|
|
3361
|
+
| `false` | Ignores the column: it’s never typed, read, or written, and queries name their columns instead of `*` |
|
|
2544
3362
|
|
|
2545
3363
|
An override of an attribute the table doesn’t have throws `InvalidModel`, and `active-record schema` reports it. So does an override that changes a column or ignores the primary key.
|
|
2546
3364
|
|
|
@@ -2561,7 +3379,7 @@ export class Post extends ApplicationRecord {
|
|
|
2561
3379
|
}
|
|
2562
3380
|
```
|
|
2563
3381
|
|
|
2564
|
-
`post.status` is now typed `"draft" | "published"`, when you read it and when you assign it. `where` and `build` still take any string, and nothing checks the value read from D1. To
|
|
3382
|
+
`post.status` is now typed `"draft" | "published"`, when you read it and when you assign it. `where` and `build` still take any string, and nothing checks the value read from D1. To have the values checked, and get a method for each, declare an [enum](#declaring-enums) instead.
|
|
2565
3383
|
|
|
2566
3384
|
## Declaring attributes yourself
|
|
2567
3385
|
|
|
@@ -2590,11 +3408,41 @@ export class User extends Model.define({
|
|
|
2590
3408
|
}
|
|
2591
3409
|
```
|
|
2592
3410
|
|
|
2593
|
-
An attribute is a type name, or `{ type, column?, null?, default? }`. To share your base class’s behavior and binding, call `define` on it: `ApplicationRecord.define({...})`.
|
|
3411
|
+
An attribute is a type name, or `{ type, column?, null?, default? }`. To share your base class’s behavior and binding, call `define` on it: `ApplicationRecord.define({...})`.
|
|
3412
|
+
|
|
3413
|
+
## Naming Models
|
|
3414
|
+
|
|
3415
|
+
A Model’s name is its class name. The generated schema lists the Model by it, and its table name, its foreign keys, and its error messages are made from it. Read it with `modelName`:
|
|
3416
|
+
|
|
3417
|
+
```ts
|
|
3418
|
+
import { BlogPost } from "./blog-post";
|
|
3419
|
+
|
|
3420
|
+
BlogPost.modelName; // "BlogPost"
|
|
3421
|
+
```
|
|
3422
|
+
|
|
3423
|
+
If your bundler renames classes, set `static modelName` to the class name, so the Model keeps its name once bundled:
|
|
3424
|
+
|
|
3425
|
+
```ts
|
|
3426
|
+
import { ApplicationRecord } from "./application-record";
|
|
3427
|
+
|
|
3428
|
+
export class BlogPost extends ApplicationRecord {
|
|
3429
|
+
static override modelName = "BlogPost";
|
|
3430
|
+
}
|
|
3431
|
+
```
|
|
3432
|
+
|
|
3433
|
+
A subclass inherits a `modelName` its parent sets. Otherwise, each class has its own: `Admin.modelName` is `"Admin"`, though `Admin` shares `User`’s table. Printing a record shows its class name.
|
|
3434
|
+
|
|
3435
|
+
:::note
|
|
3436
|
+
Wrangler keeps class names by default, even when minifying. Without `modelName`, a bundler that renames `User` to `e` makes the first query throw `InvalidModel`, because no Model named `e` is in the generated schema. Keeping class names in your bundler’s settings works too.
|
|
3437
|
+
:::
|
|
3438
|
+
|
|
3439
|
+
> **Compared with Rails**
|
|
3440
|
+
>
|
|
3441
|
+
> `modelName` is a string, where Rails’ `model_name` is an object.
|
|
2594
3442
|
|
|
2595
3443
|
## Naming tables
|
|
2596
3444
|
|
|
2597
|
-
A Model takes its table name from its
|
|
3445
|
+
A Model takes its table name from its [name](#naming-models): snake_case, pluralized.
|
|
2598
3446
|
|
|
2599
3447
|
| Class | Table |
|
|
2600
3448
|
| ---------- | ------------ |
|
|
@@ -2620,10 +3468,6 @@ A subclass shares its parent’s table. A class with no name to take one from mu
|
|
|
2620
3468
|
Pluralization follows English rules, quirks included: `Human` becomes `humen` and `Leaf` becomes `leafs`. There’s no way to add your own rules, so set `table` instead.
|
|
2621
3469
|
:::
|
|
2622
3470
|
|
|
2623
|
-
**Bundlers and class names**
|
|
2624
|
-
|
|
2625
|
-
Wrangler keeps class names by default, even when minifying. If a bundler renames `User` to `e`, the first query throws `InvalidModel`, because no Model named `e` is in the generated schema. Keep class names in your bundler’s settings.
|
|
2626
|
-
|
|
2627
3471
|
## Mapping columns
|
|
2628
3472
|
|
|
2629
3473
|
Attributes are camelCase, and map to snake_case columns:
|
|
@@ -2645,9 +3489,13 @@ To map an attribute to a column with another name, give it `{ column: "..." }`.
|
|
|
2645
3489
|
| `string` | `string` | `TEXT` |
|
|
2646
3490
|
| `integer` | `number` | `INTEGER` |
|
|
2647
3491
|
| `real` | `number` | `REAL` |
|
|
3492
|
+
| `decimal` | `string` | `DECIMAL` |
|
|
2648
3493
|
| `boolean` | `boolean` | `INTEGER`, `0` or `1` |
|
|
2649
3494
|
| `datetime` | `Date` | `TEXT`, ISO-8601, or an `INTEGER` Unix time |
|
|
3495
|
+
| `date` | `string` | `TEXT` in a `DATE` column |
|
|
3496
|
+
| `time` | `string` | `TEXT` in a `TIME` column |
|
|
2650
3497
|
| `json` | any JSON value | `TEXT`, as JSON |
|
|
3498
|
+
| `binary` | `Uint8Array` | `BLOB` |
|
|
2651
3499
|
|
|
2652
3500
|
An attribute can be `null` unless it’s declared `null: false`, and its TypeScript type includes `| null` to match.
|
|
2653
3501
|
|
|
@@ -2665,6 +3513,231 @@ Store `json` attributes in a `TEXT` column, as [D1 recommends](https://developer
|
|
|
2665
3513
|
A `datetime` can be kept as a Unix time in an `INTEGER` column, as Drizzle writes it. Declare it with `storage: "unixSeconds"` or `"unixMilliseconds"`; [Reading Unix timestamps](/adopt-a-database#reading-unix-timestamps) shows how.
|
|
2666
3514
|
:::
|
|
2667
3515
|
|
|
3516
|
+
For a value none of these hold, such as money, define a [custom type](/custom-types).
|
|
3517
|
+
|
|
3518
|
+
### Storing bytes
|
|
3519
|
+
|
|
3520
|
+
A `binary` attribute holds bytes, such as a thumbnail or a hash. A file from a form is read asynchronously, so read its bytes before you assign them:
|
|
3521
|
+
|
|
3522
|
+
```ts
|
|
3523
|
+
import { Attachment } from "./models/attachment";
|
|
3524
|
+
|
|
3525
|
+
const file = form.get("file") as File;
|
|
3526
|
+
const data = new Uint8Array(await file.arrayBuffer());
|
|
3527
|
+
const attachment = await Attachment.create({ name: file.name, data });
|
|
3528
|
+
```
|
|
3529
|
+
|
|
3530
|
+
It reads back as a `Uint8Array`, and prints as `<3 bytes of binary data>`, so logs never hold the bytes.
|
|
3531
|
+
|
|
3532
|
+
:::note
|
|
3533
|
+
A D1 row holds at most 2 MB. Keep larger files in [R2](https://developers.cloudflare.com/r2/), and store their keys.
|
|
3534
|
+
:::
|
|
3535
|
+
|
|
3536
|
+
:::tip
|
|
3537
|
+
`insertAll` and `upsertAll` take any number of rows of bytes. On D1, rows that add up to more than its 2 MB limit on one value go as several statements in one batch, which writes all of them or none. D1 counts the batch as one query.
|
|
3538
|
+
:::
|
|
3539
|
+
|
|
3540
|
+
### Storing exact numbers, days, and times
|
|
3541
|
+
|
|
3542
|
+
A `decimal` holds an exact number, such as a price, as text. Assign text, a number, or a `bigint`:
|
|
3543
|
+
|
|
3544
|
+
```ts
|
|
3545
|
+
import { Product } from "./models/product";
|
|
3546
|
+
|
|
3547
|
+
const product = Product.build({ price: "12.50" });
|
|
3548
|
+
product.price; // "12.5"
|
|
3549
|
+
```
|
|
3550
|
+
|
|
3551
|
+
A decimal reads in one form, without trailing zeros or an exponent, so `"12.50"` and `"12.5"` are the same value. A number keeps 16 significant digits, so `0.1 + 0.2` is `"0.3"`. Conditions, comparisons, and `order` compare decimals as numbers, and so do the `numericality` and `comparison` validations.
|
|
3552
|
+
|
|
3553
|
+
:::tip
|
|
3554
|
+
To do arithmetic with decimals, wrap a decimal library in a [custom type](/custom-types) stored as `"decimal"`.
|
|
3555
|
+
:::
|
|
3556
|
+
|
|
3557
|
+
:::note
|
|
3558
|
+
D1 keeps about 15 significant digits of a decimal, and rounds the rest. Postgres keeps every digit.
|
|
3559
|
+
:::
|
|
3560
|
+
|
|
3561
|
+
To round a decimal to a number of places, give it a `scale`. A `precision` limits its digits in all, so `precision - scale` digits can come before the point:
|
|
3562
|
+
|
|
3563
|
+
```ts
|
|
3564
|
+
import { Model } from "@forestfuture/active-record";
|
|
3565
|
+
|
|
3566
|
+
class Product extends Model.define({
|
|
3567
|
+
price: { type: "decimal", precision: 10, scale: 2 },
|
|
3568
|
+
}) {}
|
|
3569
|
+
|
|
3570
|
+
Product.build({ price: "1.555" }).price; // "1.56"
|
|
3571
|
+
```
|
|
3572
|
+
|
|
3573
|
+
A value is rounded half away from zero, as Postgres rounds a `NUMERIC(10, 2)` column, so a record holds what the database stores. A value with too many digits before the point throws `TypeError`. A `precision` without a `scale` rounds to whole numbers.
|
|
3574
|
+
|
|
3575
|
+
:::note
|
|
3576
|
+
`active-record schema` reads a decimal’s `precision` and `scale` from a column such as `NUMERIC(10, 2)`.
|
|
3577
|
+
:::
|
|
3578
|
+
|
|
3579
|
+
A `date` holds a day, such as `"2026-01-02"`, and a `time` holds a time of day, such as `"09:30:00"`. Neither has a time zone:
|
|
3580
|
+
|
|
3581
|
+
```ts
|
|
3582
|
+
import { Shift } from "./models/shift";
|
|
3583
|
+
|
|
3584
|
+
const shift = Shift.build({ startsOn: "2026-01-02", opensAt: "09:30" });
|
|
3585
|
+
shift.opensAt; // "09:30:00"
|
|
3586
|
+
```
|
|
3587
|
+
|
|
3588
|
+
A time always has its seconds, and a fraction only when it has one: `"09:30:15.25"`. The end of the day is `"24:00:00"`. Days and times compare and sort in order. A `Date` can’t be assigned to either, since its day and time depend on the time zone. For today’s date in UTC, assign `new Date().toISOString().slice(0, 10)`.
|
|
3589
|
+
|
|
3590
|
+
> **Compared with Rails**
|
|
3591
|
+
>
|
|
3592
|
+
> Rails holds a `decimal` as a `BigDecimal`, a `date` as a `Date`, and a `time` as a `Time` on 1
|
|
3593
|
+
> January 2000. Here each one is text, which reads the same from every database and goes into JSON
|
|
3594
|
+
> as it is.
|
|
3595
|
+
|
|
3596
|
+
## Declaring enums
|
|
3597
|
+
|
|
3598
|
+
An enum gives an attribute a fixed set of names. Declare one with `enum` in an override:
|
|
3599
|
+
|
|
3600
|
+
```ts
|
|
3601
|
+
import { ApplicationRecord } from "./application-record";
|
|
3602
|
+
|
|
3603
|
+
export class Ticket extends ApplicationRecord {
|
|
3604
|
+
static override attributes = {
|
|
3605
|
+
status: { enum: ["open", "in_progress", "closed"] }, // stored as the names
|
|
3606
|
+
priority: { enum: { low: 0, normal: 1, high: 2 } }, // stored as 0, 1, and 2
|
|
3607
|
+
} as const;
|
|
3608
|
+
}
|
|
3609
|
+
```
|
|
3610
|
+
|
|
3611
|
+
The attribute’s type is the union of its names, here `"open" | "in_progress" | "closed" | null`. A list of names stores each name as itself, as text. An object stores each name as the value you give it, an integer for an `INTEGER` column or text for a `TEXT` one. A Model declared with `define` gives the type too: `status: { type: "string", enum: ["open", "closed"] }`.
|
|
3612
|
+
|
|
3613
|
+
### Using an enum’s methods
|
|
3614
|
+
|
|
3615
|
+
Each name gets a predicate and a setter on records, and two scopes on the Model:
|
|
3616
|
+
|
|
3617
|
+
```ts
|
|
3618
|
+
const ticket = await Ticket.high().notClosed().first();
|
|
3619
|
+
|
|
3620
|
+
if (ticket?.isOpen()) {
|
|
3621
|
+
await ticket.saveAsClosed();
|
|
3622
|
+
}
|
|
3623
|
+
```
|
|
3624
|
+
|
|
3625
|
+
| Method | Does |
|
|
3626
|
+
| --------------------------------------------------- | ---------------------------------------------------------------------- |
|
|
3627
|
+
| `ticket.isOpen()` | Whether `status` is `"open"` |
|
|
3628
|
+
| `ticket.saveAsOpen()`, `ticket.saveAsOpenOrThrow()` | Sets `status` to `"open"` and saves the record, with its other changes |
|
|
3629
|
+
| `Ticket.open()`, `Ticket.notOpen()` | Scopes of the records whose `status` is, or isn’t, `"open"` |
|
|
3630
|
+
|
|
3631
|
+
A name in snake_case reads in camelCase: `in_progress` gives `isInProgress()` and `Ticket.inProgress()`. `saveAsOpen()` returns `false` when the record is invalid, as `save` does, and `saveAsOpenOrThrow()` throws.
|
|
3632
|
+
|
|
3633
|
+
`where`, `whereNot`, `pluck`, and every write take and give names, too. To read the names with their stored values, call `enumValues`:
|
|
3634
|
+
|
|
3635
|
+
```ts
|
|
3636
|
+
const priorities = Ticket.enumValues("priority"); // { low: 0, normal: 1, high: 2 }
|
|
3637
|
+
```
|
|
3638
|
+
|
|
3639
|
+
:::note
|
|
3640
|
+
Record methods follow your override as soon as you save it. The scopes are typed in the generated schema, so run `active-record schema` (or keep `--watch` running) after you add an enum.
|
|
3641
|
+
:::
|
|
3642
|
+
|
|
3643
|
+
### Keeping names apart
|
|
3644
|
+
|
|
3645
|
+
Two enums that share a name would give the same methods. Add a `prefix` or a `suffix`, `true` for the attribute’s name or a word of your own:
|
|
3646
|
+
|
|
3647
|
+
```ts
|
|
3648
|
+
import { Model } from "@forestfuture/active-record";
|
|
3649
|
+
|
|
3650
|
+
export class Conversation extends Model.define({
|
|
3651
|
+
id: "integer",
|
|
3652
|
+
status: { type: "string", enum: ["active", "archived"], prefix: true },
|
|
3653
|
+
comments: { type: "string", enum: ["active", "closed"], suffix: true },
|
|
3654
|
+
}) {}
|
|
3655
|
+
|
|
3656
|
+
// conversation.isStatusActive(), Conversation.activeComments()
|
|
3657
|
+
```
|
|
3658
|
+
|
|
3659
|
+
A method name that’s taken, by another enum, an attribute, a record method, or a static, throws `InvalidModel` when the Model is first used, and `active-record schema` reports it. So does a name TypeScript can’t declare, such as `in-progress` or `new`. Map a readable name to the stored value instead: `enum: { inProgress: "in-progress" }`. To leave an enum’s methods out, declare it with `scopes: false` or `instanceMethods: false`.
|
|
3660
|
+
|
|
3661
|
+
### Reading and assigning other values
|
|
3662
|
+
|
|
3663
|
+
Assigning a value that isn’t one of an enum’s names, or one of its stored values, throws `TypeError`, and a condition with one matches nothing. A stored value that the enum doesn’t list reads as `null`, so rows written by a newer deploy don’t break an older one. This holds even for an attribute declared `null: false`.
|
|
3664
|
+
|
|
3665
|
+
To rename a name without touching stored rows, map the new name to the old value: `enum: { drafted: "draft" }`. Otherwise, migrate the rows in the same deploy.
|
|
3666
|
+
|
|
3667
|
+
To report an unknown value as a validation error instead of throwing, declare the enum with `validate: true`:
|
|
3668
|
+
|
|
3669
|
+
```ts
|
|
3670
|
+
import { Model } from "@forestfuture/active-record";
|
|
3671
|
+
|
|
3672
|
+
export class Survey extends Model.define({
|
|
3673
|
+
id: "integer",
|
|
3674
|
+
answer: { type: "string", enum: ["yes", "no"], validate: true },
|
|
3675
|
+
}) {}
|
|
3676
|
+
```
|
|
3677
|
+
|
|
3678
|
+
A survey answered `"maybe"` is then invalid, with an `inclusion` error, and so is one with no answer, unless you declare `validate: { allowNull: true }`.
|
|
3679
|
+
|
|
3680
|
+
> **Compared with Rails**
|
|
3681
|
+
>
|
|
3682
|
+
> Rails declares `enum :status, [:open, :closed]` and stores a list by position. Here a list stores
|
|
3683
|
+
> the names, so reordering it changes nothing. `published?` is `isPublished()`, `published!` is
|
|
3684
|
+
> `saveAsPublished()` or `saveAsPublishedOrThrow()`, `not_published` is `notPublished()`, and
|
|
3685
|
+
> `Post.statuses` is `Post.enumValues("status")`. Two names stored as one value are refused.
|
|
3686
|
+
|
|
3687
|
+
### Reading enums from the database
|
|
3688
|
+
|
|
3689
|
+
When the database restricts a column to a list of names, `active-record schema` writes the list into the generated schema. A Postgres enum type does it, and so does a `CHECK` like this one:
|
|
3690
|
+
|
|
3691
|
+
```sql
|
|
3692
|
+
CREATE TABLE tasks (
|
|
3693
|
+
id TEXT PRIMARY KEY,
|
|
3694
|
+
state TEXT NOT NULL CHECK (state IN ('open', 'done'))
|
|
3695
|
+
);
|
|
3696
|
+
```
|
|
3697
|
+
|
|
3698
|
+
The generated spec holds the names, with the enum’s methods turned off:
|
|
3699
|
+
|
|
3700
|
+
```ts
|
|
3701
|
+
/** tasks — state TEXT NOT NULL CHECK (state IN ('open', 'done')) */
|
|
3702
|
+
export const tasks = {
|
|
3703
|
+
id: { type: "string", null: false, generateId: true },
|
|
3704
|
+
state: {
|
|
3705
|
+
type: "string",
|
|
3706
|
+
null: false,
|
|
3707
|
+
enum: ["open", "done"],
|
|
3708
|
+
scopes: false,
|
|
3709
|
+
instanceMethods: false,
|
|
3710
|
+
},
|
|
3711
|
+
} as const;
|
|
3712
|
+
```
|
|
3713
|
+
|
|
3714
|
+
The attribute’s type is `"open" | "done"`, assigning any other value throws `TypeError`, and `enumValues` works as for any enum. The predicates, setters, and scopes wait until you turn them on.
|
|
3715
|
+
|
|
3716
|
+
Turn them on by overriding the attribute with `enum: true`:
|
|
3717
|
+
|
|
3718
|
+
```ts
|
|
3719
|
+
import { ApplicationRecord } from "./application-record";
|
|
3720
|
+
|
|
3721
|
+
export class Task extends ApplicationRecord {
|
|
3722
|
+
static override attributes = { state: { enum: true } } as const;
|
|
3723
|
+
}
|
|
3724
|
+
|
|
3725
|
+
// task.isDone(), task.saveAsDone(), Task.open()
|
|
3726
|
+
```
|
|
3727
|
+
|
|
3728
|
+
`enum: true` keeps the database’s names, so a name a later migration adds gets its methods the next time you run `active-record schema`. A `scopes: false` or `instanceMethods: false` beside it still leaves those out, and `scopes: true` or `instanceMethods: true` alone turns on one kind. Names that clash only matter once their methods are on, and you fix them as in [Keeping names apart](#keeping-names-apart).
|
|
3729
|
+
|
|
3730
|
+
If you’d rather keep the column a plain string, override it with `enum: false`. A list of your own, such as `enum: ["open", "done", "archived"]`, replaces the database’s, with its methods on.
|
|
3731
|
+
|
|
3732
|
+
:::note
|
|
3733
|
+
`active-record schema` reads a `CHECK` whose only condition is `column IN (…)` with text values, or `column IS NULL OR column IN (…)`. Any other `CHECK` leaves the column as it was, and a list of numbers stays an `integer`. Postgres stores a one-name `IN ('open')` as `= 'open'`, so it isn’t read there.
|
|
3734
|
+
:::
|
|
3735
|
+
|
|
3736
|
+
> **Beyond Rails**
|
|
3737
|
+
>
|
|
3738
|
+
> Rails reads no enums from the database: each one is declared in its Model. Here the database gives
|
|
3739
|
+
> an enum its names and its type, and the Model still declares its methods, with `enum: true`.
|
|
3740
|
+
|
|
2668
3741
|
## Casting assigned values
|
|
2669
3742
|
|
|
2670
3743
|
Every value is cast to its attribute’s type when it’s assigned, so text from JSON, a form, or a query string becomes the right type:
|
|
@@ -2686,9 +3759,13 @@ Values are cast wherever they’re assigned: `build`, `create`, `assign`, `updat
|
|
|
2686
3759
|
| `boolean` | `true`, `false`, `1`, `0`, `"1"`, `"0"`, and `"true"`, `"false"`, `"on"`, `"off"` in any case |
|
|
2687
3760
|
| `integer` | a safe integer, or a string that’s wholly one, with an optional sign and spaces around it: `"42"`, `" -7 "`, `"+3"` |
|
|
2688
3761
|
| `real` | a finite number, or a string that’s wholly one, with an optional sign, point, and exponent: `"1.5"`, `".5"`, `"5."`, `"-2e3"` |
|
|
3762
|
+
| `decimal` | a finite number, a `bigint`, or a string that’s wholly a decimal number, as for a `real`: `"12.50"`, `"-2e3"` |
|
|
2689
3763
|
| `string` | a string |
|
|
2690
3764
|
| `datetime` | a valid `Date`; a date, `"2026-01-02"` (midnight UTC); or a date and time with `Z` or a `±HH:MM` offset: `"2026-01-02T09:30:00+02:00"` |
|
|
3765
|
+
| `date` | a day that exists, as `"YYYY-MM-DD"`: `"2026-01-02"` |
|
|
3766
|
+
| `time` | a time of day, with or without seconds and up to six digits of a fraction: `"09:30"`, `"09:30:15.25"` |
|
|
2691
3767
|
| `json` | any value JSON can write |
|
|
3768
|
+
| `binary` | a `Uint8Array`, or an `ArrayBuffer` |
|
|
2692
3769
|
|
|
2693
3770
|
Anything else throws `TypeError` naming the Model and the attribute, and the attribute keeps its value. The error shows at most 60 characters of the value, and none of a [filtered attribute](#filtering-attributes)’s. Among the values refused:
|
|
2694
3771
|
|
|
@@ -2697,7 +3774,10 @@ Anything else throws `TypeError` naming the Model and the attribute, and the att
|
|
|
2697
3774
|
- `NaN` and `Infinity`.
|
|
2698
3775
|
- A number, boolean, or `Date` for a `string`.
|
|
2699
3776
|
- For a `datetime`: a time without an offset, a lowercase `t` or `z`, a day that doesn’t exist (`"2026-02-30"`), other formats, and numbers.
|
|
3777
|
+
- For a `decimal`: text with anything but a number in it, a number too large or too small for a JavaScript `number`, such as `"1e400"` or `"1e-400"`, and one with more digits after its point than Postgres holds.
|
|
3778
|
+
- For a `date` or a `time`: a `Date`, a time zone, a day or time that doesn’t exist (`"2026-02-30"`, `"24:00:01"`), other formats (`"2026-1-2"`, `"9:30"`), and numbers.
|
|
2700
3779
|
- For a `json`: a value JSON can’t write, such as a `BigInt`, an object that refers to itself, a function, or a symbol.
|
|
3780
|
+
- For a `binary`: text, an array of numbers, or another typed array.
|
|
2701
3781
|
|
|
2702
3782
|
:::note
|
|
2703
3783
|
A `json` attribute stores what `JSON.stringify` writes: a `Map` becomes `{}` and `NaN` becomes `null`. Convert them before assigning. After a save, the record holds what was stored.
|
|
@@ -2711,7 +3791,11 @@ A stored cell is checked the same way, when the record loads or `pluck` reads it
|
|
|
2711
3791
|
- For a `string`: anything but text.
|
|
2712
3792
|
- For a `datetime`: text that isn’t a date or a date and time (`"garbage"`, `"12"`), or a number. A number is a [Unix time](/adopt-a-database#reading-unix-timestamps), which needs a `storage`.
|
|
2713
3793
|
- For a `datetime` with a `storage`: anything but a number, or one past what a `Date` can hold.
|
|
3794
|
+
- For a `decimal`: anything but a number or a decimal’s text.
|
|
3795
|
+
- For a `date`: anything but a day’s text. A date and time, such as `"2026-01-02T00:00:00.000Z"`, fails too; see [Reading `DATE` columns](/upgrading#reading-date-columns).
|
|
3796
|
+
- For a `time`: anything but a time of day’s text.
|
|
2714
3797
|
- For a `json`: text that isn’t JSON.
|
|
3798
|
+
- For a `binary`: anything but bytes.
|
|
2715
3799
|
|
|
2716
3800
|
See [Fixing cells of the wrong type](/adopt-a-database#fixing-cells-of-the-wrong-type).
|
|
2717
3801
|
|
|
@@ -2772,7 +3856,7 @@ It reads three kinds of input:
|
|
|
2772
3856
|
|
|
2773
3857
|
- **Keys you don’t name** are dropped. A named attribute the input doesn’t have is left out, and a `null` is kept.
|
|
2774
3858
|
- **A name that isn’t an attribute** is a compile error, and throws `UnknownAttribute`.
|
|
2775
|
-
- **`TypeError`** is thrown for a value that can’t be cast, a file from a form, and any other input: an array, a `Map`, `Headers`, a class instance, `null`, or a string.
|
|
3859
|
+
- **`TypeError`** is thrown for a value that can’t be cast, a file from a form (read a file’s bytes for a [`binary` attribute](#storing-bytes)), and any other input: an array, a `Map`, `Headers`, a class instance, `null`, or a string.
|
|
2776
3860
|
|
|
2777
3861
|
[Untrusted input](/untrusted-input) shows `permit` in a Worker.
|
|
2778
3862
|
|
|
@@ -2838,7 +3922,7 @@ user.savedChangeTo("email"); // ["ada@example.com", "ada@lovelace.dev"]
|
|
|
2838
3922
|
user.hasSavedChangeTo("email"); // true
|
|
2839
3923
|
```
|
|
2840
3924
|
|
|
2841
|
-
- `isChanged()`, `changed()`, `changedAttributes()`, and `changes()` describe the unsaved changes.
|
|
3925
|
+
- `isChanged()`, `changed()`, `changedAttributes()`, and `changes()` describe the unsaved changes. A new record’s changes run from its defaults, so a default it keeps isn’t a change.
|
|
2842
3926
|
- `attributeWas`, `isAttributeChanged`, and `willSaveChangeTo` look at one attribute’s unsaved change. Use them in before-callbacks.
|
|
2843
3927
|
- `savedChanges()`, `savedChangeTo`, `hasSavedChangeTo`, and `attributeBeforeLastSave` look at the last save. Use them in after-callbacks, where the record is already clean.
|
|
2844
3928
|
- `restoreAttributes()` undoes unsaved changes, to every attribute or the ones you name.
|
|
@@ -2846,7 +3930,7 @@ user.hasSavedChangeTo("email"); // true
|
|
|
2846
3930
|
An update writes only the attributes that changed, and a save with nothing changed sends nothing.
|
|
2847
3931
|
|
|
2848
3932
|
:::note
|
|
2849
|
-
Changes are found by comparing stored values, so editing a `json` value or a `
|
|
3933
|
+
Changes are found by comparing stored values, so editing a `json` value, a `Date`, or a `binary` attribute’s bytes in place counts as a change.
|
|
2850
3934
|
:::
|
|
2851
3935
|
|
|
2852
3936
|
## Writing SQL fragments
|
|
@@ -2917,7 +4001,7 @@ A name a Model doesn’t have throws `InvalidModel` when the Model is first used
|
|
|
2917
4001
|
`onQuery` listeners and error messages show a filtered attribute’s values as `"[FILTERED]"`. D1 still gets the real values. [Logging](/logging#keeping-secrets-out-of-the-logs) shows how to change the list.
|
|
2918
4002
|
|
|
2919
4003
|
- **Which attributes:** `static filterAttributes`, a list of strings and RegExps, inherited from your app’s base class. By default, it’s `passw`, `email`, `secret`, `token`, `_key`, `crypt`, `salt`, `certificate`, `otp`, `ssn`, `cvv`, `cvc`. Setting it replaces the list; `[]` filters nothing.
|
|
2920
|
-
- **Matching:** a string matches when the attribute’s snake_case name contains it, in any case: `passwordDigest` (`password_digest`) contains `passw`, and `apiKey` (`api_key`) contains `_key`. A RegExp matches the attribute or its snake_case name.
|
|
4004
|
+
- **Matching:** a string matches when the attribute’s snake_case name contains it, in any case: `passwordDigest` (`password_digest`) contains `passw`, and `apiKey` (`api_key`) contains `_key`. A string can also be written as the attribute is, so `"secretAt"`, `"secret_at"`, and `"secret"` all match `secretAt`. A RegExp matches the attribute or its snake_case name.
|
|
2921
4005
|
- **Hidden in `QueryEvent.params`:** the values bound for the attribute in inserts (in a multi-row insert’s JSON, its column in every row), updates, `updateAll`, conditions, lists and comparisons, and a filtered primary key in a record’s `UPDATE` and `DELETE`.
|
|
2922
4006
|
- **Hidden in errors:** a cast error’s value, and a filtered primary key in `RecordNotFound`.
|
|
2923
4007
|
- **Not hidden:** a bare value inside an `sql` fragment, which has no attribute (write it as `column("token").value(token)` to filter it); and `toJSON()` and `attributes()`, which are your data, not logs ([Hiding attributes](#hiding-attributes) keeps names out of `toJSON()`).
|
|
@@ -2937,6 +4021,7 @@ User { id: 1, name: 'Johnny' (was 'Alice'), email: [FILTERED], role: 'admin' }
|
|
|
2937
4021
|
- **Filtered attributes** print as `[FILTERED]`, without quotes so it can’t be mistaken for a string, and in a distinct color when the terminal shows colors. An attribute with no value still prints `null`.
|
|
2938
4022
|
- **Unsaved changes** print the new value and the old one: `'Johnny' (was 'Alice')`. Once the record is saved, the flag goes. A changed filtered attribute prints `[FILTERED] (changed)`, and so does a column a partial record never loaded: `'Johnny' (changed)`. A new record flags nothing, since all of it is unsaved.
|
|
2939
4023
|
- **A partial record** prints only the columns it loaded.
|
|
4024
|
+
- **Bytes** print as how many there are: `<3 bytes of binary data>`.
|
|
2940
4025
|
|
|
2941
4026
|
A Relation prints the SELECT it would send, without sending it:
|
|
2942
4027
|
|
|
@@ -2982,6 +4067,7 @@ The first time a Model is used, by its first query or `db.model(X)`, its declara
|
|
|
2982
4067
|
|
|
2983
4068
|
- A Model `active-record schema` hasn’t seen, or whose table has changed since. Run it again.
|
|
2984
4069
|
- No table name: an empty `table`, or a class with no name to infer one from.
|
|
4070
|
+
- A `modelName` that isn’t a string.
|
|
2985
4071
|
- An override of an attribute the table doesn’t have.
|
|
2986
4072
|
- A `primaryKey` that isn’t an attribute.
|
|
2987
4073
|
- An attribute named like a record method, such as `save` or `attributes`.
|
|
@@ -3107,12 +4193,13 @@ npx active-record schema
|
|
|
3107
4193
|
Its attributes come out the same as on D1. Only its adapter changes:
|
|
3108
4194
|
|
|
3109
4195
|
```ts src/db/schema.ts
|
|
4196
|
+
import { defineSchema } from "@forestfuture/active-record";
|
|
3110
4197
|
import { postgresql } from "@forestfuture/active-record/postgresql";
|
|
3111
4198
|
|
|
3112
|
-
export const schema = {
|
|
4199
|
+
export const schema = defineSchema({
|
|
3113
4200
|
adapter: postgresql({ binding: "HYPERDRIVE" }),
|
|
3114
4201
|
// …
|
|
3115
|
-
};
|
|
4202
|
+
});
|
|
3116
4203
|
```
|
|
3117
4204
|
|
|
3118
4205
|
## Copying the data
|
|
@@ -3278,6 +4365,10 @@ A new record is inserted, and a persisted one updates only the attributes that c
|
|
|
3278
4365
|
|
|
3279
4366
|
When a failure is exceptional, use the `OrThrow` version of each method:
|
|
3280
4367
|
|
|
4368
|
+
> **Compared with Rails**
|
|
4369
|
+
>
|
|
4370
|
+
> A TypeScript method name can’t contain `!`, so the `OrThrow` suffix takes its place. `saveOrThrow`, `createOrThrow`, `updateOrThrow`, and `destroyOrThrow` are Rails’ `save!`, `create!`, `update!`, and `destroy!`.
|
|
4371
|
+
|
|
3281
4372
|
```ts
|
|
3282
4373
|
import { RecordInvalid } from "@forestfuture/active-record";
|
|
3283
4374
|
import { User } from "./models";
|
|
@@ -3299,23 +4390,21 @@ Instead of returning `false`, they throw:
|
|
|
3299
4390
|
- `RecordNotSaved` when a callback aborted a save, with the abort’s reason as its message.
|
|
3300
4391
|
- `RecordNotDestroyed` from `destroyOrThrow()`, when a callback aborted the destroy or a `restrictWithError` association refused it.
|
|
3301
4392
|
|
|
3302
|
-
> **Compared with Rails**
|
|
3303
|
-
>
|
|
3304
|
-
> The `OrThrow` methods are Rails’ `save!`, `create!`, `update!`, and `destroy!`.
|
|
3305
|
-
|
|
3306
4393
|
### What each method returns
|
|
3307
4394
|
|
|
3308
|
-
| Method | Resolves to | Throws
|
|
3309
|
-
| ---------------------------------------- | ------------------------------------- |
|
|
3310
|
-
| `save()` / `update(attrs)` | `true` / `false` | constraint errors, `RecordDestroyed`
|
|
3311
|
-
| `saveOrThrow()` / `updateOrThrow(attrs)` | `true` | same as above, plus `RecordInvalid`, `RecordNotSaved`
|
|
3312
|
-
| `create(attrs)` | record, persisted or not | constraint errors
|
|
3313
|
-
| `createOrThrow(attrs)` | persisted record | same as above, plus `RecordInvalid`, `RecordNotSaved`
|
|
3314
|
-
| `destroy()` | destroyed record, or `false` on abort | constraint errors, `RecordDestroyed`
|
|
3315
|
-
| `destroyOrThrow()` | destroyed record | same as above, plus `RecordNotDestroyed`
|
|
3316
|
-
| `find(id)` | record | `RecordNotFound`
|
|
3317
|
-
| `findBy(conds)` | record or `null` | none
|
|
3318
|
-
| `findByOrThrow(conds)` | record | `RecordNotFound`
|
|
4395
|
+
| Method | Resolves to | Throws |
|
|
4396
|
+
| ---------------------------------------- | ------------------------------------- | ----------------------------------------------------------------- |
|
|
4397
|
+
| `save()` / `update(attrs)` | `true` / `false` | constraint errors, `RecordDestroyed` |
|
|
4398
|
+
| `saveOrThrow()` / `updateOrThrow(attrs)` | `true` | same as above, plus `RecordInvalid`, `RecordNotSaved` |
|
|
4399
|
+
| `create(attrs)` | record, persisted or not | constraint errors |
|
|
4400
|
+
| `createOrThrow(attrs)` | persisted record | same as above, plus `RecordInvalid`, `RecordNotSaved` |
|
|
4401
|
+
| `destroy()` | destroyed record, or `false` on abort | constraint errors, `RecordDestroyed` |
|
|
4402
|
+
| `destroyOrThrow()` | destroyed record | same as above, plus `RecordNotDestroyed` |
|
|
4403
|
+
| `find(id)` | record | `RecordNotFound` |
|
|
4404
|
+
| `findBy(conds)` | record or `null` | none |
|
|
4405
|
+
| `findByOrThrow(conds)` | record | `RecordNotFound` |
|
|
4406
|
+
| `findOrCreateBy(attrs)` | record, persisted or not | constraint errors |
|
|
4407
|
+
| `createOrFindBy(attrs)` | record, persisted or not | constraint errors but its own `RecordNotUnique`, `RecordNotFound` |
|
|
3319
4408
|
|
|
3320
4409
|
`false` only ever means validation failed or a callback aborted. Every method throws for anything else:
|
|
3321
4410
|
|
|
@@ -3323,6 +4412,156 @@ Instead of returning `false`, they throw:
|
|
|
3323
4412
|
- **An error thrown by a callback**, other than `abort()`, even from an after-callback once the record is saved.
|
|
3324
4413
|
- **D1’s own errors.**
|
|
3325
4414
|
|
|
4415
|
+
## Changing one attribute
|
|
4416
|
+
|
|
4417
|
+
To bump a number or flip a flag, use `increment`, `decrement`, or `toggle`. They change the record without saving it, so save it afterwards:
|
|
4418
|
+
|
|
4419
|
+
```ts
|
|
4420
|
+
const article = await Article.find(id);
|
|
4421
|
+
article.increment("viewCount"); // viewCount + 1, not saved yet
|
|
4422
|
+
article.toggle("isPinned");
|
|
4423
|
+
await article.save();
|
|
4424
|
+
```
|
|
4425
|
+
|
|
4426
|
+
`increment` and `decrement` take an amount as their second argument, and count `null` as zero. `toggle` turns `null` into `true`.
|
|
4427
|
+
|
|
4428
|
+
### Writing straight to the row
|
|
4429
|
+
|
|
4430
|
+
To write a value without validations, callbacks, or a new `updatedAt`, use a method ending in `Column`. Each one writes to the row at once:
|
|
4431
|
+
|
|
4432
|
+
```ts
|
|
4433
|
+
await article.incrementColumn("viewCount"); // adds 1 in the row, now
|
|
4434
|
+
await article.toggleColumn("isPinned");
|
|
4435
|
+
await article.updateColumns({ title: "Renamed" }); // no validations, callbacks, or updatedAt
|
|
4436
|
+
```
|
|
4437
|
+
|
|
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.
|
|
4439
|
+
- **`toggleColumn`** writes the flipped value.
|
|
4440
|
+
- **`updateColumns(attrs)`** writes the attributes you give. `updateColumn(name, value)` writes one.
|
|
4441
|
+
|
|
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`.
|
|
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
|
+
|
|
4463
|
+
### Updating counters
|
|
4464
|
+
|
|
4465
|
+
To add to a number without loading the record, pass its primary key to `updateCounters`:
|
|
4466
|
+
|
|
4467
|
+
```ts
|
|
4468
|
+
await Article.updateCounters(id, { viewCount: 1 });
|
|
4469
|
+
await Article.where({ isPinned: true }).updateCounters({ viewCount: 10 });
|
|
4470
|
+
await Article.incrementCounter("viewCount", [id], { by: 5, touch: true }); // sets updatedAt too
|
|
4471
|
+
```
|
|
4472
|
+
|
|
4473
|
+
- **`Article.updateCounters(ids, counters)`** adds to the rows with those keys, even ones a default scope leaves out.
|
|
4474
|
+
- **A Relation’s `updateCounters(counters)`** adds to every row it matches.
|
|
4475
|
+
- **`incrementCounter` and `decrementCounter`** change one attribute by one, or by the amount in `{ by: 5 }`.
|
|
4476
|
+
|
|
4477
|
+
Each one sends a single statement and resolves to the number of rows it changed. Like `updateAll`, it skips validations and callbacks. To set `updatedAt` too, pass `{ touch: true }`. To set other datetime attributes as well, name them, as in `{ touch: "viewedAt" }`.
|
|
4478
|
+
|
|
4479
|
+
To keep a count of an association’s records, see [counter caches](/associations#counting-records-with-a-counter-cache).
|
|
4480
|
+
|
|
4481
|
+
:::warning[Counting by key skips the default scope]
|
|
4482
|
+
`Article.updateCounters`, `incrementCounter`, and `decrementCounter` find rows by primary key alone. If a default scope keeps tenants apart or hides deleted rows, a key from a request can reach a row it hides. Start from a Relation instead, which keeps the default scope:
|
|
4483
|
+
|
|
4484
|
+
```ts
|
|
4485
|
+
await Article.where({ id }).updateCounters({ viewCount: 1 }); // keeps the default scope
|
|
4486
|
+
```
|
|
4487
|
+
|
|
4488
|
+
:::
|
|
4489
|
+
|
|
4490
|
+
:::note
|
|
4491
|
+
`increment` and the counters take `integer` and `real` attributes. A `decimal` is stored as text, so they refuse it.
|
|
4492
|
+
:::
|
|
4493
|
+
|
|
4494
|
+
> **Compared with Rails**
|
|
4495
|
+
>
|
|
4496
|
+
> `incrementColumn`, `decrementColumn`, and `toggleColumn` are Rails’ `increment!`, `decrement!`, and `toggle!`. A method name can’t contain `!`, and the `OrThrow` suffix means something else, so the `Column` ending names what they do: write to the row now, as `updateColumns` does.
|
|
4497
|
+
>
|
|
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`.
|
|
4499
|
+
>
|
|
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`.
|
|
4503
|
+
|
|
4504
|
+
## Finding or creating a record
|
|
4505
|
+
|
|
4506
|
+
Find a record by its attributes, or create one with them when there isn’t one, with `findOrCreateBy`:
|
|
4507
|
+
|
|
4508
|
+
```ts
|
|
4509
|
+
const travel = await Label.findOrCreateBy({ name: "travel" }); // found, or created
|
|
4510
|
+
const food = await Label.findOrInitializeBy({ name: "food" }); // found, or built and not saved
|
|
4511
|
+
```
|
|
4512
|
+
|
|
4513
|
+
`findOrCreateBy` creates the record as `create` does, so check `isPersisted()` or `errors` if it might not save. `findOrCreateByOrThrow` throws `RecordInvalid` instead. `findOrInitializeBy` builds the record without saving it.
|
|
4514
|
+
|
|
4515
|
+
They work on any Relation. A scope’s or an association’s conditions become the new record’s attributes too, so `user.posts().findOrCreateBy({ title })` finds or creates one of the user’s posts.
|
|
4516
|
+
|
|
4517
|
+
The attributes you pass become the new record’s values, so each must be one value. A list, a comparison such as `gte(18)`, or a `sql` fragment throws a `TypeError` before anything is sent. An array that an attribute holds as its value, such as a `json` attribute’s, is one value. These methods find the record that holds it.
|
|
4518
|
+
|
|
4519
|
+
### Giving new records more attributes
|
|
4520
|
+
|
|
4521
|
+
To give a new record attributes that aren’t part of the search, use `createWith`:
|
|
4522
|
+
|
|
4523
|
+
```ts
|
|
4524
|
+
const blueLabels = Label.createWith({ color: "blue" });
|
|
4525
|
+
const music = await blueLabels.findOrCreateBy({ name: "music" }); // created blue
|
|
4526
|
+
```
|
|
4527
|
+
|
|
4528
|
+
The Relation’s `build`, `create`, and `insert` use them too. Attributes you pass to `build` and `create` win over them. `insert`, `insertAll`, `upsert`, and `upsertAll` write them over the attributes you pass. `createWith(null)` removes them.
|
|
4529
|
+
|
|
4530
|
+
To set attributes in code, pass a function as the last argument. It gets the new record once its attributes are assigned, before it’s saved:
|
|
4531
|
+
|
|
4532
|
+
```ts
|
|
4533
|
+
const art = await Label.findOrCreateBy({ name: "art" }, (label) => {
|
|
4534
|
+
label.color = pickColor(); // only when it's created
|
|
4535
|
+
});
|
|
4536
|
+
```
|
|
4537
|
+
|
|
4538
|
+
The function runs only when a record is made. `build`, `create`, and `createOrThrow` take one too. Each method awaits it, except `build`, which returns the record at once. An async function given to `build` throws a `TypeError`.
|
|
4539
|
+
|
|
4540
|
+
### Creating records from concurrent requests
|
|
4541
|
+
|
|
4542
|
+
Two requests can both find nothing, and both create a record. When a UNIQUE index covers the attributes, use `createOrFindBy` instead. It inserts first, and finds the existing row when the index refuses the duplicate:
|
|
4543
|
+
|
|
4544
|
+
```ts
|
|
4545
|
+
const news = await Label.createOrFindBy({ name: "news" }); // created, or found
|
|
4546
|
+
```
|
|
4547
|
+
|
|
4548
|
+
`createOrFindByOrThrow` throws `RecordInvalid` when the record is invalid.
|
|
4549
|
+
|
|
4550
|
+
:::warning[Let the index decide]
|
|
4551
|
+
`createOrFindBy` only finds the existing row when the database refuses the insert:
|
|
4552
|
+
|
|
4553
|
+
- **Leave out a `uniqueness` validation on those attributes.** It refuses the duplicate before the insert, so `createOrFindBy` resolves to the invalid record, not the existing one. The UNIQUE index alone keeps the column unique.
|
|
4554
|
+
- **Save the record alone.** When `init` builds or sets records through its associations, a refusal may be theirs, so `createOrFindBy` throws the `RecordNotUnique` instead of finding.
|
|
4555
|
+
- **It throws `RecordNotFound` when there’s nothing to find:** when the index refused a value in an attribute you didn’t pass, when the existing row isn’t linked to the owner of an [association through another](/associations#reaching-records-through-another-association), or when a [D1 Session](/read-your-own-writes) reads from a replica that the other request’s row hasn’t reached yet.
|
|
4556
|
+
|
|
4557
|
+
:::
|
|
4558
|
+
|
|
4559
|
+
> **Compared with Rails**
|
|
4560
|
+
>
|
|
4561
|
+
> `findOrCreateBy`, `findOrInitializeBy`, `createOrFindBy`, and `createWith` are Rails’ `find_or_create_by`, `find_or_initialize_by`, `create_or_find_by`, and `create_with`, and the `OrThrow` versions are the `!` ones. The function passed last takes the place of Rails’ block.
|
|
4562
|
+
>
|
|
4563
|
+
> Rails reads a list in their attributes as `IN`, as `find_by` does. These methods refuse one instead, as [Untrusted input](/untrusted-input#querying-with-request-values) explains.
|
|
4564
|
+
|
|
3326
4565
|
## Destroying records
|
|
3327
4566
|
|
|
3328
4567
|
Destroy a record with `destroy`:
|
|
@@ -3334,10 +4573,54 @@ if (destroyed) {
|
|
|
3334
4573
|
}
|
|
3335
4574
|
```
|
|
3336
4575
|
|
|
3337
|
-
It runs the destroy callbacks and the associations’ [`dependent` options](/associations#destroying-dependent-records), then deletes the row. A destroyed record’s attributes stay readable, but setting one, or calling `save`, `update`, `destroy`, or `reload`, throws `RecordDestroyed`.
|
|
4576
|
+
It runs the destroy callbacks and the associations’ [`dependent` options](/associations#destroying-dependent-records), then deletes the row. A destroyed record’s attributes stay readable, but setting one, or calling `save`, `update`, `destroy`, or `reload`, throws `RecordDestroyed`.
|
|
4577
|
+
|
|
4578
|
+
:::note
|
|
4579
|
+
If another request already deleted the row, `save` and `destroy` still succeed.
|
|
4580
|
+
:::
|
|
4581
|
+
|
|
4582
|
+
### Destroying many records
|
|
4583
|
+
|
|
4584
|
+
Destroy every record a query matches with `destroyAll`:
|
|
4585
|
+
|
|
4586
|
+
```ts
|
|
4587
|
+
import { Post } from "./models";
|
|
4588
|
+
|
|
4589
|
+
const drafts = await Post.where({ publishedAt: null }).destroyAll(); // the destroyed posts
|
|
4590
|
+
await Post.destroyBy({ userId: user.id }); // where(…).destroyAll()
|
|
4591
|
+
const post = await Post.destroy("post-1"); // by primary key
|
|
4592
|
+
const posts = await Post.destroy(["post-2", "post-3"]);
|
|
4593
|
+
```
|
|
4594
|
+
|
|
4595
|
+
- **`destroyAll()`** loads the records, runs each one’s destroy callbacks and `dependent` options, and deletes them all in one write. It resolves to the destroyed records.
|
|
4596
|
+
- **`destroyBy(conditions)`** is `where(conditions).destroyAll()`.
|
|
4597
|
+
- **`Post.destroy(id)`** finds the record by its primary key and destroys it. Given an array of keys, it destroys those records in one write. It throws `RecordNotFound` if a key has no record, before destroying any.
|
|
4598
|
+
|
|
4599
|
+
When one record can’t be destroyed, nothing is. A callback that aborts and a `restrictWithError` association both stop the whole write with `RecordNotDestroyed`.
|
|
4600
|
+
|
|
4601
|
+
To delete rows without loading them or running callbacks, use `deleteAll`, `deleteBy`, or `Post.delete(ids)`. See [Bulk writes and batches](/batches).
|
|
4602
|
+
|
|
4603
|
+
> **Compared with Rails**
|
|
4604
|
+
>
|
|
4605
|
+
> Rails’ `destroy_all` on a Relation destroys each record in a transaction of its own, skips a record whose callback aborts, and returns every record. Here the records are destroyed in one write, and one refusal stops them all, as Rails’ `destroy_all` on an association does.
|
|
4606
|
+
|
|
4607
|
+
### Destroying a large set
|
|
4608
|
+
|
|
4609
|
+
`destroyAll` holds every record it matches in memory, and writes them together. To destroy a large set in smaller writes, destroy it [a batch at a time](/querying#writing-a-batch-at-a-time):
|
|
4610
|
+
|
|
4611
|
+
```ts
|
|
4612
|
+
import { Post } from "./models";
|
|
4613
|
+
|
|
4614
|
+
const unpublished = Post.where({ publishedAt: null });
|
|
4615
|
+
for await (const batch of unpublished.inBatches({ batchSize: 100 })) {
|
|
4616
|
+
await batch.destroyAll(); // one write per batch
|
|
4617
|
+
}
|
|
4618
|
+
```
|
|
4619
|
+
|
|
4620
|
+
Each batch is its own write, so a batch that fails leaves the earlier batches destroyed.
|
|
3338
4621
|
|
|
3339
4622
|
:::note
|
|
3340
|
-
|
|
4623
|
+
A batch bounds memory, not queries. Each record reads its `"destroy"` and restricted associations with a query of its own, so a large set sends as many reads, a batch at a time or not. On D1, that counts toward [the queries one Worker invocation can send](/querying#staying-within-d1s-query-limit).
|
|
3341
4624
|
:::
|
|
3342
4625
|
|
|
3343
4626
|
## Checking a record’s state
|
|
@@ -3348,6 +4631,31 @@ If another request already deleted the row, `save` and `destroy` still succeed.
|
|
|
3348
4631
|
| Persisted (loaded, or after a successful save) | `false` | `true` | `false` |
|
|
3349
4632
|
| Destroyed (after a successful `destroy()`) | `false` | `false` | `true` |
|
|
3350
4633
|
|
|
4634
|
+
`isPreviouslyNewRecord()` says whether the last save created the record. Use it in an after-callback that should only run for new records:
|
|
4635
|
+
|
|
4636
|
+
```ts
|
|
4637
|
+
import { Model } from "@forestfuture/active-record";
|
|
4638
|
+
|
|
4639
|
+
export class Article extends Model.define({
|
|
4640
|
+
id: { type: "integer", null: false },
|
|
4641
|
+
title: { type: "string", null: false },
|
|
4642
|
+
viewCount: { type: "integer", null: false },
|
|
4643
|
+
isPinned: { type: "boolean", null: false },
|
|
4644
|
+
viewedAt: "datetime",
|
|
4645
|
+
updatedAt: "datetime",
|
|
4646
|
+
}) {
|
|
4647
|
+
static {
|
|
4648
|
+
this.afterSave((article) => {
|
|
4649
|
+
if (article.isPreviouslyNewRecord()) {
|
|
4650
|
+
console.log(`New article: ${article.title}`); // not after later saves
|
|
4651
|
+
}
|
|
4652
|
+
});
|
|
4653
|
+
}
|
|
4654
|
+
}
|
|
4655
|
+
```
|
|
4656
|
+
|
|
4657
|
+
It’s `false` again once the record is saved again or destroyed.
|
|
4658
|
+
|
|
3351
4659
|
## Reloading records
|
|
3352
4660
|
|
|
3353
4661
|
Load a record’s row again with `reload`, discarding unsaved changes and loaded associations:
|
|
@@ -3364,7 +4672,7 @@ It throws `RecordNotFound` if the row is gone, or the record was never saved.
|
|
|
3364
4672
|
|
|
3365
4673
|
## Writing many rows
|
|
3366
4674
|
|
|
3367
|
-
To insert, update, or delete many rows at once, without validations and callbacks, use `insertAll`, `upsertAll`, `updateAll`, and `
|
|
4675
|
+
To insert, update, or delete many rows at once, without validations and callbacks, use `insertAll`, `upsertAll`, `updateAll`, `deleteAll`, and `deleteBy`. See [Bulk writes and batches](/batches).
|
|
3368
4676
|
|
|
3369
4677
|
---
|
|
3370
4678
|
|
|
@@ -3442,7 +4750,7 @@ A Hyperdrive binding’s connection string isn’t yours to change, so it always
|
|
|
3442
4750
|
|
|
3443
4751
|
## Batches are transactions
|
|
3444
4752
|
|
|
3445
|
-
[
|
|
4753
|
+
A [batch](/batches#batching-writes) is written whole or not at all, as on D1. On Postgres its writes run between `BEGIN` and `COMMIT`, on a client of its own. A query your request sends while the batch runs stays outside the transaction, so a failed batch never rolls it back.
|
|
3446
4754
|
|
|
3447
4755
|
## Reads run one after another
|
|
3448
4756
|
|
|
@@ -3452,7 +4760,7 @@ Queries you send at once with `Promise.all` inside one `withDatabase` call also
|
|
|
3452
4760
|
|
|
3453
4761
|
## Large integers
|
|
3454
4762
|
|
|
3455
|
-
A `bigint` column reads as a number. A value past `Number.MAX_SAFE_INTEGER` throws a `TypeError` naming its attribute, rather than reading as a number that’s slightly wrong.
|
|
4763
|
+
A `bigint` column reads as a number. A value past `Number.MAX_SAFE_INTEGER` throws a `TypeError` naming its attribute, rather than reading as a number that’s slightly wrong. For exact numbers of any size, use a `numeric` column and a [`decimal`](/models#storing-exact-numbers-days-and-times) attribute, which keeps every digit.
|
|
3456
4764
|
|
|
3457
4765
|
## Placeholders
|
|
3458
4766
|
|
|
@@ -3476,6 +4784,8 @@ Postgres sorts text by your database’s collation, usually its locale’s, wher
|
|
|
3476
4784
|
|
|
3477
4785
|
Postgres refuses to order `distinct()` records by a column they don’t select, and throws its own error. Select the column, or order by one you select.
|
|
3478
4786
|
|
|
4787
|
+
After `distinct()`, `pluck("title")` selects only `title`. So does `count("title")` with a `limit` or `offset`. Order them by `title`, or leave the order out.
|
|
4788
|
+
|
|
3479
4789
|
## NUL characters
|
|
3480
4790
|
|
|
3481
4791
|
Postgres text, and strings in a `jsonb` value, can’t hold the NUL character (`\u0000`). A value with one fails with Postgres’s own error.
|
|
@@ -3652,6 +4962,65 @@ export function publishedBefore(before: Date) {
|
|
|
3652
4962
|
|
|
3653
4963
|
`value` works for any attribute, and writes a boolean as 0 or 1 and a JSON value as text. The value is cast as an assigned one, so a value the attribute can’t hold throws `TypeError` naming the attribute, when `where` is given the fragment. A filtered attribute’s value is hidden from `onQuery`, as it is anywhere else.
|
|
3654
4964
|
|
|
4965
|
+
### Replacing conditions
|
|
4966
|
+
|
|
4967
|
+
Replace the conditions on some attributes with `rewhere`:
|
|
4968
|
+
|
|
4969
|
+
```ts
|
|
4970
|
+
import { User } from "./models";
|
|
4971
|
+
|
|
4972
|
+
const members = User.where({ role: "member", isActive: true });
|
|
4973
|
+
members.rewhere({ role: "admin" }); // is_active = ? AND role = ?
|
|
4974
|
+
```
|
|
4975
|
+
|
|
4976
|
+
Conditions on other attributes stay, and so do `sql` fragments. A default scope’s condition on the attribute is replaced too.
|
|
4977
|
+
|
|
4978
|
+
:::note
|
|
4979
|
+
A `whereNot` or `or` that names only those attributes is replaced. One that names other attributes too stays.
|
|
4980
|
+
:::
|
|
4981
|
+
|
|
4982
|
+
Drop parts of a query with `unscope`, or keep only some with `only`:
|
|
4983
|
+
|
|
4984
|
+
```ts
|
|
4985
|
+
import { User } from "./models";
|
|
4986
|
+
|
|
4987
|
+
const recent = User.where({ role: "admin" }).order({ createdAt: "desc" }).limit(10);
|
|
4988
|
+
recent.unscope("order", "limit"); // every admin, unordered
|
|
4989
|
+
recent.unscope({ where: "role" }); // the 10 newest users
|
|
4990
|
+
recent.only("where"); // every admin
|
|
4991
|
+
```
|
|
4992
|
+
|
|
4993
|
+
- The parts are `"where"`, `"order"`, `"limit"`, `"offset"`, `"select"`, `"distinct"`, `"includes"`, `"joins"`, `"leftJoins"`, and `"createWith"`. `{ where: "role" }` drops only the conditions on those attributes.
|
|
4994
|
+
- A default scope’s parts are dropped too. To start without the default scope, use [`unscoped()`](#defining-a-default-scope).
|
|
4995
|
+
- On an association, the link to its owner stays. `user.posts().unscope("where")` is still the user’s posts, and so is `rewhere({ userId })`. Start from `Post` to read past the owner.
|
|
4996
|
+
- Merging a Relation built with `unscope` drops those parts from the Relation it’s merged into.
|
|
4997
|
+
- A join can’t be dropped while conditions or an order merged onto it use it. That throws `IncompatibleRelation`.
|
|
4998
|
+
|
|
4999
|
+
> **Compared with Rails**
|
|
5000
|
+
>
|
|
5001
|
+
> `rewhere`, `unscope`, and `only` work as Rails’ do, with the parts named as strings. `group` and `having` aren’t parts, since a grouped Relation is a type of its own. Rails’ `invert_where` and `extending` aren’t offered. Scopes cover `extending`.
|
|
5002
|
+
|
|
5003
|
+
> **Beyond Rails**
|
|
5004
|
+
>
|
|
5005
|
+
> On an association, Rails’ `unscope(:where)` drops the link to its owner, so a read can reach records that `create` wouldn’t link to it. Here no rewrite drops the link, so reads and writes agree.
|
|
5006
|
+
|
|
5007
|
+
## Leaving records out
|
|
5008
|
+
|
|
5009
|
+
Leave out records you already have with `excluding`:
|
|
5010
|
+
|
|
5011
|
+
```ts
|
|
5012
|
+
import { User } from "./models";
|
|
5013
|
+
|
|
5014
|
+
const current = await User.firstOrThrow();
|
|
5015
|
+
const others = await User.where({ role: "admin" }).excluding(current).toArray();
|
|
5016
|
+
```
|
|
5017
|
+
|
|
5018
|
+
It takes records of the Relation’s Model, or arrays of them. A record that isn’t saved yet leaves nothing out.
|
|
5019
|
+
|
|
5020
|
+
> **Compared with Rails**
|
|
5021
|
+
>
|
|
5022
|
+
> `excluding` is Rails’ `excluding`. Its alias `without` isn’t offered.
|
|
5023
|
+
|
|
3655
5024
|
## Using raw statements
|
|
3656
5025
|
|
|
3657
5026
|
Bind what `serialize` gives when you send SQL to D1 yourself. `typeForAttribute` returns an attribute’s conversions:
|
|
@@ -3719,6 +5088,27 @@ Calling `order` again adds more keys. `reorder` replaces the order so far, and `
|
|
|
3719
5088
|
On D1, NULLs sort first in ascending order, and on Postgres last. Place them with `nulls: "first"` or `nulls: "last"` to sort them the same on both.
|
|
3720
5089
|
:::
|
|
3721
5090
|
|
|
5091
|
+
### Ordering by a list of values
|
|
5092
|
+
|
|
5093
|
+
Sort records by where their value comes in a list with `inOrderOf`:
|
|
5094
|
+
|
|
5095
|
+
```ts
|
|
5096
|
+
import { User } from "./models";
|
|
5097
|
+
|
|
5098
|
+
User.inOrderOf("role", ["owner", "admin", "member"]); // only those roles, owners first
|
|
5099
|
+
User.inOrderOf("role", ["owner", "admin"], { filter: false }); // everyone else last
|
|
5100
|
+
```
|
|
5101
|
+
|
|
5102
|
+
- By default, only records whose value is in the list are kept. Pass `filter: false` to keep the rest, after them.
|
|
5103
|
+
- Values are cast as `where`’s are, and `null` places NULL. The list is bound as one value, so it can be any length.
|
|
5104
|
+
- An order written after it sorts the records that tie, and `last()` reverses it.
|
|
5105
|
+
- It can’t be combined with `distinct()`, which throws `IncompatibleRelation`.
|
|
5106
|
+
- The database looks each record’s value up in the list, so a long list costs more on a large table. Keep it to the values you mean to order by.
|
|
5107
|
+
|
|
5108
|
+
> **Compared with Rails**
|
|
5109
|
+
>
|
|
5110
|
+
> `inOrderOf` is Rails’ `in_order_of`, `filter: false` included. Rails writes the list into a `CASE`, one bound value per item. Here the list is one bound value, so it fits D1’s limit of 100.
|
|
5111
|
+
|
|
3722
5112
|
## Paginating
|
|
3723
5113
|
|
|
3724
5114
|
`paginate` resolves to one page of records and the total they’re a page of:
|
|
@@ -3774,6 +5164,81 @@ D1 limits neither the rows a query returns nor the size of its response. `maxPer
|
|
|
3774
5164
|
>
|
|
3775
5165
|
> Rails leaves pagination to gems such as Kaminari and Pagy. Active Record builds it in, and on D1 sends the count and the page together.
|
|
3776
5166
|
|
|
5167
|
+
## Iterating over many records
|
|
5168
|
+
|
|
5169
|
+
`findEach` loads a Relation’s records a batch at a time, so a large table never sits in memory all at once:
|
|
5170
|
+
|
|
5171
|
+
```ts
|
|
5172
|
+
import { User } from "./models";
|
|
5173
|
+
|
|
5174
|
+
for await (const user of User.where({ isActive: true }).findEach()) {
|
|
5175
|
+
seen.push(user.email); // one user at a time, loaded 1,000 at a time
|
|
5176
|
+
}
|
|
5177
|
+
```
|
|
5178
|
+
|
|
5179
|
+
Batches go in primary-key order, 1,000 records each by default. Each batch is one query, and starts after the last batch’s key, so a deep batch costs no more than the first.
|
|
5180
|
+
|
|
5181
|
+
To work with each batch as an array, use `findInBatches`:
|
|
5182
|
+
|
|
5183
|
+
```ts
|
|
5184
|
+
import { User } from "./models";
|
|
5185
|
+
|
|
5186
|
+
for await (const users of User.findInBatches({ batchSize: 500 })) {
|
|
5187
|
+
const emails = users.map((user) => user.email); // up to 500 users at a time
|
|
5188
|
+
seen.push(...emails);
|
|
5189
|
+
}
|
|
5190
|
+
```
|
|
5191
|
+
|
|
5192
|
+
`includes()` preloads each batch’s associations. Breaking out of the loop sends no more queries.
|
|
5193
|
+
|
|
5194
|
+
### Writing a batch at a time
|
|
5195
|
+
|
|
5196
|
+
`inBatches` yields a Relation of each batch’s records, so `updateAll`, `deleteAll`, and `destroyAll` can write one batch at a time:
|
|
5197
|
+
|
|
5198
|
+
```ts
|
|
5199
|
+
import { Post } from "./models";
|
|
5200
|
+
|
|
5201
|
+
const drafts = Post.where({ publishedAt: null });
|
|
5202
|
+
for await (const batch of drafts.inBatches({ batchSize: 500 })) {
|
|
5203
|
+
await batch.updateAll({ title: "Untitled" });
|
|
5204
|
+
}
|
|
5205
|
+
```
|
|
5206
|
+
|
|
5207
|
+
One query reads each batch’s keys, and the write you run is another. A batch’s Relation keeps your conditions, so a row that stopped matching since the keys were read isn’t written.
|
|
5208
|
+
|
|
5209
|
+
Each batch is its own write. If one fails, the batches before it stay written.
|
|
5210
|
+
|
|
5211
|
+
### Choosing the batches
|
|
5212
|
+
|
|
5213
|
+
Each method takes the same options:
|
|
5214
|
+
|
|
5215
|
+
```ts
|
|
5216
|
+
import { Post, User } from "./models";
|
|
5217
|
+
|
|
5218
|
+
const range = User.findEach({ start, finish }); // keys from start to finish, both included
|
|
5219
|
+
const newestKeysFirst = Post.findInBatches({ order: "desc" }); // from the largest key down
|
|
5220
|
+
```
|
|
5221
|
+
|
|
5222
|
+
- `batchSize` sets the records in each batch: a whole number from 1, or `TypeError`.
|
|
5223
|
+
- `start` and `finish` bound the primary key, both included. With `order: "desc"`, `start` is the largest key and `finish` the smallest.
|
|
5224
|
+
- A `limit()` caps the records across every batch.
|
|
5225
|
+
|
|
5226
|
+
Batches follow the primary key, so a Relation with its own order throws `IncompatibleRelation`, a default scope’s order included. Remove it with `reorder()` first: `Post.reorder().findEach()`. An `offset()` throws too, so bound the walk with `start` instead.
|
|
5227
|
+
|
|
5228
|
+
:::note
|
|
5229
|
+
A row added while you iterate is visited only if its key sorts after the batch you’re on. With random keys, such as UUIDs, whether a new row is visited comes down to chance.
|
|
5230
|
+
:::
|
|
5231
|
+
|
|
5232
|
+
### Staying within D1’s query limit
|
|
5233
|
+
|
|
5234
|
+
On D1, one Worker invocation can send up to 1,000 queries, or 50 on the Free plan. `findEach` and `findInBatches` send one per batch. `inBatches` sends one for the keys, and one for an `updateAll` or `deleteAll`. A `destroyAll` loads the batch’s records and reads each record’s `"destroy"` and restricted associations, each with a query of its own, then sends its deletes as one D1 batch, which counts as one query.
|
|
5235
|
+
|
|
5236
|
+
A larger `batchSize` sends fewer queries, up to D1’s 50 MB limit on a query’s result. For a table larger than that, split the work across invocations, each with its own `start` and `finish`, such as one Queue message per range.
|
|
5237
|
+
|
|
5238
|
+
> **Compared with Rails**
|
|
5239
|
+
>
|
|
5240
|
+
> `findEach`, `findInBatches`, and `inBatches` are `find_each`, `find_in_batches`, and `in_batches`, as async iterators rather than blocks. `inBatches` takes `batchSize`, not `of:`. Rails ignores a Relation’s order with a warning, and applies an offset to every batch. Here both throw `IncompatibleRelation`.
|
|
5241
|
+
|
|
3777
5242
|
## Getting results
|
|
3778
5243
|
|
|
3779
5244
|
Run a query with one of these methods:
|
|
@@ -3788,17 +5253,29 @@ const byEmail = await User.findBy({ email: "ada@example.com" }); // or null
|
|
|
3788
5253
|
const oldest = await User.first(); // by primary key, unless ordered
|
|
3789
5254
|
const newest = await User.order({ createdAt: "asc" }).last(); // order reversed
|
|
3790
5255
|
const any = await User.take(); // no ordering at all
|
|
5256
|
+
const earliest = await User.firstOrThrow(); // or RecordNotFound
|
|
5257
|
+
const owner = await User.findSoleBy({ role: "owner" }); // the only one, or throws
|
|
3791
5258
|
const emails = await User.pluck("email"); // string[]
|
|
3792
5259
|
const pairs = await User.pluck("id", "email"); // [string, string][]
|
|
5260
|
+
const latest = await User.order({ createdAt: "desc" }).pick("email"); // string | null
|
|
5261
|
+
const adminIds = await User.where({ role: "admin" }).ids(); // primary keys
|
|
3793
5262
|
const admins2 = await User.where({ role: "admin" }).count();
|
|
3794
5263
|
const hasAdmins = await User.exists({ role: "admin" });
|
|
5264
|
+
const severalAdmins = await User.where({ role: "admin" }).hasMoreThanOne();
|
|
5265
|
+
const oneOwner = await User.where({ role: "owner" }).hasExactlyOne();
|
|
3795
5266
|
```
|
|
3796
5267
|
|
|
3797
5268
|
- `find` throws `RecordNotFound` if the id is missing. Given several ids, it returns them in order, from one query, and throws if any are missing.
|
|
3798
5269
|
- `findBy` resolves to `null` when nothing matches, and `findByOrThrow` throws `RecordNotFound`.
|
|
5270
|
+
- `findOrCreateBy` creates the record when nothing matches. See [Finding or creating a record](/persistence#finding-or-creating-a-record).
|
|
3799
5271
|
- `first` and `last` sort by the primary key unless the Relation has an order, and `last` reverses that order. An `sql` fragment can’t be reversed, so `last` throws `IrreversibleOrder` there.
|
|
5272
|
+
- `firstOrThrow`, `lastOrThrow`, and `takeOrThrow` throw `RecordNotFound` instead of resolving to `null`.
|
|
5273
|
+
- `sole` resolves to the only matching record. It throws `RecordNotFound` when nothing matches, and `SoleRecordExceeded` when more than one does. `findSoleBy(conditions)` is short for `where(conditions).sole()`.
|
|
5274
|
+
- `pick` reads one attribute from the first record. Given several attributes, it reads a tuple. It resolves to `null` when nothing matches.
|
|
5275
|
+
- `ids` plucks every primary key. On a loaded association, it leaves out records you’ve built that don’t have a key yet.
|
|
3800
5276
|
- `count()` always agrees with what `toArray()` returns, even with `limit`, `offset`, or `distinct`.
|
|
3801
5277
|
- `size()`, `isEmpty()`, and `hasAny()` count records, or check for any. On a loaded association, they answer without a query.
|
|
5278
|
+
- `hasMoreThanOne()` and `hasExactlyOne()` count no further than two records. On a loaded association, they answer without a query too.
|
|
3802
5279
|
|
|
3803
5280
|
:::tip
|
|
3804
5281
|
`exists()`, `isEmpty()`, and `hasAny()` ignore the Relation’s order, so D1 stops at the first matching row. `count()` ignores it too, unless a `limit` or `offset` needs it. D1 bills each row it reads, so checks and counts stay cheap on an ordered Relation, such as an ordered association.
|
|
@@ -3806,7 +5283,117 @@ const hasAdmins = await User.exists({ role: "admin" });
|
|
|
3806
5283
|
|
|
3807
5284
|
> **Compared with Rails**
|
|
3808
5285
|
>
|
|
3809
|
-
> `size()`, `isEmpty()`, and `hasAny()` are Rails’ `size`, `empty?`, and `any?`.
|
|
5286
|
+
> `size()`, `isEmpty()`, and `hasAny()` are Rails’ `size`, `empty?`, and `any?`, and `hasMoreThanOne()` and `hasExactlyOne()` are `many?` and `one?`. `firstOrThrow()` is `first!`, and `findSoleBy` is `find_sole_by`. There’s no `second` or `third`. Use `offset(1).first()` instead. Rails’ `ids` gives `nil` for a built record with no key, where `ids()` leaves it out.
|
|
5287
|
+
|
|
5288
|
+
## Calculating values
|
|
5289
|
+
|
|
5290
|
+
Add up, average, or find the extremes of an attribute without loading the records:
|
|
5291
|
+
|
|
5292
|
+
```ts
|
|
5293
|
+
import { Product } from "./models";
|
|
5294
|
+
|
|
5295
|
+
const total = await Product.where({ available: 1 }).sum("priceCents"); // 0 with no products
|
|
5296
|
+
const averagePrice = await Product.average("priceCents"); // a number, or null
|
|
5297
|
+
const cheapest = await Product.minimum("priceCents"); // or null
|
|
5298
|
+
const newest = await Product.maximum("createdAt"); // a Date, or null
|
|
5299
|
+
```
|
|
5300
|
+
|
|
5301
|
+
- `sum` and `average` take number attributes: integers, reals, and decimals. A decimal’s sum is text, such as `"12.8"`.
|
|
5302
|
+
- `minimum` and `maximum` take any attribute you can compare. The result has the attribute’s own type, so a datetime’s is a `Date`.
|
|
5303
|
+
- NULLs are left out. With no rows, `sum` is 0 and the others are `null`. On `none()`, they answer without a query.
|
|
5304
|
+
|
|
5305
|
+
:::note[Exact sums on D1]
|
|
5306
|
+
D1 adds up a decimal column as floating-point numbers. A sum keeps about 15 digits, and small errors can build up over many rows. For an exact sum on D1, store the amount as whole cents in an integer column, with a [custom type](/custom-types#defining-a-type) such as money. D1 adds whole numbers exactly, and `sum` returns the custom type’s value.
|
|
5307
|
+
:::
|
|
5308
|
+
|
|
5309
|
+
A calculation covers the rows `toArray()` would return, so a `limit`, an `offset`, or `distinct()` decides which values count:
|
|
5310
|
+
|
|
5311
|
+
```ts
|
|
5312
|
+
import { Product } from "./models";
|
|
5313
|
+
|
|
5314
|
+
const mostExpensive = Product.order({ priceCents: "desc" }).limit(3);
|
|
5315
|
+
const topThree = await mostExpensive.sum("priceCents"); // only those three
|
|
5316
|
+
```
|
|
5317
|
+
|
|
5318
|
+
To calculate an expression, pass an `sql` fragment:
|
|
5319
|
+
|
|
5320
|
+
```ts
|
|
5321
|
+
import { column, sql } from "@forestfuture/active-record";
|
|
5322
|
+
import { Product } from "./models";
|
|
5323
|
+
|
|
5324
|
+
const inDollars = sql`${column("priceCents")} / 100.0`;
|
|
5325
|
+
const averageDollars = await Product.average(inDollars); // a number, or null
|
|
5326
|
+
```
|
|
5327
|
+
|
|
5328
|
+
A fragment’s `sum` and `average` are numbers. Its `minimum` and `maximum` are the values the database returns.
|
|
5329
|
+
|
|
5330
|
+
:::note
|
|
5331
|
+
`calculate("sum", "priceCents")` runs the calculation its first argument names. Use it when the name comes from elsewhere, such as a report’s settings.
|
|
5332
|
+
:::
|
|
5333
|
+
|
|
5334
|
+
> **Compared with Rails**
|
|
5335
|
+
>
|
|
5336
|
+
> `average` always returns a number, where Rails returns a BigDecimal for integers and decimals. Rails puts a `limit` on the one row of its result, so `limit(3).sum(:price_cents)` adds up every row. Here, the limit picks the rows. Text attributes can’t be summed.
|
|
5337
|
+
|
|
5338
|
+
## Calculating per group
|
|
5339
|
+
|
|
5340
|
+
Group the rows by an attribute to calculate each group’s total:
|
|
5341
|
+
|
|
5342
|
+
```ts
|
|
5343
|
+
import { Product } from "./models";
|
|
5344
|
+
|
|
5345
|
+
const byAvailability = await Product.group("available").count(); // Map { 1 => 3, 0 => 1 }
|
|
5346
|
+
const inStock = byAvailability.get(1); // 3
|
|
5347
|
+
const valueByAvailability = await Product.group("available").sum("priceCents");
|
|
5348
|
+
```
|
|
5349
|
+
|
|
5350
|
+
- Each calculation returns a `Map` from the group’s value to its result. `count`, `sum`, `average`, `minimum`, and `maximum` all work this way.
|
|
5351
|
+
- The keys have the attribute’s own type, so a datetime’s key is a `Date` and an enum’s is its name. Rows with a NULL value form a group with a `null` key.
|
|
5352
|
+
- The groups come in the order the database returns them, unless you order them.
|
|
5353
|
+
|
|
5354
|
+
To group by several attributes, or by an expression, pass each one to `group`:
|
|
5355
|
+
|
|
5356
|
+
```ts
|
|
5357
|
+
import { column, sql } from "@forestfuture/active-record";
|
|
5358
|
+
import { Product } from "./models";
|
|
5359
|
+
|
|
5360
|
+
const band = sql`CASE WHEN ${column("priceCents")} >= ${10_000} THEN 'pricey' ELSE 'cheap' END`;
|
|
5361
|
+
const byBand = await Product.group("available", band).count(); // Map { [1, "cheap"] => 2, … }
|
|
5362
|
+
```
|
|
5363
|
+
|
|
5364
|
+
Each key is then an array of the values, in the order you passed them. An expression’s value is whatever the database returns.
|
|
5365
|
+
|
|
5366
|
+
:::note
|
|
5367
|
+
A `Map` finds an array or `Date` key only if it’s the same object, so `get([1, "cheap"])` finds nothing. Loop over the `Map` to read those groups.
|
|
5368
|
+
:::
|
|
5369
|
+
|
|
5370
|
+
To keep only some groups, pass a condition on their totals to `having`:
|
|
5371
|
+
|
|
5372
|
+
```ts
|
|
5373
|
+
import { sql } from "@forestfuture/active-record";
|
|
5374
|
+
import { Product } from "./models";
|
|
5375
|
+
|
|
5376
|
+
const crowded = Product.group("available").having(sql`COUNT(*) > ${1}`);
|
|
5377
|
+
const crowdedCounts = await crowded.count(); // Map { 1 => 3 }
|
|
5378
|
+
```
|
|
5379
|
+
|
|
5380
|
+
To sort the groups, order them by a grouped attribute or by a total. A `limit` then picks groups:
|
|
5381
|
+
|
|
5382
|
+
```ts
|
|
5383
|
+
import { sql } from "@forestfuture/active-record";
|
|
5384
|
+
import { Product } from "./models";
|
|
5385
|
+
|
|
5386
|
+
const largestFirst = Product.group("available").order(sql`COUNT(*) DESC`);
|
|
5387
|
+
const largest = await largestFirst.limit(1).count(); // Map { 1 => 3 }
|
|
5388
|
+
```
|
|
5389
|
+
|
|
5390
|
+
- `where`, `limit`, `offset`, and `distinct()` work before or after `group`. After `distinct()`, `count`, `sum`, and `average` take each group’s distinct values.
|
|
5391
|
+
- You can only order by attributes you group by, or by an `sql` fragment. `group` drops an earlier order by any other attribute, such as one from a default scope. It keeps an earlier fragment, so call `reorder()` before `group` when a default scope orders by one. With a `limit` or `offset`, `group` throws instead of dropping an order, so call `reorder()` first there too.
|
|
5392
|
+
- On `none()`, each calculation returns an empty `Map` without a query.
|
|
5393
|
+
|
|
5394
|
+
> **Compared with Rails**
|
|
5395
|
+
>
|
|
5396
|
+
> Results are a `Map`, not a Hash, so a key that’s an array or a time matches only by identity. A grouped Relation has no records, so there’s no `to_a` on it. Ordering groups by an attribute that isn’t grouped throws an error instead of reaching the database, and `group` drops such an order written before it, where Rails sends it and Postgres refuses it.
|
|
3810
5397
|
|
|
3811
5398
|
## Selecting attributes
|
|
3812
5399
|
|
|
@@ -3851,13 +5438,13 @@ console.log(params); // ["admin", 10]
|
|
|
3851
5438
|
|
|
3852
5439
|
The values come back in `params`, apart from the SQL.
|
|
3853
5440
|
|
|
3854
|
-
A
|
|
5441
|
+
A `none()` Relation shows `1 = 0`, the condition that matches nothing.
|
|
3855
5442
|
|
|
3856
5443
|
:::note
|
|
3857
5444
|
`toSql()` returns the real values, filtered attributes included. To see what a query sent, with those filtered, use [`onQuery`](/logging).
|
|
3858
5445
|
:::
|
|
3859
5446
|
|
|
3860
|
-
|
|
5447
|
+
Bulk writes and [batches](/batches#batching-writes) have no `toSql()`. Use [`onQuery`](/logging) to see what they sent.
|
|
3861
5448
|
|
|
3862
5449
|
> **Compared with Rails**
|
|
3863
5450
|
>
|
|
@@ -3893,31 +5480,153 @@ export class User extends Model.define({
|
|
|
3893
5480
|
Call it as a static, or on any Relation of the Model:
|
|
3894
5481
|
|
|
3895
5482
|
```ts
|
|
3896
|
-
const admins = await User.active().where({ role: "admin" }).toArray();
|
|
3897
|
-
const recent = await User.createdAfter(new Date(Date.now() - 86_400_000)).count();
|
|
5483
|
+
const admins = await User.active().where({ role: "admin" }).toArray();
|
|
5484
|
+
const recent = await User.createdAfter(new Date(Date.now() - 86_400_000)).count();
|
|
5485
|
+
```
|
|
5486
|
+
|
|
5487
|
+
- A scope’s arguments, and anything it computes such as `new Date()`, are evaluated when you call it.
|
|
5488
|
+
- Scopes are inherited, including those on your app’s base class ([Shared behavior](/shared-behavior)). A subclass can replace one with `static override active = this.scope(…)`.
|
|
5489
|
+
- A scope can’t reuse a Relation method’s name (`where`, `count`) or a Model static’s (`validates`, `scope`, `all`).
|
|
5490
|
+
- Inside a scope, `q` has every Relation method but not the Model’s other scopes. Share logic between scopes with a plain function.
|
|
5491
|
+
|
|
5492
|
+
:::note
|
|
5493
|
+
A scope whose body names its own class needs its type written out: `static roots: ScopeStatic<[]> = this.scope(…)`.
|
|
5494
|
+
:::
|
|
5495
|
+
|
|
5496
|
+
An [enum](/models#declaring-enums) gives its Model a scope for each name, and a `not…` scope: `Ticket.open()` and `Ticket.notOpen()`. Conditions take its names, one or a list: `Ticket.where({ status: ["open", "in_progress"] })`.
|
|
5497
|
+
|
|
5498
|
+
## Defining a default scope
|
|
5499
|
+
|
|
5500
|
+
A default scope narrows every query on a Model. Declare one in the class’s `static {}` block:
|
|
5501
|
+
|
|
5502
|
+
```ts
|
|
5503
|
+
import { ApplicationRecord } from "./application-record";
|
|
5504
|
+
|
|
5505
|
+
export class Product extends ApplicationRecord {
|
|
5506
|
+
static {
|
|
5507
|
+
this.defaultScope((q) => q.where({ available: 1 }));
|
|
5508
|
+
}
|
|
5509
|
+
}
|
|
5510
|
+
```
|
|
5511
|
+
|
|
5512
|
+
Queries start from it, and new records take its conditions’ values:
|
|
5513
|
+
|
|
5514
|
+
```ts
|
|
5515
|
+
const listed = await Product.order({ name: "asc" }).toArray(); // available products only
|
|
5516
|
+
const draft = Product.build({ name: "Pen" }); // available: 1, from the default scope
|
|
5517
|
+
```
|
|
5518
|
+
|
|
5519
|
+
- It applies to everything that queries the Model: `find`, `count`, `updateAll`, `deleteAll`, its scopes, and associations that read it, preloads included.
|
|
5520
|
+
- `reload`, uniqueness validation, and a record’s own `save` and `destroy` ignore it, since they work by primary key.
|
|
5521
|
+
- `insert`, `insertAll`, `upsert`, and `upsertAll` write its conditions’ values over the values you give. `build` and `create` use the values you give.
|
|
5522
|
+
- Several default scopes all apply. A subclass adds its own to its parent’s.
|
|
5523
|
+
- An order in a default scope is the Relation’s order. `reorder` replaces it.
|
|
5524
|
+
- `rewhere` replaces its condition on an attribute, and [`unscope`](#replacing-conditions) drops its parts.
|
|
5525
|
+
|
|
5526
|
+
To leave the default scope out, start from `unscoped()`:
|
|
5527
|
+
|
|
5528
|
+
```ts
|
|
5529
|
+
const everything = await Product.unscoped().toArray(); // available or not
|
|
5530
|
+
```
|
|
5531
|
+
|
|
5532
|
+
`unscoped()` is a Model static only. With a database you hold, call it inside [`withDatabase`](/connecting#using-the-requests-database).
|
|
5533
|
+
|
|
5534
|
+
:::warning[Default scopes hide records from associations too]
|
|
5535
|
+
A default scope that hides soft-deleted records also hides them from every association. A comment on a deleted post then fails to save with “Post must exist”. And `dependent: "destroy"` leaves a deleted post’s comments behind. An upsert that updates a deleted post writes `deletedAt: null`, which brings the post back. It does this even when you pass a `deletedAt`. For soft deletes, use a named scope instead:
|
|
5536
|
+
|
|
5537
|
+
```ts
|
|
5538
|
+
class Post extends ApplicationRecord {
|
|
5539
|
+
static kept = this.scope((q) => q.where({ deletedAt: null }));
|
|
5540
|
+
}
|
|
5541
|
+
```
|
|
5542
|
+
|
|
5543
|
+
Then call `Post.kept()` where deleted posts should stay hidden.
|
|
5544
|
+
:::
|
|
5545
|
+
|
|
5546
|
+
> **Compared with Rails**
|
|
5547
|
+
>
|
|
5548
|
+
> `this.defaultScope` is Rails’ `default_scope`, applied the same way. `unscoped()` is only a static: Rails also has it on a Relation, where `Post.where(…).unscoped` drops every condition, the Relation’s own included. Rails’ block form, `Post.unscoped { … }`, and `all_queries: true` aren’t here.
|
|
5549
|
+
|
|
5550
|
+
## Merging Relations
|
|
5551
|
+
|
|
5552
|
+
Combine two Relations of the same Model with `merge`. Their conditions are joined with AND, and anything the argument sets, such as an order, limit, or select, replaces the receiver’s:
|
|
5553
|
+
|
|
5554
|
+
```ts
|
|
5555
|
+
const recent = User.order({ createdAt: "desc" }).limit(10);
|
|
5556
|
+
const admins = await User.where({ role: "admin" }).merge(recent).toArray();
|
|
5557
|
+
```
|
|
5558
|
+
|
|
5559
|
+
To merge a Relation of another Model, join that Model first. See [Joining associations](#joining-associations).
|
|
5560
|
+
|
|
5561
|
+
> **Compared with Rails**
|
|
5562
|
+
>
|
|
5563
|
+
> Rails adds the argument’s order to the receiver’s. Active Record replaces it.
|
|
5564
|
+
|
|
5565
|
+
## Joining associations
|
|
5566
|
+
|
|
5567
|
+
`joins` finds the records that have a linked record, through the associations you’ve declared. Name an association, or nest them in an object:
|
|
5568
|
+
|
|
5569
|
+
```ts
|
|
5570
|
+
import { Author } from "./models";
|
|
5571
|
+
|
|
5572
|
+
const commented = Author.joins({ articles: "comments" }).distinct();
|
|
5573
|
+
const authors = await commented.toArray(); // each author with a commented article, once
|
|
5574
|
+
```
|
|
5575
|
+
|
|
5576
|
+
A record comes back once for each linked record, so an author with three commented articles appears three times. Add `distinct()` to get each record once.
|
|
5577
|
+
|
|
5578
|
+
A joined query loads only its own Model’s columns, and every Relation method works on it. `count()` counts the rows `toArray()` returns, and `updateAll` and `deleteAll` write the records the join finds.
|
|
5579
|
+
|
|
5580
|
+
The association’s `scope` and the joined Model’s default scope are part of the join. So joining an association scoped to published articles finds only authors with a published article.
|
|
5581
|
+
|
|
5582
|
+
### Keeping records without a link
|
|
5583
|
+
|
|
5584
|
+
`leftJoins` joins the same way, but keeps the records that have no linked record:
|
|
5585
|
+
|
|
5586
|
+
```ts
|
|
5587
|
+
import { Author } from "./models";
|
|
5588
|
+
|
|
5589
|
+
const withProfiles = Author.leftJoins("profile"); // every author, with a profile or not
|
|
5590
|
+
const everyAuthor = await withProfiles.toArray();
|
|
5591
|
+
```
|
|
5592
|
+
|
|
5593
|
+
### Filtering by a joined Model
|
|
5594
|
+
|
|
5595
|
+
Merge a Relation of the joined Model to filter or sort by its attributes:
|
|
5596
|
+
|
|
5597
|
+
```ts
|
|
5598
|
+
import { Article, Author } from "./models";
|
|
5599
|
+
|
|
5600
|
+
const mary = Author.where({ name: "Mary" });
|
|
5601
|
+
const byMary = Article.joins("author").merge(mary);
|
|
5602
|
+
const titles = await byMary.pluck("title");
|
|
5603
|
+
|
|
5604
|
+
const byName = Author.order({ name: "asc" });
|
|
5605
|
+
const byAuthorName = Article.joins("author").merge(byName);
|
|
3898
5606
|
```
|
|
3899
5607
|
|
|
3900
|
-
|
|
3901
|
-
- Scopes are inherited, including those on your app’s base class ([Shared behavior](/shared-behavior)). A subclass can replace one with `static override active = this.scope(…)`.
|
|
3902
|
-
- A scope can’t reuse a Relation method’s name (`where`, `count`) or a Model static’s (`validates`, `scope`, `all`).
|
|
3903
|
-
- Inside a scope, `q` has every Relation method but not the Model’s other scopes. Share logic between scopes with a plain function.
|
|
5608
|
+
Its conditions, its scopes, and its order apply to the joined table. As with any `merge`, the joined Model’s order replaces the receiver’s.
|
|
3904
5609
|
|
|
3905
5610
|
:::note
|
|
3906
|
-
A
|
|
5611
|
+
The merged Relation can only add conditions and an order. A `limit`, `offset`, `select`, `distinct()`, `includes`, or `joins` of its own throws `IncompatibleRelation`. Merging a Model the query doesn’t join, or joins more than once, throws it too. So does `distinct()` on a query ordered by a joined Model.
|
|
3907
5612
|
:::
|
|
3908
5613
|
|
|
3909
|
-
|
|
3910
|
-
|
|
3911
|
-
|
|
5614
|
+
:::note
|
|
5615
|
+
A join reads one database. Joining an association to a Model on another database throws `IncompatibleRelation` when you write the query.
|
|
5616
|
+
:::
|
|
3912
5617
|
|
|
3913
|
-
|
|
3914
|
-
|
|
3915
|
-
|
|
3916
|
-
```
|
|
5618
|
+
:::note
|
|
5619
|
+
A polymorphic `belongsTo` can’t be joined, because its records may be in several tables. Joining one throws `IncompatibleRelation`. Join the `as:` association of each Model instead, such as `Photo.joins("likes")`.
|
|
5620
|
+
:::
|
|
3917
5621
|
|
|
3918
5622
|
> **Compared with Rails**
|
|
3919
5623
|
>
|
|
3920
|
-
> Rails
|
|
5624
|
+
> - Rails builds the SQL for a merged Model the query doesn’t join, and the database rejects it when the query runs. Active Record throws `IncompatibleRelation` when you write it.
|
|
5625
|
+
> - Rails applies a merged Relation’s `limit` to the whole query. Active Record refuses it.
|
|
5626
|
+
> - Rails leaves `distinct` with an order on a joined table to the database, which Postgres refuses and SQLite runs. Active Record throws `IncompatibleRelation` on both.
|
|
5627
|
+
> - With a `hasMany` join, Rails’ `find(1, 2)` counts the duplicate rows and raises `RecordNotFound`. Active Record returns each record once.
|
|
5628
|
+
> - With a `hasMany` join, Rails’ `destroy_all` destroys a record once for each of its rows, running its callbacks each time. Active Record destroys each record once.
|
|
5629
|
+
> - Rails’ `where(author: { name: "Mary" })`, `where.missing`, `eager_load`, and joins through another association aren’t here yet. Joining a `through` association throws `IncompatibleRelation`. Merge a Relation of the joined Model instead, and preload with `includes`.
|
|
3921
5630
|
|
|
3922
5631
|
## Preloading associations
|
|
3923
5632
|
|
|
@@ -4033,7 +5742,7 @@ export class Product extends ApplicationRecord {}
|
|
|
4033
5742
|
|
|
4034
5743
|
TypeScript can’t give a class types from its name. So `active-record schema` loads your Model files, finds `Product`, and writes a declaration giving the `Product` class the `products` table’s attributes. That’s why the schema is generated from your Models as well as your migrations, and why it changes when you add or rename a Model.
|
|
4035
5744
|
|
|
4036
|
-
When your Worker runs, `Product` finds its attributes the first time it’s used. Its table comes from its
|
|
5745
|
+
When your Worker runs, `Product` finds its attributes the first time it’s used. Its table comes from its [name](/models#naming-models), and the table’s attributes from the schema that `ApplicationRecord` holds. The schema lists each Model by that name, and a Model missing from the list throws `InvalidModel`, telling you to run `active-record schema`. Without that check, a development server, which doesn’t type-check, would run a Model whose types were never generated.
|
|
4037
5746
|
|
|
4038
5747
|
`ApplicationRecord` itself is a file in your app, `src/models/application-record.ts`, which `active-record schema` writes once. It’s an abstract class that holds the generated schema, and it’s where behavior shared by every Model goes. See [Shared behavior](/shared-behavior).
|
|
4039
5748
|
|
|
@@ -4078,7 +5787,7 @@ The library’s guarantees are tested against a real D1 database (through Minifl
|
|
|
4078
5787
|
| Only a Model’s own names are attributes or associations | [`name-lookups`](https://github.com/forestfuture/active-record/blob/main/tests/conformance/name-lookups.test.ts) |
|
|
4079
5788
|
| `permit` keeps only the named attributes, reading own keys only | [`permit`](https://github.com/forestfuture/active-record/blob/main/tests/conformance/permit.test.ts) |
|
|
4080
5789
|
| Filtered attributes’ values never reach listeners or errors | [`filter-attributes`](https://github.com/forestfuture/active-record/blob/main/tests/conformance/filter-attributes.test.ts) |
|
|
4081
|
-
| A request’s database stays with that request | [`current-database`](https://github.com/forestfuture/active-record/blob/main/tests/integration/current-database.test.ts)
|
|
5790
|
+
| A request’s database stays with that request | [`current-database`](https://github.com/forestfuture/active-record/blob/main/tests/integration/d1/current-database.test.ts) |
|
|
4082
5791
|
| Names, assigned values, conditions, bound text, permitted keys, and JSON hold for any input, not only chosen ones | [`properties`](https://github.com/forestfuture/active-record/tree/main/tests) (`*-properties.test.ts`, generated with fast-check) |
|
|
4083
5792
|
| The tests cover at least 90% of the library’s and command line’s branches, and CI fails below that | [`coverage`](https://github.com/forestfuture/active-record/blob/main/vite.config.ts) |
|
|
4084
5793
|
| CI’s actions are pinned, and release jobs run no install scripts | [`ci-workflows`](https://github.com/forestfuture/active-record/blob/main/tests/unit/ci-workflows.test.ts) |
|
|
@@ -4168,7 +5877,7 @@ Please report a security problem privately, as the [security policy](https://git
|
|
|
4168
5877
|
# Multiple databases
|
|
4169
5878
|
Source: https://active-record.forestfuture.dev/several-databases
|
|
4170
5879
|
|
|
4171
|
-
A Worker can bind several D1 databases. Each gets its own schema file and base class, and each Model queries the database its base class names.
|
|
5880
|
+
A Worker can bind several D1 databases, or a D1 database and a Postgres one. Each gets its own schema file and base class, and each Model queries the database its base class names.
|
|
4172
5881
|
|
|
4173
5882
|
## Binding the databases
|
|
4174
5883
|
|
|
@@ -4260,6 +5969,62 @@ If `createOrThrow` throws, nothing reaches `LOGS`.
|
|
|
4260
5969
|
The second write can still fail after the first one succeeds. A batch can’t join them either. It writes to one database, so entries from two throw `IncompatibleRelation`.
|
|
4261
5970
|
:::
|
|
4262
5971
|
|
|
5972
|
+
## Associating Models on different databases
|
|
5973
|
+
|
|
5974
|
+
An association can link Models on different databases. Declare it as usual:
|
|
5975
|
+
|
|
5976
|
+
```ts
|
|
5977
|
+
import { belongsTo, hasMany } from "@forestfuture/active-record";
|
|
5978
|
+
|
|
5979
|
+
export class User extends DbRecord {
|
|
5980
|
+
entries = hasMany(Entry); // on LOGS
|
|
5981
|
+
}
|
|
5982
|
+
|
|
5983
|
+
export class Entry extends LogsRecord {
|
|
5984
|
+
user = belongsTo(User, { optional: true }); // on DB; an entry may have no user
|
|
5985
|
+
}
|
|
5986
|
+
```
|
|
5987
|
+
|
|
5988
|
+
Each read goes to the database its Model is on:
|
|
5989
|
+
|
|
5990
|
+
```ts
|
|
5991
|
+
export async function errorEntriesOf(userId: number) {
|
|
5992
|
+
const user = await User.find(userId); // on DB
|
|
5993
|
+
return user.entries().where({ level: "error" }).toArray(); // on LOGS
|
|
5994
|
+
}
|
|
5995
|
+
|
|
5996
|
+
export async function entriesWithUsers() {
|
|
5997
|
+
return Entry.includes("user").toArray(); // the entries on LOGS, then their users on DB
|
|
5998
|
+
}
|
|
5999
|
+
```
|
|
6000
|
+
|
|
6001
|
+
`includes` loads the users from `DB` once the entries are loaded, in one more round trip. Each other database a [preload](/associations#preloading-associations) reaches adds one.
|
|
6002
|
+
|
|
6003
|
+
Records you create through an association are written to their own database:
|
|
6004
|
+
|
|
6005
|
+
```ts
|
|
6006
|
+
export async function logFor(user: User, message: string) {
|
|
6007
|
+
return user.entries().create({ level: "info", message }); // on LOGS, with the user's key
|
|
6008
|
+
}
|
|
6009
|
+
```
|
|
6010
|
+
|
|
6011
|
+
Saving a record also saves the records built through it, each on its own database. Here the user is written to `DB` first, then the entry to `LOGS` with the user’s new key:
|
|
6012
|
+
|
|
6013
|
+
```ts
|
|
6014
|
+
export async function signUpWithEntry(email: string) {
|
|
6015
|
+
const user = User.build({ email });
|
|
6016
|
+
user.entries().build({ level: "info", message: "signed up" });
|
|
6017
|
+
await user.saveOrThrow(); // the user on DB, then the entry on LOGS
|
|
6018
|
+
return user;
|
|
6019
|
+
}
|
|
6020
|
+
```
|
|
6021
|
+
|
|
6022
|
+
[`dependent` strategies](/associations#destroying-dependent-records) work the same way. With `dependent: "destroy"` on a user’s entries, destroying the user destroys its entries on `LOGS`, then deletes the user from `DB`.
|
|
6023
|
+
|
|
6024
|
+
:::warning[Each database is written on its own]
|
|
6025
|
+
A save or a destroy that reaches two databases writes to each one separately. If the second write fails, the first stays written. A batch writes to one database, so `batch` throws `IncompatibleRelation` for a record whose writes reach another one.
|
|
6026
|
+
:::
|
|
6027
|
+
|
|
4263
6028
|
## Reading your own writes on each
|
|
4264
6029
|
|
|
4265
6030
|
With read replication, give each database its own Session. Nest a `withSession` call for each, and give each its own cookie name:
|
|
@@ -4342,6 +6107,48 @@ Name the binding with `--database`:
|
|
|
4342
6107
|
npx active-record console --database LOGS
|
|
4343
6108
|
```
|
|
4344
6109
|
|
|
6110
|
+
## Using databases on different adapters
|
|
6111
|
+
|
|
6112
|
+
One project can keep some of its tables on D1 and others on Postgres. First install `pg` and PGlite, as [PostgreSQL](/postgresql) describes.
|
|
6113
|
+
|
|
6114
|
+
Name each database’s adapter in `active-record.jsonc`, and give the Postgres one its own migrations folder:
|
|
6115
|
+
|
|
6116
|
+
```jsonc active-record.jsonc
|
|
6117
|
+
{
|
|
6118
|
+
"databases": {
|
|
6119
|
+
"DB": { "adapter": "d1" },
|
|
6120
|
+
"HYPERDRIVE": {
|
|
6121
|
+
"adapter": "postgresql",
|
|
6122
|
+
"migrationsDir": "pg-migrations",
|
|
6123
|
+
"url": "postgres://localhost/shop_development",
|
|
6124
|
+
},
|
|
6125
|
+
},
|
|
6126
|
+
}
|
|
6127
|
+
```
|
|
6128
|
+
|
|
6129
|
+
D1 and Postgres write their SQL differently, so each database needs a folder of its own. Both adapters read `migrations/` by default, and the command refuses two databases on different adapters that share one.
|
|
6130
|
+
|
|
6131
|
+
To add your Hyperdrive bindings to a file that names only D1 databases, run `init` with the adapter:
|
|
6132
|
+
|
|
6133
|
+
```sh
|
|
6134
|
+
npx active-record init --adapter postgresql
|
|
6135
|
+
```
|
|
6136
|
+
|
|
6137
|
+
`npx active-record schema` reads each database with its own adapter. `src/db/DB.ts` imports `d1`, and `src/db/HYPERDRIVE.ts` imports `postgresql`. Build each Model on its database’s base class:
|
|
6138
|
+
|
|
6139
|
+
```ts
|
|
6140
|
+
import { HyperdriveRecord } from "./hyperdrive-record";
|
|
6141
|
+
|
|
6142
|
+
export class Order extends HyperdriveRecord {}
|
|
6143
|
+
```
|
|
6144
|
+
|
|
6145
|
+
Name the database with `--database` for the generators, `migrate`, and the console:
|
|
6146
|
+
|
|
6147
|
+
```sh
|
|
6148
|
+
npx active-record g model Order total:integer --database HYPERDRIVE
|
|
6149
|
+
npx active-record migrate --database HYPERDRIVE
|
|
6150
|
+
```
|
|
6151
|
+
|
|
4345
6152
|
---
|
|
4346
6153
|
|
|
4347
6154
|
# Shared behavior
|
|
@@ -4506,7 +6313,7 @@ test("emails are saved in lowercase", async () => {
|
|
|
4506
6313
|
});
|
|
4507
6314
|
```
|
|
4508
6315
|
|
|
4509
|
-
Outside a Worker, the database given to `withDatabase` serves every Model, whatever binding its base class names. For code that takes a database explicitly, pass it one: `connect(database.binding).model(User)`.
|
|
6316
|
+
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)`.
|
|
4510
6317
|
|
|
4511
6318
|
## Testing your Worker
|
|
4512
6319
|
|
|
@@ -4603,7 +6410,7 @@ export async function updateAccount(account: Account, request: Request): Promise
|
|
|
4603
6410
|
|
|
4604
6411
|
## Querying with request values
|
|
4605
6412
|
|
|
4606
|
-
Check that a value is a string before you query with it
|
|
6413
|
+
Check that a value is a string before you query with it:
|
|
4607
6414
|
|
|
4608
6415
|
```ts
|
|
4609
6416
|
export async function accept(request: Request): Promise<Response> {
|
|
@@ -4620,10 +6427,26 @@ export async function accept(request: Request): Promise<Response> {
|
|
|
4620
6427
|
}
|
|
4621
6428
|
```
|
|
4622
6429
|
|
|
6430
|
+
JSON can send `null` or a list. `findBy({ token: null })` matches rows whose token is NULL, and `findBy({ token: [first, second] })` matches a row with either token.
|
|
6431
|
+
|
|
6432
|
+
`findOrCreateBy`, `findOrInitializeBy`, and `createOrFindBy` refuse a list. They throw a `TypeError` before they query, since their attributes become the new record’s values.
|
|
6433
|
+
|
|
4623
6434
|
:::note
|
|
4624
6435
|
A value that can’t be cast matches nothing, so `whereNot({ id: "abc" })` excludes nothing.
|
|
4625
6436
|
:::
|
|
4626
6437
|
|
|
6438
|
+
> **Beyond Rails**
|
|
6439
|
+
>
|
|
6440
|
+
> Rails’ `find_or_create_by` reads a list as `IN`, as `find_by` does. Rails doesn’t need to refuse one. A request’s params must be permitted before a model takes them, and `permit(:email)` keeps only single values.
|
|
6441
|
+
>
|
|
6442
|
+
> Here, `await request.json()` is a plain object, and `permit` is up to you. So `findOrCreateBy(await request.json())` could find another user’s row. The find-or-create methods refuse a list instead. `findBy` and `where` still read a list as `IN`.
|
|
6443
|
+
|
|
6444
|
+
### Rewriting queries
|
|
6445
|
+
|
|
6446
|
+
Pass `rewhere` and `unscope` the attribute names and values you chose, never a request’s. They widen a query, where `where` only narrows one, so `Post.where({ published: true }).rewhere(await request.json())` would find any post the body names.
|
|
6447
|
+
|
|
6448
|
+
An association’s link to its owner always stays. `user.posts().rewhere({ userId: 2 })` finds nothing, since no post belongs to both users.
|
|
6449
|
+
|
|
4627
6450
|
---
|
|
4628
6451
|
|
|
4629
6452
|
# Upgrading
|
|
@@ -4631,6 +6454,95 @@ Source: https://active-record.forestfuture.dev/upgrading
|
|
|
4631
6454
|
|
|
4632
6455
|
Each section moves an app up one release. Start from the release you’re on.
|
|
4633
6456
|
|
|
6457
|
+
## Upgrading from 0.7 to 0.8
|
|
6458
|
+
|
|
6459
|
+
In 0.8, a `belongsTo` requires its record, a batch prepares its writes in a callback, a new record’s changes run from its defaults, a `hasOne`’s new record replaces its old one, a `hasMany` gives its records its own key, a bulk write gives its Relation’s values over yours, the generated schema is a `defineSchema` call and reads a `DATE` column as a `date`, and `serialize` can give bytes. Upgrade in nine steps.
|
|
6460
|
+
|
|
6461
|
+
### Marking optional associations
|
|
6462
|
+
|
|
6463
|
+
Saving now fails with “must exist” when a `belongsTo` points at nothing. Add `optional: true` to each one whose foreign key can be `null`:
|
|
6464
|
+
|
|
6465
|
+
```ts
|
|
6466
|
+
import { belongsTo } from "@forestfuture/active-record";
|
|
6467
|
+
|
|
6468
|
+
export class Category extends ApplicationRecord {
|
|
6469
|
+
parent = belongsTo(Category, { optional: true });
|
|
6470
|
+
}
|
|
6471
|
+
```
|
|
6472
|
+
|
|
6473
|
+
A record built through its owner’s `hasMany` or `hasOne` passes without it.
|
|
6474
|
+
|
|
6475
|
+
### Reading a new record’s changes
|
|
6476
|
+
|
|
6477
|
+
A new record’s `changes()`, `changed()`, and `isChanged()` no longer list its declared defaults or generated id, and `savedChanges()` after a create leaves out the defaults it kept. Check code that reads them on new records, such as a callback that tests `isChanged()` before an insert. Use `isNewRecord()` to ask whether a record is new.
|
|
6478
|
+
|
|
6479
|
+
### Preparing batch writes in a callback
|
|
6480
|
+
|
|
6481
|
+
Pass `batch` and `db.batch` a callback that returns the writes, instead of an array:
|
|
6482
|
+
|
|
6483
|
+
```ts
|
|
6484
|
+
import { batch } from "@forestfuture/active-record";
|
|
6485
|
+
|
|
6486
|
+
await batch((b) => [b.save(user), b.deleteAll(Post.where({ userId: user.id }))]);
|
|
6487
|
+
```
|
|
6488
|
+
|
|
6489
|
+
Records’ `toSave()` and `toDestroy()`, and the `to…` methods such as `toInsert` and `toDeleteAll`, are gone. Call `b.save`, `b.destroy`, `b.insert`, and the rest instead.
|
|
6490
|
+
|
|
6491
|
+
### Replacing a hasOne’s record
|
|
6492
|
+
|
|
6493
|
+
Building or creating a record through a saved owner’s `hasOne` now removes the old record, by the association’s `dependent` strategy. Without one, the old record’s foreign key is set to `NULL`, which fails on a `NOT NULL` column. Set `dependent: "destroy"` or `"delete"` where the old record should go instead. Building twice through an unsaved owner now saves only the last record. See [Replacing the record](/associations#replacing-the-record).
|
|
6494
|
+
|
|
6495
|
+
### Checking keys given through a hasMany
|
|
6496
|
+
|
|
6497
|
+
A record built, created, or inserted through a `hasMany` now always gets its owner’s key, as one built through a `hasOne` already did. A foreign key you pass, such as `user.posts().build({ userId: otherId })`, is replaced. To write a record for another owner, build it through that owner, or through the Model: `Post.build({ userId: otherId })`.
|
|
6498
|
+
|
|
6499
|
+
### Checking values given to bulk writes
|
|
6500
|
+
|
|
6501
|
+
`insert`, `insertAll`, `upsert`, and `upsertAll` through a Relation now write its equality conditions, its `createWith` attributes, and its default scope’s values over the attributes you pass. So `Post.where({ userId: 1 }).insert({ title: "Hi", userId: 2 })` now writes `userId: 1`. Check bulk writes that pass a value their Relation also sets. To write the value you pass, leave the condition out. To write over a default scope’s value, start from `Post.unscoped()`. `build` and `create` still use the values you pass.
|
|
6502
|
+
|
|
6503
|
+
### Regenerating the schema
|
|
6504
|
+
|
|
6505
|
+
Run `schema` in your project’s folder:
|
|
6506
|
+
|
|
6507
|
+
```sh
|
|
6508
|
+
npx active-record schema
|
|
6509
|
+
```
|
|
6510
|
+
|
|
6511
|
+
The generated `schema.ts` now declares `schema` with `defineSchema({ … })`, which an [enum](/models#declaring-enums)’s scopes need. Until you regenerate it, `active-record schema --check` reports it as out of date.
|
|
6512
|
+
|
|
6513
|
+
### Reading `DATE` columns
|
|
6514
|
+
|
|
6515
|
+
The generated schema now reads a `DATE` column as a [`date`](/models#storing-exact-numbers-days-and-times), a day’s text such as `"2026-01-02"`, where it was a `datetime`. Update code that reads one as a `Date`, or keep the attribute a `datetime` with an override:
|
|
6516
|
+
|
|
6517
|
+
```ts
|
|
6518
|
+
import { ApplicationRecord } from "./application-record";
|
|
6519
|
+
|
|
6520
|
+
export class Event extends ApplicationRecord {
|
|
6521
|
+
static override attributes = { startsOn: "datetime" } as const;
|
|
6522
|
+
}
|
|
6523
|
+
```
|
|
6524
|
+
|
|
6525
|
+
On D1, a `DATE` column that a `datetime` wrote holds a date and time, such as `"2026-01-02T00:00:00.000Z"`, and a `date` can’t read it. Count the rows whose time isn’t midnight:
|
|
6526
|
+
|
|
6527
|
+
```sql
|
|
6528
|
+
SELECT count(*) FROM events
|
|
6529
|
+
WHERE length(starts_on) > 10 AND substr(starts_on, 11) <> 'T00:00:00.000Z';
|
|
6530
|
+
```
|
|
6531
|
+
|
|
6532
|
+
If there are none, keep only each day:
|
|
6533
|
+
|
|
6534
|
+
```sql
|
|
6535
|
+
UPDATE events SET starts_on = substr(starts_on, 1, 10) WHERE length(starts_on) > 10;
|
|
6536
|
+
```
|
|
6537
|
+
|
|
6538
|
+
Postgres stores a `date` without a time, so its rows need no change.
|
|
6539
|
+
|
|
6540
|
+
A `TIME` column is now a [`time`](/models#storing-exact-numbers-days-and-times), where it was a `string`, and reads as `"09:30:00"`. A `NUMERIC` or `DECIMAL` column is now a `decimal`, where it was an error.
|
|
6541
|
+
|
|
6542
|
+
### Typing serialized values
|
|
6543
|
+
|
|
6544
|
+
`typeForAttribute(name).serialize` now returns `string | number | Uint8Array | null`, since a [`binary` attribute](/models#storing-bytes) is stored as bytes. Code that gives its result a narrower type, such as `string | number | null`, needs the wider one.
|
|
6545
|
+
|
|
4634
6546
|
## Upgrading from 0.6 to 0.7
|
|
4635
6547
|
|
|
4636
6548
|
In 0.7, the adapters ship inside `@forestfuture/active-record`, so an app on D1 installs one package. Upgrade in four steps.
|
|
@@ -4673,7 +6585,7 @@ It writes `active-record.jsonc`, naming each database in your Wrangler config’
|
|
|
4673
6585
|
}
|
|
4674
6586
|
```
|
|
4675
6587
|
|
|
4676
|
-
Every `active-record` command reads it. Each database’s migrations folder stays in your Wrangler config. `--adapter` is gone, and `--config` now names this file.
|
|
6588
|
+
Every `active-record` command reads it. Each database’s migrations folder stays in your Wrangler config. `--adapter` is gone, and `--config` now names this file. If you used `--config` to name a Wrangler config in another folder, name it in the database’s entry with [`wranglerConfig`](/command-line#declaring-your-databases) instead.
|
|
4677
6589
|
|
|
4678
6590
|
### Regenerating the schema
|
|
4679
6591
|
|
|
@@ -4809,30 +6721,208 @@ const valid = await account.isValid();
|
|
|
4809
6721
|
| Rule | Options | Error type |
|
|
4810
6722
|
| -------------- | -------------------------------------------------------------------------------------------- | ---------------------------------------------- |
|
|
4811
6723
|
| `presence` | `true` | `blank` |
|
|
6724
|
+
| `absence` | `true` | `present` |
|
|
4812
6725
|
| `length` | `{ minimum, maximum, is }` | `tooShort`, `tooLong`, `wrongLength` |
|
|
4813
6726
|
| `format` | `{ with: /re/ }`, or a regex | `invalid` |
|
|
4814
6727
|
| `inclusion` | `{ in: [...] }`, or an array | `inclusion` |
|
|
6728
|
+
| `exclusion` | `{ in: [...] }`, or an array | `exclusion` |
|
|
4815
6729
|
| `numericality` | `{ onlyInteger, greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo }`, or `true` | `notANumber`, `notAnInteger`, `greaterThan`, … |
|
|
6730
|
+
| `comparison` | `{ greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo, equalTo, otherThan }` | `blank`, `greaterThan`, … |
|
|
6731
|
+
| `acceptance` | `true`, or `{ accept: [...] }` | `accepted` |
|
|
4816
6732
|
| `uniqueness` | `{ scope: [...], caseSensitive }`, or `true` | `taken` |
|
|
4817
6733
|
|
|
4818
|
-
Every validation runs, in the order declared, so one attribute can collect several errors. Every rule also accepts these options:
|
|
6734
|
+
Every validation runs, in the order declared, so one attribute can collect several errors. Within one `validates` call, the rules run in the table’s order. Every rule also accepts these options:
|
|
4819
6735
|
|
|
4820
|
-
- **`allowNull`** skips the rule when the value is `null`. Otherwise `null` fails `presence`, `format`, `inclusion`, and `
|
|
6736
|
+
- **`allowNull`** skips the rule when the value is `null`. Otherwise `null` fails `presence`, `format`, `inclusion`, `numericality`, `comparison`, and `acceptance`, counts as length 0, and is never taken.
|
|
6737
|
+
- **`allowBlank`** skips the rule when the value is blank: `null`, or a string that’s only whitespace.
|
|
4821
6738
|
- **`message`** replaces the default messages from that call.
|
|
4822
6739
|
- **`if: (record) => boolean`** validates only when it returns `true`.
|
|
6740
|
+
- **`unless: (record) => boolean`** skips the rule when it returns `true`. With `if` as well, both must allow it.
|
|
6741
|
+
- **`strict`** throws instead of adding an error. See [Raising instead of collecting errors](#raising-instead-of-collecting-errors).
|
|
6742
|
+
- **`on`** and **`exceptOn`** run the rule only when creating, only when updating, or in a context of your own. See [Validating only when creating or updating](#validating-only-when-creating-or-updating).
|
|
4823
6743
|
|
|
4824
6744
|
The default messages are in English: “can’t be blank”, “is too short (minimum is 3 characters)”, “has already been taken”, and so on. [Finding a built-in message](#finding-a-built-in-message) lists them all, and [Changing error messages](#changing-error-messages) shows how to replace them.
|
|
4825
6745
|
|
|
4826
6746
|
### Validator details
|
|
4827
6747
|
|
|
4828
6748
|
- **`presence`** fails a string that’s only whitespace. For a boolean, use `inclusion: [true, false]`, since `false` is a value.
|
|
4829
|
-
- **`
|
|
6749
|
+
- **`absence`** passes what `presence` fails: `null` and a string that’s only whitespace. So `false` fails it.
|
|
6750
|
+
- **`inclusion`** is added for you by an [enum](/models#reading-and-assigning-other-values) declared `validate: true`.
|
|
6751
|
+
- **`exclusion`** passes `null` unless the list holds it.
|
|
6752
|
+
- **`numericality`** only accepts numbers, so a numeric string such as `"12"` is `notANumber`. A [`decimal`](/models#storing-exact-numbers-days-and-times) attribute’s text is the exception: it’s compared with each bound as a number, exactly.
|
|
6753
|
+
- **`comparison`** compares a number with a number, a string with a string, or a Date with a Date by its time. A `decimal` attribute compares as a number, with a number or a decimal’s text. A bound is a value, or a function of the record (see [Comparing with another attribute](#comparing-with-another-attribute)). A blank value fails once, as `blank`. Blank means `null` or a string that’s only whitespace. Comparing a number with a Date, or any two different kinds, throws `TypeError`. Against a bound of `NaN` or an invalid Date, only `otherThan` passes.
|
|
6754
|
+
- **`acceptance`** is for a box that must be ticked. It passes `true` and `"1"`, or the values you give in `{ accept: [...] }`. A checkbox left unticked sends nothing, so `null` fails too. To let `null` pass, add `allowNull: true`.
|
|
4830
6755
|
- **`uniqueness`** leaves the record itself out when updating, and never treats `null` as taken, as SQLite’s UNIQUE does. `caseSensitive: false` compares with SQLite’s `lower()`, which only lowercases ASCII letters.
|
|
4831
6756
|
|
|
6757
|
+
> **Compared with Rails**
|
|
6758
|
+
>
|
|
6759
|
+
> Rails treats `false` as blank, so it passes `absence`. Here `false` passes `presence`, so it fails `absence`.
|
|
6760
|
+
>
|
|
6761
|
+
> Rails’ `acceptance` lets `nil` pass, since its form helpers send `"0"` for an unticked checkbox. A plain HTML checkbox sends nothing, so here `null` fails.
|
|
6762
|
+
>
|
|
6763
|
+
> Rails’ `allow_blank` also skips `false`, `[]`, and `{}`. Here `allowBlank` skips what `presence` fails: `null` and a string that’s only whitespace.
|
|
6764
|
+
>
|
|
6765
|
+
> Rails’ `confirmation` isn’t here yet.
|
|
6766
|
+
|
|
4832
6767
|
:::warning[Uniqueness isn’t a guarantee]
|
|
4833
|
-
Two requests can both check that an email is free, then both insert it. `uniqueness` gives a friendly error early, but only a UNIQUE index in the table prevents duplicates, so declare both. When the index catches a duplicate, the save throws [`RecordNotUnique`](/errors#constraint-errors).
|
|
6768
|
+
Two requests can both check that an email is free, then both insert it. `uniqueness` gives a friendly error early, but only a UNIQUE index in the table prevents duplicates, so declare both. When the index catches a duplicate, the save throws [`RecordNotUnique`](/errors#constraint-errors). For attributes you create with [`createOrFindBy`](/persistence#creating-records-from-concurrent-requests), declare only the index.
|
|
6769
|
+
:::
|
|
6770
|
+
|
|
6771
|
+
### Comparing with another attribute
|
|
6772
|
+
|
|
6773
|
+
Give `comparison` a function of the record to compare with another attribute:
|
|
6774
|
+
|
|
6775
|
+
```ts
|
|
6776
|
+
import { Model } from "@forestfuture/active-record";
|
|
6777
|
+
|
|
6778
|
+
export class Event extends Model.define({
|
|
6779
|
+
id: { type: "integer", null: false },
|
|
6780
|
+
startsAt: { type: "datetime", null: false },
|
|
6781
|
+
endsAt: { type: "datetime", null: false },
|
|
6782
|
+
}) {
|
|
6783
|
+
static {
|
|
6784
|
+
this.validates("endsAt", { comparison: { greaterThan: (event) => event.startsAt } });
|
|
6785
|
+
}
|
|
6786
|
+
}
|
|
6787
|
+
```
|
|
6788
|
+
|
|
6789
|
+
When the function returns `null`, that bound is skipped. Validate the other attribute’s presence to report it.
|
|
6790
|
+
|
|
6791
|
+
> **Compared with Rails**
|
|
6792
|
+
>
|
|
6793
|
+
> Rails names the other attribute with a symbol, `comparison: { greater_than: :starts_at }`. Here a function does it, so the attribute’s name is typed.
|
|
6794
|
+
|
|
6795
|
+
### Raising instead of collecting errors
|
|
6796
|
+
|
|
6797
|
+
For a value only a bug in your own code could set, pass `strict: true`. A failing rule then throws `StrictValidationFailed` with its full message, instead of adding an error:
|
|
6798
|
+
|
|
6799
|
+
```ts
|
|
6800
|
+
import { Model } from "@forestfuture/active-record";
|
|
6801
|
+
|
|
6802
|
+
export class Invoice extends Model.define({
|
|
6803
|
+
id: { type: "integer", null: false },
|
|
6804
|
+
total: { type: "integer", null: false },
|
|
6805
|
+
currency: { type: "string", null: false },
|
|
6806
|
+
}) {
|
|
6807
|
+
static {
|
|
6808
|
+
this.validates("currency", { inclusion: ["USD", "EUR"], strict: true });
|
|
6809
|
+
}
|
|
6810
|
+
}
|
|
6811
|
+
```
|
|
6812
|
+
|
|
6813
|
+
```ts
|
|
6814
|
+
const invoice = Invoice.build({ total: 1200, currency: "GBP" });
|
|
6815
|
+
await invoice.isValid(); // throws "Currency is not included in the list"
|
|
6816
|
+
```
|
|
6817
|
+
|
|
6818
|
+
`isValid()`, `save()`, and `saveOrThrow()` all throw it, and the validations after it don’t run. To throw an error class of your own, pass the class as `strict`, such as `strict: UnknownCurrency`. It’s made with the same message.
|
|
6819
|
+
|
|
6820
|
+
## Validating only when creating or updating
|
|
6821
|
+
|
|
6822
|
+
By default, a rule runs on every save. To run it only when a record is created, pass `on: "create"`:
|
|
6823
|
+
|
|
6824
|
+
```ts
|
|
6825
|
+
import { Model } from "@forestfuture/active-record";
|
|
6826
|
+
|
|
6827
|
+
export class Member extends Model.define({
|
|
6828
|
+
id: { type: "integer", null: false },
|
|
6829
|
+
email: { type: "string", null: false },
|
|
6830
|
+
password: "string",
|
|
6831
|
+
inviteCode: "string",
|
|
6832
|
+
}) {
|
|
6833
|
+
static validationContexts = ["signup"] as const;
|
|
6834
|
+
|
|
6835
|
+
static {
|
|
6836
|
+
this.validates("email", { format: /@/ });
|
|
6837
|
+
this.validates("password", { presence: true, on: "create" });
|
|
6838
|
+
this.validates("inviteCode", { presence: true, on: "signup" });
|
|
6839
|
+
}
|
|
6840
|
+
}
|
|
6841
|
+
```
|
|
6842
|
+
|
|
6843
|
+
A new record is validated in the `"create"` context, and a saved one in `"update"`. A rule with `on` runs only in the contexts it names, so `password` is checked when a member is created, and not when one is updated. To name several contexts, pass a list, such as `on: ["create", "signup"]`.
|
|
6844
|
+
|
|
6845
|
+
`exceptOn` works the other way. The rule runs in every context except the ones it names.
|
|
6846
|
+
|
|
6847
|
+
### Naming your own contexts
|
|
6848
|
+
|
|
6849
|
+
For a step of your own, such as a signup form, list its name in the Model’s `static validationContexts`, with `as const`. Then pass it to `isValid` or `save`:
|
|
6850
|
+
|
|
6851
|
+
```ts
|
|
6852
|
+
const member = Member.build({ email: "ada@example.com", password: "secret" });
|
|
6853
|
+
await member.isValid("signup"); // false: invite code can't be blank
|
|
6854
|
+
await member.save({ context: "signup" });
|
|
6855
|
+
```
|
|
6856
|
+
|
|
6857
|
+
Rules without `on` run in every context. A context you pass takes the place of `"create"` or `"update"`, so the `on: "create"` rules don’t run. To run both, pass both:
|
|
6858
|
+
|
|
6859
|
+
```ts
|
|
6860
|
+
await member.save({ context: ["create", "signup"] });
|
|
6861
|
+
```
|
|
6862
|
+
|
|
6863
|
+
`"create"` and `"update"` are always there, so list only your own. A context the Model doesn’t list is a compile error in `on` and `exceptOn`. Passed to `isValid` or `save`, it throws `TypeError`.
|
|
6864
|
+
|
|
6865
|
+
:::note
|
|
6866
|
+
List contexts on each Model. A Model’s subclass shares its list, and an abstract base class can’t have one.
|
|
6867
|
+
:::
|
|
6868
|
+
|
|
6869
|
+
### Validating associated records in a context
|
|
6870
|
+
|
|
6871
|
+
When you pass a context of your own, the records validated with the owner are validated in it too. These are the records checked by `validatesAssociated`, and the records [saved with their owner](/associations#autosaving). With `"create"` or `"update"`, each record uses its own: a new record is validated in `"create"` even when its owner is updated. A list that holds a context of your own reaches them whole, so `["create", "signup"]` runs the `on: "create"` rules of related records that are already saved, too.
|
|
6872
|
+
|
|
6873
|
+
> **Beyond Rails**
|
|
6874
|
+
>
|
|
6875
|
+
> Rails accepts any context name, so a misspelled one quietly runs none of its rules. Here a Model lists its contexts, and a name it doesn’t list is a compile error or a `TypeError`.
|
|
6876
|
+
|
|
6877
|
+
> **Compared with Rails**
|
|
6878
|
+
>
|
|
6879
|
+
> `valid?(:signup)` is `isValid("signup")`, `save(context: :signup)` is `save({ context: "signup" })`, and `except_on:` is `exceptOn`.
|
|
6880
|
+
|
|
6881
|
+
## Validating associated records
|
|
6882
|
+
|
|
6883
|
+
To validate an association’s records with their owner, call `this.validatesAssociated`:
|
|
6884
|
+
|
|
6885
|
+
```ts
|
|
6886
|
+
import { hasMany, Model } from "@forestfuture/active-record";
|
|
6887
|
+
|
|
6888
|
+
export class Track extends Model.define({
|
|
6889
|
+
id: { type: "integer", null: false },
|
|
6890
|
+
playlistId: { type: "integer", null: false },
|
|
6891
|
+
title: { type: "string", null: false },
|
|
6892
|
+
}) {
|
|
6893
|
+
static {
|
|
6894
|
+
this.validates("title", { presence: true });
|
|
6895
|
+
}
|
|
6896
|
+
}
|
|
6897
|
+
|
|
6898
|
+
export class Playlist extends Model.define({
|
|
6899
|
+
id: { type: "integer", null: false },
|
|
6900
|
+
name: { type: "string", null: false },
|
|
6901
|
+
}) {
|
|
6902
|
+
tracks = hasMany(Track);
|
|
6903
|
+
|
|
6904
|
+
static {
|
|
6905
|
+
this.validatesAssociated("tracks");
|
|
6906
|
+
}
|
|
6907
|
+
}
|
|
6908
|
+
```
|
|
6909
|
+
|
|
6910
|
+
An invalid track makes its playlist invalid, with a “Tracks is invalid” error, and keeps its own errors. If the association isn’t loaded, validating the playlist loads it, with one query. A record marked for destruction isn’t validated. Records built through an association are [validated with their owner](/associations#autosaving) even without `validatesAssociated`.
|
|
6911
|
+
|
|
6912
|
+
`validatesAssociated` takes `if`, `unless`, `on`, `exceptOn`, `message`, and `strict`, as `validates` does. The association’s name is typed, so a misspelled one is a compile error.
|
|
6913
|
+
|
|
6914
|
+
You can declare `validatesAssociated` on both sides of an association. A record that’s already being validated counts as valid, so validating either side finishes.
|
|
6915
|
+
|
|
6916
|
+
:::note
|
|
6917
|
+
Each track is validated with its own rules and callbacks, so a `uniqueness` rule on a track sends a query for every track. Use `validatesAssociated` on associations that stay small.
|
|
4834
6918
|
:::
|
|
4835
6919
|
|
|
6920
|
+
> **Compared with Rails**
|
|
6921
|
+
>
|
|
6922
|
+
> When `validates_associated` and autosave both check a record, Rails validates it twice and adds “is invalid” twice. Here it’s validated once, with one error.
|
|
6923
|
+
>
|
|
6924
|
+
> Rails’ `validates_associated` on both sides of an association recurses until the stack overflows. Here the record already being validated counts as valid.
|
|
6925
|
+
|
|
4836
6926
|
## Reading errors
|
|
4837
6927
|
|
|
4838
6928
|
A record’s `errors` hold each failed rule:
|
|
@@ -4868,11 +6958,11 @@ export class Booking extends Model.define({
|
|
|
4868
6958
|
endsAt: { type: "datetime", null: false },
|
|
4869
6959
|
}) {
|
|
4870
6960
|
static {
|
|
4871
|
-
this.errorMessages({
|
|
6961
|
+
this.errorMessages({ onTheHour: "must be on the hour" });
|
|
4872
6962
|
|
|
4873
6963
|
this.afterValidation((booking) => {
|
|
4874
|
-
if (booking.
|
|
4875
|
-
booking.errors.add("
|
|
6964
|
+
if (booking.startsAt.getUTCMinutes() !== 0) {
|
|
6965
|
+
booking.errors.add("startsAt", { type: "onTheHour" });
|
|
4876
6966
|
}
|
|
4877
6967
|
if (booking.startsAt.getUTCDay() === 0) {
|
|
4878
6968
|
booking.errors.add("base", "The room is closed on Sundays");
|
|
@@ -4882,17 +6972,18 @@ export class Booking extends Model.define({
|
|
|
4882
6972
|
}
|
|
4883
6973
|
```
|
|
4884
6974
|
|
|
4885
|
-
`errors.add` takes the attribute, or `"base"`, then either a `type` or a message. A `type` takes its message from the Model’s `errorMessages`, as `
|
|
6975
|
+
`errors.add` takes the attribute, or `"base"`, then either a `type` or a message. A `type` takes its message from the Model’s `errorMessages`, as `onTheHour` does above. See [Changing error messages](#changing-error-messages). A message is used as written, and its type is `"invalid"`:
|
|
4886
6976
|
|
|
4887
6977
|
```ts
|
|
4888
|
-
const
|
|
4889
|
-
const
|
|
6978
|
+
const startsAt = new Date("2026-05-03T10:30:00Z"); // a Sunday
|
|
6979
|
+
const endsAt = new Date("2026-05-03T11:30:00Z");
|
|
6980
|
+
const booking = Booking.build({ startsAt, endsAt });
|
|
4890
6981
|
await booking.isValid(); // false
|
|
4891
6982
|
|
|
4892
6983
|
booking.errors.toArray();
|
|
4893
|
-
// [{ attribute: "
|
|
6984
|
+
// [{ attribute: "startsAt", type: "onTheHour", message: "must be on the hour" },
|
|
4894
6985
|
// { attribute: "base", type: "invalid", message: "The room is closed on Sundays" }]
|
|
4895
|
-
booking.errors.fullMessages(); // ["
|
|
6986
|
+
booking.errors.fullMessages(); // ["Starts at must be on the hour", "The room is closed on Sundays"]
|
|
4896
6987
|
```
|
|
4897
6988
|
|
|
4898
6989
|
To fill in a placeholder, pass its value with the type:
|
|
@@ -4911,7 +7002,7 @@ Each validation run, from `isValid()`, `save()`, or `saveOrThrow()`, starts by c
|
|
|
4911
7002
|
|
|
4912
7003
|
> **Compared with Rails**
|
|
4913
7004
|
>
|
|
4914
|
-
> Rails’ `errors.add(:
|
|
7005
|
+
> Rails’ `errors.add(:starts_at, :on_the_hour)` is `errors.add("startsAt", { type: "onTheHour" })` here, since a type and a message are both strings in TypeScript. When Rails is given a message instead, that text is the type too; here the type is `"invalid"`. Rails’ `message:` and `strict:` options and its procs aren’t here.
|
|
4915
7006
|
|
|
4916
7007
|
## Changing error messages
|
|
4917
7008
|
|
|
@@ -4986,9 +7077,9 @@ In a Model, `attributes` and `humanAttributeNames` can only name the Model’s a
|
|
|
4986
7077
|
|
|
4987
7078
|
A message can show these values:
|
|
4988
7079
|
|
|
4989
|
-
- **`%{count}`**: the number
|
|
7080
|
+
- **`%{count}`**: the rule’s number or bound, such as the `minimum` of `tooShort` or the bound of `greaterThan`. A Date bound shows as an ISO string. A bound’s function that returns a [filtered attribute](/models#filtering-attributes)’s value shows `[FILTERED]`.
|
|
4990
7081
|
- **`%{attribute}`**: the attribute’s name, as `fullMessages()` shows it.
|
|
4991
|
-
- **`%{model}`**: the Model’s
|
|
7082
|
+
- **`%{model}`**: the Model’s name in words, so `BlogPost` reads as “Blog post”. It’s the class name, unless the Model sets [`static modelName`](/models#naming-models).
|
|
4992
7083
|
- **`%{value}`**: the attribute’s value. A [filtered attribute](/models#filtering-attributes) shows `[FILTERED]`.
|
|
4993
7084
|
|
|
4994
7085
|
A value passed to `errors.add` with the type, such as `count`, fills in the placeholder of the same name.
|
|
@@ -5008,23 +7099,29 @@ A type with no message anywhere throws a `TypeError` when the error is added.
|
|
|
5008
7099
|
|
|
5009
7100
|
Each error type has a built-in message. To replace one, use its type as the key in `errorMessages`:
|
|
5010
7101
|
|
|
5011
|
-
| Type | Added by
|
|
5012
|
-
| -------------------------- |
|
|
5013
|
-
| `blank` | `presence`
|
|
5014
|
-
| `
|
|
5015
|
-
| `
|
|
5016
|
-
| `
|
|
5017
|
-
| `
|
|
5018
|
-
| `
|
|
5019
|
-
| `
|
|
5020
|
-
| `
|
|
5021
|
-
| `
|
|
5022
|
-
| `
|
|
5023
|
-
| `
|
|
5024
|
-
| `
|
|
5025
|
-
| `
|
|
5026
|
-
| `
|
|
5027
|
-
| `
|
|
7102
|
+
| Type | Added by | Message |
|
|
7103
|
+
| -------------------------- | ---------------------------------------------------------- | ----------------------------------------------------------- |
|
|
7104
|
+
| `blank` | `presence`, and `comparison` for a blank value | can’t be blank |
|
|
7105
|
+
| `present` | `absence` | must be blank |
|
|
7106
|
+
| `invalid` | `format` and an invalid autosaved association | is invalid |
|
|
7107
|
+
| `inclusion` | `inclusion` | is not included in the list |
|
|
7108
|
+
| `exclusion` | `exclusion` | is reserved |
|
|
7109
|
+
| `tooShort` | `length: { minimum }` | is too short (minimum is `%{count}` characters) |
|
|
7110
|
+
| `tooLong` | `length: { maximum }` | is too long (maximum is `%{count}` characters) |
|
|
7111
|
+
| `wrongLength` | `length: { is }` | is the wrong length (should be `%{count}` characters) |
|
|
7112
|
+
| `notANumber` | `numericality` | is not a number |
|
|
7113
|
+
| `notAnInteger` | `numericality: { onlyInteger }` | must be an integer |
|
|
7114
|
+
| `greaterThan` | `numericality` or `comparison`: `{ greaterThan }` | must be greater than `%{count}` |
|
|
7115
|
+
| `greaterThanOrEqualTo` | `numericality` or `comparison`: `{ greaterThanOrEqualTo }` | must be greater than or equal to `%{count}` |
|
|
7116
|
+
| `lessThan` | `numericality` or `comparison`: `{ lessThan }` | must be less than `%{count}` |
|
|
7117
|
+
| `lessThanOrEqualTo` | `numericality` or `comparison`: `{ lessThanOrEqualTo }` | must be less than or equal to `%{count}` |
|
|
7118
|
+
| `equalTo` | `comparison: { equalTo }` | must be equal to `%{count}` |
|
|
7119
|
+
| `otherThan` | `comparison: { otherThan }` | must be other than `%{count}` |
|
|
7120
|
+
| `accepted` | `acceptance` | must be accepted |
|
|
7121
|
+
| `taken` | `uniqueness` | has already been taken |
|
|
7122
|
+
| `required` | a `belongsTo` whose record doesn’t exist | must exist |
|
|
7123
|
+
| `restrictDependentDestroy` | a has-one with `dependent: "restrictWithError"` | Cannot delete record because a dependent `%{record}` exists |
|
|
7124
|
+
| `restrictDependentDestroy` | a has-many with `dependent: "restrictWithError"` | Cannot delete record because dependent `%{record}` exist |
|
|
5028
7125
|
|
|
5029
7126
|
With a count of 1, the three `length` messages say “1 character”. `restrictDependentDestroy` goes on `"base"`, and `%{record}` is the association’s name in lowercase. To replace it, give both forms: `restrictDependentDestroy: { hasOne: "…", hasMany: "…" }`.
|
|
5030
7127
|
|