@forestfuture/active-record 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/config-schema.json +6 -2
- package/dist/adapter.d.mts +3 -3
- package/dist/adapter.mjs +5 -4
- package/dist/batch-ReqVoCfa.mjs +9559 -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/epoch-storage-CDlQZcBB.mjs +988 -0
- package/dist/{for-adapters-t3-LukJQ.d.mts → for-adapters-B0xMP6Dq.d.mts} +8 -6
- package/dist/{for-adapters-D_Iu0gS_.mjs → for-adapters-CfXMGeOu.mjs} +3 -5
- package/dist/{for-adapters-Ch6CoHD4.mjs → for-adapters-DhNV1mWf.mjs} +46 -10
- package/dist/{generated-model-Cnt0Ot9q.mjs → generated-model-g5oWsDKE.mjs} +728 -540
- package/dist/index-BATasvJa.d.mts +241 -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-wOSILvSB.mjs} +211 -112
- package/dist/{plugin-XOHYndhP.mjs → plugin-x5-d3TSN.mjs} +148 -52
- package/dist/postgresql.d.mts +1 -9
- package/dist/postgresql.mjs +42 -26
- package/dist/src-D56_3odT.mjs +46 -0
- package/dist/{storage-override-CpbkdIqE.mjs → storage-override-n4w1cS_M.mjs} +61 -28
- package/dist/validations-DHDVV8hB.d.mts +1996 -0
- package/llms-full.txt +2354 -363
- package/package.json +1 -1
- package/skills/active-record/SKILL.md +22 -14
- 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,25 @@ 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 show how many records an association has, keep a counter cache rather than counting on each read: `article = belongsTo(Article, { counterCache: true })` with a `commentsCount` attribute, which `article.comments().size()` reads. Saves, destroys and the association's `delete`/`clear`/`deleteAll()` keep it; bulk writes (`insertAll`, `updateAll`, a Relation's `deleteAll`) don't, so follow them with `Article.resetCounters(id, "comments")`. Add one to existing rows with `{ active: false }`, reset each, then drop `active: false`.
|
|
377
|
+
- To work through more records than a request should hold (a backfill, an export, a cleanup), iterate in batches rather than `toArray()` or `offset` pages: `for await (const user of User.where(…).findEach())`, `findInBatches()` for arrays, and `inBatches()` for a Relation per batch to `updateAll`, `deleteAll` or `destroyAll`. Batches go in primary-key order, so `reorder()` a Relation that has an order (a default scope's too), and bound them with `start` and `finish`, not `offset`. On D1 a Worker invocation sends at most 1,000 queries (50 on Free), and each batch sends one (`inBatches` reads its keys, then sends the write, and a `destroyAll` adds a load and each record's dependent reads; a `db.batch` counts as one): split a larger job across invocations by `start` and `finish`.
|
|
378
|
+
- 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()`.
|
|
379
|
+
- 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
380
|
- 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.
|
|
381
|
+
- 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.
|
|
382
|
+
- 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.
|
|
383
|
+
- 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
384
|
|
|
379
385
|
```
|
|
380
386
|
|
|
@@ -398,7 +404,7 @@ export class Author extends Model.define({
|
|
|
398
404
|
id: { type: "string", null: false, generateId: true },
|
|
399
405
|
name: { type: "string", null: false },
|
|
400
406
|
}) {
|
|
401
|
-
articles = hasMany(Article, { dependent: "destroy" }); // Article's authorId
|
|
407
|
+
articles = hasMany(Article, { dependent: "destroy", autosave: true }); // Article's authorId
|
|
402
408
|
profile = hasOne(Profile, { dependent: "delete" }); // Profile's authorId
|
|
403
409
|
}
|
|
404
410
|
|
|
@@ -443,11 +449,35 @@ await article.save();
|
|
|
443
449
|
- **`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
450
|
- **`record.author.create(attrs)`** and **`createOrThrow(attrs)`** save a new record at once, and point at it. The record itself isn’t saved.
|
|
445
451
|
|
|
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)
|
|
452
|
+
| Option | Does |
|
|
453
|
+
| ------------ | --------------------------------------------------------------------------------------------------------- |
|
|
454
|
+
| `foreignKey` | The attribute on this record that holds the link. Defaults to the association’s name + `Id` |
|
|
455
|
+
| `primaryKey` | The attribute on the target it points at. Defaults to the target’s primary key |
|
|
456
|
+
| `scope` | Narrows the target, `(q) => q.where(…)`. See [Scoping associations](#scoping-associations) |
|
|
457
|
+
| `optional` | Lets the record point at nothing. See [Requiring the record](#requiring-the-record) |
|
|
458
|
+
| `autosave` | `true` saves the record’s changes with this record. See [Saving changed records](#saving-changed-records) |
|
|
459
|
+
|
|
460
|
+
### Requiring the record
|
|
461
|
+
|
|
462
|
+
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.
|
|
463
|
+
|
|
464
|
+
If a record may point at nothing, pass `optional: true`. A top-level category has no parent:
|
|
465
|
+
|
|
466
|
+
```ts
|
|
467
|
+
import { belongsTo, hasMany } from "@forestfuture/active-record";
|
|
468
|
+
|
|
469
|
+
export class Category extends ApplicationRecord {
|
|
470
|
+
// foreign key: parentId, from the association's name; optional, since a top-level category has none
|
|
471
|
+
parent = belongsTo(Category, { optional: true });
|
|
472
|
+
children = hasMany(Category, { foreignKey: "parentId" }); // not the default, categoryId
|
|
473
|
+
}
|
|
474
|
+
```
|
|
475
|
+
|
|
476
|
+
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).
|
|
477
|
+
|
|
478
|
+
> **Compared with Rails**
|
|
479
|
+
>
|
|
480
|
+
> 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
481
|
|
|
452
482
|
## hasMany
|
|
453
483
|
|
|
@@ -466,7 +496,12 @@ await author.articles().where({ title: "Untitled" }).deleteAll(); // bulk writes
|
|
|
466
496
|
- **`record.posts()`** is a Relation of the associated records, with every Relation method and the target’s scopes.
|
|
467
497
|
- **`record.posts().build(attrs)`** builds a record with the owner’s key, saved with the owner. See [Autosaving](#autosaving).
|
|
468
498
|
- **`record.posts().create(attrs)`** and **`createOrThrow(attrs)`** save a new record at once. The owner must already be saved.
|
|
469
|
-
- **`
|
|
499
|
+
- **`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.
|
|
500
|
+
- **`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`.
|
|
501
|
+
- **`record.posts().destroy(...records)`** destroys records with their callbacks, whatever the strategy.
|
|
502
|
+
- **`record.posts().clear()`** removes every record, as `deleteAll()` does.
|
|
503
|
+
- **`record.posts().destroyAll()`** destroys every record with its callbacks, whatever the strategy, and leaves the association empty.
|
|
504
|
+
- **`insert`, `upsert`, `updateAll`, and `deleteAll`** write to the owner’s records. See [Writing many rows](#writing-many-rows).
|
|
470
505
|
|
|
471
506
|
| Option | Does |
|
|
472
507
|
| ------------ | ---------------------------------------------------------------------------------------------------------------- |
|
|
@@ -474,6 +509,7 @@ await author.articles().where({ title: "Untitled" }).deleteAll(); // bulk writes
|
|
|
474
509
|
| `primaryKey` | The attribute on this record the foreign key points at. Defaults to the primary key |
|
|
475
510
|
| `scope` | Narrows or orders the records, `(q) => q.order(…)`. See [Scoping associations](#scoping-associations) |
|
|
476
511
|
| `dependent` | What destroying the owner does to the records. See [Destroying dependent records](#destroying-dependent-records) |
|
|
512
|
+
| `autosave` | `true` saves the records’ changes with the owner. See [Saving changed records](#saving-changed-records) |
|
|
477
513
|
|
|
478
514
|
## hasOne
|
|
479
515
|
|
|
@@ -487,17 +523,128 @@ if (profile === null) await author.profile.create({ bio: "Writer" }); // saved a
|
|
|
487
523
|
```
|
|
488
524
|
|
|
489
525
|
- **`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.
|
|
526
|
+
- **`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
527
|
- **`record.profile.build(attrs)`** builds a record with the owner’s key, saved with the owner.
|
|
491
528
|
- **`record.profile.create(attrs)`** and **`createOrThrow(attrs)`** save a new record at once. The owner must already be saved.
|
|
492
529
|
|
|
493
530
|
`hasOne` takes the same options as `hasMany`.
|
|
494
531
|
|
|
532
|
+
### Replacing the record
|
|
533
|
+
|
|
534
|
+
Giving a saved owner a new record removes its old one, by the association’s `dependent` strategy:
|
|
535
|
+
|
|
536
|
+
```ts
|
|
537
|
+
const author = await Author.find(authorId);
|
|
538
|
+
const profile = Profile.build({ bio: "Novelist" });
|
|
539
|
+
|
|
540
|
+
await author.profile.set(profile); // saves it, and deletes the old profile in the same batch
|
|
541
|
+
```
|
|
542
|
+
|
|
543
|
+
| `dependent` | What happens to the old record |
|
|
544
|
+
| ----------------------------------------- | ------------------------------------------------ |
|
|
545
|
+
| `"destroy"` | It’s destroyed, with its own callbacks |
|
|
546
|
+
| `"delete"` | It’s deleted, without callbacks |
|
|
547
|
+
| `"nullify"`, a restrict strategy, or none | Its foreign key is set to `NULL`, and it’s saved |
|
|
548
|
+
|
|
549
|
+
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`.
|
|
550
|
+
|
|
551
|
+
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.
|
|
552
|
+
|
|
553
|
+
> **Compared with Rails**
|
|
554
|
+
>
|
|
555
|
+
> `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.
|
|
556
|
+
|
|
557
|
+
## Polymorphic associations
|
|
558
|
+
|
|
559
|
+
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:
|
|
560
|
+
|
|
561
|
+
```ts
|
|
562
|
+
import { belongsTo, hasMany, Model } from "@forestfuture/active-record";
|
|
563
|
+
|
|
564
|
+
export class Photo extends Model.define({
|
|
565
|
+
id: { type: "integer", null: false },
|
|
566
|
+
title: { type: "string", null: false },
|
|
567
|
+
}) {
|
|
568
|
+
likes = hasMany(Like, { as: "likeable" }); // Like's likeableType is "Photo"
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
export class Video extends Model.define({
|
|
572
|
+
id: { type: "integer", null: false },
|
|
573
|
+
title: { type: "string", null: false },
|
|
574
|
+
}) {
|
|
575
|
+
likes = hasMany(Like, { as: "likeable" }); // Like's likeableType is "Video"
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
export class Like extends Model.define({
|
|
579
|
+
id: { type: "integer", null: false },
|
|
580
|
+
likeableType: { type: "string", null: false },
|
|
581
|
+
likeableId: { type: "integer", null: false },
|
|
582
|
+
}) {
|
|
583
|
+
likeable = belongsTo([Photo, Video]); // its own likeableType and likeableId
|
|
584
|
+
}
|
|
585
|
+
```
|
|
586
|
+
|
|
587
|
+
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.
|
|
588
|
+
|
|
589
|
+
- **`await like.likeable()`** reads the record of the Model the type names, or `null`.
|
|
590
|
+
- **`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.
|
|
591
|
+
- **`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.
|
|
592
|
+
|
|
593
|
+
Here’s each of them at work:
|
|
594
|
+
|
|
595
|
+
```ts
|
|
596
|
+
const like = await Like.find(likeId);
|
|
597
|
+
const liked = await like.likeable(); // a Photo, a Video, or null
|
|
598
|
+
|
|
599
|
+
like.likeable.set(video); // likeableType "Video", likeableId video.id
|
|
600
|
+
await like.save();
|
|
601
|
+
|
|
602
|
+
const likes = await video.likes().toArray(); // the likes whose type is "Video"
|
|
603
|
+
```
|
|
604
|
+
|
|
605
|
+
| Option | Does |
|
|
606
|
+
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
|
|
607
|
+
| `foreignType` | The attribute that holds the type. Defaults to the association’s name + `Type`, or on a `hasMany` or `hasOne`, the `as` name + `Type` |
|
|
608
|
+
| `as` | On a `hasMany` or `hasOne`: the name of the target’s polymorphic `belongsTo`. Its foreign key defaults to that name + `Id` |
|
|
609
|
+
|
|
610
|
+
The polymorphic `belongsTo` also takes `foreignKey`, `primaryKey`, `optional`, and `autosave`, as any `belongsTo` does.
|
|
611
|
+
|
|
612
|
+
:::note
|
|
613
|
+
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.
|
|
614
|
+
:::
|
|
615
|
+
|
|
616
|
+
### Storing the type
|
|
617
|
+
|
|
618
|
+
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`.
|
|
619
|
+
|
|
620
|
+
:::warning[Set modelName if your bundler renames classes]
|
|
621
|
+
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).
|
|
622
|
+
:::
|
|
623
|
+
|
|
624
|
+
### Preloading polymorphic records
|
|
625
|
+
|
|
626
|
+
`includes` preloads a polymorphic association with one query for each listed Model:
|
|
627
|
+
|
|
628
|
+
```ts
|
|
629
|
+
const likes = await Like.includes("likeable").toArray(); // likes, photos and videos, in one round trip
|
|
630
|
+
|
|
631
|
+
for (const like of likes) {
|
|
632
|
+
console.log(like.loaded("likeable")?.title); // no query: already loaded
|
|
633
|
+
}
|
|
634
|
+
```
|
|
635
|
+
|
|
636
|
+
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.
|
|
637
|
+
|
|
638
|
+
> **Compared with Rails**
|
|
639
|
+
>
|
|
640
|
+
> 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.
|
|
641
|
+
|
|
495
642
|
## Naming foreign keys
|
|
496
643
|
|
|
497
644
|
A foreign key names an attribute, such as `authorId`, rather than a column. By default, it’s inferred:
|
|
498
645
|
|
|
499
646
|
- **`belongsTo`** uses the association’s name + `Id`. `author = belongsTo(Author)` uses the record’s own `authorId`.
|
|
500
|
-
- **`hasMany` and `hasOne`** use the Model’s
|
|
647
|
+
- **`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
648
|
|
|
502
649
|
If the name doesn’t follow the convention, pass `foreignKey`:
|
|
503
650
|
|
|
@@ -513,7 +660,7 @@ Keys are checked the first time a Model is used, and a missing attribute throws
|
|
|
513
660
|
|
|
514
661
|
**Bundlers and class names**
|
|
515
662
|
|
|
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.
|
|
663
|
+
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
664
|
|
|
518
665
|
## Caching loaded records
|
|
519
666
|
|
|
@@ -528,7 +675,7 @@ const latest = await author?.articles().first();
|
|
|
528
675
|
|
|
529
676
|
- Changing a foreign key makes the next read query again.
|
|
530
677
|
- `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`
|
|
678
|
+
- 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
679
|
- 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
680
|
|
|
534
681
|
> **Beyond Rails**
|
|
@@ -555,7 +702,7 @@ for (const each of authors) {
|
|
|
555
702
|
|
|
556
703
|
Nest with an object: `includes({ articles: "comments" })` or `includes({ articles: ["comments", "tags"] })`.
|
|
557
704
|
|
|
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.
|
|
705
|
+
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
706
|
|
|
560
707
|
:::note
|
|
561
708
|
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 +710,7 @@ With a `limit` or `offset`, `includes` ends the order with the primary key, so t
|
|
|
563
710
|
|
|
564
711
|
> **Beyond Rails**
|
|
565
712
|
>
|
|
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.
|
|
713
|
+
> 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
714
|
|
|
568
715
|
:::note
|
|
569
716
|
`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 +745,55 @@ ada.profile.build({ bio: "Mathematician" });
|
|
|
598
745
|
await ada.saveOrThrow(); // the author, both articles and the profile, in one batch
|
|
599
746
|
```
|
|
600
747
|
|
|
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.
|
|
748
|
+
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.
|
|
749
|
+
|
|
750
|
+
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.
|
|
602
751
|
|
|
603
|
-
|
|
752
|
+
#### Saving changed records
|
|
753
|
+
|
|
754
|
+
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:
|
|
755
|
+
|
|
756
|
+
```ts
|
|
757
|
+
const author = await Author.find(authorId);
|
|
758
|
+
const articles = await author.articles().toArray();
|
|
759
|
+
|
|
760
|
+
for (const article of articles) article.title = article.title.toUpperCase();
|
|
761
|
+
await author.saveOrThrow(); // every article that changed, in one batch
|
|
762
|
+
```
|
|
763
|
+
|
|
764
|
+
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.
|
|
765
|
+
|
|
766
|
+
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”.
|
|
767
|
+
|
|
768
|
+
`autosave: true` works on a `hasOne` and a `belongsTo` too. A `belongsTo`’s record is saved before its owner.
|
|
769
|
+
|
|
770
|
+
#### Removing records on save
|
|
771
|
+
|
|
772
|
+
Mark a record with `markForDestruction()` to destroy it when its owner is saved:
|
|
773
|
+
|
|
774
|
+
```ts
|
|
775
|
+
const author = await Author.find(authorId);
|
|
776
|
+
const articles = await author.articles().toArray();
|
|
777
|
+
|
|
778
|
+
for (const article of articles) {
|
|
779
|
+
if (article.title.startsWith("Draft")) article.markForDestruction();
|
|
780
|
+
}
|
|
781
|
+
await author.saveOrThrow(); // destroys the drafts, with their comments
|
|
782
|
+
```
|
|
783
|
+
|
|
784
|
+
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.
|
|
785
|
+
|
|
786
|
+
`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.
|
|
787
|
+
|
|
788
|
+
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`.
|
|
789
|
+
|
|
790
|
+
:::note
|
|
791
|
+
A mark only counts through an association declared `autosave: true`.
|
|
792
|
+
:::
|
|
793
|
+
|
|
794
|
+
> **Compared with Rails**
|
|
795
|
+
>
|
|
796
|
+
> `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
797
|
|
|
605
798
|
:::warning[Keys D1 generates]
|
|
606
799
|
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 +814,7 @@ export class Blog extends Model.define({ id: { type: "integer", null: false } })
|
|
|
621
814
|
}
|
|
622
815
|
```
|
|
623
816
|
|
|
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.
|
|
817
|
+
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
818
|
|
|
626
819
|
:::note
|
|
627
820
|
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 +838,149 @@ export class Category extends Model.define({
|
|
|
645
838
|
foreignKey: "parentId",
|
|
646
839
|
scope: (q) => q.top(),
|
|
647
840
|
});
|
|
648
|
-
parent = belongsTo(Category, { foreignKey: "parentId" });
|
|
841
|
+
parent = belongsTo(Category, { foreignKey: "parentId", optional: true });
|
|
842
|
+
}
|
|
843
|
+
```
|
|
844
|
+
|
|
845
|
+
## Reaching records through another association
|
|
846
|
+
|
|
847
|
+
Reach records through another association with `through`. A tag has many articles through its taggings:
|
|
848
|
+
|
|
849
|
+
```ts
|
|
850
|
+
import { belongsTo, hasMany, Model } from "@forestfuture/active-record";
|
|
851
|
+
|
|
852
|
+
export class Tag extends Model.define({
|
|
853
|
+
id: { type: "integer", null: false },
|
|
854
|
+
name: { type: "string", null: false },
|
|
855
|
+
}) {
|
|
856
|
+
taggings = hasMany(Tagging);
|
|
857
|
+
articles = hasMany(Article, { through: "taggings" }); // each tagging's article
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
export class Tagging extends Model.define({
|
|
861
|
+
id: { type: "integer", null: false },
|
|
862
|
+
articleId: { type: "string", null: false },
|
|
863
|
+
tagId: { type: "integer", null: false },
|
|
864
|
+
}) {
|
|
865
|
+
article = belongsTo(Article);
|
|
866
|
+
tag = belongsTo(Tag);
|
|
649
867
|
}
|
|
650
868
|
```
|
|
651
869
|
|
|
870
|
+
`through` names one of the Model’s own associations, here `taggings`. The join Model’s association with the same name, singular or plural, leads on to the records: `articles` follows each tagging’s `article`.
|
|
871
|
+
|
|
872
|
+
| Option | Does |
|
|
873
|
+
| --------- | ----------------------------------------------------------------------------------------------- |
|
|
874
|
+
| `through` | The association to go through |
|
|
875
|
+
| `source` | The join Model’s association to follow. Defaults to this association’s name, singular or plural |
|
|
876
|
+
| `scope` | Narrows or orders the records. See [Scoping associations](#scoping-associations) |
|
|
877
|
+
|
|
878
|
+
### Naming the source
|
|
879
|
+
|
|
880
|
+
If the join Model’s association has another name, pass it as `source`:
|
|
881
|
+
|
|
882
|
+
```ts
|
|
883
|
+
import { hasMany } from "@forestfuture/active-record";
|
|
884
|
+
|
|
885
|
+
writers = hasMany(Author, { through: "articles", source: "author" }); // each article's author
|
|
886
|
+
```
|
|
887
|
+
|
|
888
|
+
### Reading and preloading
|
|
889
|
+
|
|
890
|
+
Read it as you would any `hasMany`:
|
|
891
|
+
|
|
892
|
+
```ts
|
|
893
|
+
const tag = await Tag.find(tagId);
|
|
894
|
+
const articles = await tag.articles().order({ title: "asc" }).toArray(); // one query
|
|
895
|
+
|
|
896
|
+
const tags = await Tag.includes("articles").toArray(); // tags, taggings, and articles: one round trip
|
|
897
|
+
for (const each of tags) console.log(each.name, each.loaded("articles").length);
|
|
898
|
+
```
|
|
899
|
+
|
|
900
|
+
- **`tag.articles()`** is a Relation, with every Relation method, read in one query. Its writes go to the taggings, as [below](#writing-through-it).
|
|
901
|
+
- **Each record comes back once**, however many join records point at it.
|
|
902
|
+
- **`includes("articles")`** loads the join records and the articles with the tags’ own query, in one round trip on D1. The join records aren’t kept as `taggings` unless you include them too.
|
|
903
|
+
|
|
904
|
+
The scopes of both associations it goes through apply, and so does its own `scope`.
|
|
905
|
+
|
|
906
|
+
### Going through a belongsTo or a hasOne
|
|
907
|
+
|
|
908
|
+
`through` can name a `belongsTo`, a `hasMany`, or a `hasOne`, and the association it follows can be any of the three. A `hasOne` goes through a `belongsTo` or a `hasOne`:
|
|
909
|
+
|
|
910
|
+
```ts
|
|
911
|
+
import { hasOne } from "@forestfuture/active-record";
|
|
912
|
+
|
|
913
|
+
author = hasOne(Author, { through: "article" }); // the article's author
|
|
914
|
+
```
|
|
915
|
+
|
|
916
|
+
An association can also go through one that goes through another, as `writers` does above through `articles`.
|
|
917
|
+
|
|
918
|
+
### Writing through it
|
|
919
|
+
|
|
920
|
+
Add records through the association with `push`, `build`, and `create`. Each makes the join record that links the owner to the record:
|
|
921
|
+
|
|
922
|
+
```ts
|
|
923
|
+
const tag = await Tag.find(tagId);
|
|
924
|
+
const article = await Article.find(articleId);
|
|
925
|
+
|
|
926
|
+
await tag.articles().push(article); // saves a tagging that links them
|
|
927
|
+
const draft = await tag.articles().create({ authorId: article.authorId, title: "Draft" });
|
|
928
|
+
|
|
929
|
+
await tag.articles().delete(article); // deletes the tagging; the article stays
|
|
930
|
+
```
|
|
931
|
+
|
|
932
|
+
- **`push(article)`** saves a tagging for each article, in one write. A new article is saved first.
|
|
933
|
+
- **`build(attributes)`** builds the article and its tagging. Saving the tag saves both. Saving the article on its own saves no tagging.
|
|
934
|
+
- **`create(attributes)`** saves the article, then its tagging. An invalid article comes back unsaved, and nothing is written.
|
|
935
|
+
|
|
936
|
+
On a tag that isn’t saved yet, `push` and `build` wait for the tag’s save. `create` throws `RecordNotSaved` there, as it does through a `hasMany`.
|
|
937
|
+
|
|
938
|
+
Records built or created through it take the equality values of its `scope`, and their join records take those of the association it goes through.
|
|
939
|
+
|
|
940
|
+
#### Removing records
|
|
941
|
+
|
|
942
|
+
Removing records through the association removes their join records. The records themselves stay:
|
|
943
|
+
|
|
944
|
+
| Method | Does |
|
|
945
|
+
| ------------------ | --------------------------------------------------------------------------------------------------- |
|
|
946
|
+
| `delete(article)` | Deletes the tag’s taggings to the article, without callbacks |
|
|
947
|
+
| `destroy(article)` | Destroys those taggings, running their callbacks, in one write |
|
|
948
|
+
| `clear()` | Deletes every tagging to the tag’s articles, without callbacks. The tag then has no articles loaded |
|
|
949
|
+
| `deleteAll()` | Deletes the same taggings, and resolves to how many it deleted |
|
|
950
|
+
| `destroyAll()` | Destroys the same taggings, running their callbacks, and resolves to the articles |
|
|
951
|
+
|
|
952
|
+
An article the tag doesn’t reach removes nothing. To remove an article itself, destroy it: `await article.destroy()`.
|
|
953
|
+
|
|
954
|
+
In a batch, pass the association to the write: `b.deleteAll(tag.articles())` deletes the tag’s taggings.
|
|
955
|
+
|
|
956
|
+
:::warning[A narrowed deleteAll or destroyAll removes the records themselves]
|
|
957
|
+
`updateAll`, and a narrowed `deleteAll` or `destroyAll`, act on the records, as any Relation’s do. `tag.articles().where({ title: "Draft" }).deleteAll()` deletes those articles for every tag, not the tag’s taggings.
|
|
958
|
+
:::
|
|
959
|
+
|
|
960
|
+
#### Removing join records with dependent
|
|
961
|
+
|
|
962
|
+
A `hasMany` through a join Model takes `dependent: "destroy"` or `dependent: "deleteAll"`, which acts on its join records. With `"destroy"`, destroying the tag destroys its taggings, running their callbacks, and `delete` destroys them too. With `"deleteAll"`, destroying the tag deletes them without callbacks. `clear` and `deleteAll` always delete them without callbacks.
|
|
963
|
+
|
|
964
|
+
#### Setting a hasOne through another
|
|
965
|
+
|
|
966
|
+
A `hasOne` that goes through another `hasOne` has `set`. `await member.club.set(club)` points the member’s membership at the club, or creates a membership if there isn’t one, with the equality values of the membership association’s `scope`. `set(null)` destroys the membership. It has no `build` or `create`.
|
|
967
|
+
|
|
968
|
+
#### Spotting read-only associations
|
|
969
|
+
|
|
970
|
+
Writes need a join Model: the association has to go through a `hasMany` (a `hasOne`, for a `hasOne`), and follow a `belongsTo` from there, with neither going through another. Any other write throws `ReadonlyAssociation`, naming the association that stops it. `writers` above is read-only, since it goes through `articles`, which goes through `taggings`.
|
|
971
|
+
|
|
972
|
+
`insert`, `insertAll`, `upsert`, and `upsertAll` throw `ReadonlyAssociation` on any association through another, since they write no join records.
|
|
973
|
+
|
|
974
|
+
:::note
|
|
975
|
+
Every association it goes through must be on one database. One that reaches [another database](/several-databases#associating-models-on-different-databases) is an `InvalidModel` for now ([#435](https://github.com/forestfuture/active-record/issues/435)).
|
|
976
|
+
:::
|
|
977
|
+
|
|
978
|
+
> **Compared with Rails**
|
|
979
|
+
>
|
|
980
|
+
> `through` and `source` work as Rails’ `has_many :through` and `has_one :through` options do. Rails reads through a SQL join, so a record two join records point at comes back twice unless the association is `distinct`. Here it comes back once.
|
|
981
|
+
>
|
|
982
|
+
> Writing through it works as in Rails: `destroy` destroys the join records rather than the records, `clear` deletes them whatever `dependent` is, and `insert_all` through it raises. Rails also writes through a `belongsTo` or `hasOne` hop by building or updating that hop’s record, which can change a record that other records share. Here that throws `ReadonlyAssociation`. Rails’ `disable_joins` has no counterpart yet.
|
|
983
|
+
|
|
652
984
|
## Destroying dependent records
|
|
653
985
|
|
|
654
986
|
Set what destroying the owner does to its records with `dependent`:
|
|
@@ -661,29 +993,161 @@ Set what destroying the owner does to its records with `dependent`:
|
|
|
661
993
|
| `"restrictWithException"` | The destroy throws `DeleteRestriction` while there are records |
|
|
662
994
|
| `"restrictWithError"` | The destroy returns `false`, with an error on the owner’s `base` |
|
|
663
995
|
|
|
664
|
-
Everything a destroy does
|
|
996
|
+
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
997
|
|
|
666
998
|
:::note
|
|
667
999
|
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
1000
|
:::
|
|
669
1001
|
|
|
1002
|
+
## Counting records with a counter cache
|
|
1003
|
+
|
|
1004
|
+
To keep a count of an article’s comments on the article itself, declare `counterCache` on the comment’s `belongsTo`:
|
|
1005
|
+
|
|
1006
|
+
```ts
|
|
1007
|
+
import { belongsTo, hasMany, Model } from "@forestfuture/active-record";
|
|
1008
|
+
|
|
1009
|
+
export class Article extends Model.define({
|
|
1010
|
+
id: { type: "integer", null: false },
|
|
1011
|
+
title: { type: "string", null: false },
|
|
1012
|
+
commentsCount: { type: "integer", null: false },
|
|
1013
|
+
updatedAt: "datetime",
|
|
1014
|
+
}) {
|
|
1015
|
+
comments = hasMany(Comment);
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
export class Comment extends Model.define({
|
|
1019
|
+
id: { type: "integer", null: false },
|
|
1020
|
+
articleId: "integer",
|
|
1021
|
+
body: { type: "string", null: false },
|
|
1022
|
+
}) {
|
|
1023
|
+
article = belongsTo(Article, { counterCache: true }); // keeps Article's commentsCount
|
|
1024
|
+
}
|
|
1025
|
+
```
|
|
1026
|
+
|
|
1027
|
+
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"`.
|
|
1028
|
+
|
|
1029
|
+
Creating a comment adds one to its article’s count, and destroying it takes one away:
|
|
1030
|
+
|
|
1031
|
+
```ts
|
|
1032
|
+
const article = await Article.find(id);
|
|
1033
|
+
const comment = await article.comments().create({ body: "First!" }); // commentsCount + 1
|
|
1034
|
+
await comment.destroy(); // commentsCount - 1
|
|
1035
|
+
```
|
|
1036
|
+
|
|
1037
|
+
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.
|
|
1038
|
+
|
|
1039
|
+
:::tip
|
|
1040
|
+
Each change is written in the same atomic batch as the comment, so the count can’t drift from the rows.
|
|
1041
|
+
:::
|
|
1042
|
+
|
|
1043
|
+
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.
|
|
1044
|
+
|
|
1045
|
+
:::note
|
|
1046
|
+
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.
|
|
1047
|
+
:::
|
|
1048
|
+
|
|
1049
|
+
### Reading the count
|
|
1050
|
+
|
|
1051
|
+
`size()`, `isEmpty()`, and `hasAny()` on the association read the count, without a query:
|
|
1052
|
+
|
|
1053
|
+
```ts
|
|
1054
|
+
await article.comments().create({ body: "Hello" });
|
|
1055
|
+
const count = await article.comments().size(); // reads commentsCount, no query
|
|
1056
|
+
```
|
|
1057
|
+
|
|
1058
|
+
An association reads the counter named for it: `comments` reads `commentsCount`. If its counter has another name, name it on the `hasMany` too:
|
|
1059
|
+
|
|
1060
|
+
```ts
|
|
1061
|
+
import { belongsTo, hasMany, Model } from "@forestfuture/active-record";
|
|
1062
|
+
|
|
1063
|
+
export class Forum extends Model.define({
|
|
1064
|
+
id: { type: "integer", null: false },
|
|
1065
|
+
replyCount: { type: "integer", null: false },
|
|
1066
|
+
}) {
|
|
1067
|
+
replies = hasMany(Reply, { counterCache: "replyCount" }); // not repliesCount
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
export class Reply extends Model.define({
|
|
1071
|
+
id: { type: "integer", null: false },
|
|
1072
|
+
forumId: "integer",
|
|
1073
|
+
}) {
|
|
1074
|
+
forum = belongsTo(Forum, { counterCache: "replyCount" });
|
|
1075
|
+
}
|
|
1076
|
+
```
|
|
1077
|
+
|
|
1078
|
+
An association with any other name counts its rows, so one narrowed by a scope counts only its own records.
|
|
1079
|
+
|
|
1080
|
+
:::note
|
|
1081
|
+
`count()` always counts the rows.
|
|
1082
|
+
:::
|
|
1083
|
+
|
|
1084
|
+
### Resetting a count
|
|
1085
|
+
|
|
1086
|
+
To set a count from the rows, after a bulk write for example, use `resetCounters`:
|
|
1087
|
+
|
|
1088
|
+
```ts
|
|
1089
|
+
await Article.resetCounters(id, "comments", { touch: true });
|
|
1090
|
+
```
|
|
1091
|
+
|
|
1092
|
+
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.
|
|
1093
|
+
|
|
1094
|
+
### Adding a counter to existing records
|
|
1095
|
+
|
|
1096
|
+
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`:
|
|
1097
|
+
|
|
1098
|
+
```ts
|
|
1099
|
+
import { belongsTo, Model } from "@forestfuture/active-record";
|
|
1100
|
+
|
|
1101
|
+
export class ImportedComment extends Model.define({
|
|
1102
|
+
id: { type: "integer", null: false },
|
|
1103
|
+
articleId: "integer",
|
|
1104
|
+
}) {
|
|
1105
|
+
static table = "comments";
|
|
1106
|
+
// Writes keep commentsCount, but nothing reads it until active: false goes.
|
|
1107
|
+
article = belongsTo(Article, { counterCache: { attribute: "commentsCount", active: false } });
|
|
1108
|
+
}
|
|
1109
|
+
```
|
|
1110
|
+
|
|
1111
|
+
Writes keep the count up to date, while `size()` and the others count the rows. Run `resetCounters` for each article, then remove `active: false`.
|
|
1112
|
+
|
|
1113
|
+
> **Compared with Rails**
|
|
1114
|
+
>
|
|
1115
|
+
> 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.
|
|
1116
|
+
>
|
|
1117
|
+
> `counterCache` names an attribute, where Rails’ `counter_cache` names a column. Rails also makes the counter read-only. Here it’s an ordinary attribute.
|
|
1118
|
+
>
|
|
1119
|
+
> In Rails, removing records through a scoped association leaves the count too high, and `reset_counters` on one writes the scope’s count into the counter. Here the removal counts its records out, and `resetCounters` refuses the scoped association.
|
|
1120
|
+
>
|
|
1121
|
+
> Rails counts a comment twice when two `belongs_to`s keep the same counter. Here that throws `InvalidModel`.
|
|
1122
|
+
>
|
|
1123
|
+
> Rails’ `belongs_to … touch: true` also touches the article when its count changes. That option isn’t built yet ([#353](https://github.com/forestfuture/active-record/issues/353)).
|
|
1124
|
+
|
|
670
1125
|
## Writing many rows
|
|
671
1126
|
|
|
672
|
-
`insert`, `updateAll`, and `deleteAll` work through a `hasMany`, scoped to the owner’s records
|
|
1127
|
+
`insert`, `updateAll`, and `deleteAll` work through a `hasMany`, scoped to the owner’s records:
|
|
673
1128
|
|
|
674
1129
|
```ts
|
|
675
1130
|
await article.comments().deleteAll(); // one DELETE for the article's comments
|
|
676
1131
|
```
|
|
677
1132
|
|
|
1133
|
+
In a batch, pass the association to the write: `b.deleteAll(article.comments())`.
|
|
1134
|
+
|
|
1135
|
+
`upsert` and `upsertAll` through a `hasMany` only update the owner’s records. When a row clashes with another owner’s record, that record stays as it is. The row isn’t written, counted, or returned. To find out whether a row was skipped, compare `rowsAffected` with the number of rows you gave.
|
|
1136
|
+
|
|
1137
|
+
> **Beyond Rails**
|
|
1138
|
+
>
|
|
1139
|
+
> In Rails, `upsert_all` through an association writes the owner’s key into a clashing row. So `current_user.posts.upsert_all(rows)`, given an id from a request, moves another user’s post to the current user. Here that row is skipped, as `onDuplicate: "skip"` skips a duplicate.
|
|
1140
|
+
|
|
678
1141
|
`deleteAll()` on the association follows its `dependent` strategy: it deletes the records for `"destroy"` or `"deleteAll"`, and otherwise sets their foreign keys to `NULL`. See [Bulk writes and batches](/batches).
|
|
679
1142
|
|
|
680
1143
|
## Not built yet
|
|
681
1144
|
|
|
682
1145
|
These features aren’t in Active Record yet. The code shows the shape they’re likely to take.
|
|
683
1146
|
|
|
684
|
-
- **
|
|
685
|
-
- **
|
|
686
|
-
- **
|
|
1147
|
+
- **Autosaving through an association through another** ([#450](https://github.com/forestfuture/active-record/issues/450)): `articles = hasMany(Article, { through: "taggings", autosave: true })`, which saves the tag’s changed articles with it.
|
|
1148
|
+
- **Associations through another across databases** ([#435](https://github.com/forestfuture/active-record/issues/435)): an association whose hops are on different databases, read with a query per database.
|
|
1149
|
+
- **Never autosaving** ([#378](https://github.com/forestfuture/active-record/issues/378)): `articles = hasMany(Article, { autosave: false })`, which never saves the association’s records with the owner, not even new ones.
|
|
1150
|
+
- **Numbered autosave errors** ([#379](https://github.com/forestfuture/active-record/issues/379)): `hasMany(Article, { autosave: true, indexErrors: true })`, which names a copied error by the record’s position, `articles[1].title`.
|
|
687
1151
|
- **Inverse associations** ([#62](https://github.com/forestfuture/active-record/issues/62)): after `await post.comments().toArray()`, each `comment.post()` returns that same post, without a query.
|
|
688
1152
|
|
|
689
1153
|
---
|
|
@@ -712,11 +1176,16 @@ console.log(deleted, rowsAffected, rows[0]?.id); // the new comment's key
|
|
|
712
1176
|
|
|
713
1177
|
- **`updateAll(changes)`** takes attributes or an `sql` fragment, and resolves to the number of rows updated. It leaves `updatedAt` alone. With a `limit` or `offset`, the Relation’s order picks which rows are written.
|
|
714
1178
|
- **`deleteAll()`** resolves to the number of rows deleted. On `none()`, both send nothing and resolve to `0`.
|
|
715
|
-
- **`
|
|
1179
|
+
- **`deleteBy(conditions)`** is `where(conditions).deleteAll()`. **`Comment.delete(id)`** deletes by primary key, and takes an array of keys too. Both resolve to the number of rows deleted.
|
|
1180
|
+
- **`insert(attrs)`** writes one row. It resolves to `{ rowsAffected, rows }`, and `rows` holds the new row’s primary key. Declared defaults and timestamps fill what isn’t given. A Relation’s equality conditions are written over what is given. So `Post.where({ userId: 1 }).insert({ title: "Hi", userId: 2 })` writes `userId: 1`.
|
|
1181
|
+
|
|
1182
|
+
:::note
|
|
1183
|
+
To run each record’s callbacks, destroy the records with [`destroyAll`](/persistence#destroying-many-records) instead.
|
|
1184
|
+
:::
|
|
716
1185
|
|
|
717
1186
|
### Inserting many rows
|
|
718
1187
|
|
|
719
|
-
Insert many rows
|
|
1188
|
+
Insert many rows at once with `insertAll`:
|
|
720
1189
|
|
|
721
1190
|
```ts
|
|
722
1191
|
import { Author, Comment } from "./models";
|
|
@@ -729,9 +1198,11 @@ await Author.upsert({ id: "author-1", name: "Ada" }); // insert, or update the n
|
|
|
729
1198
|
await Author.insert({ id: "author-1", name: "Ada" }, { onDuplicate: "skip" });
|
|
730
1199
|
```
|
|
731
1200
|
|
|
732
|
-
- **`insertAll(rows)`** inserts every row, however many
|
|
1201
|
+
- **`insertAll(rows)`** inserts every row, however many. Every row must have the same attributes. A duplicate throws and writes nothing.
|
|
733
1202
|
- **`{ 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`.
|
|
1203
|
+
- **`upsert(attrs)`** and **`upsertAll(rows)`** update a row that clashes with the primary key, or with the unique index named by `uniqueBy`. The attributes you give are updated. So are the values a Relation adds to each row, from its equality conditions, its default scope, and `createWith`. Defaults filled in for you aren’t updated. `updatedAt` is set.
|
|
1204
|
+
- **Through a Relation**, `insertAll`, `upsert`, and `upsertAll` write its equality conditions over each row’s values, as `insert` does.
|
|
1205
|
+
- **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
1206
|
|
|
736
1207
|
### Returning attributes
|
|
737
1208
|
|
|
@@ -757,37 +1228,44 @@ await Comment.insert({ articleId, body: "Three" }, { returning: false });
|
|
|
757
1228
|
|
|
758
1229
|
> **Compared with Rails**
|
|
759
1230
|
>
|
|
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
|
|
1231
|
+
> 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
1232
|
|
|
762
1233
|
## Batching writes
|
|
763
1234
|
|
|
764
|
-
|
|
1235
|
+
Prepare several writes in `batch`’s callback to write them atomically:
|
|
765
1236
|
|
|
766
1237
|
```ts
|
|
767
1238
|
import { batch } from "@forestfuture/active-record";
|
|
768
1239
|
import { Article, Author } from "./models";
|
|
769
1240
|
|
|
770
1241
|
const authorId = crypto.randomUUID(); // generated in code, so rows can point at it
|
|
771
|
-
await batch([
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
Article.where({ authorId: "author-1" })
|
|
1242
|
+
await batch((b) => [
|
|
1243
|
+
b.insert(Author, { id: authorId, name: "Grace" }),
|
|
1244
|
+
b.insert(Article, { authorId, title: "Hello" }),
|
|
1245
|
+
b.deleteAll(Article.where({ authorId: "author-1" })),
|
|
775
1246
|
]);
|
|
776
1247
|
```
|
|
777
1248
|
|
|
778
|
-
|
|
1249
|
+
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()`.
|
|
1250
|
+
|
|
1251
|
+
`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
1252
|
|
|
780
1253
|
- **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
|
|
1254
|
+
- **Errors:** a write that can’t be prepared, such as one with an unknown attribute, rejects the batch before anything is sent.
|
|
1255
|
+
- **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`.
|
|
1256
|
+
- **Relations in `db.batch`:** `Article.where(…)` uses the current database. Build it with `db.model(Article).where(…)` to write on `db`.
|
|
783
1257
|
|
|
784
1258
|
:::note
|
|
785
|
-
D1 can’t keep a transaction open across `await`s, so
|
|
1259
|
+
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
1260
|
:::
|
|
787
1261
|
|
|
1262
|
+
> **Compared with Rails**
|
|
1263
|
+
>
|
|
1264
|
+
> 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.
|
|
1265
|
+
|
|
788
1266
|
## Batching records
|
|
789
1267
|
|
|
790
|
-
Add a record’s save or destroy to a batch with `
|
|
1268
|
+
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
1269
|
|
|
792
1270
|
```ts
|
|
793
1271
|
import { batch } from "@forestfuture/active-record";
|
|
@@ -798,35 +1276,44 @@ article.title = "Final";
|
|
|
798
1276
|
const author = Author.build({ name: "Hedy" });
|
|
799
1277
|
const old = await Author.find(oldAuthorId);
|
|
800
1278
|
|
|
801
|
-
const [savedArticle, savedAuthor] = await batch([
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
Comment.where({ articleId })
|
|
1279
|
+
const [savedArticle, savedAuthor] = await batch((b) => [
|
|
1280
|
+
b.save(article),
|
|
1281
|
+
b.save(author),
|
|
1282
|
+
b.destroy(old), // with its dependents
|
|
1283
|
+
b.deleteAll(Comment.where({ articleId })),
|
|
806
1284
|
]);
|
|
807
1285
|
```
|
|
808
1286
|
|
|
809
1287
|
When the batch runs:
|
|
810
1288
|
|
|
811
1289
|
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,
|
|
1290
|
+
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
1291
|
3. Each record takes its saved state, then its after-callbacks run.
|
|
1292
|
+
4. Every record’s [commit callbacks](/callbacks#running-code-after-the-commit) run, in the same order.
|
|
814
1293
|
|
|
815
1294
|
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
1295
|
|
|
1296
|
+
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`:
|
|
1297
|
+
|
|
1298
|
+
```ts
|
|
1299
|
+
import { batch } from "@forestfuture/active-record";
|
|
1300
|
+
|
|
1301
|
+
await batch((b) => [b.save(member, { context: "signup" })]);
|
|
1302
|
+
```
|
|
1303
|
+
|
|
817
1304
|
> **Compared with Rails**
|
|
818
1305
|
>
|
|
819
1306
|
> 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
1307
|
|
|
821
|
-
|
|
1308
|
+
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
1309
|
|
|
823
1310
|
```ts
|
|
824
1311
|
import { batch } from "@forestfuture/active-record";
|
|
825
1312
|
import { Post } from "./models";
|
|
826
1313
|
|
|
827
|
-
await batch([
|
|
828
|
-
Post.where({ publishedAt: null })
|
|
829
|
-
|
|
1314
|
+
await batch((b) => [
|
|
1315
|
+
b.updateAll(Post.where({ publishedAt: null }), { publishedAt: new Date() }),
|
|
1316
|
+
b.destroy(user), // and the user's posts, since posts are dependent: "destroy"
|
|
830
1317
|
]);
|
|
831
1318
|
```
|
|
832
1319
|
|
|
@@ -873,28 +1360,47 @@ export class Order extends Model.define({
|
|
|
873
1360
|
|
|
874
1361
|
Callbacks of one kind run in the order declared. A subclass runs its parent’s callbacks, then its own.
|
|
875
1362
|
|
|
1363
|
+
To run a validation callback only in some [validation contexts](/validations#validating-only-when-creating-or-updating), pass `on` to `beforeValidation` or `afterValidation`:
|
|
1364
|
+
|
|
1365
|
+
```ts
|
|
1366
|
+
this.beforeValidation(
|
|
1367
|
+
(order) => {
|
|
1368
|
+
order.placedAt = new Date();
|
|
1369
|
+
},
|
|
1370
|
+
{ on: "create" },
|
|
1371
|
+
);
|
|
1372
|
+
```
|
|
1373
|
+
|
|
876
1374
|
:::note
|
|
877
1375
|
Once a Model has been used, registering another callback throws `InvalidModel`, so request code can’t add one that leaks into later requests.
|
|
878
1376
|
:::
|
|
879
1377
|
|
|
880
1378
|
## Callback order
|
|
881
1379
|
|
|
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
|
-
|
|
|
1380
|
+
| Order | Callback | Runs | `abort()` |
|
|
1381
|
+
| -------------- | -------------------- | -------------------------------------------------------- | --------------------------------- |
|
|
1382
|
+
| **Saving** | | | |
|
|
1383
|
+
| 1 | `beforeValidation` | Before the validators, on every save, and on `isValid()` | Stops the save |
|
|
1384
|
+
| 2 | `afterValidation` | After the validators | Stops the save |
|
|
1385
|
+
| 3 | `beforeSave` | Before every write, new or persisted | Stops the save |
|
|
1386
|
+
| 4 | `beforeCreate` | Before inserting a new record | Stops the save |
|
|
1387
|
+
| 4 | `beforeUpdate` | Before updating a persisted record | Stops the save |
|
|
1388
|
+
| | _The write to D1_ | Skipped when a persisted record has no changes | |
|
|
1389
|
+
| 5 | `afterCreate` | After inserting a new record | Too late: `AbortAfterPersistence` |
|
|
1390
|
+
| 5 | `afterUpdate` | After updating a persisted record | Too late: `AbortAfterPersistence` |
|
|
1391
|
+
| 6 | `afterSave` | After every successful save | Too late: `AbortAfterPersistence` |
|
|
1392
|
+
| 7 | `afterCommit` | Last, after every after-callback | Too late: `AbortAfterPersistence` |
|
|
1393
|
+
| 7 | `afterCreateCommit` | Last, after inserting a new record | Too late: `AbortAfterPersistence` |
|
|
1394
|
+
| 7 | `afterUpdateCommit` | Last, after updating a persisted record | Too late: `AbortAfterPersistence` |
|
|
1395
|
+
| 7 | `afterSaveCommit` | Last, after every successful save | Too late: `AbortAfterPersistence` |
|
|
1396
|
+
| **Destroying** | | | |
|
|
1397
|
+
| 1 | `beforeDestroy` | Before the `dependent` strategies and the DELETE | Stops the destroy |
|
|
1398
|
+
| | _The delete in D1_ | With the dependents, in one batch | |
|
|
1399
|
+
| 2 | `afterDestroy` | After the record is destroyed | Too late: `AbortAfterPersistence` |
|
|
1400
|
+
| 3 | `afterCommit` | Last, after every after-callback | Too late: `AbortAfterPersistence` |
|
|
1401
|
+
| 3 | `afterDestroyCommit` | Last, after the record is destroyed | Too late: `AbortAfterPersistence` |
|
|
1402
|
+
| **Refused** | | | |
|
|
1403
|
+
| 1 | `afterRollback` | When the database refuses the save or destroy | Nothing to stop |
|
|
898
1404
|
|
|
899
1405
|
A save runs either the create pair or the update pair, never both.
|
|
900
1406
|
|
|
@@ -903,7 +1409,45 @@ A save runs either the create pair or the update pair, never both.
|
|
|
903
1409
|
- **An after-callback that changes an attribute** leaves the record dirty. Nothing is written again.
|
|
904
1410
|
|
|
905
1411
|
:::warning[Nothing is rolled back]
|
|
906
|
-
|
|
1412
|
+
The database has kept a save’s writes before any after-callback runs. An error thrown by an after-callback or a commit callback reaches the caller, but the record stays saved. The callbacks after it don’t run. In a batch, that includes the other records’ callbacks.
|
|
1413
|
+
:::
|
|
1414
|
+
|
|
1415
|
+
## Running code after the commit
|
|
1416
|
+
|
|
1417
|
+
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:
|
|
1418
|
+
|
|
1419
|
+
```ts
|
|
1420
|
+
this.afterCreateCommit(async (user) => {
|
|
1421
|
+
await sendWelcomeEmail(user.email);
|
|
1422
|
+
});
|
|
1423
|
+
```
|
|
1424
|
+
|
|
1425
|
+
- **`afterCommit`** runs after a create, an update, or a destroy.
|
|
1426
|
+
- **`afterCreateCommit`**, **`afterUpdateCommit`**, and **`afterDestroyCommit`** run after one kind of write. **`afterSaveCommit`** runs after a create or an update.
|
|
1427
|
+
- **Commit callbacks of every kind** run in the order you declared them.
|
|
1428
|
+
|
|
1429
|
+
:::note
|
|
1430
|
+
Destroying a record that was never saved runs no commit callback, since there was no row to delete.
|
|
1431
|
+
:::
|
|
1432
|
+
|
|
1433
|
+
## Handling a refused write
|
|
1434
|
+
|
|
1435
|
+
`afterRollback` runs when the database refuses a record’s save or destroy:
|
|
1436
|
+
|
|
1437
|
+
```ts
|
|
1438
|
+
this.afterRollback((order) => {
|
|
1439
|
+
console.warn(`Order ${order.id} wasn’t saved`);
|
|
1440
|
+
});
|
|
1441
|
+
```
|
|
1442
|
+
|
|
1443
|
+
- **A constraint error** refuses the record’s write, and the save then throws the [constraint error](/errors#constraint-errors).
|
|
1444
|
+
- **In a batch**, one refused write refuses them all, so `afterRollback` runs for every record in it.
|
|
1445
|
+
- **A failed validation or an `abort()`** sends nothing, so `afterRollback` doesn’t run.
|
|
1446
|
+
|
|
1447
|
+
The record keeps its unsaved state, and no after-callback or commit callback runs for it.
|
|
1448
|
+
|
|
1449
|
+
:::note
|
|
1450
|
+
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
1451
|
:::
|
|
908
1452
|
|
|
909
1453
|
## Stopping a save
|
|
@@ -935,11 +1479,12 @@ These callbacks aren’t in Active Record yet. The code shows the shape they’r
|
|
|
935
1479
|
- **Around callbacks** ([#48](https://github.com/forestfuture/active-record/issues/48)): `this.aroundSave(async (record, proceed) => { …; await proceed(); … })`, and `aroundCreate`, `aroundUpdate`, and `aroundDestroy`.
|
|
936
1480
|
- **`afterInitialize` and `afterFind`** ([#49](https://github.com/forestfuture/active-record/issues/49)): for every record built or loaded, and every record loaded.
|
|
937
1481
|
- **`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
1482
|
|
|
940
1483
|
> **Compared with Rails**
|
|
941
1484
|
>
|
|
942
|
-
>
|
|
1485
|
+
> `after_commit` and its `on:` forms are `afterCommit`, `afterCreateCommit`, `afterUpdateCommit`, `afterSaveCommit`, and `afterDestroyCommit`, run in the order declared, as Rails 7.1 runs them. In Rails, `after_save` runs before the save’s transaction commits. Here, the database has already kept the write before any after-callback runs, so every after-callback is already “after commit”. An error in `afterSave` rolls a Rails save back; here the record stays saved, and its commit callbacks don’t run.
|
|
1486
|
+
>
|
|
1487
|
+
> `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
1488
|
>
|
|
944
1489
|
> Rails’ `if:` and `unless:` options for callbacks aren’t needed: write the condition inside the callback.
|
|
945
1490
|
|
|
@@ -1064,7 +1609,10 @@ Most names are Rails’ own, in camelCase:
|
|
|
1064
1609
|
| `foreign_key: :user_id` | `foreignKey: "userId"` |
|
|
1065
1610
|
| `save!`, `create!`, `find_by!` | `saveOrThrow`, `createOrThrow`, `findByOrThrow` |
|
|
1066
1611
|
| `new_record?`, `persisted?` | `isNewRecord()`, `isPersisted()` |
|
|
1612
|
+
| `find_or_create_by(name:) do … end` | `findOrCreateBy({ name }, (tag) => …)` |
|
|
1067
1613
|
| `empty?`, `any?` | `isEmpty()`, `hasAny()` |
|
|
1614
|
+
| `many?`, `one?` | `hasMoreThanOne()`, `hasExactlyOne()` |
|
|
1615
|
+
| `unscope(:order, where: :role)` | `unscope("order", { where: "role" })` |
|
|
1068
1616
|
| `changed?`, `saved_change_to_email?` | `isChanged()`, `hasSavedChangeTo("email")` |
|
|
1069
1617
|
| `rails generate model Post title:string` | `npx active-record g model Post title:string` |
|
|
1070
1618
|
| `db/schema.rb`, `rails db:schema:dump` | `src/db/schema.ts`, `npx active-record schema` |
|
|
@@ -1073,6 +1621,7 @@ Most names are Rails’ own, in camelCase:
|
|
|
1073
1621
|
| `has_many :posts, dependent: :destroy` | `posts = hasMany(Post, { dependent: "destroy" })` |
|
|
1074
1622
|
| `post.author = user` | `post.author.set(user)` |
|
|
1075
1623
|
| `build_profile` | `user.profile.build()` |
|
|
1624
|
+
| `user.profile = profile` | `await user.profile.set(profile)` |
|
|
1076
1625
|
| `reload_author` | `post.reloadAssociation("author")` |
|
|
1077
1626
|
| `throw :abort` | `throw abort("reason")` |
|
|
1078
1627
|
| `to_json` | `toJSON()` |
|
|
@@ -1105,7 +1654,7 @@ export class Product extends ApplicationRecord {
|
|
|
1105
1654
|
|
|
1106
1655
|
## Writing atomically
|
|
1107
1656
|
|
|
1108
|
-
There’s no `transaction do … end`, since D1 can’t keep a transaction open across awaits.
|
|
1657
|
+
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
1658
|
|
|
1110
1659
|
## Primary keys
|
|
1111
1660
|
|
|
@@ -1122,6 +1671,9 @@ The generators follow `rails generate model` and `rails generate migration`. A c
|
|
|
1122
1671
|
- `insert` and `insertAll` raise on duplicates. Skipping them is opt-in, with `{ onDuplicate: "skip" }`.
|
|
1123
1672
|
- `insert` fills in declared defaults, since that’s where keys are generated.
|
|
1124
1673
|
- `merge` replaces the order rather than appending to it.
|
|
1674
|
+
- `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.
|
|
1675
|
+
- `find(1, 2)` on a `hasMany` join returns each record once.
|
|
1676
|
+
- `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
1677
|
- `last()` can’t reverse an `sql` fragment order, and throws `IrreversibleOrder`, rather than trying to parse SQL.
|
|
1126
1678
|
- `find(1, 1)` always returns an array, so its return type follows its arguments.
|
|
1127
1679
|
- `dependent:` strategies run after the owner’s `beforeDestroy` callbacks, wherever they’re declared, so an `abort()` always protects the records.
|
|
@@ -1130,7 +1682,7 @@ The generators follow `rails generate model` and `rails generate migration`. A c
|
|
|
1130
1682
|
|
|
1131
1683
|
## Not built yet
|
|
1132
1684
|
|
|
1133
|
-
|
|
1685
|
+
`has_many :through`, `where` keyed by an association, `where.missing`, `eager_load`, single-table inheritance, `destroy_async`, and error messages in other languages.
|
|
1134
1686
|
|
|
1135
1687
|
---
|
|
1136
1688
|
|
|
@@ -1163,10 +1715,12 @@ Run it again after you add a database to your Wrangler config. It adds each data
|
|
|
1163
1715
|
Added LOGS to active-record.jsonc (on d1)
|
|
1164
1716
|
```
|
|
1165
1717
|
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
|
1169
|
-
|
|
|
1718
|
+
It adds only databases on the adapters the file already uses. To add another adapter’s databases, name it with `--adapter`.
|
|
1719
|
+
|
|
1720
|
+
| Option | |
|
|
1721
|
+
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1722
|
+
| `--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. |
|
|
1723
|
+
| `--config <file>` | Write this file, in place of `active-record.jsonc`. |
|
|
1170
1724
|
|
|
1171
1725
|
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
1726
|
|
|
@@ -1183,9 +1737,23 @@ With `--adapter postgresql` and no Hyperdrive binding, it writes a `DATABASE_URL
|
|
|
1183
1737
|
}
|
|
1184
1738
|
```
|
|
1185
1739
|
|
|
1186
|
-
Your generated schema names each database by its binding. The `$schema` line lets your editor complete and check the file.
|
|
1740
|
+
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.
|
|
1741
|
+
|
|
1742
|
+
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.
|
|
1743
|
+
|
|
1744
|
+
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`:
|
|
1745
|
+
|
|
1746
|
+
```jsonc
|
|
1747
|
+
{
|
|
1748
|
+
"databases": {
|
|
1749
|
+
"DB": { "adapter": "d1", "wranglerConfig": "../worker/wrangler.jsonc" },
|
|
1750
|
+
},
|
|
1751
|
+
}
|
|
1752
|
+
```
|
|
1753
|
+
|
|
1754
|
+
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
1755
|
|
|
1188
|
-
On
|
|
1756
|
+
On Postgres, the file holds a database’s settings:
|
|
1189
1757
|
|
|
1190
1758
|
```jsonc
|
|
1191
1759
|
{
|
|
@@ -1318,18 +1886,20 @@ On D1, each column becomes an attribute by the first of these that applies:
|
|
|
1318
1886
|
1. **An override in the Model:** `static override attributes = { available: "boolean" } as const`.
|
|
1319
1887
|
2. **The column’s declared type:**
|
|
1320
1888
|
|
|
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
|
-
|
|
|
1889
|
+
| Declared as | Attribute |
|
|
1890
|
+
| --------------------------------------------------- | ------------------------------------------------ |
|
|
1891
|
+
| `INTEGER`, `INT`, `BIGINT`, … (anything with `INT`) | `integer` |
|
|
1892
|
+
| `TEXT`, `VARCHAR(…)`, `CHAR(…)`, `CLOB` | `string` |
|
|
1893
|
+
| `REAL`, `FLOAT`, `DOUBLE` | `real` |
|
|
1894
|
+
| `NUMERIC`, `DECIMAL` | `decimal`, with a size’s `precision` and `scale` |
|
|
1895
|
+
| `BOOLEAN` | `boolean` |
|
|
1896
|
+
| `DATETIME`, `TIMESTAMP` | `datetime` |
|
|
1897
|
+
| `DATE` | `date` |
|
|
1898
|
+
| `TIME` | `time` |
|
|
1899
|
+
| `TEXT` with `CHECK (json_valid(column))` | `json` |
|
|
1900
|
+
| `JSON` | `json` |
|
|
1901
|
+
| `BLOB` | `binary` |
|
|
1902
|
+
| anything else | `string` |
|
|
1333
1903
|
|
|
1334
1904
|
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
1905
|
|
|
@@ -1338,8 +1908,9 @@ Also:
|
|
|
1338
1908
|
- **Names:** `price_cents` becomes `priceCents`. A column whose name doesn’t come back the same from camelCase gets `column: "…"`.
|
|
1339
1909
|
- **`NOT NULL`** becomes `null: false`. A primary key is never null.
|
|
1340
1910
|
- **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.
|
|
1911
|
+
- **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
1912
|
- **Foreign keys** take the referenced column’s type. They don’t create associations, which are behavior you declare.
|
|
1913
|
+
- **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
1914
|
- **Left out:** SQLite’s own tables, Cloudflare’s (`_cf_…`), the migrations table, and virtual tables.
|
|
1344
1915
|
|
|
1345
1916
|
**Notes it prints** when the schema is written:
|
|
@@ -1354,19 +1925,23 @@ Also:
|
|
|
1354
1925
|
|
|
1355
1926
|
On Postgres, an override in the Model still comes first. Otherwise each column’s type decides, since Postgres’s types are real:
|
|
1356
1927
|
|
|
1357
|
-
| Type
|
|
1358
|
-
|
|
|
1359
|
-
| `smallint`, `integer`, `bigint`
|
|
1360
|
-
| `real`, `double precision`
|
|
1361
|
-
| `
|
|
1362
|
-
| `
|
|
1363
|
-
| `
|
|
1364
|
-
| `
|
|
1365
|
-
| `
|
|
1366
|
-
| `
|
|
1367
|
-
|
|
|
1368
|
-
|
|
1369
|
-
|
|
1928
|
+
| Type | Attribute |
|
|
1929
|
+
| -------------------------------------------- | ---------------------------------------------- |
|
|
1930
|
+
| `smallint`, `integer`, `bigint` | `integer` |
|
|
1931
|
+
| `real`, `double precision` | `real` |
|
|
1932
|
+
| `numeric` | `decimal`, with its `precision` and `scale` |
|
|
1933
|
+
| `boolean` | `boolean` |
|
|
1934
|
+
| `timestamptz`, `timestamp` | `datetime` |
|
|
1935
|
+
| `date` | `date` |
|
|
1936
|
+
| `time` | `time` |
|
|
1937
|
+
| `json`, `jsonb` | `json` |
|
|
1938
|
+
| `bytea` | `binary` |
|
|
1939
|
+
| `text`, `varchar`, `char`, `citext`, `uuid` | `string` |
|
|
1940
|
+
| an enum type | `string`, with the enum’s labels as its `enum` |
|
|
1941
|
+
| an array | An error: not supported |
|
|
1942
|
+
| anything else (`inet`, `interval`, `timetz`) | `string`, with a note |
|
|
1943
|
+
|
|
1944
|
+
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
1945
|
|
|
1371
1946
|
**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
1947
|
|
|
@@ -1405,9 +1980,13 @@ npx active-record g migration <Name> [columns] [options]
|
|
|
1405
1980
|
| `string` (the default) | `TEXT` | `TEXT` |
|
|
1406
1981
|
| `integer` | `INTEGER` | `BIGINT` |
|
|
1407
1982
|
| `real` | `REAL` | `DOUBLE PRECISION` |
|
|
1983
|
+
| `decimal` | `DECIMAL` | `NUMERIC` |
|
|
1408
1984
|
| `boolean` | `BOOLEAN` | `BOOLEAN` |
|
|
1409
1985
|
| `datetime` | `DATETIME` | `TIMESTAMPTZ` |
|
|
1986
|
+
| `date` | `DATE` | `DATE` |
|
|
1987
|
+
| `time` | `TIME` | `TIME` |
|
|
1410
1988
|
| `json` | `TEXT CHECK (json_valid(column))` | `JSONB` |
|
|
1989
|
+
| `binary` | `BLOB` | `BYTEA` |
|
|
1411
1990
|
|
|
1412
1991
|
A `references` column is `<name>_id`, typed like the referenced table’s key, with `REFERENCES <plural> (id)` and an index.
|
|
1413
1992
|
|
|
@@ -1421,7 +2000,8 @@ The key `g model` writes:
|
|
|
1421
2000
|
Timestamps are `created_at` and `updated_at`, `NOT NULL`, as `DATETIME` on D1 and `TIMESTAMPTZ` on Postgres.
|
|
1422
2001
|
|
|
1423
2002
|
- **`!`** 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`,
|
|
2003
|
+
- **`=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`).
|
|
2004
|
+
- **`{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
2005
|
- **`:unique`** adds a unique index, and **`:index`** an index, named like `index_products_on_sku`.
|
|
1426
2006
|
- **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
2007
|
|
|
@@ -1551,7 +2131,7 @@ const posts = await models.Post.where({ userId: user.id }).toArray();
|
|
|
1551
2131
|
|
|
1552
2132
|
## Batching writes
|
|
1553
2133
|
|
|
1554
|
-
`batch`
|
|
2134
|
+
`batch` saves and destroys records and runs bulk writes atomically:
|
|
1555
2135
|
|
|
1556
2136
|
```ts
|
|
1557
2137
|
import { batch } from "@forestfuture/active-record";
|
|
@@ -1561,10 +2141,10 @@ const user = User.build({ email: "grace@example.com" });
|
|
|
1561
2141
|
const post = Post.build({ userId: user.id, title: "Hello" });
|
|
1562
2142
|
|
|
1563
2143
|
// Atomic: all written, or none.
|
|
1564
|
-
await batch([
|
|
2144
|
+
await batch((b) => [b.save(user), b.save(post), b.deleteAll(Post.where({ userId: "old" }))]);
|
|
1565
2145
|
```
|
|
1566
2146
|
|
|
1567
|
-
|
|
2147
|
+
`batch` writes a Model’s rows on the current database. `db.batch` uses an explicit one. See [Bulk writes and batches](/batches).
|
|
1568
2148
|
|
|
1569
2149
|
---
|
|
1570
2150
|
|
|
@@ -1600,7 +2180,7 @@ Leave with `quit`, `exit`, or Ctrl-D. Ctrl-C stops a line that’s still running
|
|
|
1600
2180
|
## What you can use
|
|
1601
2181
|
|
|
1602
2182
|
- **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(
|
|
2183
|
+
- **`db`,** your connected database, for `db.batch(...)` and `db.model(...)`.
|
|
1604
2184
|
- **Top-level `await`,** and `const` and `let`, which last until you leave.
|
|
1605
2185
|
|
|
1606
2186
|
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 +2226,9 @@ The SQL comes from the database’s own `onQuery`, so a listener you set on your
|
|
|
1646
2226
|
|
|
1647
2227
|
| Option | |
|
|
1648
2228
|
| ------------------- | ------------------------------------------------------------------------------------------------------- |
|
|
1649
|
-
| `--database <name>` | The
|
|
2229
|
+
| `--database <name>` | The database to open, when `active-record.jsonc` names several. |
|
|
1650
2230
|
| `--models <path>` | Where your Models are: a folder (`src/models` by default) or one file (`src/models.ts`). |
|
|
1651
|
-
| `--config <file>` | Use this
|
|
2231
|
+
| `--config <file>` | Use this config file, in place of `active-record.jsonc`. |
|
|
1652
2232
|
| `--no-history` | Don’t keep what you type in the history file. |
|
|
1653
2233
|
| `--verbose` | Print each statement a line runs, to begin with. `.verbose` turns it on and off. |
|
|
1654
2234
|
| `-e, --eval <code>` | Run this code, print its result, and exit. See [Running one piece of code](#running-one-piece-of-code). |
|
|
@@ -1658,7 +2238,7 @@ The SQL comes from the database’s own `onQuery`, so a listener you set on your
|
|
|
1658
2238
|
|
|
1659
2239
|
## Where your data lives
|
|
1660
2240
|
|
|
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.
|
|
2241
|
+
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
2242
|
|
|
1663
2243
|
It opens your remote database only when you ask with `--remote`, and never for a binding your config marks `remote: true` by itself.
|
|
1664
2244
|
|
|
@@ -1722,49 +2302,189 @@ A token needs **D1: Edit** and **Workers Scripts: Edit**, and the account needs
|
|
|
1722
2302
|
npx active-record console -e 'await User.count()'
|
|
1723
2303
|
```
|
|
1724
2304
|
|
|
1725
|
-
```text
|
|
1726
|
-
42
|
|
2305
|
+
```text
|
|
2306
|
+
42
|
|
2307
|
+
```
|
|
2308
|
+
|
|
2309
|
+
- **The result is on stdout.** A string prints as it is, without quotes, so `$(…)` captures it, and anything else prints as the console prints it, without `#=> `. `undefined` prints nothing. What your code logs with `console.log` comes first, and `console.error` goes to stderr, as in `node -e`.
|
|
2310
|
+
- **Everything else is on stderr:** which database and Models it opened, the SQL with `--verbose`, and a refusal to start.
|
|
2311
|
+
- **A failure exits 1.** Its stack goes to stderr, no result goes to stdout, and no statement after it runs. Success exits 0.
|
|
2312
|
+
- **Join statements with `;`.** The last value is the result: `-e 'await User.create({ name: "Dan" }); await User.count()'`.
|
|
2313
|
+
- **It keeps no history,** ignores what is piped to it, and has no time limit: stop it with Ctrl-C, or run it under `timeout`.
|
|
2314
|
+
|
|
2315
|
+
:::note
|
|
2316
|
+
Await every call. `User.find(1)` without `await` prints `Promise { <pending> }`, and a promise you don’t await may not finish before the console exits, and its failure isn’t reported.
|
|
2317
|
+
:::
|
|
2318
|
+
|
|
2319
|
+
:::note
|
|
2320
|
+
Put the code in single quotes, so your shell leaves `$`, `!`, and backticks alone. With `--remote`, `$(…)` makes stdout a pipe, so there is no terminal to ask: add `--yes`, as in `npx active-record console --remote --yes -e 'await User.count()'`.
|
|
2321
|
+
:::
|
|
2322
|
+
|
|
2323
|
+
## Running a few lines at once
|
|
2324
|
+
|
|
2325
|
+
Lines you paste or pipe run in order, each after the one before, and the console finishes them before it exits:
|
|
2326
|
+
|
|
2327
|
+
```sh
|
|
2328
|
+
echo 'await User.count()' | npx active-record console
|
|
2329
|
+
```
|
|
2330
|
+
|
|
2331
|
+
That prints the same transcript a session does (the database, a prompt before each line, `#=> ` before each result) and exits 0 even when a line fails. For a script that checks the result or the exit code, use `-e`.
|
|
2332
|
+
|
|
2333
|
+
:::note
|
|
2334
|
+
The console reads your TypeScript Models directly, including extensionless imports and `tsconfig.json` paths, so it works in TypeScript projects. It needs Node.js 22.13 or later, and `wrangler` and `@forestfuture/active-record` installed in your project. It uses your copies, so your Models and the console share one library.
|
|
2335
|
+
:::
|
|
2336
|
+
|
|
2337
|
+
:::warning[Only in projects you trust]
|
|
2338
|
+
The console runs your project’s code: your Models, and the `wrangler` and `@forestfuture/active-record` in its `node_modules`. Run it in a project you’d run `wrangler dev` in.
|
|
2339
|
+
:::
|
|
2340
|
+
|
|
2341
|
+
> **Compared with Rails**
|
|
2342
|
+
>
|
|
2343
|
+
> This is `rails console` for D1: your Models in scope, and records printed as `inspect` prints them. `-e` is `rails runner` with the last value printed, which `rails runner` leaves to you.
|
|
2344
|
+
|
|
2345
|
+
> **Beyond Rails**
|
|
2346
|
+
>
|
|
2347
|
+
> `rails console` opens whichever environment you start it in, without asking. `--remote` asks you to type the database’s name first, and its prompt says `remote>`.
|
|
2348
|
+
|
|
2349
|
+
---
|
|
2350
|
+
|
|
2351
|
+
# Custom types
|
|
2352
|
+
Source: https://active-record.forestfuture.dev/custom-types
|
|
2353
|
+
|
|
2354
|
+
A custom type holds a value the built-in types don’t, such as money or a list of sizes. Its values are stored in their column as one of the built-in types.
|
|
2355
|
+
|
|
2356
|
+
## Defining a type
|
|
2357
|
+
|
|
2358
|
+
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:
|
|
2359
|
+
|
|
2360
|
+
```ts
|
|
2361
|
+
import { defineType } from "@forestfuture/active-record";
|
|
2362
|
+
|
|
2363
|
+
export class Money {
|
|
2364
|
+
readonly cents: number;
|
|
2365
|
+
|
|
2366
|
+
constructor(cents: number) {
|
|
2367
|
+
this.cents = cents;
|
|
2368
|
+
}
|
|
2369
|
+
|
|
2370
|
+
toString() {
|
|
2371
|
+
return `$${(this.cents / 100).toFixed(2)}`;
|
|
2372
|
+
}
|
|
2373
|
+
}
|
|
2374
|
+
|
|
2375
|
+
export const money = defineType({
|
|
2376
|
+
storedAs: "integer",
|
|
2377
|
+
cast(input) {
|
|
2378
|
+
if (input instanceof Money) return input;
|
|
2379
|
+
if (Number.isSafeInteger(input)) return new Money(input as number);
|
|
2380
|
+
throw new TypeError("money is a Money or a whole number of cents");
|
|
2381
|
+
},
|
|
2382
|
+
serialize: (value) => value.cents,
|
|
2383
|
+
deserialize: (cents) => new Money(cents),
|
|
2384
|
+
});
|
|
2385
|
+
```
|
|
2386
|
+
|
|
2387
|
+
A type has three functions:
|
|
2388
|
+
|
|
2389
|
+
| Function | Takes | Returns |
|
|
2390
|
+
| ------------- | ---------------------------------- | ---------------------------------- |
|
|
2391
|
+
| `cast` | a value given to the attribute | the type’s value, or throws |
|
|
2392
|
+
| `serialize` | the type’s value | a value of the type it’s stored as |
|
|
2393
|
+
| `deserialize` | a value of the type it’s stored as | the type’s value |
|
|
2394
|
+
|
|
2395
|
+
The attribute’s TypeScript type is what `cast` returns, so `Money` here.
|
|
2396
|
+
|
|
2397
|
+
:::note
|
|
2398
|
+
None of them is called with `null`, which is always NULL.
|
|
2399
|
+
:::
|
|
2400
|
+
|
|
2401
|
+
## Using a type
|
|
2402
|
+
|
|
2403
|
+
Give the type to a generated attribute in `static attributes`:
|
|
2404
|
+
|
|
2405
|
+
```ts
|
|
2406
|
+
import { ApplicationRecord } from "./application-record";
|
|
2407
|
+
|
|
2408
|
+
export class Product extends ApplicationRecord {
|
|
2409
|
+
static override attributes = {
|
|
2410
|
+
priceCents: money,
|
|
2411
|
+
} as const;
|
|
2412
|
+
}
|
|
2413
|
+
```
|
|
2414
|
+
|
|
2415
|
+
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.
|
|
2416
|
+
|
|
2417
|
+
A Model that declares its attributes itself takes the type in place of a type’s name:
|
|
2418
|
+
|
|
2419
|
+
```ts
|
|
2420
|
+
import { Model } from "@forestfuture/active-record";
|
|
2421
|
+
|
|
2422
|
+
export class Invoice extends Model.define({
|
|
2423
|
+
id: { type: "integer", null: false },
|
|
2424
|
+
total: { type: money, null: false },
|
|
2425
|
+
}) {}
|
|
2426
|
+
```
|
|
2427
|
+
|
|
2428
|
+
## Refusing values
|
|
2429
|
+
|
|
2430
|
+
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`:
|
|
2431
|
+
|
|
2432
|
+
```ts
|
|
2433
|
+
import { Product } from "./models/product";
|
|
2434
|
+
|
|
2435
|
+
Product.permit({ priceCents: "abc" }, "priceCents");
|
|
2436
|
+
// TypeError: Product: "abc" isn't a valid value for "priceCents"
|
|
2437
|
+
```
|
|
2438
|
+
|
|
2439
|
+
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.
|
|
2440
|
+
|
|
2441
|
+
## Querying by a type
|
|
2442
|
+
|
|
2443
|
+
Conditions take the type’s values, and anything `cast` takes:
|
|
2444
|
+
|
|
2445
|
+
```ts
|
|
2446
|
+
import { gte } from "@forestfuture/active-record";
|
|
2447
|
+
|
|
2448
|
+
const cheap = await Product.where({ priceCents: new Money(500) }).toArray();
|
|
2449
|
+
const pricey = await Product.where({ priceCents: gte(new Money(10_000)) })
|
|
2450
|
+
.order({ priceCents: "desc" })
|
|
2451
|
+
.toArray();
|
|
1727
2452
|
```
|
|
1728
2453
|
|
|
1729
|
-
|
|
1730
|
-
- **Everything else is on stderr:** which database and Models it opened, the SQL with `--verbose`, and a refusal to start.
|
|
1731
|
-
- **A failure exits 1.** Its stack goes to stderr, no result goes to stdout, and no statement after it runs. Success exits 0.
|
|
1732
|
-
- **Join statements with `;`.** The last value is the result: `-e 'await User.create({ name: "Dan" }); await User.count()'`.
|
|
1733
|
-
- **It keeps no history,** ignores what is piped to it, and has no time limit: stop it with Ctrl-C, or run it under `timeout`.
|
|
1734
|
-
|
|
1735
|
-
:::note
|
|
1736
|
-
Await every call. `User.find(1)` without `await` prints `Promise { <pending> }`, and a promise you don’t await may not finish before the console exits, and its failure isn’t reported.
|
|
1737
|
-
:::
|
|
2454
|
+
Values compare and sort as their stored values do, so money sorts by cents. A value `cast` throws for matches nothing.
|
|
1738
2455
|
|
|
1739
|
-
|
|
1740
|
-
Put the code in single quotes, so your shell leaves `$`, `!`, and backticks alone. With `--remote`, `$(…)` makes stdout a pipe, so there is no terminal to ask: add `--yes`, as in `npx active-record console --remote --yes -e 'await User.count()'`.
|
|
1741
|
-
:::
|
|
2456
|
+
## Changing values in place
|
|
1742
2457
|
|
|
1743
|
-
|
|
2458
|
+
A type can hold a value you change in place. This one keeps a list of sizes as text:
|
|
1744
2459
|
|
|
1745
|
-
|
|
2460
|
+
```ts
|
|
2461
|
+
import { defineType } from "@forestfuture/active-record";
|
|
1746
2462
|
|
|
1747
|
-
|
|
1748
|
-
|
|
2463
|
+
export const sizes = defineType({
|
|
2464
|
+
storedAs: "string",
|
|
2465
|
+
cast(input) {
|
|
2466
|
+
if (Array.isArray(input) && input.every((size) => typeof size === "string")) {
|
|
2467
|
+
return input as string[];
|
|
2468
|
+
}
|
|
2469
|
+
throw new TypeError("sizes are a list of strings");
|
|
2470
|
+
},
|
|
2471
|
+
serialize: (list) => list.join(","),
|
|
2472
|
+
deserialize: (text) => (text === "" ? [] : text.split(",")),
|
|
2473
|
+
});
|
|
1749
2474
|
```
|
|
1750
2475
|
|
|
1751
|
-
|
|
2476
|
+
Changes are found by comparing what `serialize` returns, so a size pushed onto the list is a change, and `save()` writes it:
|
|
1752
2477
|
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
2478
|
+
```ts
|
|
2479
|
+
shirt.sizes.push("XL");
|
|
2480
|
+
shirt.isChanged(); // true
|
|
2481
|
+
```
|
|
1756
2482
|
|
|
1757
|
-
|
|
1758
|
-
The console runs your project’s code: your Models, and the `wrangler` and `@forestfuture/active-record` in its `node_modules`. Run it in a project you’d run `wrangler dev` in.
|
|
1759
|
-
:::
|
|
2483
|
+
An equal value in another object, such as a new `Money` of the same cents, isn’t a change.
|
|
1760
2484
|
|
|
1761
2485
|
> **Compared with Rails**
|
|
1762
2486
|
>
|
|
1763
|
-
>
|
|
1764
|
-
|
|
1765
|
-
> **Beyond Rails**
|
|
1766
|
-
>
|
|
1767
|
-
> `rails console` opens whichever environment you start it in, without asking. `--remote` asks you to type the database’s name first, and its prompt says `remote>`.
|
|
2487
|
+
> 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.
|
|
1768
2488
|
|
|
1769
2489
|
---
|
|
1770
2490
|
|
|
@@ -1789,13 +2509,15 @@ Bind your D1 database in your Wrangler config:
|
|
|
1789
2509
|
|
|
1790
2510
|
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
2511
|
|
|
2512
|
+
If your Wrangler config is in another folder, name it in the database’s entry with [`wranglerConfig`](/command-line#declaring-your-databases).
|
|
2513
|
+
|
|
1792
2514
|
## Reading your own writes
|
|
1793
2515
|
|
|
1794
2516
|
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
2517
|
|
|
1796
2518
|
## Sending queries in one round trip
|
|
1797
2519
|
|
|
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.
|
|
2520
|
+
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
2521
|
|
|
1800
2522
|
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
2523
|
|
|
@@ -1805,29 +2527,31 @@ D1 also differs in these ways.
|
|
|
1805
2527
|
|
|
1806
2528
|
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
2529
|
|
|
1808
|
-
What you can make atomic is a set of writes prepared in advance: [`batch
|
|
2530
|
+
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
2531
|
|
|
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.
|
|
2532
|
+
- A destroy’s [`dependent` strategies](/associations#destroying-dependent-records) on the owner’s database are written in one batch with its DELETE.
|
|
2533
|
+
- 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
2534
|
|
|
1813
2535
|
## Generating keys in code
|
|
1814
2536
|
|
|
1815
2537
|
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
2538
|
|
|
1817
|
-
- A graph of new records built through associations saves in one atomic batch.
|
|
2539
|
+
- A graph of new records built through associations on one database saves in one atomic batch.
|
|
1818
2540
|
- A batch can insert rows that point at each other.
|
|
1819
2541
|
|
|
1820
2542
|
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
2543
|
|
|
1822
2544
|
## Uniqueness is checked twice
|
|
1823
2545
|
|
|
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.
|
|
2546
|
+
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
2547
|
|
|
1826
2548
|
`caseSensitive: false` compares with SQLite’s `lower()`, which only lowercases ASCII letters, so `"Ä"` and `"ä"` are still different.
|
|
1827
2549
|
|
|
1828
2550
|
## Bound parameters
|
|
1829
2551
|
|
|
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.
|
|
2552
|
+
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.
|
|
2553
|
+
|
|
2554
|
+
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
2555
|
|
|
1832
2556
|
## Foreign keys are enforced
|
|
1833
2557
|
|
|
@@ -1837,6 +2561,10 @@ D1 enforces the foreign keys a table declares with `REFERENCES`. Destroying a re
|
|
|
1837
2561
|
|
|
1838
2562
|
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
2563
|
|
|
2564
|
+
## Decimals keep about 15 digits
|
|
2565
|
+
|
|
2566
|
+
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.
|
|
2567
|
+
|
|
1840
2568
|
---
|
|
1841
2569
|
|
|
1842
2570
|
# Errors
|
|
@@ -1856,7 +2584,8 @@ if (error instanceof ActiveRecordError) {
|
|
|
1856
2584
|
|
|
1857
2585
|
| Error | When |
|
|
1858
2586
|
| ----------------------- | ------------------------------------------------------------------------ |
|
|
1859
|
-
| `RecordNotFound` | `find`, `
|
|
2587
|
+
| `RecordNotFound` | `find`, `sole`, an `OrThrow` finder, or `reload` found nothing |
|
|
2588
|
+
| `SoleRecordExceeded` | `sole` or `findSoleBy` found more than one record |
|
|
1860
2589
|
| `RecordInvalid` | an `OrThrow` save found the record invalid; the record is on `.record` |
|
|
1861
2590
|
| `RecordNotSaved` | a save was aborted by a callback, or needs an owner that isn’t saved |
|
|
1862
2591
|
| `RecordNotDestroyed` | a destroy was aborted, or restricted by `restrictWithError` |
|
|
@@ -1875,6 +2604,7 @@ A usage error means the code needs to change:
|
|
|
1875
2604
|
| `MissingAttribute` | reading an attribute that `select` didn’t load |
|
|
1876
2605
|
| `UnknownAssociation` | an association that isn’t declared |
|
|
1877
2606
|
| `AssociationNotLoaded` | `loaded()` on an association that wasn’t loaded |
|
|
2607
|
+
| `UnknownModelName` | a polymorphic association’s stored type that names none of the Models it lists |
|
|
1878
2608
|
| `IncompatibleRelation` | two Relations or writes can’t be used together (below) |
|
|
1879
2609
|
| `IrreversibleOrder` | `last()` on a Relation ordered by an `sql` fragment |
|
|
1880
2610
|
| `DeleteRestriction` | destroying an owner whose `restrictWithException` association still has records |
|
|
@@ -1890,10 +2620,10 @@ A name from a request, such as `?include=` or a JSON key, only ever matches the
|
|
|
1890
2620
|
`IncompatibleRelation` is thrown for combinations that can’t make a correct query or write:
|
|
1891
2621
|
|
|
1892
2622
|
- **`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
|
|
2623
|
+
- **`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
2624
|
- **`includes`** with `select(...).distinct()`. Preloading needs the keys, and adding them would undo the `distinct`.
|
|
1895
2625
|
- **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
|
|
2626
|
+
- **`updateAll` or `deleteAll`** after `distinct()`: they reject with it, and so does a batch preparing them.
|
|
1897
2627
|
|
|
1898
2628
|
## Constraint errors
|
|
1899
2629
|
|
|
@@ -2013,20 +2743,21 @@ SQLite can’t add a required column without a default, so the generator refuses
|
|
|
2013
2743
|
parent_id TEXT REFERENCES categories (id),
|
|
2014
2744
|
```
|
|
2015
2745
|
|
|
2016
|
-
2. In the Model, use `Category` itself, and add the other direction if you want it.
|
|
2746
|
+
2. In the Model, use `Category` itself, make it optional too, and add the other direction if you want it.
|
|
2017
2747
|
|
|
2018
2748
|
```ts
|
|
2019
2749
|
import { belongsTo, hasMany } from "@forestfuture/active-record";
|
|
2020
2750
|
|
|
2021
2751
|
export class Category extends ApplicationRecord {
|
|
2022
|
-
|
|
2752
|
+
// foreign key: parentId, from the association's name; optional, since a top-level category has none
|
|
2753
|
+
parent = belongsTo(Category, { optional: true });
|
|
2023
2754
|
children = hasMany(Category, { foreignKey: "parentId" }); // not the default, categoryId
|
|
2024
2755
|
}
|
|
2025
2756
|
```
|
|
2026
2757
|
|
|
2027
2758
|
> **Compared with Rails**
|
|
2028
2759
|
>
|
|
2029
|
-
> Rails writes `belongs_to :parent, class_name: "Category", optional: true`. Here the association takes the class itself, so there’s no `class_name
|
|
2760
|
+
> 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
2761
|
|
|
2031
2762
|
## Keeping Models in another folder
|
|
2032
2763
|
|
|
@@ -2438,7 +3169,7 @@ export class Base extends Model {
|
|
|
2438
3169
|
}
|
|
2439
3170
|
```
|
|
2440
3171
|
|
|
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.
|
|
3172
|
+
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
3173
|
|
|
2443
3174
|
### Seeing a filtered attribute
|
|
2444
3175
|
|
|
@@ -2471,200 +3202,458 @@ A Model describes one table. Its attributes come from your migrations, through t
|
|
|
2471
3202
|
|
|
2472
3203
|
## Defining Models
|
|
2473
3204
|
|
|
2474
|
-
### Generating `ApplicationRecord`
|
|
3205
|
+
### Generating `ApplicationRecord`
|
|
3206
|
+
|
|
3207
|
+
The first time you run `active-record schema`, it writes `src/models/application-record.ts`:
|
|
3208
|
+
|
|
3209
|
+
```ts
|
|
3210
|
+
import { Model } from "@forestfuture/active-record";
|
|
3211
|
+
import { schema } from "../db/schema";
|
|
3212
|
+
|
|
3213
|
+
export abstract class ApplicationRecord extends Model {
|
|
3214
|
+
static override schema = schema;
|
|
3215
|
+
}
|
|
3216
|
+
```
|
|
3217
|
+
|
|
3218
|
+
It’s an ordinary class, and yours to edit. The schema it holds gives each Model its attributes and the D1 binding its queries use. Methods, callbacks, and scopes you write on it are every Model’s. See [Shared behavior](/shared-behavior).
|
|
3219
|
+
|
|
3220
|
+
`ApplicationRecord` has no table of its own, so you can’t query it.
|
|
3221
|
+
|
|
3222
|
+
### Extending `ApplicationRecord`
|
|
3223
|
+
|
|
3224
|
+
Define each Model by extending `ApplicationRecord`:
|
|
3225
|
+
|
|
3226
|
+
```ts
|
|
3227
|
+
import { ApplicationRecord } from "./application-record";
|
|
3228
|
+
|
|
3229
|
+
export class Product extends ApplicationRecord {
|
|
3230
|
+
static newest = this.scope((q) => q.order({ createdAt: "desc" }));
|
|
3231
|
+
}
|
|
3232
|
+
```
|
|
3233
|
+
|
|
3234
|
+
The class name names the table, so `Product` reads and writes `products`. The table’s attributes, primary key, and types come from `src/db/schema.ts`.
|
|
3235
|
+
|
|
3236
|
+
[`active-record schema`](/command-line#active-record-schema) writes that file from your migrations and your Models. Run it after you add a Model or a migration. [`active-record g model`](/generators) runs it for you.
|
|
3237
|
+
|
|
3238
|
+
A subclass shares its parent’s table:
|
|
3239
|
+
|
|
3240
|
+
```ts
|
|
3241
|
+
import { Product } from "./models";
|
|
3242
|
+
|
|
3243
|
+
export class FeaturedProduct extends Product {}
|
|
3244
|
+
```
|
|
3245
|
+
|
|
3246
|
+
You can still set `static primaryKey`, as long as it names an attribute.
|
|
3247
|
+
|
|
3248
|
+
### Overriding attributes
|
|
3249
|
+
|
|
3250
|
+
Generated attributes are usually all you need. When a column holds something its type doesn’t say, such as a boolean in a plain `INTEGER`, override the attribute in `static attributes`:
|
|
3251
|
+
|
|
3252
|
+
```ts
|
|
3253
|
+
import { ApplicationRecord } from "./application-record";
|
|
3254
|
+
|
|
3255
|
+
export class Product extends ApplicationRecord {
|
|
3256
|
+
static override attributes = {
|
|
3257
|
+
available: "boolean", // the column is a plain INTEGER: read it as a boolean
|
|
3258
|
+
internalNotes: false, // ignored: never read or written
|
|
3259
|
+
priceCents: { default: () => 100 }, // replaces the column's default, 0
|
|
3260
|
+
} as const;
|
|
3261
|
+
|
|
3262
|
+
static inStock = this.scope((q) => q.where({ available: true }));
|
|
3263
|
+
}
|
|
3264
|
+
```
|
|
3265
|
+
|
|
3266
|
+
Write the object `as const`, so TypeScript keeps each type name. Without it, the class is a compile error.
|
|
3267
|
+
|
|
3268
|
+
An override is one of these:
|
|
3269
|
+
|
|
3270
|
+
| Override | Does |
|
|
3271
|
+
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------- |
|
|
3272
|
+
| `"boolean"` (a type name) | Reads and writes the attribute as that type |
|
|
3273
|
+
| `money` (a [custom type](/custom-types)) | Reads and writes the attribute as that type |
|
|
3274
|
+
| `{ type?, null?, default?, generateId? }` | Replaces those parts of the generated attribute; `null: false` makes it non-null in TypeScript |
|
|
3275
|
+
| `{ enum, prefix?, suffix?, … }` | Makes the attribute an [enum](#declaring-enums), of its column’s type |
|
|
3276
|
+
| `{ enum: true }`, `{ enum: false }` | Turns on the methods of an [enum read from the database](#reading-enums-from-the-database), or drops it |
|
|
3277
|
+
| `false` | Ignores the column: it’s never typed, read, or written, and queries name their columns instead of `*` |
|
|
3278
|
+
|
|
3279
|
+
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.
|
|
3280
|
+
|
|
3281
|
+
- **Changing a `type`** drops the generated default or `generateId`, so the column’s own default applies unless you give one.
|
|
3282
|
+
- **A `default` and `generateId`** replace each other, so an attribute has one or the other. `generateId` is only for strings.
|
|
3283
|
+
- **A `default`** isn’t type-checked yet ([#74](https://github.com/forestfuture/active-record/issues/74)). One that returns a value the type can’t cast throws `TypeError` when a record is built.
|
|
3284
|
+
- **Ignoring a `NOT NULL` column** without a default makes inserts fail, so give it a default in a migration first.
|
|
3285
|
+
|
|
3286
|
+
### Narrowing types
|
|
3287
|
+
|
|
3288
|
+
To give an attribute a narrower type than its column’s, declare it in the class:
|
|
3289
|
+
|
|
3290
|
+
```ts
|
|
3291
|
+
import { ApplicationRecord } from "./application-record";
|
|
3292
|
+
|
|
3293
|
+
export class Post extends ApplicationRecord {
|
|
3294
|
+
declare status: "draft" | "published";
|
|
3295
|
+
}
|
|
3296
|
+
```
|
|
3297
|
+
|
|
3298
|
+
`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.
|
|
3299
|
+
|
|
3300
|
+
## Declaring attributes yourself
|
|
3301
|
+
|
|
3302
|
+
For a view, or a table your migrations don’t make, declare the attributes with `define`. TypeScript infers the record’s properties from the object:
|
|
3303
|
+
|
|
3304
|
+
```ts
|
|
3305
|
+
import { column, Model, sql } from "@forestfuture/active-record";
|
|
3306
|
+
|
|
3307
|
+
export class User extends Model.define({
|
|
3308
|
+
id: { type: "string", null: false, generateId: true },
|
|
3309
|
+
email: { type: "string", null: false },
|
|
3310
|
+
role: "string",
|
|
3311
|
+
isActive: "boolean", // column: is_active
|
|
3312
|
+
htmlURL: "string", // column: html_url (a run of capitals is one word)
|
|
3313
|
+
legacyId: { type: "integer", column: "person_identifier" },
|
|
3314
|
+
settings: { type: "json", default: () => ({ theme: "light" }) },
|
|
3315
|
+
createdAt: "datetime",
|
|
3316
|
+
updatedAt: "datetime",
|
|
3317
|
+
}) {
|
|
3318
|
+
static primaryKey = "id"; // the default
|
|
3319
|
+
|
|
3320
|
+
static active = this.scope((q) => q.where({ isActive: true }));
|
|
3321
|
+
static createdAfter = this.scope((q, since: Date) =>
|
|
3322
|
+
q.where(sql`${column("createdAt")} > ${since}`),
|
|
3323
|
+
);
|
|
3324
|
+
}
|
|
3325
|
+
```
|
|
3326
|
+
|
|
3327
|
+
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({...})`.
|
|
3328
|
+
|
|
3329
|
+
## Naming Models
|
|
3330
|
+
|
|
3331
|
+
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`:
|
|
3332
|
+
|
|
3333
|
+
```ts
|
|
3334
|
+
import { BlogPost } from "./blog-post";
|
|
3335
|
+
|
|
3336
|
+
BlogPost.modelName; // "BlogPost"
|
|
3337
|
+
```
|
|
3338
|
+
|
|
3339
|
+
If your bundler renames classes, set `static modelName` to the class name, so the Model keeps its name once bundled:
|
|
3340
|
+
|
|
3341
|
+
```ts
|
|
3342
|
+
import { ApplicationRecord } from "./application-record";
|
|
3343
|
+
|
|
3344
|
+
export class BlogPost extends ApplicationRecord {
|
|
3345
|
+
static override modelName = "BlogPost";
|
|
3346
|
+
}
|
|
3347
|
+
```
|
|
3348
|
+
|
|
3349
|
+
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.
|
|
3350
|
+
|
|
3351
|
+
:::note
|
|
3352
|
+
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.
|
|
3353
|
+
:::
|
|
3354
|
+
|
|
3355
|
+
> **Compared with Rails**
|
|
3356
|
+
>
|
|
3357
|
+
> `modelName` is a string, where Rails’ `model_name` is an object.
|
|
3358
|
+
|
|
3359
|
+
## Naming tables
|
|
3360
|
+
|
|
3361
|
+
A Model takes its table name from its [name](#naming-models): snake_case, pluralized.
|
|
3362
|
+
|
|
3363
|
+
| Class | Table |
|
|
3364
|
+
| ---------- | ------------ |
|
|
3365
|
+
| `User` | `users` |
|
|
3366
|
+
| `BlogPost` | `blog_posts` |
|
|
3367
|
+
| `Category` | `categories` |
|
|
3368
|
+
| `Person` | `people` |
|
|
3369
|
+
| `Sheep` | `sheep` |
|
|
3370
|
+
|
|
3371
|
+
To use another name, set `static table`:
|
|
3372
|
+
|
|
3373
|
+
```ts
|
|
3374
|
+
import { ApplicationRecord } from "./application-record";
|
|
3375
|
+
|
|
3376
|
+
export class Account extends ApplicationRecord {
|
|
3377
|
+
static override table = "billing_accounts";
|
|
3378
|
+
}
|
|
3379
|
+
```
|
|
3380
|
+
|
|
3381
|
+
A subclass shares its parent’s table. A class with no name to take one from must set `static table`.
|
|
3382
|
+
|
|
3383
|
+
:::note
|
|
3384
|
+
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.
|
|
3385
|
+
:::
|
|
3386
|
+
|
|
3387
|
+
## Mapping columns
|
|
3388
|
+
|
|
3389
|
+
Attributes are camelCase, and map to snake_case columns:
|
|
3390
|
+
|
|
3391
|
+
| Attribute | Column |
|
|
3392
|
+
| ------------------- | --------------------- |
|
|
3393
|
+
| `createdAt` | `created_at` |
|
|
3394
|
+
| `externalAccountId` | `external_account_id` |
|
|
3395
|
+
| `htmlURL` | `html_url` |
|
|
3396
|
+
| `userID` | `user_id` |
|
|
3397
|
+
| `sha256Hash` | `sha256_hash` |
|
|
3398
|
+
|
|
3399
|
+
To map an attribute to a column with another name, give it `{ column: "..." }`. Conditions, ordering, and association keys always name attributes; only SQL fragments name columns.
|
|
3400
|
+
|
|
3401
|
+
## Attribute types
|
|
3402
|
+
|
|
3403
|
+
| Type | JavaScript | Stored in D1 as |
|
|
3404
|
+
| ---------- | -------------- | ------------------------------------------- |
|
|
3405
|
+
| `string` | `string` | `TEXT` |
|
|
3406
|
+
| `integer` | `number` | `INTEGER` |
|
|
3407
|
+
| `real` | `number` | `REAL` |
|
|
3408
|
+
| `decimal` | `string` | `DECIMAL` |
|
|
3409
|
+
| `boolean` | `boolean` | `INTEGER`, `0` or `1` |
|
|
3410
|
+
| `datetime` | `Date` | `TEXT`, ISO-8601, or an `INTEGER` Unix time |
|
|
3411
|
+
| `date` | `string` | `TEXT` in a `DATE` column |
|
|
3412
|
+
| `time` | `string` | `TEXT` in a `TIME` column |
|
|
3413
|
+
| `json` | any JSON value | `TEXT`, as JSON |
|
|
3414
|
+
| `binary` | `Uint8Array` | `BLOB` |
|
|
3415
|
+
|
|
3416
|
+
An attribute can be `null` unless it’s declared `null: false`, and its TypeScript type includes `| null` to match.
|
|
3417
|
+
|
|
3418
|
+
A `datetime` read from text with no time zone, such as SQLite’s `DEFAULT CURRENT_TIMESTAMP` writes, is UTC in any time zone.
|
|
3419
|
+
|
|
3420
|
+
:::note
|
|
3421
|
+
A column that holds both ISO text and SQLite’s date text compares as text. See [Comparing dates in two forms](/adopt-a-database#comparing-dates-in-two-forms).
|
|
3422
|
+
:::
|
|
3423
|
+
|
|
3424
|
+
:::note
|
|
3425
|
+
Store `json` attributes in a `TEXT` column, as [D1 recommends](https://developers.cloudflare.com/d1/sql-api/query-json/#types), and add `CHECK (json_valid(settings))` to have D1 reject invalid JSON. A column declared `JSON` works too.
|
|
3426
|
+
:::
|
|
3427
|
+
|
|
3428
|
+
:::note
|
|
3429
|
+
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.
|
|
3430
|
+
:::
|
|
3431
|
+
|
|
3432
|
+
For a value none of these hold, such as money, define a [custom type](/custom-types).
|
|
3433
|
+
|
|
3434
|
+
### Storing bytes
|
|
3435
|
+
|
|
3436
|
+
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:
|
|
3437
|
+
|
|
3438
|
+
```ts
|
|
3439
|
+
import { Attachment } from "./models/attachment";
|
|
3440
|
+
|
|
3441
|
+
const file = form.get("file") as File;
|
|
3442
|
+
const data = new Uint8Array(await file.arrayBuffer());
|
|
3443
|
+
const attachment = await Attachment.create({ name: file.name, data });
|
|
3444
|
+
```
|
|
3445
|
+
|
|
3446
|
+
It reads back as a `Uint8Array`, and prints as `<3 bytes of binary data>`, so logs never hold the bytes.
|
|
3447
|
+
|
|
3448
|
+
:::note
|
|
3449
|
+
A D1 row holds at most 2 MB. Keep larger files in [R2](https://developers.cloudflare.com/r2/), and store their keys.
|
|
3450
|
+
:::
|
|
3451
|
+
|
|
3452
|
+
:::tip
|
|
3453
|
+
`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.
|
|
3454
|
+
:::
|
|
3455
|
+
|
|
3456
|
+
### Storing exact numbers, days, and times
|
|
2475
3457
|
|
|
2476
|
-
|
|
3458
|
+
A `decimal` holds an exact number, such as a price, as text. Assign text, a number, or a `bigint`:
|
|
2477
3459
|
|
|
2478
3460
|
```ts
|
|
2479
|
-
import {
|
|
2480
|
-
import { schema } from "../db/schema";
|
|
3461
|
+
import { Product } from "./models/product";
|
|
2481
3462
|
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
}
|
|
3463
|
+
const product = Product.build({ price: "12.50" });
|
|
3464
|
+
product.price; // "12.5"
|
|
2485
3465
|
```
|
|
2486
3466
|
|
|
2487
|
-
|
|
3467
|
+
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.
|
|
2488
3468
|
|
|
2489
|
-
|
|
3469
|
+
:::tip
|
|
3470
|
+
To do arithmetic with decimals, wrap a decimal library in a [custom type](/custom-types) stored as `"decimal"`.
|
|
3471
|
+
:::
|
|
2490
3472
|
|
|
2491
|
-
|
|
3473
|
+
:::note
|
|
3474
|
+
D1 keeps about 15 significant digits of a decimal, and rounds the rest. Postgres keeps every digit.
|
|
3475
|
+
:::
|
|
2492
3476
|
|
|
2493
|
-
|
|
3477
|
+
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:
|
|
2494
3478
|
|
|
2495
3479
|
```ts
|
|
2496
|
-
import {
|
|
3480
|
+
import { Model } from "@forestfuture/active-record";
|
|
2497
3481
|
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
}
|
|
3482
|
+
class Product extends Model.define({
|
|
3483
|
+
price: { type: "decimal", precision: 10, scale: 2 },
|
|
3484
|
+
}) {}
|
|
3485
|
+
|
|
3486
|
+
Product.build({ price: "1.555" }).price; // "1.56"
|
|
2501
3487
|
```
|
|
2502
3488
|
|
|
2503
|
-
|
|
3489
|
+
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.
|
|
2504
3490
|
|
|
2505
|
-
|
|
3491
|
+
:::note
|
|
3492
|
+
`active-record schema` reads a decimal’s `precision` and `scale` from a column such as `NUMERIC(10, 2)`.
|
|
3493
|
+
:::
|
|
2506
3494
|
|
|
2507
|
-
A
|
|
3495
|
+
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:
|
|
2508
3496
|
|
|
2509
3497
|
```ts
|
|
2510
|
-
import {
|
|
3498
|
+
import { Shift } from "./models/shift";
|
|
2511
3499
|
|
|
2512
|
-
|
|
3500
|
+
const shift = Shift.build({ startsOn: "2026-01-02", opensAt: "09:30" });
|
|
3501
|
+
shift.opensAt; // "09:30:00"
|
|
2513
3502
|
```
|
|
2514
3503
|
|
|
2515
|
-
|
|
3504
|
+
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)`.
|
|
2516
3505
|
|
|
2517
|
-
|
|
3506
|
+
> **Compared with Rails**
|
|
3507
|
+
>
|
|
3508
|
+
> Rails holds a `decimal` as a `BigDecimal`, a `date` as a `Date`, and a `time` as a `Time` on 1
|
|
3509
|
+
> January 2000. Here each one is text, which reads the same from every database and goes into JSON
|
|
3510
|
+
> as it is.
|
|
2518
3511
|
|
|
2519
|
-
|
|
3512
|
+
## Declaring enums
|
|
3513
|
+
|
|
3514
|
+
An enum gives an attribute a fixed set of names. Declare one with `enum` in an override:
|
|
2520
3515
|
|
|
2521
3516
|
```ts
|
|
2522
3517
|
import { ApplicationRecord } from "./application-record";
|
|
2523
3518
|
|
|
2524
|
-
export class
|
|
3519
|
+
export class Ticket extends ApplicationRecord {
|
|
2525
3520
|
static override attributes = {
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
priceCents: { default: () => 100 }, // replaces the column's default, 0
|
|
3521
|
+
status: { enum: ["open", "in_progress", "closed"] }, // stored as the names
|
|
3522
|
+
priority: { enum: { low: 0, normal: 1, high: 2 } }, // stored as 0, 1, and 2
|
|
2529
3523
|
} as const;
|
|
2530
|
-
|
|
2531
|
-
static inStock = this.scope((q) => q.where({ available: true }));
|
|
2532
3524
|
}
|
|
2533
3525
|
```
|
|
2534
3526
|
|
|
2535
|
-
|
|
3527
|
+
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"] }`.
|
|
2536
3528
|
|
|
2537
|
-
|
|
3529
|
+
### Using an enum’s methods
|
|
2538
3530
|
|
|
2539
|
-
|
|
2540
|
-
| ----------------------------------------- | ----------------------------------------------------------------------------------------------------- |
|
|
2541
|
-
| `"boolean"` (a type name) | Reads and writes the attribute as that type |
|
|
2542
|
-
| `{ type?, null?, default?, generateId? }` | Replaces those parts of the generated attribute; `null: false` makes it non-null in TypeScript |
|
|
2543
|
-
| `false` | Ignores the column: it’s never typed, read, or written, and queries name their columns instead of `*` |
|
|
3531
|
+
Each name gets a predicate and a setter on records, and two scopes on the Model:
|
|
2544
3532
|
|
|
2545
|
-
|
|
3533
|
+
```ts
|
|
3534
|
+
const ticket = await Ticket.high().notClosed().first();
|
|
2546
3535
|
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
|
|
2550
|
-
|
|
3536
|
+
if (ticket?.isOpen()) {
|
|
3537
|
+
await ticket.saveAsClosed();
|
|
3538
|
+
}
|
|
3539
|
+
```
|
|
2551
3540
|
|
|
2552
|
-
|
|
3541
|
+
| Method | Does |
|
|
3542
|
+
| --------------------------------------------------- | ---------------------------------------------------------------------- |
|
|
3543
|
+
| `ticket.isOpen()` | Whether `status` is `"open"` |
|
|
3544
|
+
| `ticket.saveAsOpen()`, `ticket.saveAsOpenOrThrow()` | Sets `status` to `"open"` and saves the record, with its other changes |
|
|
3545
|
+
| `Ticket.open()`, `Ticket.notOpen()` | Scopes of the records whose `status` is, or isn’t, `"open"` |
|
|
2553
3546
|
|
|
2554
|
-
|
|
3547
|
+
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.
|
|
2555
3548
|
|
|
2556
|
-
|
|
2557
|
-
import { ApplicationRecord } from "./application-record";
|
|
3549
|
+
`where`, `whereNot`, `pluck`, and every write take and give names, too. To read the names with their stored values, call `enumValues`:
|
|
2558
3550
|
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
}
|
|
3551
|
+
```ts
|
|
3552
|
+
const priorities = Ticket.enumValues("priority"); // { low: 0, normal: 1, high: 2 }
|
|
2562
3553
|
```
|
|
2563
3554
|
|
|
2564
|
-
|
|
3555
|
+
:::note
|
|
3556
|
+
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.
|
|
3557
|
+
:::
|
|
2565
3558
|
|
|
2566
|
-
|
|
3559
|
+
### Keeping names apart
|
|
2567
3560
|
|
|
2568
|
-
|
|
3561
|
+
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:
|
|
2569
3562
|
|
|
2570
3563
|
```ts
|
|
2571
|
-
import {
|
|
3564
|
+
import { Model } from "@forestfuture/active-record";
|
|
2572
3565
|
|
|
2573
|
-
export class
|
|
2574
|
-
id:
|
|
2575
|
-
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
htmlURL: "string", // column: html_url (a run of capitals is one word)
|
|
2579
|
-
legacyId: { type: "integer", column: "person_identifier" },
|
|
2580
|
-
settings: { type: "json", default: () => ({ theme: "light" }) },
|
|
2581
|
-
createdAt: "datetime",
|
|
2582
|
-
updatedAt: "datetime",
|
|
2583
|
-
}) {
|
|
2584
|
-
static primaryKey = "id"; // the default
|
|
3566
|
+
export class Conversation extends Model.define({
|
|
3567
|
+
id: "integer",
|
|
3568
|
+
status: { type: "string", enum: ["active", "archived"], prefix: true },
|
|
3569
|
+
comments: { type: "string", enum: ["active", "closed"], suffix: true },
|
|
3570
|
+
}) {}
|
|
2585
3571
|
|
|
2586
|
-
|
|
2587
|
-
static createdAfter = this.scope((q, since: Date) =>
|
|
2588
|
-
q.where(sql`${column("createdAt")} > ${since}`),
|
|
2589
|
-
);
|
|
2590
|
-
}
|
|
3572
|
+
// conversation.isStatusActive(), Conversation.activeComments()
|
|
2591
3573
|
```
|
|
2592
3574
|
|
|
2593
|
-
|
|
3575
|
+
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`.
|
|
2594
3576
|
|
|
2595
|
-
|
|
3577
|
+
### Reading and assigning other values
|
|
2596
3578
|
|
|
2597
|
-
|
|
3579
|
+
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`.
|
|
2598
3580
|
|
|
2599
|
-
|
|
2600
|
-
| ---------- | ------------ |
|
|
2601
|
-
| `User` | `users` |
|
|
2602
|
-
| `BlogPost` | `blog_posts` |
|
|
2603
|
-
| `Category` | `categories` |
|
|
2604
|
-
| `Person` | `people` |
|
|
2605
|
-
| `Sheep` | `sheep` |
|
|
3581
|
+
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.
|
|
2606
3582
|
|
|
2607
|
-
To
|
|
3583
|
+
To report an unknown value as a validation error instead of throwing, declare the enum with `validate: true`:
|
|
2608
3584
|
|
|
2609
3585
|
```ts
|
|
2610
|
-
import {
|
|
3586
|
+
import { Model } from "@forestfuture/active-record";
|
|
2611
3587
|
|
|
2612
|
-
export class
|
|
2613
|
-
|
|
2614
|
-
}
|
|
3588
|
+
export class Survey extends Model.define({
|
|
3589
|
+
id: "integer",
|
|
3590
|
+
answer: { type: "string", enum: ["yes", "no"], validate: true },
|
|
3591
|
+
}) {}
|
|
2615
3592
|
```
|
|
2616
3593
|
|
|
2617
|
-
A
|
|
3594
|
+
A survey answered `"maybe"` is then invalid, with an `inclusion` error, and so is one with no answer, unless you declare `validate: { allowNull: true }`.
|
|
2618
3595
|
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
|
|
3596
|
+
> **Compared with Rails**
|
|
3597
|
+
>
|
|
3598
|
+
> Rails declares `enum :status, [:open, :closed]` and stores a list by position. Here a list stores
|
|
3599
|
+
> the names, so reordering it changes nothing. `published?` is `isPublished()`, `published!` is
|
|
3600
|
+
> `saveAsPublished()` or `saveAsPublishedOrThrow()`, `not_published` is `notPublished()`, and
|
|
3601
|
+
> `Post.statuses` is `Post.enumValues("status")`. Two names stored as one value are refused.
|
|
2622
3602
|
|
|
2623
|
-
|
|
3603
|
+
### Reading enums from the database
|
|
2624
3604
|
|
|
2625
|
-
|
|
3605
|
+
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:
|
|
2626
3606
|
|
|
2627
|
-
|
|
3607
|
+
```sql
|
|
3608
|
+
CREATE TABLE tasks (
|
|
3609
|
+
id TEXT PRIMARY KEY,
|
|
3610
|
+
state TEXT NOT NULL CHECK (state IN ('open', 'done'))
|
|
3611
|
+
);
|
|
3612
|
+
```
|
|
2628
3613
|
|
|
2629
|
-
|
|
3614
|
+
The generated spec holds the names, with the enum’s methods turned off:
|
|
2630
3615
|
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
3616
|
+
```ts
|
|
3617
|
+
/** tasks — state TEXT NOT NULL CHECK (state IN ('open', 'done')) */
|
|
3618
|
+
export const tasks = {
|
|
3619
|
+
id: { type: "string", null: false, generateId: true },
|
|
3620
|
+
state: {
|
|
3621
|
+
type: "string",
|
|
3622
|
+
null: false,
|
|
3623
|
+
enum: ["open", "done"],
|
|
3624
|
+
scopes: false,
|
|
3625
|
+
instanceMethods: false,
|
|
3626
|
+
},
|
|
3627
|
+
} as const;
|
|
3628
|
+
```
|
|
2638
3629
|
|
|
2639
|
-
|
|
3630
|
+
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.
|
|
2640
3631
|
|
|
2641
|
-
|
|
3632
|
+
Turn them on by overriding the attribute with `enum: true`:
|
|
2642
3633
|
|
|
2643
|
-
|
|
2644
|
-
|
|
2645
|
-
| `string` | `string` | `TEXT` |
|
|
2646
|
-
| `integer` | `number` | `INTEGER` |
|
|
2647
|
-
| `real` | `number` | `REAL` |
|
|
2648
|
-
| `boolean` | `boolean` | `INTEGER`, `0` or `1` |
|
|
2649
|
-
| `datetime` | `Date` | `TEXT`, ISO-8601, or an `INTEGER` Unix time |
|
|
2650
|
-
| `json` | any JSON value | `TEXT`, as JSON |
|
|
3634
|
+
```ts
|
|
3635
|
+
import { ApplicationRecord } from "./application-record";
|
|
2651
3636
|
|
|
2652
|
-
|
|
3637
|
+
export class Task extends ApplicationRecord {
|
|
3638
|
+
static override attributes = { state: { enum: true } } as const;
|
|
3639
|
+
}
|
|
2653
3640
|
|
|
2654
|
-
|
|
3641
|
+
// task.isDone(), task.saveAsDone(), Task.open()
|
|
3642
|
+
```
|
|
2655
3643
|
|
|
2656
|
-
|
|
2657
|
-
A column that holds both ISO text and SQLite’s date text compares as text. See [Comparing dates in two forms](/adopt-a-database#comparing-dates-in-two-forms).
|
|
2658
|
-
:::
|
|
3644
|
+
`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).
|
|
2659
3645
|
|
|
2660
|
-
|
|
2661
|
-
Store `json` attributes in a `TEXT` column, as [D1 recommends](https://developers.cloudflare.com/d1/sql-api/query-json/#types), and add `CHECK (json_valid(settings))` to have D1 reject invalid JSON. A column declared `JSON` works too.
|
|
2662
|
-
:::
|
|
3646
|
+
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.
|
|
2663
3647
|
|
|
2664
3648
|
:::note
|
|
2665
|
-
|
|
3649
|
+
`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.
|
|
2666
3650
|
:::
|
|
2667
3651
|
|
|
3652
|
+
> **Beyond Rails**
|
|
3653
|
+
>
|
|
3654
|
+
> Rails reads no enums from the database: each one is declared in its Model. Here the database gives
|
|
3655
|
+
> an enum its names and its type, and the Model still declares its methods, with `enum: true`.
|
|
3656
|
+
|
|
2668
3657
|
## Casting assigned values
|
|
2669
3658
|
|
|
2670
3659
|
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 +3675,13 @@ Values are cast wherever they’re assigned: `build`, `create`, `assign`, `updat
|
|
|
2686
3675
|
| `boolean` | `true`, `false`, `1`, `0`, `"1"`, `"0"`, and `"true"`, `"false"`, `"on"`, `"off"` in any case |
|
|
2687
3676
|
| `integer` | a safe integer, or a string that’s wholly one, with an optional sign and spaces around it: `"42"`, `" -7 "`, `"+3"` |
|
|
2688
3677
|
| `real` | a finite number, or a string that’s wholly one, with an optional sign, point, and exponent: `"1.5"`, `".5"`, `"5."`, `"-2e3"` |
|
|
3678
|
+
| `decimal` | a finite number, a `bigint`, or a string that’s wholly a decimal number, as for a `real`: `"12.50"`, `"-2e3"` |
|
|
2689
3679
|
| `string` | a string |
|
|
2690
3680
|
| `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"` |
|
|
3681
|
+
| `date` | a day that exists, as `"YYYY-MM-DD"`: `"2026-01-02"` |
|
|
3682
|
+
| `time` | a time of day, with or without seconds and up to six digits of a fraction: `"09:30"`, `"09:30:15.25"` |
|
|
2691
3683
|
| `json` | any value JSON can write |
|
|
3684
|
+
| `binary` | a `Uint8Array`, or an `ArrayBuffer` |
|
|
2692
3685
|
|
|
2693
3686
|
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
3687
|
|
|
@@ -2697,7 +3690,10 @@ Anything else throws `TypeError` naming the Model and the attribute, and the att
|
|
|
2697
3690
|
- `NaN` and `Infinity`.
|
|
2698
3691
|
- A number, boolean, or `Date` for a `string`.
|
|
2699
3692
|
- 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.
|
|
3693
|
+
- 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.
|
|
3694
|
+
- 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
3695
|
- For a `json`: a value JSON can’t write, such as a `BigInt`, an object that refers to itself, a function, or a symbol.
|
|
3696
|
+
- For a `binary`: text, an array of numbers, or another typed array.
|
|
2701
3697
|
|
|
2702
3698
|
:::note
|
|
2703
3699
|
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 +3707,11 @@ A stored cell is checked the same way, when the record loads or `pluck` reads it
|
|
|
2711
3707
|
- For a `string`: anything but text.
|
|
2712
3708
|
- 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
3709
|
- For a `datetime` with a `storage`: anything but a number, or one past what a `Date` can hold.
|
|
3710
|
+
- For a `decimal`: anything but a number or a decimal’s text.
|
|
3711
|
+
- 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).
|
|
3712
|
+
- For a `time`: anything but a time of day’s text.
|
|
2714
3713
|
- For a `json`: text that isn’t JSON.
|
|
3714
|
+
- For a `binary`: anything but bytes.
|
|
2715
3715
|
|
|
2716
3716
|
See [Fixing cells of the wrong type](/adopt-a-database#fixing-cells-of-the-wrong-type).
|
|
2717
3717
|
|
|
@@ -2772,7 +3772,7 @@ It reads three kinds of input:
|
|
|
2772
3772
|
|
|
2773
3773
|
- **Keys you don’t name** are dropped. A named attribute the input doesn’t have is left out, and a `null` is kept.
|
|
2774
3774
|
- **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.
|
|
3775
|
+
- **`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
3776
|
|
|
2777
3777
|
[Untrusted input](/untrusted-input) shows `permit` in a Worker.
|
|
2778
3778
|
|
|
@@ -2838,7 +3838,7 @@ user.savedChangeTo("email"); // ["ada@example.com", "ada@lovelace.dev"]
|
|
|
2838
3838
|
user.hasSavedChangeTo("email"); // true
|
|
2839
3839
|
```
|
|
2840
3840
|
|
|
2841
|
-
- `isChanged()`, `changed()`, `changedAttributes()`, and `changes()` describe the unsaved changes.
|
|
3841
|
+
- `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
3842
|
- `attributeWas`, `isAttributeChanged`, and `willSaveChangeTo` look at one attribute’s unsaved change. Use them in before-callbacks.
|
|
2843
3843
|
- `savedChanges()`, `savedChangeTo`, `hasSavedChangeTo`, and `attributeBeforeLastSave` look at the last save. Use them in after-callbacks, where the record is already clean.
|
|
2844
3844
|
- `restoreAttributes()` undoes unsaved changes, to every attribute or the ones you name.
|
|
@@ -2846,7 +3846,7 @@ user.hasSavedChangeTo("email"); // true
|
|
|
2846
3846
|
An update writes only the attributes that changed, and a save with nothing changed sends nothing.
|
|
2847
3847
|
|
|
2848
3848
|
:::note
|
|
2849
|
-
Changes are found by comparing stored values, so editing a `json` value or a `
|
|
3849
|
+
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
3850
|
:::
|
|
2851
3851
|
|
|
2852
3852
|
## Writing SQL fragments
|
|
@@ -2917,7 +3917,7 @@ A name a Model doesn’t have throws `InvalidModel` when the Model is first used
|
|
|
2917
3917
|
`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
3918
|
|
|
2919
3919
|
- **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.
|
|
3920
|
+
- **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
3921
|
- **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
3922
|
- **Hidden in errors:** a cast error’s value, and a filtered primary key in `RecordNotFound`.
|
|
2923
3923
|
- **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 +3937,7 @@ User { id: 1, name: 'Johnny' (was 'Alice'), email: [FILTERED], role: 'admin' }
|
|
|
2937
3937
|
- **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
3938
|
- **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
3939
|
- **A partial record** prints only the columns it loaded.
|
|
3940
|
+
- **Bytes** print as how many there are: `<3 bytes of binary data>`.
|
|
2940
3941
|
|
|
2941
3942
|
A Relation prints the SELECT it would send, without sending it:
|
|
2942
3943
|
|
|
@@ -2982,6 +3983,7 @@ The first time a Model is used, by its first query or `db.model(X)`, its declara
|
|
|
2982
3983
|
|
|
2983
3984
|
- A Model `active-record schema` hasn’t seen, or whose table has changed since. Run it again.
|
|
2984
3985
|
- No table name: an empty `table`, or a class with no name to infer one from.
|
|
3986
|
+
- A `modelName` that isn’t a string.
|
|
2985
3987
|
- An override of an attribute the table doesn’t have.
|
|
2986
3988
|
- A `primaryKey` that isn’t an attribute.
|
|
2987
3989
|
- An attribute named like a record method, such as `save` or `attributes`.
|
|
@@ -3107,12 +4109,13 @@ npx active-record schema
|
|
|
3107
4109
|
Its attributes come out the same as on D1. Only its adapter changes:
|
|
3108
4110
|
|
|
3109
4111
|
```ts src/db/schema.ts
|
|
4112
|
+
import { defineSchema } from "@forestfuture/active-record";
|
|
3110
4113
|
import { postgresql } from "@forestfuture/active-record/postgresql";
|
|
3111
4114
|
|
|
3112
|
-
export const schema = {
|
|
4115
|
+
export const schema = defineSchema({
|
|
3113
4116
|
adapter: postgresql({ binding: "HYPERDRIVE" }),
|
|
3114
4117
|
// …
|
|
3115
|
-
};
|
|
4118
|
+
});
|
|
3116
4119
|
```
|
|
3117
4120
|
|
|
3118
4121
|
## Copying the data
|
|
@@ -3278,6 +4281,10 @@ A new record is inserted, and a persisted one updates only the attributes that c
|
|
|
3278
4281
|
|
|
3279
4282
|
When a failure is exceptional, use the `OrThrow` version of each method:
|
|
3280
4283
|
|
|
4284
|
+
> **Compared with Rails**
|
|
4285
|
+
>
|
|
4286
|
+
> 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!`.
|
|
4287
|
+
|
|
3281
4288
|
```ts
|
|
3282
4289
|
import { RecordInvalid } from "@forestfuture/active-record";
|
|
3283
4290
|
import { User } from "./models";
|
|
@@ -3299,23 +4306,21 @@ Instead of returning `false`, they throw:
|
|
|
3299
4306
|
- `RecordNotSaved` when a callback aborted a save, with the abort’s reason as its message.
|
|
3300
4307
|
- `RecordNotDestroyed` from `destroyOrThrow()`, when a callback aborted the destroy or a `restrictWithError` association refused it.
|
|
3301
4308
|
|
|
3302
|
-
> **Compared with Rails**
|
|
3303
|
-
>
|
|
3304
|
-
> The `OrThrow` methods are Rails’ `save!`, `create!`, `update!`, and `destroy!`.
|
|
3305
|
-
|
|
3306
4309
|
### What each method returns
|
|
3307
4310
|
|
|
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`
|
|
4311
|
+
| Method | Resolves to | Throws |
|
|
4312
|
+
| ---------------------------------------- | ------------------------------------- | ----------------------------------------------------------------- |
|
|
4313
|
+
| `save()` / `update(attrs)` | `true` / `false` | constraint errors, `RecordDestroyed` |
|
|
4314
|
+
| `saveOrThrow()` / `updateOrThrow(attrs)` | `true` | same as above, plus `RecordInvalid`, `RecordNotSaved` |
|
|
4315
|
+
| `create(attrs)` | record, persisted or not | constraint errors |
|
|
4316
|
+
| `createOrThrow(attrs)` | persisted record | same as above, plus `RecordInvalid`, `RecordNotSaved` |
|
|
4317
|
+
| `destroy()` | destroyed record, or `false` on abort | constraint errors, `RecordDestroyed` |
|
|
4318
|
+
| `destroyOrThrow()` | destroyed record | same as above, plus `RecordNotDestroyed` |
|
|
4319
|
+
| `find(id)` | record | `RecordNotFound` |
|
|
4320
|
+
| `findBy(conds)` | record or `null` | none |
|
|
4321
|
+
| `findByOrThrow(conds)` | record | `RecordNotFound` |
|
|
4322
|
+
| `findOrCreateBy(attrs)` | record, persisted or not | constraint errors |
|
|
4323
|
+
| `createOrFindBy(attrs)` | record, persisted or not | constraint errors but its own `RecordNotUnique`, `RecordNotFound` |
|
|
3319
4324
|
|
|
3320
4325
|
`false` only ever means validation failed or a callback aborted. Every method throws for anything else:
|
|
3321
4326
|
|
|
@@ -3323,6 +4328,135 @@ Instead of returning `false`, they throw:
|
|
|
3323
4328
|
- **An error thrown by a callback**, other than `abort()`, even from an after-callback once the record is saved.
|
|
3324
4329
|
- **D1’s own errors.**
|
|
3325
4330
|
|
|
4331
|
+
## Changing one attribute
|
|
4332
|
+
|
|
4333
|
+
To bump a number or flip a flag, use `increment`, `decrement`, or `toggle`. They change the record without saving it, so save it afterwards:
|
|
4334
|
+
|
|
4335
|
+
```ts
|
|
4336
|
+
const article = await Article.find(id);
|
|
4337
|
+
article.increment("viewCount"); // viewCount + 1, not saved yet
|
|
4338
|
+
article.toggle("isPinned");
|
|
4339
|
+
await article.save();
|
|
4340
|
+
```
|
|
4341
|
+
|
|
4342
|
+
`increment` and `decrement` take an amount as their second argument, and count `null` as zero. `toggle` turns `null` into `true`.
|
|
4343
|
+
|
|
4344
|
+
### Writing straight to the row
|
|
4345
|
+
|
|
4346
|
+
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:
|
|
4347
|
+
|
|
4348
|
+
```ts
|
|
4349
|
+
await article.incrementColumn("viewCount"); // adds 1 in the row, now
|
|
4350
|
+
await article.toggleColumn("isPinned");
|
|
4351
|
+
await article.updateColumns({ title: "Renamed" }); // no validations, callbacks, or updatedAt
|
|
4352
|
+
```
|
|
4353
|
+
|
|
4354
|
+
- **`incrementColumn` and `decrementColumn`** add to the value in the row, not the one the record loaded. When two requests increment the same row, both count. The record then holds the row’s new value.
|
|
4355
|
+
- **`toggleColumn`** writes the flipped value.
|
|
4356
|
+
- **`updateColumns(attrs)`** writes the attributes you give. `updateColumn(name, value)` writes one.
|
|
4357
|
+
|
|
4358
|
+
Each resolves to `true`, or `false` when the row is gone. The record’s other unsaved changes stay unsaved. A record that was never saved has no row, so these methods throw `RecordNotSaved`.
|
|
4359
|
+
|
|
4360
|
+
### Updating counters
|
|
4361
|
+
|
|
4362
|
+
To add to a number without loading the record, pass its primary key to `updateCounters`:
|
|
4363
|
+
|
|
4364
|
+
```ts
|
|
4365
|
+
await Article.updateCounters(id, { viewCount: 1 });
|
|
4366
|
+
await Article.where({ isPinned: true }).updateCounters({ viewCount: 10 });
|
|
4367
|
+
await Article.incrementCounter("viewCount", [id], { by: 5, touch: true }); // sets updatedAt too
|
|
4368
|
+
```
|
|
4369
|
+
|
|
4370
|
+
- **`Article.updateCounters(ids, counters)`** adds to the rows with those keys, even ones a default scope leaves out.
|
|
4371
|
+
- **A Relation’s `updateCounters(counters)`** adds to every row it matches.
|
|
4372
|
+
- **`incrementCounter` and `decrementCounter`** change one attribute by one, or by the amount in `{ by: 5 }`.
|
|
4373
|
+
|
|
4374
|
+
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" }`.
|
|
4375
|
+
|
|
4376
|
+
To keep a count of an association’s records, see [counter caches](/associations#counting-records-with-a-counter-cache).
|
|
4377
|
+
|
|
4378
|
+
:::warning[Counting by key skips the default scope]
|
|
4379
|
+
`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:
|
|
4380
|
+
|
|
4381
|
+
```ts
|
|
4382
|
+
await Article.where({ id }).updateCounters({ viewCount: 1 }); // keeps the default scope
|
|
4383
|
+
```
|
|
4384
|
+
|
|
4385
|
+
:::
|
|
4386
|
+
|
|
4387
|
+
:::note
|
|
4388
|
+
`increment` and the counters take `integer` and `real` attributes. A `decimal` is stored as text, so they refuse it.
|
|
4389
|
+
:::
|
|
4390
|
+
|
|
4391
|
+
> **Compared with Rails**
|
|
4392
|
+
>
|
|
4393
|
+
> `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.
|
|
4394
|
+
>
|
|
4395
|
+
> Rails’ `toggle!` runs the save callbacks and saves the record’s other changes. `toggleColumn` runs no callbacks and writes only the one attribute. For callbacks, call `toggle`, then `save`.
|
|
4396
|
+
>
|
|
4397
|
+
> Rails’ `increment!` keeps the value it worked out. `incrementColumn` reads the row’s new value back, so it includes other requests’ increments.
|
|
4398
|
+
|
|
4399
|
+
## Finding or creating a record
|
|
4400
|
+
|
|
4401
|
+
Find a record by its attributes, or create one with them when there isn’t one, with `findOrCreateBy`:
|
|
4402
|
+
|
|
4403
|
+
```ts
|
|
4404
|
+
const travel = await Label.findOrCreateBy({ name: "travel" }); // found, or created
|
|
4405
|
+
const food = await Label.findOrInitializeBy({ name: "food" }); // found, or built and not saved
|
|
4406
|
+
```
|
|
4407
|
+
|
|
4408
|
+
`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.
|
|
4409
|
+
|
|
4410
|
+
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.
|
|
4411
|
+
|
|
4412
|
+
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.
|
|
4413
|
+
|
|
4414
|
+
### Giving new records more attributes
|
|
4415
|
+
|
|
4416
|
+
To give a new record attributes that aren’t part of the search, use `createWith`:
|
|
4417
|
+
|
|
4418
|
+
```ts
|
|
4419
|
+
const blueLabels = Label.createWith({ color: "blue" });
|
|
4420
|
+
const music = await blueLabels.findOrCreateBy({ name: "music" }); // created blue
|
|
4421
|
+
```
|
|
4422
|
+
|
|
4423
|
+
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.
|
|
4424
|
+
|
|
4425
|
+
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:
|
|
4426
|
+
|
|
4427
|
+
```ts
|
|
4428
|
+
const art = await Label.findOrCreateBy({ name: "art" }, (label) => {
|
|
4429
|
+
label.color = pickColor(); // only when it's created
|
|
4430
|
+
});
|
|
4431
|
+
```
|
|
4432
|
+
|
|
4433
|
+
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`.
|
|
4434
|
+
|
|
4435
|
+
### Creating records from concurrent requests
|
|
4436
|
+
|
|
4437
|
+
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:
|
|
4438
|
+
|
|
4439
|
+
```ts
|
|
4440
|
+
const news = await Label.createOrFindBy({ name: "news" }); // created, or found
|
|
4441
|
+
```
|
|
4442
|
+
|
|
4443
|
+
`createOrFindByOrThrow` throws `RecordInvalid` when the record is invalid.
|
|
4444
|
+
|
|
4445
|
+
:::warning[Let the index decide]
|
|
4446
|
+
`createOrFindBy` only finds the existing row when the database refuses the insert:
|
|
4447
|
+
|
|
4448
|
+
- **Leave out a `uniqueness` validation on those attributes.** It refuses the duplicate before the insert, so `createOrFindBy` resolves to the invalid record, not the existing one. The UNIQUE index alone keeps the column unique.
|
|
4449
|
+
- **Save the record alone.** When `init` builds or sets records through its associations, a refusal may be theirs, so `createOrFindBy` throws the `RecordNotUnique` instead of finding.
|
|
4450
|
+
- **It throws `RecordNotFound` when there’s nothing to find:** when the index refused a value in an attribute you didn’t pass, when the existing row isn’t linked to the owner of an [association through another](/associations#reaching-records-through-another-association), or when a [D1 Session](/read-your-own-writes) reads from a replica that the other request’s row hasn’t reached yet.
|
|
4451
|
+
|
|
4452
|
+
:::
|
|
4453
|
+
|
|
4454
|
+
> **Compared with Rails**
|
|
4455
|
+
>
|
|
4456
|
+
> `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.
|
|
4457
|
+
>
|
|
4458
|
+
> 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.
|
|
4459
|
+
|
|
3326
4460
|
## Destroying records
|
|
3327
4461
|
|
|
3328
4462
|
Destroy a record with `destroy`:
|
|
@@ -3334,10 +4468,54 @@ if (destroyed) {
|
|
|
3334
4468
|
}
|
|
3335
4469
|
```
|
|
3336
4470
|
|
|
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`.
|
|
4471
|
+
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`.
|
|
4472
|
+
|
|
4473
|
+
:::note
|
|
4474
|
+
If another request already deleted the row, `save` and `destroy` still succeed.
|
|
4475
|
+
:::
|
|
4476
|
+
|
|
4477
|
+
### Destroying many records
|
|
4478
|
+
|
|
4479
|
+
Destroy every record a query matches with `destroyAll`:
|
|
4480
|
+
|
|
4481
|
+
```ts
|
|
4482
|
+
import { Post } from "./models";
|
|
4483
|
+
|
|
4484
|
+
const drafts = await Post.where({ publishedAt: null }).destroyAll(); // the destroyed posts
|
|
4485
|
+
await Post.destroyBy({ userId: user.id }); // where(…).destroyAll()
|
|
4486
|
+
const post = await Post.destroy("post-1"); // by primary key
|
|
4487
|
+
const posts = await Post.destroy(["post-2", "post-3"]);
|
|
4488
|
+
```
|
|
4489
|
+
|
|
4490
|
+
- **`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.
|
|
4491
|
+
- **`destroyBy(conditions)`** is `where(conditions).destroyAll()`.
|
|
4492
|
+
- **`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.
|
|
4493
|
+
|
|
4494
|
+
When one record can’t be destroyed, nothing is. A callback that aborts and a `restrictWithError` association both stop the whole write with `RecordNotDestroyed`.
|
|
4495
|
+
|
|
4496
|
+
To delete rows without loading them or running callbacks, use `deleteAll`, `deleteBy`, or `Post.delete(ids)`. See [Bulk writes and batches](/batches).
|
|
4497
|
+
|
|
4498
|
+
> **Compared with Rails**
|
|
4499
|
+
>
|
|
4500
|
+
> 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.
|
|
4501
|
+
|
|
4502
|
+
### Destroying a large set
|
|
4503
|
+
|
|
4504
|
+
`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):
|
|
4505
|
+
|
|
4506
|
+
```ts
|
|
4507
|
+
import { Post } from "./models";
|
|
4508
|
+
|
|
4509
|
+
const unpublished = Post.where({ publishedAt: null });
|
|
4510
|
+
for await (const batch of unpublished.inBatches({ batchSize: 100 })) {
|
|
4511
|
+
await batch.destroyAll(); // one write per batch
|
|
4512
|
+
}
|
|
4513
|
+
```
|
|
4514
|
+
|
|
4515
|
+
Each batch is its own write, so a batch that fails leaves the earlier batches destroyed.
|
|
3338
4516
|
|
|
3339
4517
|
:::note
|
|
3340
|
-
|
|
4518
|
+
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
4519
|
:::
|
|
3342
4520
|
|
|
3343
4521
|
## Checking a record’s state
|
|
@@ -3348,6 +4526,30 @@ If another request already deleted the row, `save` and `destroy` still succeed.
|
|
|
3348
4526
|
| Persisted (loaded, or after a successful save) | `false` | `true` | `false` |
|
|
3349
4527
|
| Destroyed (after a successful `destroy()`) | `false` | `false` | `true` |
|
|
3350
4528
|
|
|
4529
|
+
`isPreviouslyNewRecord()` says whether the last save created the record. Use it in an after-callback that should only run for new records:
|
|
4530
|
+
|
|
4531
|
+
```ts
|
|
4532
|
+
import { Model } from "@forestfuture/active-record";
|
|
4533
|
+
|
|
4534
|
+
export class Article extends Model.define({
|
|
4535
|
+
id: { type: "integer", null: false },
|
|
4536
|
+
title: { type: "string", null: false },
|
|
4537
|
+
viewCount: { type: "integer", null: false },
|
|
4538
|
+
isPinned: { type: "boolean", null: false },
|
|
4539
|
+
updatedAt: "datetime",
|
|
4540
|
+
}) {
|
|
4541
|
+
static {
|
|
4542
|
+
this.afterSave((article) => {
|
|
4543
|
+
if (article.isPreviouslyNewRecord()) {
|
|
4544
|
+
console.log(`New article: ${article.title}`); // not after later saves
|
|
4545
|
+
}
|
|
4546
|
+
});
|
|
4547
|
+
}
|
|
4548
|
+
}
|
|
4549
|
+
```
|
|
4550
|
+
|
|
4551
|
+
It’s `false` again once the record is saved again or destroyed.
|
|
4552
|
+
|
|
3351
4553
|
## Reloading records
|
|
3352
4554
|
|
|
3353
4555
|
Load a record’s row again with `reload`, discarding unsaved changes and loaded associations:
|
|
@@ -3364,7 +4566,7 @@ It throws `RecordNotFound` if the row is gone, or the record was never saved.
|
|
|
3364
4566
|
|
|
3365
4567
|
## Writing many rows
|
|
3366
4568
|
|
|
3367
|
-
To insert, update, or delete many rows at once, without validations and callbacks, use `insertAll`, `upsertAll`, `updateAll`, and `
|
|
4569
|
+
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
4570
|
|
|
3369
4571
|
---
|
|
3370
4572
|
|
|
@@ -3442,7 +4644,7 @@ A Hyperdrive binding’s connection string isn’t yours to change, so it always
|
|
|
3442
4644
|
|
|
3443
4645
|
## Batches are transactions
|
|
3444
4646
|
|
|
3445
|
-
[
|
|
4647
|
+
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
4648
|
|
|
3447
4649
|
## Reads run one after another
|
|
3448
4650
|
|
|
@@ -3452,7 +4654,7 @@ Queries you send at once with `Promise.all` inside one `withDatabase` call also
|
|
|
3452
4654
|
|
|
3453
4655
|
## Large integers
|
|
3454
4656
|
|
|
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.
|
|
4657
|
+
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
4658
|
|
|
3457
4659
|
## Placeholders
|
|
3458
4660
|
|
|
@@ -3476,6 +4678,8 @@ Postgres sorts text by your database’s collation, usually its locale’s, wher
|
|
|
3476
4678
|
|
|
3477
4679
|
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
4680
|
|
|
4681
|
+
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.
|
|
4682
|
+
|
|
3479
4683
|
## NUL characters
|
|
3480
4684
|
|
|
3481
4685
|
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 +4856,65 @@ export function publishedBefore(before: Date) {
|
|
|
3652
4856
|
|
|
3653
4857
|
`value` works for any attribute, and writes a boolean as 0 or 1 and a JSON value as text. The value is cast as an assigned one, so a value the attribute can’t hold throws `TypeError` naming the attribute, when `where` is given the fragment. A filtered attribute’s value is hidden from `onQuery`, as it is anywhere else.
|
|
3654
4858
|
|
|
4859
|
+
### Replacing conditions
|
|
4860
|
+
|
|
4861
|
+
Replace the conditions on some attributes with `rewhere`:
|
|
4862
|
+
|
|
4863
|
+
```ts
|
|
4864
|
+
import { User } from "./models";
|
|
4865
|
+
|
|
4866
|
+
const members = User.where({ role: "member", isActive: true });
|
|
4867
|
+
members.rewhere({ role: "admin" }); // is_active = ? AND role = ?
|
|
4868
|
+
```
|
|
4869
|
+
|
|
4870
|
+
Conditions on other attributes stay, and so do `sql` fragments. A default scope’s condition on the attribute is replaced too.
|
|
4871
|
+
|
|
4872
|
+
:::note
|
|
4873
|
+
A `whereNot` or `or` that names only those attributes is replaced. One that names other attributes too stays.
|
|
4874
|
+
:::
|
|
4875
|
+
|
|
4876
|
+
Drop parts of a query with `unscope`, or keep only some with `only`:
|
|
4877
|
+
|
|
4878
|
+
```ts
|
|
4879
|
+
import { User } from "./models";
|
|
4880
|
+
|
|
4881
|
+
const recent = User.where({ role: "admin" }).order({ createdAt: "desc" }).limit(10);
|
|
4882
|
+
recent.unscope("order", "limit"); // every admin, unordered
|
|
4883
|
+
recent.unscope({ where: "role" }); // the 10 newest users
|
|
4884
|
+
recent.only("where"); // every admin
|
|
4885
|
+
```
|
|
4886
|
+
|
|
4887
|
+
- The parts are `"where"`, `"order"`, `"limit"`, `"offset"`, `"select"`, `"distinct"`, `"includes"`, `"joins"`, `"leftJoins"`, and `"createWith"`. `{ where: "role" }` drops only the conditions on those attributes.
|
|
4888
|
+
- A default scope’s parts are dropped too. To start without the default scope, use [`unscoped()`](#defining-a-default-scope).
|
|
4889
|
+
- On an association, the link to its owner stays. `user.posts().unscope("where")` is still the user’s posts, and so is `rewhere({ userId })`. Start from `Post` to read past the owner.
|
|
4890
|
+
- Merging a Relation built with `unscope` drops those parts from the Relation it’s merged into.
|
|
4891
|
+
- A join can’t be dropped while conditions or an order merged onto it use it. That throws `IncompatibleRelation`.
|
|
4892
|
+
|
|
4893
|
+
> **Compared with Rails**
|
|
4894
|
+
>
|
|
4895
|
+
> `rewhere`, `unscope`, and `only` work as Rails’ do, with the parts named as strings. `group` and `having` aren’t parts, since a grouped Relation is a type of its own. Rails’ `invert_where` and `extending` aren’t offered. Scopes cover `extending`.
|
|
4896
|
+
|
|
4897
|
+
> **Beyond Rails**
|
|
4898
|
+
>
|
|
4899
|
+
> On an association, Rails’ `unscope(:where)` drops the link to its owner, so a read can reach records that `create` wouldn’t link to it. Here no rewrite drops the link, so reads and writes agree.
|
|
4900
|
+
|
|
4901
|
+
## Leaving records out
|
|
4902
|
+
|
|
4903
|
+
Leave out records you already have with `excluding`:
|
|
4904
|
+
|
|
4905
|
+
```ts
|
|
4906
|
+
import { User } from "./models";
|
|
4907
|
+
|
|
4908
|
+
const current = await User.firstOrThrow();
|
|
4909
|
+
const others = await User.where({ role: "admin" }).excluding(current).toArray();
|
|
4910
|
+
```
|
|
4911
|
+
|
|
4912
|
+
It takes records of the Relation’s Model, or arrays of them. A record that isn’t saved yet leaves nothing out.
|
|
4913
|
+
|
|
4914
|
+
> **Compared with Rails**
|
|
4915
|
+
>
|
|
4916
|
+
> `excluding` is Rails’ `excluding`. Its alias `without` isn’t offered.
|
|
4917
|
+
|
|
3655
4918
|
## Using raw statements
|
|
3656
4919
|
|
|
3657
4920
|
Bind what `serialize` gives when you send SQL to D1 yourself. `typeForAttribute` returns an attribute’s conversions:
|
|
@@ -3719,6 +4982,27 @@ Calling `order` again adds more keys. `reorder` replaces the order so far, and `
|
|
|
3719
4982
|
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
4983
|
:::
|
|
3721
4984
|
|
|
4985
|
+
### Ordering by a list of values
|
|
4986
|
+
|
|
4987
|
+
Sort records by where their value comes in a list with `inOrderOf`:
|
|
4988
|
+
|
|
4989
|
+
```ts
|
|
4990
|
+
import { User } from "./models";
|
|
4991
|
+
|
|
4992
|
+
User.inOrderOf("role", ["owner", "admin", "member"]); // only those roles, owners first
|
|
4993
|
+
User.inOrderOf("role", ["owner", "admin"], { filter: false }); // everyone else last
|
|
4994
|
+
```
|
|
4995
|
+
|
|
4996
|
+
- By default, only records whose value is in the list are kept. Pass `filter: false` to keep the rest, after them.
|
|
4997
|
+
- Values are cast as `where`’s are, and `null` places NULL. The list is bound as one value, so it can be any length.
|
|
4998
|
+
- An order written after it sorts the records that tie, and `last()` reverses it.
|
|
4999
|
+
- It can’t be combined with `distinct()`, which throws `IncompatibleRelation`.
|
|
5000
|
+
- 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.
|
|
5001
|
+
|
|
5002
|
+
> **Compared with Rails**
|
|
5003
|
+
>
|
|
5004
|
+
> `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.
|
|
5005
|
+
|
|
3722
5006
|
## Paginating
|
|
3723
5007
|
|
|
3724
5008
|
`paginate` resolves to one page of records and the total they’re a page of:
|
|
@@ -3774,6 +5058,81 @@ D1 limits neither the rows a query returns nor the size of its response. `maxPer
|
|
|
3774
5058
|
>
|
|
3775
5059
|
> 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
5060
|
|
|
5061
|
+
## Iterating over many records
|
|
5062
|
+
|
|
5063
|
+
`findEach` loads a Relation’s records a batch at a time, so a large table never sits in memory all at once:
|
|
5064
|
+
|
|
5065
|
+
```ts
|
|
5066
|
+
import { User } from "./models";
|
|
5067
|
+
|
|
5068
|
+
for await (const user of User.where({ isActive: true }).findEach()) {
|
|
5069
|
+
seen.push(user.email); // one user at a time, loaded 1,000 at a time
|
|
5070
|
+
}
|
|
5071
|
+
```
|
|
5072
|
+
|
|
5073
|
+
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.
|
|
5074
|
+
|
|
5075
|
+
To work with each batch as an array, use `findInBatches`:
|
|
5076
|
+
|
|
5077
|
+
```ts
|
|
5078
|
+
import { User } from "./models";
|
|
5079
|
+
|
|
5080
|
+
for await (const users of User.findInBatches({ batchSize: 500 })) {
|
|
5081
|
+
const emails = users.map((user) => user.email); // up to 500 users at a time
|
|
5082
|
+
seen.push(...emails);
|
|
5083
|
+
}
|
|
5084
|
+
```
|
|
5085
|
+
|
|
5086
|
+
`includes()` preloads each batch’s associations. Breaking out of the loop sends no more queries.
|
|
5087
|
+
|
|
5088
|
+
### Writing a batch at a time
|
|
5089
|
+
|
|
5090
|
+
`inBatches` yields a Relation of each batch’s records, so `updateAll`, `deleteAll`, and `destroyAll` can write one batch at a time:
|
|
5091
|
+
|
|
5092
|
+
```ts
|
|
5093
|
+
import { Post } from "./models";
|
|
5094
|
+
|
|
5095
|
+
const drafts = Post.where({ publishedAt: null });
|
|
5096
|
+
for await (const batch of drafts.inBatches({ batchSize: 500 })) {
|
|
5097
|
+
await batch.updateAll({ title: "Untitled" });
|
|
5098
|
+
}
|
|
5099
|
+
```
|
|
5100
|
+
|
|
5101
|
+
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.
|
|
5102
|
+
|
|
5103
|
+
Each batch is its own write. If one fails, the batches before it stay written.
|
|
5104
|
+
|
|
5105
|
+
### Choosing the batches
|
|
5106
|
+
|
|
5107
|
+
Each method takes the same options:
|
|
5108
|
+
|
|
5109
|
+
```ts
|
|
5110
|
+
import { Post, User } from "./models";
|
|
5111
|
+
|
|
5112
|
+
const range = User.findEach({ start, finish }); // keys from start to finish, both included
|
|
5113
|
+
const newestKeysFirst = Post.findInBatches({ order: "desc" }); // from the largest key down
|
|
5114
|
+
```
|
|
5115
|
+
|
|
5116
|
+
- `batchSize` sets the records in each batch: a whole number from 1, or `TypeError`.
|
|
5117
|
+
- `start` and `finish` bound the primary key, both included. With `order: "desc"`, `start` is the largest key and `finish` the smallest.
|
|
5118
|
+
- A `limit()` caps the records across every batch.
|
|
5119
|
+
|
|
5120
|
+
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.
|
|
5121
|
+
|
|
5122
|
+
:::note
|
|
5123
|
+
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.
|
|
5124
|
+
:::
|
|
5125
|
+
|
|
5126
|
+
### Staying within D1’s query limit
|
|
5127
|
+
|
|
5128
|
+
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.
|
|
5129
|
+
|
|
5130
|
+
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.
|
|
5131
|
+
|
|
5132
|
+
> **Compared with Rails**
|
|
5133
|
+
>
|
|
5134
|
+
> `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`.
|
|
5135
|
+
|
|
3777
5136
|
## Getting results
|
|
3778
5137
|
|
|
3779
5138
|
Run a query with one of these methods:
|
|
@@ -3788,17 +5147,29 @@ const byEmail = await User.findBy({ email: "ada@example.com" }); // or null
|
|
|
3788
5147
|
const oldest = await User.first(); // by primary key, unless ordered
|
|
3789
5148
|
const newest = await User.order({ createdAt: "asc" }).last(); // order reversed
|
|
3790
5149
|
const any = await User.take(); // no ordering at all
|
|
5150
|
+
const earliest = await User.firstOrThrow(); // or RecordNotFound
|
|
5151
|
+
const owner = await User.findSoleBy({ role: "owner" }); // the only one, or throws
|
|
3791
5152
|
const emails = await User.pluck("email"); // string[]
|
|
3792
5153
|
const pairs = await User.pluck("id", "email"); // [string, string][]
|
|
5154
|
+
const latest = await User.order({ createdAt: "desc" }).pick("email"); // string | null
|
|
5155
|
+
const adminIds = await User.where({ role: "admin" }).ids(); // primary keys
|
|
3793
5156
|
const admins2 = await User.where({ role: "admin" }).count();
|
|
3794
5157
|
const hasAdmins = await User.exists({ role: "admin" });
|
|
5158
|
+
const severalAdmins = await User.where({ role: "admin" }).hasMoreThanOne();
|
|
5159
|
+
const oneOwner = await User.where({ role: "owner" }).hasExactlyOne();
|
|
3795
5160
|
```
|
|
3796
5161
|
|
|
3797
5162
|
- `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
5163
|
- `findBy` resolves to `null` when nothing matches, and `findByOrThrow` throws `RecordNotFound`.
|
|
5164
|
+
- `findOrCreateBy` creates the record when nothing matches. See [Finding or creating a record](/persistence#finding-or-creating-a-record).
|
|
3799
5165
|
- `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.
|
|
5166
|
+
- `firstOrThrow`, `lastOrThrow`, and `takeOrThrow` throw `RecordNotFound` instead of resolving to `null`.
|
|
5167
|
+
- `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()`.
|
|
5168
|
+
- `pick` reads one attribute from the first record. Given several attributes, it reads a tuple. It resolves to `null` when nothing matches.
|
|
5169
|
+
- `ids` plucks every primary key. On a loaded association, it leaves out records you’ve built that don’t have a key yet.
|
|
3800
5170
|
- `count()` always agrees with what `toArray()` returns, even with `limit`, `offset`, or `distinct`.
|
|
3801
5171
|
- `size()`, `isEmpty()`, and `hasAny()` count records, or check for any. On a loaded association, they answer without a query.
|
|
5172
|
+
- `hasMoreThanOne()` and `hasExactlyOne()` count no further than two records. On a loaded association, they answer without a query too.
|
|
3802
5173
|
|
|
3803
5174
|
:::tip
|
|
3804
5175
|
`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 +5177,117 @@ const hasAdmins = await User.exists({ role: "admin" });
|
|
|
3806
5177
|
|
|
3807
5178
|
> **Compared with Rails**
|
|
3808
5179
|
>
|
|
3809
|
-
> `size()`, `isEmpty()`, and `hasAny()` are Rails’ `size`, `empty?`, and `any?`.
|
|
5180
|
+
> `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.
|
|
5181
|
+
|
|
5182
|
+
## Calculating values
|
|
5183
|
+
|
|
5184
|
+
Add up, average, or find the extremes of an attribute without loading the records:
|
|
5185
|
+
|
|
5186
|
+
```ts
|
|
5187
|
+
import { Product } from "./models";
|
|
5188
|
+
|
|
5189
|
+
const total = await Product.where({ available: 1 }).sum("priceCents"); // 0 with no products
|
|
5190
|
+
const averagePrice = await Product.average("priceCents"); // a number, or null
|
|
5191
|
+
const cheapest = await Product.minimum("priceCents"); // or null
|
|
5192
|
+
const newest = await Product.maximum("createdAt"); // a Date, or null
|
|
5193
|
+
```
|
|
5194
|
+
|
|
5195
|
+
- `sum` and `average` take number attributes: integers, reals, and decimals. A decimal’s sum is text, such as `"12.8"`.
|
|
5196
|
+
- `minimum` and `maximum` take any attribute you can compare. The result has the attribute’s own type, so a datetime’s is a `Date`.
|
|
5197
|
+
- NULLs are left out. With no rows, `sum` is 0 and the others are `null`. On `none()`, they answer without a query.
|
|
5198
|
+
|
|
5199
|
+
:::note[Exact sums on D1]
|
|
5200
|
+
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.
|
|
5201
|
+
:::
|
|
5202
|
+
|
|
5203
|
+
A calculation covers the rows `toArray()` would return, so a `limit`, an `offset`, or `distinct()` decides which values count:
|
|
5204
|
+
|
|
5205
|
+
```ts
|
|
5206
|
+
import { Product } from "./models";
|
|
5207
|
+
|
|
5208
|
+
const mostExpensive = Product.order({ priceCents: "desc" }).limit(3);
|
|
5209
|
+
const topThree = await mostExpensive.sum("priceCents"); // only those three
|
|
5210
|
+
```
|
|
5211
|
+
|
|
5212
|
+
To calculate an expression, pass an `sql` fragment:
|
|
5213
|
+
|
|
5214
|
+
```ts
|
|
5215
|
+
import { column, sql } from "@forestfuture/active-record";
|
|
5216
|
+
import { Product } from "./models";
|
|
5217
|
+
|
|
5218
|
+
const inDollars = sql`${column("priceCents")} / 100.0`;
|
|
5219
|
+
const averageDollars = await Product.average(inDollars); // a number, or null
|
|
5220
|
+
```
|
|
5221
|
+
|
|
5222
|
+
A fragment’s `sum` and `average` are numbers. Its `minimum` and `maximum` are the values the database returns.
|
|
5223
|
+
|
|
5224
|
+
:::note
|
|
5225
|
+
`calculate("sum", "priceCents")` runs the calculation its first argument names. Use it when the name comes from elsewhere, such as a report’s settings.
|
|
5226
|
+
:::
|
|
5227
|
+
|
|
5228
|
+
> **Compared with Rails**
|
|
5229
|
+
>
|
|
5230
|
+
> `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.
|
|
5231
|
+
|
|
5232
|
+
## Calculating per group
|
|
5233
|
+
|
|
5234
|
+
Group the rows by an attribute to calculate each group’s total:
|
|
5235
|
+
|
|
5236
|
+
```ts
|
|
5237
|
+
import { Product } from "./models";
|
|
5238
|
+
|
|
5239
|
+
const byAvailability = await Product.group("available").count(); // Map { 1 => 3, 0 => 1 }
|
|
5240
|
+
const inStock = byAvailability.get(1); // 3
|
|
5241
|
+
const valueByAvailability = await Product.group("available").sum("priceCents");
|
|
5242
|
+
```
|
|
5243
|
+
|
|
5244
|
+
- Each calculation returns a `Map` from the group’s value to its result. `count`, `sum`, `average`, `minimum`, and `maximum` all work this way.
|
|
5245
|
+
- 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.
|
|
5246
|
+
- The groups come in the order the database returns them, unless you order them.
|
|
5247
|
+
|
|
5248
|
+
To group by several attributes, or by an expression, pass each one to `group`:
|
|
5249
|
+
|
|
5250
|
+
```ts
|
|
5251
|
+
import { column, sql } from "@forestfuture/active-record";
|
|
5252
|
+
import { Product } from "./models";
|
|
5253
|
+
|
|
5254
|
+
const band = sql`CASE WHEN ${column("priceCents")} >= ${10_000} THEN 'pricey' ELSE 'cheap' END`;
|
|
5255
|
+
const byBand = await Product.group("available", band).count(); // Map { [1, "cheap"] => 2, … }
|
|
5256
|
+
```
|
|
5257
|
+
|
|
5258
|
+
Each key is then an array of the values, in the order you passed them. An expression’s value is whatever the database returns.
|
|
5259
|
+
|
|
5260
|
+
:::note
|
|
5261
|
+
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.
|
|
5262
|
+
:::
|
|
5263
|
+
|
|
5264
|
+
To keep only some groups, pass a condition on their totals to `having`:
|
|
5265
|
+
|
|
5266
|
+
```ts
|
|
5267
|
+
import { sql } from "@forestfuture/active-record";
|
|
5268
|
+
import { Product } from "./models";
|
|
5269
|
+
|
|
5270
|
+
const crowded = Product.group("available").having(sql`COUNT(*) > ${1}`);
|
|
5271
|
+
const crowdedCounts = await crowded.count(); // Map { 1 => 3 }
|
|
5272
|
+
```
|
|
5273
|
+
|
|
5274
|
+
To sort the groups, order them by a grouped attribute or by a total. A `limit` then picks groups:
|
|
5275
|
+
|
|
5276
|
+
```ts
|
|
5277
|
+
import { sql } from "@forestfuture/active-record";
|
|
5278
|
+
import { Product } from "./models";
|
|
5279
|
+
|
|
5280
|
+
const largestFirst = Product.group("available").order(sql`COUNT(*) DESC`);
|
|
5281
|
+
const largest = await largestFirst.limit(1).count(); // Map { 1 => 3 }
|
|
5282
|
+
```
|
|
5283
|
+
|
|
5284
|
+
- `where`, `limit`, `offset`, and `distinct()` work before or after `group`. After `distinct()`, `count`, `sum`, and `average` take each group’s distinct values.
|
|
5285
|
+
- 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.
|
|
5286
|
+
- On `none()`, each calculation returns an empty `Map` without a query.
|
|
5287
|
+
|
|
5288
|
+
> **Compared with Rails**
|
|
5289
|
+
>
|
|
5290
|
+
> 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
5291
|
|
|
3811
5292
|
## Selecting attributes
|
|
3812
5293
|
|
|
@@ -3851,13 +5332,13 @@ console.log(params); // ["admin", 10]
|
|
|
3851
5332
|
|
|
3852
5333
|
The values come back in `params`, apart from the SQL.
|
|
3853
5334
|
|
|
3854
|
-
A
|
|
5335
|
+
A `none()` Relation shows `1 = 0`, the condition that matches nothing.
|
|
3855
5336
|
|
|
3856
5337
|
:::note
|
|
3857
5338
|
`toSql()` returns the real values, filtered attributes included. To see what a query sent, with those filtered, use [`onQuery`](/logging).
|
|
3858
5339
|
:::
|
|
3859
5340
|
|
|
3860
|
-
|
|
5341
|
+
Bulk writes and [batches](/batches#batching-writes) have no `toSql()`. Use [`onQuery`](/logging) to see what they sent.
|
|
3861
5342
|
|
|
3862
5343
|
> **Compared with Rails**
|
|
3863
5344
|
>
|
|
@@ -3893,31 +5374,153 @@ export class User extends Model.define({
|
|
|
3893
5374
|
Call it as a static, or on any Relation of the Model:
|
|
3894
5375
|
|
|
3895
5376
|
```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();
|
|
5377
|
+
const admins = await User.active().where({ role: "admin" }).toArray();
|
|
5378
|
+
const recent = await User.createdAfter(new Date(Date.now() - 86_400_000)).count();
|
|
5379
|
+
```
|
|
5380
|
+
|
|
5381
|
+
- A scope’s arguments, and anything it computes such as `new Date()`, are evaluated when you call it.
|
|
5382
|
+
- 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(…)`.
|
|
5383
|
+
- A scope can’t reuse a Relation method’s name (`where`, `count`) or a Model static’s (`validates`, `scope`, `all`).
|
|
5384
|
+
- Inside a scope, `q` has every Relation method but not the Model’s other scopes. Share logic between scopes with a plain function.
|
|
5385
|
+
|
|
5386
|
+
:::note
|
|
5387
|
+
A scope whose body names its own class needs its type written out: `static roots: ScopeStatic<[]> = this.scope(…)`.
|
|
5388
|
+
:::
|
|
5389
|
+
|
|
5390
|
+
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"] })`.
|
|
5391
|
+
|
|
5392
|
+
## Defining a default scope
|
|
5393
|
+
|
|
5394
|
+
A default scope narrows every query on a Model. Declare one in the class’s `static {}` block:
|
|
5395
|
+
|
|
5396
|
+
```ts
|
|
5397
|
+
import { ApplicationRecord } from "./application-record";
|
|
5398
|
+
|
|
5399
|
+
export class Product extends ApplicationRecord {
|
|
5400
|
+
static {
|
|
5401
|
+
this.defaultScope((q) => q.where({ available: 1 }));
|
|
5402
|
+
}
|
|
5403
|
+
}
|
|
5404
|
+
```
|
|
5405
|
+
|
|
5406
|
+
Queries start from it, and new records take its conditions’ values:
|
|
5407
|
+
|
|
5408
|
+
```ts
|
|
5409
|
+
const listed = await Product.order({ name: "asc" }).toArray(); // available products only
|
|
5410
|
+
const draft = Product.build({ name: "Pen" }); // available: 1, from the default scope
|
|
5411
|
+
```
|
|
5412
|
+
|
|
5413
|
+
- It applies to everything that queries the Model: `find`, `count`, `updateAll`, `deleteAll`, its scopes, and associations that read it, preloads included.
|
|
5414
|
+
- `reload`, uniqueness validation, and a record’s own `save` and `destroy` ignore it, since they work by primary key.
|
|
5415
|
+
- `insert`, `insertAll`, `upsert`, and `upsertAll` write its conditions’ values over the values you give. `build` and `create` use the values you give.
|
|
5416
|
+
- Several default scopes all apply. A subclass adds its own to its parent’s.
|
|
5417
|
+
- An order in a default scope is the Relation’s order. `reorder` replaces it.
|
|
5418
|
+
- `rewhere` replaces its condition on an attribute, and [`unscope`](#replacing-conditions) drops its parts.
|
|
5419
|
+
|
|
5420
|
+
To leave the default scope out, start from `unscoped()`:
|
|
5421
|
+
|
|
5422
|
+
```ts
|
|
5423
|
+
const everything = await Product.unscoped().toArray(); // available or not
|
|
5424
|
+
```
|
|
5425
|
+
|
|
5426
|
+
`unscoped()` is a Model static only. With a database you hold, call it inside [`withDatabase`](/connecting#using-the-requests-database).
|
|
5427
|
+
|
|
5428
|
+
:::warning[Default scopes hide records from associations too]
|
|
5429
|
+
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:
|
|
5430
|
+
|
|
5431
|
+
```ts
|
|
5432
|
+
class Post extends ApplicationRecord {
|
|
5433
|
+
static kept = this.scope((q) => q.where({ deletedAt: null }));
|
|
5434
|
+
}
|
|
5435
|
+
```
|
|
5436
|
+
|
|
5437
|
+
Then call `Post.kept()` where deleted posts should stay hidden.
|
|
5438
|
+
:::
|
|
5439
|
+
|
|
5440
|
+
> **Compared with Rails**
|
|
5441
|
+
>
|
|
5442
|
+
> `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.
|
|
5443
|
+
|
|
5444
|
+
## Merging Relations
|
|
5445
|
+
|
|
5446
|
+
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:
|
|
5447
|
+
|
|
5448
|
+
```ts
|
|
5449
|
+
const recent = User.order({ createdAt: "desc" }).limit(10);
|
|
5450
|
+
const admins = await User.where({ role: "admin" }).merge(recent).toArray();
|
|
5451
|
+
```
|
|
5452
|
+
|
|
5453
|
+
To merge a Relation of another Model, join that Model first. See [Joining associations](#joining-associations).
|
|
5454
|
+
|
|
5455
|
+
> **Compared with Rails**
|
|
5456
|
+
>
|
|
5457
|
+
> Rails adds the argument’s order to the receiver’s. Active Record replaces it.
|
|
5458
|
+
|
|
5459
|
+
## Joining associations
|
|
5460
|
+
|
|
5461
|
+
`joins` finds the records that have a linked record, through the associations you’ve declared. Name an association, or nest them in an object:
|
|
5462
|
+
|
|
5463
|
+
```ts
|
|
5464
|
+
import { Author } from "./models";
|
|
5465
|
+
|
|
5466
|
+
const commented = Author.joins({ articles: "comments" }).distinct();
|
|
5467
|
+
const authors = await commented.toArray(); // each author with a commented article, once
|
|
5468
|
+
```
|
|
5469
|
+
|
|
5470
|
+
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.
|
|
5471
|
+
|
|
5472
|
+
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.
|
|
5473
|
+
|
|
5474
|
+
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.
|
|
5475
|
+
|
|
5476
|
+
### Keeping records without a link
|
|
5477
|
+
|
|
5478
|
+
`leftJoins` joins the same way, but keeps the records that have no linked record:
|
|
5479
|
+
|
|
5480
|
+
```ts
|
|
5481
|
+
import { Author } from "./models";
|
|
5482
|
+
|
|
5483
|
+
const withProfiles = Author.leftJoins("profile"); // every author, with a profile or not
|
|
5484
|
+
const everyAuthor = await withProfiles.toArray();
|
|
5485
|
+
```
|
|
5486
|
+
|
|
5487
|
+
### Filtering by a joined Model
|
|
5488
|
+
|
|
5489
|
+
Merge a Relation of the joined Model to filter or sort by its attributes:
|
|
5490
|
+
|
|
5491
|
+
```ts
|
|
5492
|
+
import { Article, Author } from "./models";
|
|
5493
|
+
|
|
5494
|
+
const mary = Author.where({ name: "Mary" });
|
|
5495
|
+
const byMary = Article.joins("author").merge(mary);
|
|
5496
|
+
const titles = await byMary.pluck("title");
|
|
5497
|
+
|
|
5498
|
+
const byName = Author.order({ name: "asc" });
|
|
5499
|
+
const byAuthorName = Article.joins("author").merge(byName);
|
|
3898
5500
|
```
|
|
3899
5501
|
|
|
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.
|
|
5502
|
+
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
5503
|
|
|
3905
5504
|
:::note
|
|
3906
|
-
A
|
|
5505
|
+
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
5506
|
:::
|
|
3908
5507
|
|
|
3909
|
-
|
|
3910
|
-
|
|
3911
|
-
|
|
5508
|
+
:::note
|
|
5509
|
+
A join reads one database. Joining an association to a Model on another database throws `IncompatibleRelation` when you write the query.
|
|
5510
|
+
:::
|
|
3912
5511
|
|
|
3913
|
-
|
|
3914
|
-
|
|
3915
|
-
|
|
3916
|
-
```
|
|
5512
|
+
:::note
|
|
5513
|
+
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")`.
|
|
5514
|
+
:::
|
|
3917
5515
|
|
|
3918
5516
|
> **Compared with Rails**
|
|
3919
5517
|
>
|
|
3920
|
-
> Rails
|
|
5518
|
+
> - 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.
|
|
5519
|
+
> - Rails applies a merged Relation’s `limit` to the whole query. Active Record refuses it.
|
|
5520
|
+
> - 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.
|
|
5521
|
+
> - With a `hasMany` join, Rails’ `find(1, 2)` counts the duplicate rows and raises `RecordNotFound`. Active Record returns each record once.
|
|
5522
|
+
> - 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.
|
|
5523
|
+
> - 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
5524
|
|
|
3922
5525
|
## Preloading associations
|
|
3923
5526
|
|
|
@@ -4033,7 +5636,7 @@ export class Product extends ApplicationRecord {}
|
|
|
4033
5636
|
|
|
4034
5637
|
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
5638
|
|
|
4036
|
-
When your Worker runs, `Product` finds its attributes the first time it’s used. Its table comes from its
|
|
5639
|
+
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
5640
|
|
|
4038
5641
|
`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
5642
|
|
|
@@ -4078,7 +5681,7 @@ The library’s guarantees are tested against a real D1 database (through Minifl
|
|
|
4078
5681
|
| 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
5682
|
| `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
5683
|
| 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)
|
|
5684
|
+
| 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
5685
|
| 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
5686
|
| 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
5687
|
| 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 +5771,7 @@ Please report a security problem privately, as the [security policy](https://git
|
|
|
4168
5771
|
# Multiple databases
|
|
4169
5772
|
Source: https://active-record.forestfuture.dev/several-databases
|
|
4170
5773
|
|
|
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.
|
|
5774
|
+
A Worker can bind several D1 databases, or a D1 database and a Postgres one. Each gets its own schema file and base class, and each Model queries the database its base class names.
|
|
4172
5775
|
|
|
4173
5776
|
## Binding the databases
|
|
4174
5777
|
|
|
@@ -4260,6 +5863,62 @@ If `createOrThrow` throws, nothing reaches `LOGS`.
|
|
|
4260
5863
|
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
5864
|
:::
|
|
4262
5865
|
|
|
5866
|
+
## Associating Models on different databases
|
|
5867
|
+
|
|
5868
|
+
An association can link Models on different databases. Declare it as usual:
|
|
5869
|
+
|
|
5870
|
+
```ts
|
|
5871
|
+
import { belongsTo, hasMany } from "@forestfuture/active-record";
|
|
5872
|
+
|
|
5873
|
+
export class User extends DbRecord {
|
|
5874
|
+
entries = hasMany(Entry); // on LOGS
|
|
5875
|
+
}
|
|
5876
|
+
|
|
5877
|
+
export class Entry extends LogsRecord {
|
|
5878
|
+
user = belongsTo(User, { optional: true }); // on DB; an entry may have no user
|
|
5879
|
+
}
|
|
5880
|
+
```
|
|
5881
|
+
|
|
5882
|
+
Each read goes to the database its Model is on:
|
|
5883
|
+
|
|
5884
|
+
```ts
|
|
5885
|
+
export async function errorEntriesOf(userId: number) {
|
|
5886
|
+
const user = await User.find(userId); // on DB
|
|
5887
|
+
return user.entries().where({ level: "error" }).toArray(); // on LOGS
|
|
5888
|
+
}
|
|
5889
|
+
|
|
5890
|
+
export async function entriesWithUsers() {
|
|
5891
|
+
return Entry.includes("user").toArray(); // the entries on LOGS, then their users on DB
|
|
5892
|
+
}
|
|
5893
|
+
```
|
|
5894
|
+
|
|
5895
|
+
`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.
|
|
5896
|
+
|
|
5897
|
+
Records you create through an association are written to their own database:
|
|
5898
|
+
|
|
5899
|
+
```ts
|
|
5900
|
+
export async function logFor(user: User, message: string) {
|
|
5901
|
+
return user.entries().create({ level: "info", message }); // on LOGS, with the user's key
|
|
5902
|
+
}
|
|
5903
|
+
```
|
|
5904
|
+
|
|
5905
|
+
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:
|
|
5906
|
+
|
|
5907
|
+
```ts
|
|
5908
|
+
export async function signUpWithEntry(email: string) {
|
|
5909
|
+
const user = User.build({ email });
|
|
5910
|
+
user.entries().build({ level: "info", message: "signed up" });
|
|
5911
|
+
await user.saveOrThrow(); // the user on DB, then the entry on LOGS
|
|
5912
|
+
return user;
|
|
5913
|
+
}
|
|
5914
|
+
```
|
|
5915
|
+
|
|
5916
|
+
[`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`.
|
|
5917
|
+
|
|
5918
|
+
:::warning[Each database is written on its own]
|
|
5919
|
+
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.
|
|
5920
|
+
:::
|
|
5921
|
+
|
|
4263
5922
|
## Reading your own writes on each
|
|
4264
5923
|
|
|
4265
5924
|
With read replication, give each database its own Session. Nest a `withSession` call for each, and give each its own cookie name:
|
|
@@ -4342,6 +6001,48 @@ Name the binding with `--database`:
|
|
|
4342
6001
|
npx active-record console --database LOGS
|
|
4343
6002
|
```
|
|
4344
6003
|
|
|
6004
|
+
## Using databases on different adapters
|
|
6005
|
+
|
|
6006
|
+
One project can keep some of its tables on D1 and others on Postgres. First install `pg` and PGlite, as [PostgreSQL](/postgresql) describes.
|
|
6007
|
+
|
|
6008
|
+
Name each database’s adapter in `active-record.jsonc`, and give the Postgres one its own migrations folder:
|
|
6009
|
+
|
|
6010
|
+
```jsonc active-record.jsonc
|
|
6011
|
+
{
|
|
6012
|
+
"databases": {
|
|
6013
|
+
"DB": { "adapter": "d1" },
|
|
6014
|
+
"HYPERDRIVE": {
|
|
6015
|
+
"adapter": "postgresql",
|
|
6016
|
+
"migrationsDir": "pg-migrations",
|
|
6017
|
+
"url": "postgres://localhost/shop_development",
|
|
6018
|
+
},
|
|
6019
|
+
},
|
|
6020
|
+
}
|
|
6021
|
+
```
|
|
6022
|
+
|
|
6023
|
+
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.
|
|
6024
|
+
|
|
6025
|
+
To add your Hyperdrive bindings to a file that names only D1 databases, run `init` with the adapter:
|
|
6026
|
+
|
|
6027
|
+
```sh
|
|
6028
|
+
npx active-record init --adapter postgresql
|
|
6029
|
+
```
|
|
6030
|
+
|
|
6031
|
+
`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:
|
|
6032
|
+
|
|
6033
|
+
```ts
|
|
6034
|
+
import { HyperdriveRecord } from "./hyperdrive-record";
|
|
6035
|
+
|
|
6036
|
+
export class Order extends HyperdriveRecord {}
|
|
6037
|
+
```
|
|
6038
|
+
|
|
6039
|
+
Name the database with `--database` for the generators, `migrate`, and the console:
|
|
6040
|
+
|
|
6041
|
+
```sh
|
|
6042
|
+
npx active-record g model Order total:integer --database HYPERDRIVE
|
|
6043
|
+
npx active-record migrate --database HYPERDRIVE
|
|
6044
|
+
```
|
|
6045
|
+
|
|
4345
6046
|
---
|
|
4346
6047
|
|
|
4347
6048
|
# Shared behavior
|
|
@@ -4506,7 +6207,7 @@ test("emails are saved in lowercase", async () => {
|
|
|
4506
6207
|
});
|
|
4507
6208
|
```
|
|
4508
6209
|
|
|
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)`.
|
|
6210
|
+
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
6211
|
|
|
4511
6212
|
## Testing your Worker
|
|
4512
6213
|
|
|
@@ -4603,7 +6304,7 @@ export async function updateAccount(account: Account, request: Request): Promise
|
|
|
4603
6304
|
|
|
4604
6305
|
## Querying with request values
|
|
4605
6306
|
|
|
4606
|
-
Check that a value is a string before you query with it
|
|
6307
|
+
Check that a value is a string before you query with it:
|
|
4607
6308
|
|
|
4608
6309
|
```ts
|
|
4609
6310
|
export async function accept(request: Request): Promise<Response> {
|
|
@@ -4620,10 +6321,26 @@ export async function accept(request: Request): Promise<Response> {
|
|
|
4620
6321
|
}
|
|
4621
6322
|
```
|
|
4622
6323
|
|
|
6324
|
+
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.
|
|
6325
|
+
|
|
6326
|
+
`findOrCreateBy`, `findOrInitializeBy`, and `createOrFindBy` refuse a list. They throw a `TypeError` before they query, since their attributes become the new record’s values.
|
|
6327
|
+
|
|
4623
6328
|
:::note
|
|
4624
6329
|
A value that can’t be cast matches nothing, so `whereNot({ id: "abc" })` excludes nothing.
|
|
4625
6330
|
:::
|
|
4626
6331
|
|
|
6332
|
+
> **Beyond Rails**
|
|
6333
|
+
>
|
|
6334
|
+
> 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.
|
|
6335
|
+
>
|
|
6336
|
+
> 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`.
|
|
6337
|
+
|
|
6338
|
+
### Rewriting queries
|
|
6339
|
+
|
|
6340
|
+
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.
|
|
6341
|
+
|
|
6342
|
+
An association’s link to its owner always stays. `user.posts().rewhere({ userId: 2 })` finds nothing, since no post belongs to both users.
|
|
6343
|
+
|
|
4627
6344
|
---
|
|
4628
6345
|
|
|
4629
6346
|
# Upgrading
|
|
@@ -4631,6 +6348,95 @@ Source: https://active-record.forestfuture.dev/upgrading
|
|
|
4631
6348
|
|
|
4632
6349
|
Each section moves an app up one release. Start from the release you’re on.
|
|
4633
6350
|
|
|
6351
|
+
## Upgrading from 0.7 to 0.8
|
|
6352
|
+
|
|
6353
|
+
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.
|
|
6354
|
+
|
|
6355
|
+
### Marking optional associations
|
|
6356
|
+
|
|
6357
|
+
Saving now fails with “must exist” when a `belongsTo` points at nothing. Add `optional: true` to each one whose foreign key can be `null`:
|
|
6358
|
+
|
|
6359
|
+
```ts
|
|
6360
|
+
import { belongsTo } from "@forestfuture/active-record";
|
|
6361
|
+
|
|
6362
|
+
export class Category extends ApplicationRecord {
|
|
6363
|
+
parent = belongsTo(Category, { optional: true });
|
|
6364
|
+
}
|
|
6365
|
+
```
|
|
6366
|
+
|
|
6367
|
+
A record built through its owner’s `hasMany` or `hasOne` passes without it.
|
|
6368
|
+
|
|
6369
|
+
### Reading a new record’s changes
|
|
6370
|
+
|
|
6371
|
+
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.
|
|
6372
|
+
|
|
6373
|
+
### Preparing batch writes in a callback
|
|
6374
|
+
|
|
6375
|
+
Pass `batch` and `db.batch` a callback that returns the writes, instead of an array:
|
|
6376
|
+
|
|
6377
|
+
```ts
|
|
6378
|
+
import { batch } from "@forestfuture/active-record";
|
|
6379
|
+
|
|
6380
|
+
await batch((b) => [b.save(user), b.deleteAll(Post.where({ userId: user.id }))]);
|
|
6381
|
+
```
|
|
6382
|
+
|
|
6383
|
+
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.
|
|
6384
|
+
|
|
6385
|
+
### Replacing a hasOne’s record
|
|
6386
|
+
|
|
6387
|
+
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).
|
|
6388
|
+
|
|
6389
|
+
### Checking keys given through a hasMany
|
|
6390
|
+
|
|
6391
|
+
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 })`.
|
|
6392
|
+
|
|
6393
|
+
### Checking values given to bulk writes
|
|
6394
|
+
|
|
6395
|
+
`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.
|
|
6396
|
+
|
|
6397
|
+
### Regenerating the schema
|
|
6398
|
+
|
|
6399
|
+
Run `schema` in your project’s folder:
|
|
6400
|
+
|
|
6401
|
+
```sh
|
|
6402
|
+
npx active-record schema
|
|
6403
|
+
```
|
|
6404
|
+
|
|
6405
|
+
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.
|
|
6406
|
+
|
|
6407
|
+
### Reading `DATE` columns
|
|
6408
|
+
|
|
6409
|
+
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:
|
|
6410
|
+
|
|
6411
|
+
```ts
|
|
6412
|
+
import { ApplicationRecord } from "./application-record";
|
|
6413
|
+
|
|
6414
|
+
export class Event extends ApplicationRecord {
|
|
6415
|
+
static override attributes = { startsOn: "datetime" } as const;
|
|
6416
|
+
}
|
|
6417
|
+
```
|
|
6418
|
+
|
|
6419
|
+
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:
|
|
6420
|
+
|
|
6421
|
+
```sql
|
|
6422
|
+
SELECT count(*) FROM events
|
|
6423
|
+
WHERE length(starts_on) > 10 AND substr(starts_on, 11) <> 'T00:00:00.000Z';
|
|
6424
|
+
```
|
|
6425
|
+
|
|
6426
|
+
If there are none, keep only each day:
|
|
6427
|
+
|
|
6428
|
+
```sql
|
|
6429
|
+
UPDATE events SET starts_on = substr(starts_on, 1, 10) WHERE length(starts_on) > 10;
|
|
6430
|
+
```
|
|
6431
|
+
|
|
6432
|
+
Postgres stores a `date` without a time, so its rows need no change.
|
|
6433
|
+
|
|
6434
|
+
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.
|
|
6435
|
+
|
|
6436
|
+
### Typing serialized values
|
|
6437
|
+
|
|
6438
|
+
`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.
|
|
6439
|
+
|
|
4634
6440
|
## Upgrading from 0.6 to 0.7
|
|
4635
6441
|
|
|
4636
6442
|
In 0.7, the adapters ship inside `@forestfuture/active-record`, so an app on D1 installs one package. Upgrade in four steps.
|
|
@@ -4673,7 +6479,7 @@ It writes `active-record.jsonc`, naming each database in your Wrangler config’
|
|
|
4673
6479
|
}
|
|
4674
6480
|
```
|
|
4675
6481
|
|
|
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.
|
|
6482
|
+
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
6483
|
|
|
4678
6484
|
### Regenerating the schema
|
|
4679
6485
|
|
|
@@ -4809,30 +6615,208 @@ const valid = await account.isValid();
|
|
|
4809
6615
|
| Rule | Options | Error type |
|
|
4810
6616
|
| -------------- | -------------------------------------------------------------------------------------------- | ---------------------------------------------- |
|
|
4811
6617
|
| `presence` | `true` | `blank` |
|
|
6618
|
+
| `absence` | `true` | `present` |
|
|
4812
6619
|
| `length` | `{ minimum, maximum, is }` | `tooShort`, `tooLong`, `wrongLength` |
|
|
4813
6620
|
| `format` | `{ with: /re/ }`, or a regex | `invalid` |
|
|
4814
6621
|
| `inclusion` | `{ in: [...] }`, or an array | `inclusion` |
|
|
6622
|
+
| `exclusion` | `{ in: [...] }`, or an array | `exclusion` |
|
|
4815
6623
|
| `numericality` | `{ onlyInteger, greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo }`, or `true` | `notANumber`, `notAnInteger`, `greaterThan`, … |
|
|
6624
|
+
| `comparison` | `{ greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo, equalTo, otherThan }` | `blank`, `greaterThan`, … |
|
|
6625
|
+
| `acceptance` | `true`, or `{ accept: [...] }` | `accepted` |
|
|
4816
6626
|
| `uniqueness` | `{ scope: [...], caseSensitive }`, or `true` | `taken` |
|
|
4817
6627
|
|
|
4818
|
-
Every validation runs, in the order declared, so one attribute can collect several errors. Every rule also accepts these options:
|
|
6628
|
+
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
6629
|
|
|
4820
|
-
- **`allowNull`** skips the rule when the value is `null`. Otherwise `null` fails `presence`, `format`, `inclusion`, and `
|
|
6630
|
+
- **`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.
|
|
6631
|
+
- **`allowBlank`** skips the rule when the value is blank: `null`, or a string that’s only whitespace.
|
|
4821
6632
|
- **`message`** replaces the default messages from that call.
|
|
4822
6633
|
- **`if: (record) => boolean`** validates only when it returns `true`.
|
|
6634
|
+
- **`unless: (record) => boolean`** skips the rule when it returns `true`. With `if` as well, both must allow it.
|
|
6635
|
+
- **`strict`** throws instead of adding an error. See [Raising instead of collecting errors](#raising-instead-of-collecting-errors).
|
|
6636
|
+
- **`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
6637
|
|
|
4824
6638
|
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
6639
|
|
|
4826
6640
|
### Validator details
|
|
4827
6641
|
|
|
4828
6642
|
- **`presence`** fails a string that’s only whitespace. For a boolean, use `inclusion: [true, false]`, since `false` is a value.
|
|
4829
|
-
- **`
|
|
6643
|
+
- **`absence`** passes what `presence` fails: `null` and a string that’s only whitespace. So `false` fails it.
|
|
6644
|
+
- **`inclusion`** is added for you by an [enum](/models#reading-and-assigning-other-values) declared `validate: true`.
|
|
6645
|
+
- **`exclusion`** passes `null` unless the list holds it.
|
|
6646
|
+
- **`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.
|
|
6647
|
+
- **`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.
|
|
6648
|
+
- **`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
6649
|
- **`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
6650
|
|
|
6651
|
+
> **Compared with Rails**
|
|
6652
|
+
>
|
|
6653
|
+
> Rails treats `false` as blank, so it passes `absence`. Here `false` passes `presence`, so it fails `absence`.
|
|
6654
|
+
>
|
|
6655
|
+
> 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.
|
|
6656
|
+
>
|
|
6657
|
+
> Rails’ `allow_blank` also skips `false`, `[]`, and `{}`. Here `allowBlank` skips what `presence` fails: `null` and a string that’s only whitespace.
|
|
6658
|
+
>
|
|
6659
|
+
> Rails’ `confirmation` isn’t here yet.
|
|
6660
|
+
|
|
4832
6661
|
:::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).
|
|
6662
|
+
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.
|
|
6663
|
+
:::
|
|
6664
|
+
|
|
6665
|
+
### Comparing with another attribute
|
|
6666
|
+
|
|
6667
|
+
Give `comparison` a function of the record to compare with another attribute:
|
|
6668
|
+
|
|
6669
|
+
```ts
|
|
6670
|
+
import { Model } from "@forestfuture/active-record";
|
|
6671
|
+
|
|
6672
|
+
export class Event extends Model.define({
|
|
6673
|
+
id: { type: "integer", null: false },
|
|
6674
|
+
startsAt: { type: "datetime", null: false },
|
|
6675
|
+
endsAt: { type: "datetime", null: false },
|
|
6676
|
+
}) {
|
|
6677
|
+
static {
|
|
6678
|
+
this.validates("endsAt", { comparison: { greaterThan: (event) => event.startsAt } });
|
|
6679
|
+
}
|
|
6680
|
+
}
|
|
6681
|
+
```
|
|
6682
|
+
|
|
6683
|
+
When the function returns `null`, that bound is skipped. Validate the other attribute’s presence to report it.
|
|
6684
|
+
|
|
6685
|
+
> **Compared with Rails**
|
|
6686
|
+
>
|
|
6687
|
+
> 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.
|
|
6688
|
+
|
|
6689
|
+
### Raising instead of collecting errors
|
|
6690
|
+
|
|
6691
|
+
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:
|
|
6692
|
+
|
|
6693
|
+
```ts
|
|
6694
|
+
import { Model } from "@forestfuture/active-record";
|
|
6695
|
+
|
|
6696
|
+
export class Invoice extends Model.define({
|
|
6697
|
+
id: { type: "integer", null: false },
|
|
6698
|
+
total: { type: "integer", null: false },
|
|
6699
|
+
currency: { type: "string", null: false },
|
|
6700
|
+
}) {
|
|
6701
|
+
static {
|
|
6702
|
+
this.validates("currency", { inclusion: ["USD", "EUR"], strict: true });
|
|
6703
|
+
}
|
|
6704
|
+
}
|
|
6705
|
+
```
|
|
6706
|
+
|
|
6707
|
+
```ts
|
|
6708
|
+
const invoice = Invoice.build({ total: 1200, currency: "GBP" });
|
|
6709
|
+
await invoice.isValid(); // throws "Currency is not included in the list"
|
|
6710
|
+
```
|
|
6711
|
+
|
|
6712
|
+
`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.
|
|
6713
|
+
|
|
6714
|
+
## Validating only when creating or updating
|
|
6715
|
+
|
|
6716
|
+
By default, a rule runs on every save. To run it only when a record is created, pass `on: "create"`:
|
|
6717
|
+
|
|
6718
|
+
```ts
|
|
6719
|
+
import { Model } from "@forestfuture/active-record";
|
|
6720
|
+
|
|
6721
|
+
export class Member extends Model.define({
|
|
6722
|
+
id: { type: "integer", null: false },
|
|
6723
|
+
email: { type: "string", null: false },
|
|
6724
|
+
password: "string",
|
|
6725
|
+
inviteCode: "string",
|
|
6726
|
+
}) {
|
|
6727
|
+
static validationContexts = ["signup"] as const;
|
|
6728
|
+
|
|
6729
|
+
static {
|
|
6730
|
+
this.validates("email", { format: /@/ });
|
|
6731
|
+
this.validates("password", { presence: true, on: "create" });
|
|
6732
|
+
this.validates("inviteCode", { presence: true, on: "signup" });
|
|
6733
|
+
}
|
|
6734
|
+
}
|
|
6735
|
+
```
|
|
6736
|
+
|
|
6737
|
+
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"]`.
|
|
6738
|
+
|
|
6739
|
+
`exceptOn` works the other way. The rule runs in every context except the ones it names.
|
|
6740
|
+
|
|
6741
|
+
### Naming your own contexts
|
|
6742
|
+
|
|
6743
|
+
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`:
|
|
6744
|
+
|
|
6745
|
+
```ts
|
|
6746
|
+
const member = Member.build({ email: "ada@example.com", password: "secret" });
|
|
6747
|
+
await member.isValid("signup"); // false: invite code can't be blank
|
|
6748
|
+
await member.save({ context: "signup" });
|
|
6749
|
+
```
|
|
6750
|
+
|
|
6751
|
+
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:
|
|
6752
|
+
|
|
6753
|
+
```ts
|
|
6754
|
+
await member.save({ context: ["create", "signup"] });
|
|
6755
|
+
```
|
|
6756
|
+
|
|
6757
|
+
`"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`.
|
|
6758
|
+
|
|
6759
|
+
:::note
|
|
6760
|
+
List contexts on each Model. A Model’s subclass shares its list, and an abstract base class can’t have one.
|
|
6761
|
+
:::
|
|
6762
|
+
|
|
6763
|
+
### Validating associated records in a context
|
|
6764
|
+
|
|
6765
|
+
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.
|
|
6766
|
+
|
|
6767
|
+
> **Beyond Rails**
|
|
6768
|
+
>
|
|
6769
|
+
> 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`.
|
|
6770
|
+
|
|
6771
|
+
> **Compared with Rails**
|
|
6772
|
+
>
|
|
6773
|
+
> `valid?(:signup)` is `isValid("signup")`, `save(context: :signup)` is `save({ context: "signup" })`, and `except_on:` is `exceptOn`.
|
|
6774
|
+
|
|
6775
|
+
## Validating associated records
|
|
6776
|
+
|
|
6777
|
+
To validate an association’s records with their owner, call `this.validatesAssociated`:
|
|
6778
|
+
|
|
6779
|
+
```ts
|
|
6780
|
+
import { hasMany, Model } from "@forestfuture/active-record";
|
|
6781
|
+
|
|
6782
|
+
export class Track extends Model.define({
|
|
6783
|
+
id: { type: "integer", null: false },
|
|
6784
|
+
playlistId: { type: "integer", null: false },
|
|
6785
|
+
title: { type: "string", null: false },
|
|
6786
|
+
}) {
|
|
6787
|
+
static {
|
|
6788
|
+
this.validates("title", { presence: true });
|
|
6789
|
+
}
|
|
6790
|
+
}
|
|
6791
|
+
|
|
6792
|
+
export class Playlist extends Model.define({
|
|
6793
|
+
id: { type: "integer", null: false },
|
|
6794
|
+
name: { type: "string", null: false },
|
|
6795
|
+
}) {
|
|
6796
|
+
tracks = hasMany(Track);
|
|
6797
|
+
|
|
6798
|
+
static {
|
|
6799
|
+
this.validatesAssociated("tracks");
|
|
6800
|
+
}
|
|
6801
|
+
}
|
|
6802
|
+
```
|
|
6803
|
+
|
|
6804
|
+
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`.
|
|
6805
|
+
|
|
6806
|
+
`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.
|
|
6807
|
+
|
|
6808
|
+
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.
|
|
6809
|
+
|
|
6810
|
+
:::note
|
|
6811
|
+
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
6812
|
:::
|
|
4835
6813
|
|
|
6814
|
+
> **Compared with Rails**
|
|
6815
|
+
>
|
|
6816
|
+
> 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.
|
|
6817
|
+
>
|
|
6818
|
+
> Rails’ `validates_associated` on both sides of an association recurses until the stack overflows. Here the record already being validated counts as valid.
|
|
6819
|
+
|
|
4836
6820
|
## Reading errors
|
|
4837
6821
|
|
|
4838
6822
|
A record’s `errors` hold each failed rule:
|
|
@@ -4868,11 +6852,11 @@ export class Booking extends Model.define({
|
|
|
4868
6852
|
endsAt: { type: "datetime", null: false },
|
|
4869
6853
|
}) {
|
|
4870
6854
|
static {
|
|
4871
|
-
this.errorMessages({
|
|
6855
|
+
this.errorMessages({ onTheHour: "must be on the hour" });
|
|
4872
6856
|
|
|
4873
6857
|
this.afterValidation((booking) => {
|
|
4874
|
-
if (booking.
|
|
4875
|
-
booking.errors.add("
|
|
6858
|
+
if (booking.startsAt.getUTCMinutes() !== 0) {
|
|
6859
|
+
booking.errors.add("startsAt", { type: "onTheHour" });
|
|
4876
6860
|
}
|
|
4877
6861
|
if (booking.startsAt.getUTCDay() === 0) {
|
|
4878
6862
|
booking.errors.add("base", "The room is closed on Sundays");
|
|
@@ -4882,17 +6866,18 @@ export class Booking extends Model.define({
|
|
|
4882
6866
|
}
|
|
4883
6867
|
```
|
|
4884
6868
|
|
|
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 `
|
|
6869
|
+
`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
6870
|
|
|
4887
6871
|
```ts
|
|
4888
|
-
const
|
|
4889
|
-
const
|
|
6872
|
+
const startsAt = new Date("2026-05-03T10:30:00Z"); // a Sunday
|
|
6873
|
+
const endsAt = new Date("2026-05-03T11:30:00Z");
|
|
6874
|
+
const booking = Booking.build({ startsAt, endsAt });
|
|
4890
6875
|
await booking.isValid(); // false
|
|
4891
6876
|
|
|
4892
6877
|
booking.errors.toArray();
|
|
4893
|
-
// [{ attribute: "
|
|
6878
|
+
// [{ attribute: "startsAt", type: "onTheHour", message: "must be on the hour" },
|
|
4894
6879
|
// { attribute: "base", type: "invalid", message: "The room is closed on Sundays" }]
|
|
4895
|
-
booking.errors.fullMessages(); // ["
|
|
6880
|
+
booking.errors.fullMessages(); // ["Starts at must be on the hour", "The room is closed on Sundays"]
|
|
4896
6881
|
```
|
|
4897
6882
|
|
|
4898
6883
|
To fill in a placeholder, pass its value with the type:
|
|
@@ -4911,7 +6896,7 @@ Each validation run, from `isValid()`, `save()`, or `saveOrThrow()`, starts by c
|
|
|
4911
6896
|
|
|
4912
6897
|
> **Compared with Rails**
|
|
4913
6898
|
>
|
|
4914
|
-
> Rails’ `errors.add(:
|
|
6899
|
+
> 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
6900
|
|
|
4916
6901
|
## Changing error messages
|
|
4917
6902
|
|
|
@@ -4986,9 +6971,9 @@ In a Model, `attributes` and `humanAttributeNames` can only name the Model’s a
|
|
|
4986
6971
|
|
|
4987
6972
|
A message can show these values:
|
|
4988
6973
|
|
|
4989
|
-
- **`%{count}`**: the number
|
|
6974
|
+
- **`%{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
6975
|
- **`%{attribute}`**: the attribute’s name, as `fullMessages()` shows it.
|
|
4991
|
-
- **`%{model}`**: the Model’s
|
|
6976
|
+
- **`%{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
6977
|
- **`%{value}`**: the attribute’s value. A [filtered attribute](/models#filtering-attributes) shows `[FILTERED]`.
|
|
4993
6978
|
|
|
4994
6979
|
A value passed to `errors.add` with the type, such as `count`, fills in the placeholder of the same name.
|
|
@@ -5008,23 +6993,29 @@ A type with no message anywhere throws a `TypeError` when the error is added.
|
|
|
5008
6993
|
|
|
5009
6994
|
Each error type has a built-in message. To replace one, use its type as the key in `errorMessages`:
|
|
5010
6995
|
|
|
5011
|
-
| Type | Added by
|
|
5012
|
-
| -------------------------- |
|
|
5013
|
-
| `blank` | `presence`
|
|
5014
|
-
| `
|
|
5015
|
-
| `
|
|
5016
|
-
| `
|
|
5017
|
-
| `
|
|
5018
|
-
| `
|
|
5019
|
-
| `
|
|
5020
|
-
| `
|
|
5021
|
-
| `
|
|
5022
|
-
| `
|
|
5023
|
-
| `
|
|
5024
|
-
| `
|
|
5025
|
-
| `
|
|
5026
|
-
| `
|
|
5027
|
-
| `
|
|
6996
|
+
| Type | Added by | Message |
|
|
6997
|
+
| -------------------------- | ---------------------------------------------------------- | ----------------------------------------------------------- |
|
|
6998
|
+
| `blank` | `presence`, and `comparison` for a blank value | can’t be blank |
|
|
6999
|
+
| `present` | `absence` | must be blank |
|
|
7000
|
+
| `invalid` | `format` and an invalid autosaved association | is invalid |
|
|
7001
|
+
| `inclusion` | `inclusion` | is not included in the list |
|
|
7002
|
+
| `exclusion` | `exclusion` | is reserved |
|
|
7003
|
+
| `tooShort` | `length: { minimum }` | is too short (minimum is `%{count}` characters) |
|
|
7004
|
+
| `tooLong` | `length: { maximum }` | is too long (maximum is `%{count}` characters) |
|
|
7005
|
+
| `wrongLength` | `length: { is }` | is the wrong length (should be `%{count}` characters) |
|
|
7006
|
+
| `notANumber` | `numericality` | is not a number |
|
|
7007
|
+
| `notAnInteger` | `numericality: { onlyInteger }` | must be an integer |
|
|
7008
|
+
| `greaterThan` | `numericality` or `comparison`: `{ greaterThan }` | must be greater than `%{count}` |
|
|
7009
|
+
| `greaterThanOrEqualTo` | `numericality` or `comparison`: `{ greaterThanOrEqualTo }` | must be greater than or equal to `%{count}` |
|
|
7010
|
+
| `lessThan` | `numericality` or `comparison`: `{ lessThan }` | must be less than `%{count}` |
|
|
7011
|
+
| `lessThanOrEqualTo` | `numericality` or `comparison`: `{ lessThanOrEqualTo }` | must be less than or equal to `%{count}` |
|
|
7012
|
+
| `equalTo` | `comparison: { equalTo }` | must be equal to `%{count}` |
|
|
7013
|
+
| `otherThan` | `comparison: { otherThan }` | must be other than `%{count}` |
|
|
7014
|
+
| `accepted` | `acceptance` | must be accepted |
|
|
7015
|
+
| `taken` | `uniqueness` | has already been taken |
|
|
7016
|
+
| `required` | a `belongsTo` whose record doesn’t exist | must exist |
|
|
7017
|
+
| `restrictDependentDestroy` | a has-one with `dependent: "restrictWithError"` | Cannot delete record because a dependent `%{record}` exists |
|
|
7018
|
+
| `restrictDependentDestroy` | a has-many with `dependent: "restrictWithError"` | Cannot delete record because dependent `%{record}` exist |
|
|
5028
7019
|
|
|
5029
7020
|
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
7021
|
|