@forestfuture/active-record 0.8.1 → 0.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter.d.mts +2 -2
- package/dist/adapter.mjs +4 -4
- package/dist/{batch-Ms5p9lKq.mjs → batch-D3nP3g83.mjs} +6147 -5558
- package/dist/cli.mjs +3 -3
- package/dist/command.mjs +5 -5
- package/dist/d1.d.mts +2 -2
- package/dist/d1.mjs +4 -4
- package/dist/{identifiers-Dh5DFACX.mjs → epoch-storage-C7186hd1.mjs} +86 -86
- package/dist/{for-adapters-BbIMUNcz.mjs → for-adapters-CgEQfuyD.mjs} +2 -2
- package/dist/{for-adapters-BT2GDjIA.d.mts → for-adapters-DAn1wSYz.d.mts} +1 -1
- package/dist/{for-adapters-C-MQxaIx.mjs → for-adapters-l4rNitkK.mjs} +1 -1
- package/dist/{generated-model-DJA8vmNE.mjs → generated-model-FB7oT7V1.mjs} +285 -281
- package/dist/{index-D5getfHx.d.mts → index-BfX3Dgy_.d.mts} +26 -5
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +4 -4
- package/dist/{plugin-CZPDqguF.mjs → plugin-BY2QaRpq.mjs} +3 -3
- package/dist/{plugin-Cf-5Z0_h.mjs → plugin-IHD0I6Rg.mjs} +3 -3
- package/dist/postgresql.d.mts +1 -1
- package/dist/postgresql.mjs +4 -4
- package/dist/{src-BAVZKQ7J.mjs → src-DnuvSHF6.mjs} +2 -2
- package/dist/{storage-override-0ZgeP2sc.mjs → storage-override-BFC-GSR0.mjs} +1 -1
- package/dist/{validations-BSZ5gVeI.d.mts → validations-DFLjJ203.d.mts} +239 -188
- package/llms-full.txt +1163 -339
- package/package.json +1 -1
- package/skills/active-record/SKILL.md +2 -2
package/llms-full.txt
CHANGED
|
@@ -9,8 +9,6 @@ Source: https://active-record.forestfuture.dev/
|
|
|
9
9
|
npm install @forestfuture/active-record
|
|
10
10
|
```
|
|
11
11
|
|
|
12
|
-
The same Models and queries run on D1 and on Postgres. See the [PostgreSQL adapter](/postgresql).
|
|
13
|
-
|
|
14
12
|
**[Get started](/getting-started)**
|
|
15
13
|
|
|
16
14
|
From an empty Worker to two related Models in about ten minutes.
|
|
@@ -25,6 +23,37 @@ See what’s different
|
|
|
25
23
|
|
|
26
24
|
## A Model and its queries
|
|
27
25
|
|
|
26
|
+
Use a Model in your Worker with no connection setup. It finds its database from its binding:
|
|
27
|
+
|
|
28
|
+
```ts Worker
|
|
29
|
+
import { User } from "./models/user";
|
|
30
|
+
|
|
31
|
+
export default {
|
|
32
|
+
async fetch(request: Request): Promise<Response> {
|
|
33
|
+
// GET: the 20 newest active users, each with their posts.
|
|
34
|
+
if (request.method === "GET") {
|
|
35
|
+
const users = await User.active()
|
|
36
|
+
.includes("posts") // loaded in one extra query, not one per user
|
|
37
|
+
.order({ createdAt: "desc" })
|
|
38
|
+
.limit(20)
|
|
39
|
+
.toArray();
|
|
40
|
+
return Response.json(users);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// POST: sign up a user with a first post, saved together.
|
|
44
|
+
const { email } = await request.json<{ email: string }>();
|
|
45
|
+
const user = User.build({ email });
|
|
46
|
+
user.posts().build({ title: "Hello, world" });
|
|
47
|
+
|
|
48
|
+
// save() validates and runs callbacks; false means it wasn't saved, and why is in errors.
|
|
49
|
+
if (!(await user.save())) {
|
|
50
|
+
return Response.json({ errors: user.errors.fullMessages() }, { status: 422 });
|
|
51
|
+
}
|
|
52
|
+
return Response.json(user, { status: 201 });
|
|
53
|
+
},
|
|
54
|
+
} satisfies ExportedHandler<Env>;
|
|
55
|
+
```
|
|
56
|
+
|
|
28
57
|
```ts Model
|
|
29
58
|
import { hasMany } from "@forestfuture/active-record";
|
|
30
59
|
import { ApplicationRecord } from "./application-record";
|
|
@@ -92,6 +121,20 @@ CREATE TABLE posts (
|
|
|
92
121
|
CREATE INDEX index_posts_on_user_id ON posts (user_id);
|
|
93
122
|
```
|
|
94
123
|
|
|
124
|
+
## Choose your database
|
|
125
|
+
|
|
126
|
+
**[Cloudflare D1](/d1)**
|
|
127
|
+
|
|
128
|
+
Bind a D1 database, and read from nearby replicas with Sessions.
|
|
129
|
+
|
|
130
|
+
Use D1
|
|
131
|
+
|
|
132
|
+
**[Postgres](/postgresql)**
|
|
133
|
+
|
|
134
|
+
Connect through Hyperdrive in a Worker, or directly on Node.
|
|
135
|
+
|
|
136
|
+
Use Postgres
|
|
137
|
+
|
|
95
138
|
## What’s inside
|
|
96
139
|
|
|
97
140
|
**[Models, declared once](/models)**
|
|
@@ -124,8 +167,6 @@ works differently on its database.
|
|
|
124
167
|
# Existing databases
|
|
125
168
|
Source: https://active-record.forestfuture.dev/adopt-a-database
|
|
126
169
|
|
|
127
|
-
Active Record reads a database’s tables from its migrations. If your database already has migrations, from Drizzle, Prisma, or Wrangler, point Active Record at them. If it doesn’t, start from a snapshot of its schema.
|
|
128
|
-
|
|
129
170
|
## Using Drizzle’s migrations
|
|
130
171
|
|
|
131
172
|
Drizzle writes its migrations to `drizzle/`, its `out` setting. Tell Wrangler where they are:
|
|
@@ -271,7 +312,7 @@ The column stays an `INTEGER`. `createdAt` and `updatedAt` declared this way are
|
|
|
271
312
|
Under `unixSeconds`, a `Date` is stored to the second, so a condition such as `lt(date)` compares to the second too.
|
|
272
313
|
|
|
273
314
|
:::warning[A Date in an sql fragment]
|
|
274
|
-
A `Date` beside that column in a `sql` fragment throws `TypeError`: a fragment has no attribute, so it would bind as ISO text. Use `column("publishedAt").value(date)`, which writes it as the attribute stores it. See [Writing SQL fragments](/
|
|
315
|
+
A `Date` beside that column in a `sql` fragment throws `TypeError`: a fragment has no attribute, so it would bind as ISO text. Use `column("publishedAt").value(date)`, which writes it as the attribute stores it. See [Writing SQL fragments](/conditions#writing-sql-fragments).
|
|
275
316
|
:::
|
|
276
317
|
|
|
277
318
|
:::note
|
|
@@ -316,7 +357,9 @@ SQLite converts a value to the column’s declared type only when it can: `'42'`
|
|
|
316
357
|
# AI agents
|
|
317
358
|
Source: https://active-record.forestfuture.dev/ai-agents
|
|
318
359
|
|
|
319
|
-
|
|
360
|
+
:::tip
|
|
361
|
+
The agent skill gives your agent the guide and its rules, and is what most projects need. The rest are for agents that can’t load a skill, or for a pointer that’s always in context.
|
|
362
|
+
:::
|
|
320
363
|
|
|
321
364
|
## Giving your agent the docs
|
|
322
365
|
|
|
@@ -373,7 +416,7 @@ Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for
|
|
|
373
416
|
- For a raw `env.DB.prepare(…).bind(…)` statement, bind `Post.typeForAttribute("publishedAt").serialize(date)`, which writes the value as the attribute stores it, and read a cell with `.deserialize(cell)`. A value the attribute can't hold throws `TypeError`.
|
|
374
417
|
- Bulk writes run when called, without callbacks: `await posts.deleteAll()`, `deleteBy({…})` and `updateAll(…)` resolve to how many rows; `insert(…)`, `insertAll`, `upsert` and `upsertAll` to `{ rowsAffected, rows }`, where `rows` holds each written row's primary key, or the attributes `returning: [...]` names (`returning: false` for none). Through a Relation they write its equality values and `createWith` over the attributes given (`Post.where({ userId: 1 }).insert({ userId: 2, … })` writes `userId: 1`), where `build` and `create` keep the given ones. Make several writes atomic by preparing them in one batch's callback: `batch((b) => [b.insert(Post, {…}), b.updateAll(Post.where(…), {…}), b.save(user), b.destroy(post)])`. The callback can't await, so load what the writes need first. D1 has no interactive transactions, so a read-then-write can't be atomic.
|
|
375
418
|
- Count with the database, not in memory: `post.incrementColumn("viewCount")` or `Post.updateCounters(id, { viewCount: 1 })` add to the row atomically, where `post.viewCount++` then `save()` loses another request's increment. The counter statics (`Post.updateCounters(ids, …)`, `incrementCounter`) skip the default scope, so with a key from a request, and a default scope that separates tenants or hides deleted rows, write `Post.where({ id }).updateCounters({ … })`, which keeps it. The `…Column` methods and `updateColumns` skip validations, callbacks and `updatedAt`, so use `update` for a change those should see; `increment` and `toggle` only change the record in memory. In an after-callback, `record.isPreviouslyNewRecord()` says whether the save created it.
|
|
376
|
-
- To mark a record changed without saving it (a cache key, a "last seen"), `await record.touch()` sets `updatedAt`, or `touch("lastSeenAt")` that attribute too, with no validation or save callback; `Post.where(…).touchAll()` touches many rows. A touch runs `afterTouch` and the update commit callbacks (`afterUpdateCommit` included), so code there that should run only on a save belongs in `afterUpdate` or `afterSave`.
|
|
419
|
+
- To mark a record changed without saving it (a cache key, a "last seen"), `await record.touch()` sets `updatedAt`, or `touch("lastSeenAt")` that attribute too, with no validation or save callback; `Post.where(…).touchAll()` touches many rows. A touch runs `afterTouch` and the update commit callbacks (`afterUpdateCommit` included), so code there that should run only on a save belongs in `afterUpdate` or `afterSave`. To keep a parent's `updatedAt` current as its children change (a cache key), declare `belongsTo(Article, { touch: true })` on the child rather than touching the parent in a callback: the parent is touched in the child's batch, runs its own touch callbacks, and touches its own parents in turn. A parent that isn't loaded costs one SELECT per level, so preload the chain (`includes({ article: "blog" })`) when saving many. `hasOne(Profile, { touch: true })` touches a user's profile the same way when the user is updated, destroyed or touched. For a bulk import, wrap it in `Article.noTouching(async () => { … })`, so no article is touched per comment, then touch each article once after it.
|
|
377
420
|
- To show how many records an association has, keep a counter cache rather than counting on each read: `article = belongsTo(Article, { counterCache: true })` with a `commentsCount` attribute, which `article.comments().size()` reads. Saves, destroys and the association's `delete`/`clear`/`deleteAll()` keep it; bulk writes (`insertAll`, `updateAll`, a Relation's `deleteAll`) don't, so follow them with `Article.resetCounters(id, "comments")`. Add one to existing rows with `{ active: false }`, reset each, then drop `active: false`.
|
|
378
421
|
- To work through more records than a request should hold (a backfill, an export, a cleanup), iterate in batches rather than `toArray()` or `offset` pages: `for await (const user of User.where(…).findEach())`, `findInBatches()` for arrays, and `inBatches()` for a Relation per batch to `updateAll`, `deleteAll` or `destroyAll`. Batches go in primary-key order, so `reorder()` a Relation that has an order (a default scope's too), and bound them with `start` and `finish`, not `offset`. On D1 a Worker invocation sends at most 1,000 queries (50 on Free), and each batch sends one (`inBatches` reads its keys, then sends the write, and a `destroyAll` adds a load and each record's dependent reads; a `db.batch` counts as one): split a larger job across invocations by `start` and `finish`.
|
|
379
422
|
- 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()`.
|
|
@@ -392,8 +435,6 @@ Copy it again after upgrading Active Record, since the rules can change.
|
|
|
392
435
|
# Associations
|
|
393
436
|
Source: https://active-record.forestfuture.dev/associations
|
|
394
437
|
|
|
395
|
-
Associations connect Models: `belongsTo`, `hasMany`, and `hasOne`.
|
|
396
|
-
|
|
397
438
|
## Defining associations
|
|
398
439
|
|
|
399
440
|
Declare each association as a field, passing the target Model’s class. The field’s name is the association’s name:
|
|
@@ -901,142 +942,7 @@ export class Category extends Model.define({
|
|
|
901
942
|
|
|
902
943
|
## Reaching records through another association
|
|
903
944
|
|
|
904
|
-
Reach records through another association with `through
|
|
905
|
-
|
|
906
|
-
```ts
|
|
907
|
-
import { belongsTo, hasMany, Model } from "@forestfuture/active-record";
|
|
908
|
-
|
|
909
|
-
export class Tag extends Model.define({
|
|
910
|
-
id: { type: "integer", null: false },
|
|
911
|
-
name: { type: "string", null: false },
|
|
912
|
-
}) {
|
|
913
|
-
taggings = hasMany(Tagging);
|
|
914
|
-
articles = hasMany(Article, { through: "taggings" }); // each tagging's article
|
|
915
|
-
}
|
|
916
|
-
|
|
917
|
-
export class Tagging extends Model.define({
|
|
918
|
-
id: { type: "integer", null: false },
|
|
919
|
-
articleId: { type: "string", null: false },
|
|
920
|
-
tagId: { type: "integer", null: false },
|
|
921
|
-
}) {
|
|
922
|
-
article = belongsTo(Article);
|
|
923
|
-
tag = belongsTo(Tag);
|
|
924
|
-
}
|
|
925
|
-
```
|
|
926
|
-
|
|
927
|
-
`through` names one of the Model’s own associations, here `taggings`. The join Model’s association with the same name, singular or plural, leads on to the records: `articles` follows each tagging’s `article`.
|
|
928
|
-
|
|
929
|
-
| Option | Does |
|
|
930
|
-
| --------- | ----------------------------------------------------------------------------------------------- |
|
|
931
|
-
| `through` | The association to go through |
|
|
932
|
-
| `source` | The join Model’s association to follow. Defaults to this association’s name, singular or plural |
|
|
933
|
-
| `scope` | Narrows or orders the records. See [Scoping associations](#scoping-associations) |
|
|
934
|
-
|
|
935
|
-
### Naming the source
|
|
936
|
-
|
|
937
|
-
If the join Model’s association has another name, pass it as `source`:
|
|
938
|
-
|
|
939
|
-
```ts
|
|
940
|
-
import { hasMany } from "@forestfuture/active-record";
|
|
941
|
-
|
|
942
|
-
writers = hasMany(Author, { through: "articles", source: "author" }); // each article's author
|
|
943
|
-
```
|
|
944
|
-
|
|
945
|
-
### Reading and preloading
|
|
946
|
-
|
|
947
|
-
Read it as you would any `hasMany`:
|
|
948
|
-
|
|
949
|
-
```ts
|
|
950
|
-
const tag = await Tag.find(tagId);
|
|
951
|
-
const articles = await tag.articles().order({ title: "asc" }).toArray(); // one query
|
|
952
|
-
|
|
953
|
-
const tags = await Tag.includes("articles").toArray(); // tags, taggings, and articles: one round trip
|
|
954
|
-
for (const each of tags) console.log(each.name, each.loaded("articles").length);
|
|
955
|
-
```
|
|
956
|
-
|
|
957
|
-
- **`tag.articles()`** is a Relation, with every Relation method, read in one query. Its writes go to the taggings, as [below](#writing-through-it).
|
|
958
|
-
- **Each record comes back once**, however many join records point at it.
|
|
959
|
-
- **`includes("articles")`** loads the join records and the articles with the tags’ own query, in one round trip on D1. The join records aren’t kept as `taggings` unless you include them too.
|
|
960
|
-
|
|
961
|
-
The scopes of both associations it goes through apply, and so does its own `scope`.
|
|
962
|
-
|
|
963
|
-
### Going through a belongsTo or a hasOne
|
|
964
|
-
|
|
965
|
-
`through` can name a `belongsTo`, a `hasMany`, or a `hasOne`, and the association it follows can be any of the three. A `hasOne` goes through a `belongsTo` or a `hasOne`:
|
|
966
|
-
|
|
967
|
-
```ts
|
|
968
|
-
import { hasOne } from "@forestfuture/active-record";
|
|
969
|
-
|
|
970
|
-
author = hasOne(Author, { through: "article" }); // the article's author
|
|
971
|
-
```
|
|
972
|
-
|
|
973
|
-
An association can also go through one that goes through another, as `writers` does above through `articles`.
|
|
974
|
-
|
|
975
|
-
### Writing through it
|
|
976
|
-
|
|
977
|
-
Add records through the association with `push`, `build`, and `create`. Each makes the join record that links the owner to the record:
|
|
978
|
-
|
|
979
|
-
```ts
|
|
980
|
-
const tag = await Tag.find(tagId);
|
|
981
|
-
const article = await Article.find(articleId);
|
|
982
|
-
|
|
983
|
-
await tag.articles().push(article); // saves a tagging that links them
|
|
984
|
-
const draft = await tag.articles().create({ authorId: article.authorId, title: "Draft" });
|
|
985
|
-
|
|
986
|
-
await tag.articles().delete(article); // deletes the tagging; the article stays
|
|
987
|
-
```
|
|
988
|
-
|
|
989
|
-
- **`push(article)`** saves a tagging for each article, in one write. A new article is saved first.
|
|
990
|
-
- **`build(attributes)`** builds the article and its tagging. Saving the tag saves both. Saving the article on its own saves no tagging.
|
|
991
|
-
- **`create(attributes)`** saves the article, then its tagging. An invalid article comes back unsaved, and nothing is written.
|
|
992
|
-
|
|
993
|
-
On a tag that isn’t saved yet, `push` and `build` wait for the tag’s save. `create` throws `RecordNotSaved` there, as it does through a `hasMany`.
|
|
994
|
-
|
|
995
|
-
Records built or created through it take the equality values of its `scope`, and their join records take those of the association it goes through.
|
|
996
|
-
|
|
997
|
-
#### Removing records
|
|
998
|
-
|
|
999
|
-
Removing records through the association removes their join records. The records themselves stay:
|
|
1000
|
-
|
|
1001
|
-
| Method | Does |
|
|
1002
|
-
| ------------------ | --------------------------------------------------------------------------------------------------- |
|
|
1003
|
-
| `delete(article)` | Deletes the tag’s taggings to the article, without callbacks |
|
|
1004
|
-
| `destroy(article)` | Destroys those taggings, running their callbacks, in one write |
|
|
1005
|
-
| `clear()` | Deletes every tagging to the tag’s articles, without callbacks. The tag then has no articles loaded |
|
|
1006
|
-
| `deleteAll()` | Deletes the same taggings, and resolves to how many it deleted |
|
|
1007
|
-
| `destroyAll()` | Destroys the same taggings, running their callbacks, and resolves to the articles |
|
|
1008
|
-
|
|
1009
|
-
An article the tag doesn’t reach removes nothing. To remove an article itself, destroy it: `await article.destroy()`.
|
|
1010
|
-
|
|
1011
|
-
In a batch, pass the association to the write: `b.deleteAll(tag.articles())` deletes the tag’s taggings.
|
|
1012
|
-
|
|
1013
|
-
:::warning[A narrowed deleteAll or destroyAll removes the records themselves]
|
|
1014
|
-
`updateAll`, and a narrowed `deleteAll` or `destroyAll`, act on the records, as any Relation’s do. `tag.articles().where({ title: "Draft" }).deleteAll()` deletes those articles for every tag, not the tag’s taggings.
|
|
1015
|
-
:::
|
|
1016
|
-
|
|
1017
|
-
#### Removing join records with dependent
|
|
1018
|
-
|
|
1019
|
-
A `hasMany` through a join Model takes `dependent: "destroy"` or `dependent: "deleteAll"`, which acts on its join records. With `"destroy"`, destroying the tag destroys its taggings, running their callbacks, and `delete` destroys them too. With `"deleteAll"`, destroying the tag deletes them without callbacks. `clear` and `deleteAll` always delete them without callbacks.
|
|
1020
|
-
|
|
1021
|
-
#### Setting a hasOne through another
|
|
1022
|
-
|
|
1023
|
-
A `hasOne` that goes through another `hasOne` has `set`. `await member.club.set(club)` points the member’s membership at the club, or creates a membership if there isn’t one, with the equality values of the membership association’s `scope`. `set(null)` destroys the membership. It has no `build` or `create`.
|
|
1024
|
-
|
|
1025
|
-
#### Spotting read-only associations
|
|
1026
|
-
|
|
1027
|
-
Writes need a join Model: the association has to go through a `hasMany` (a `hasOne`, for a `hasOne`), and follow a `belongsTo` from there, with neither going through another. Any other write throws `ReadonlyAssociation`, naming the association that stops it. `writers` above is read-only, since it goes through `articles`, which goes through `taggings`.
|
|
1028
|
-
|
|
1029
|
-
`insert`, `insertAll`, `upsert`, and `upsertAll` throw `ReadonlyAssociation` on any association through another, since they write no join records.
|
|
1030
|
-
|
|
1031
|
-
:::note
|
|
1032
|
-
Every association it goes through must be on one database. One that reaches [another database](/several-databases#associating-models-on-different-databases) is an `InvalidModel` for now ([#435](https://github.com/forestfuture/active-record/issues/435)).
|
|
1033
|
-
:::
|
|
1034
|
-
|
|
1035
|
-
> **Compared with Rails**
|
|
1036
|
-
>
|
|
1037
|
-
> `through` and `source` work as Rails’ `has_many :through` and `has_one :through` options do. Rails reads through a SQL join, so a record two join records point at comes back twice unless the association is `distinct`. Here it comes back once.
|
|
1038
|
-
>
|
|
1039
|
-
> Writing through it works as in Rails: `destroy` destroys the join records rather than the records, `clear` deletes them whatever `dependent` is, and `insert_all` through it raises. Rails also writes through a `belongsTo` or `hasOne` hop by building or updating that hop’s record, which can change a record that other records share. Here that throws `ReadonlyAssociation`. Rails’ `disable_joins` has no counterpart yet.
|
|
945
|
+
Reach records through another association with `through`, such as a tag’s articles through its taggings. See [Through associations](/through-associations).
|
|
1040
946
|
|
|
1041
947
|
## Destroying dependent records
|
|
1042
948
|
|
|
@@ -1176,8 +1082,186 @@ Writes keep the count up to date, while `size()` and the others count the rows.
|
|
|
1176
1082
|
> In Rails, removing records through a scoped association leaves the count too high, and `reset_counters` on one writes the scope’s count into the counter. Here the removal counts its records out, and `resetCounters` refuses the scoped association.
|
|
1177
1083
|
>
|
|
1178
1084
|
> Rails counts a comment twice when two `belongs_to`s keep the same counter. Here that throws `InvalidModel`.
|
|
1085
|
+
|
|
1086
|
+
## Touching the record it belongs to
|
|
1087
|
+
|
|
1088
|
+
To set an article’s `updatedAt` whenever one of its comments changes, declare `touch: true` on the comment’s `belongsTo`:
|
|
1089
|
+
|
|
1090
|
+
```ts
|
|
1091
|
+
import { belongsTo, Model } from "@forestfuture/active-record";
|
|
1092
|
+
|
|
1093
|
+
export class Comment extends Model.define({
|
|
1094
|
+
id: { type: "integer", null: false },
|
|
1095
|
+
articleId: "integer",
|
|
1096
|
+
body: { type: "string", null: false },
|
|
1097
|
+
updatedAt: "datetime",
|
|
1098
|
+
}) {
|
|
1099
|
+
article = belongsTo(Article, { touch: true });
|
|
1100
|
+
}
|
|
1101
|
+
```
|
|
1102
|
+
|
|
1103
|
+
Creating, updating, or destroying a comment then touches its article. So does calling `touch()` on the comment:
|
|
1104
|
+
|
|
1105
|
+
```ts
|
|
1106
|
+
const article = await Article.find(id);
|
|
1107
|
+
const comment = await article.comments().create({ body: "First!" }); // sets article.updatedAt
|
|
1108
|
+
await comment.update({ body: "Edited" }); // sets it again
|
|
1109
|
+
await comment.touch(); // and again
|
|
1110
|
+
```
|
|
1111
|
+
|
|
1112
|
+
The article’s new time is written in the same atomic batch as the comment. A save with nothing to write doesn’t touch it. Changing a comment’s `articleId` touches both the old article and the new one.
|
|
1113
|
+
|
|
1114
|
+
:::note
|
|
1115
|
+
`updateColumns`, `updateAll`, `insert`, and the other bulk writes don’t touch the article, since they run no callbacks.
|
|
1116
|
+
:::
|
|
1117
|
+
|
|
1118
|
+
To set another datetime attribute too, name it. It’s set to the same time as `updatedAt`:
|
|
1119
|
+
|
|
1120
|
+
```ts
|
|
1121
|
+
import { belongsTo, Model } from "@forestfuture/active-record";
|
|
1122
|
+
|
|
1123
|
+
export class Reply extends Model.define({
|
|
1124
|
+
id: { type: "integer", null: false },
|
|
1125
|
+
articleId: "integer",
|
|
1126
|
+
body: { type: "string", null: false },
|
|
1127
|
+
}) {
|
|
1128
|
+
static table = "comments";
|
|
1129
|
+
article = belongsTo(Article, { touch: "lastCommentedAt" }); // and updatedAt
|
|
1130
|
+
}
|
|
1131
|
+
```
|
|
1132
|
+
|
|
1133
|
+
To set several, list them: `touch: ["lastCommentedAt", "lastActivityAt"]`.
|
|
1134
|
+
|
|
1135
|
+
:::note
|
|
1136
|
+
A Model without `updatedAt` needs a named attribute. Touching a Model on [another database](/several-databases) throws `InvalidModel`, since the touch couldn’t be written in the same batch.
|
|
1137
|
+
:::
|
|
1138
|
+
|
|
1139
|
+
### Running the article’s callbacks
|
|
1140
|
+
|
|
1141
|
+
The article is touched as `article.touch()` touches it. It runs its `afterTouch` callbacks, then its update commit callbacks. An article that declares `touch` on its own `belongsTo` touches that record too:
|
|
1142
|
+
|
|
1143
|
+
```ts
|
|
1144
|
+
import { belongsTo, hasMany, Model } from "@forestfuture/active-record";
|
|
1145
|
+
|
|
1146
|
+
export class Blog extends Model.define({
|
|
1147
|
+
id: { type: "integer", null: false },
|
|
1148
|
+
updatedAt: "datetime",
|
|
1149
|
+
}) {}
|
|
1150
|
+
|
|
1151
|
+
export class Article extends Model.define({
|
|
1152
|
+
id: { type: "integer", null: false },
|
|
1153
|
+
blogId: "integer",
|
|
1154
|
+
title: { type: "string", null: false },
|
|
1155
|
+
updatedAt: "datetime",
|
|
1156
|
+
lastCommentedAt: "datetime",
|
|
1157
|
+
}) {
|
|
1158
|
+
blog = belongsTo(Blog, { touch: true }); // touching an article touches its blog
|
|
1159
|
+
comments = hasMany(Comment);
|
|
1160
|
+
}
|
|
1161
|
+
```
|
|
1162
|
+
|
|
1163
|
+
An article the same save creates, such as one built with `comment.article.build()`, is touched after it’s inserted. It runs `afterTouch` and its create commit callbacks, but not the update ones.
|
|
1164
|
+
|
|
1165
|
+
A write touches each record once, however many of its comments touch it.
|
|
1166
|
+
|
|
1167
|
+
### Loading the article
|
|
1168
|
+
|
|
1169
|
+
The article is loaded before the comment is written, so its callbacks can run. A loaded article sends no query, such as one reached through `article.comments()`. Each level of the chain that isn’t loaded takes one query, and each one waits for the one before it. Preload the chain to skip them:
|
|
1170
|
+
|
|
1171
|
+
```ts
|
|
1172
|
+
const comments = await Comment.includes({ article: "blog" }).toArray();
|
|
1173
|
+
for (const each of comments) await each.touch(); // no query to load an article or blog
|
|
1174
|
+
```
|
|
1175
|
+
|
|
1176
|
+
Inside [`noTouching`](#turning-touches-off), the touch doesn’t load the article.
|
|
1177
|
+
|
|
1178
|
+
The article is found through the association, so the association’s scope and Article’s default scope apply. An article they hide isn’t touched.
|
|
1179
|
+
|
|
1180
|
+
### Touching with a counter cache
|
|
1181
|
+
|
|
1182
|
+
A comment that also keeps a [counter cache](#counting-records-with-a-counter-cache) on the article touches it the same way, in the same batch as the count. An article the default scope hides is counted, but isn’t touched.
|
|
1183
|
+
|
|
1184
|
+
### Turning touches off
|
|
1185
|
+
|
|
1186
|
+
To import many comments without touching their article for each one, run the import in `Article.noTouching`:
|
|
1187
|
+
|
|
1188
|
+
```ts
|
|
1189
|
+
await Article.noTouching(async () => {
|
|
1190
|
+
for (const body of bodies) {
|
|
1191
|
+
await Comment.create({ articleId, body }); // doesn't touch the article
|
|
1192
|
+
}
|
|
1193
|
+
});
|
|
1194
|
+
const article = await Article.find(articleId);
|
|
1195
|
+
await article.touch(); // touch it once, after the import
|
|
1196
|
+
```
|
|
1197
|
+
|
|
1198
|
+
Inside the block, no article is touched. A comment’s `belongsTo` leaves its article alone, and `article.touch()` writes nothing and resolves to `false`. Once the block ends, articles are touched again.
|
|
1199
|
+
|
|
1200
|
+
`noTouching` covers the Model you call it on and the Models that extend it. To turn off touches for every Model, call `ApplicationRecord.noTouching`. It covers only the code the block runs and what that code awaits, so other requests still touch.
|
|
1201
|
+
|
|
1202
|
+
:::note
|
|
1203
|
+
The comments still set their own `updatedAt` when they’re saved. `Article.touchAll()` and `Article.updateCounters(id, counters, { touch: true })` still set the articles’ `updatedAt`. A comment whose `belongsTo` also keeps a counter cache still counts, but doesn’t touch the article.
|
|
1204
|
+
:::
|
|
1205
|
+
|
|
1206
|
+
:::note
|
|
1207
|
+
Like `withDatabase`, `noTouching` needs [Node.js compatibility](/connecting#using-the-requests-database).
|
|
1208
|
+
:::
|
|
1209
|
+
|
|
1210
|
+
> **Compared with Rails**
|
|
1211
|
+
>
|
|
1212
|
+
> Rails’ `touch:` takes `true` or one column. Here it also takes a list of attributes.
|
|
1213
|
+
>
|
|
1214
|
+
> Rails does nothing when the article has no `updated_at`, and writes the time to any column you name. Here both throw `InvalidModel` when the Model is first used.
|
|
1215
|
+
>
|
|
1216
|
+
> With a counter cache, Rails sets the time in the counter’s `UPDATE` and runs none of the article’s callbacks. Here the article is touched as it is without one, so its `afterTouch` and commit callbacks run.
|
|
1217
|
+
>
|
|
1218
|
+
> When a comment moves to another article, Rails finds the old one without the association’s scope. Here the scope applies to both.
|
|
1219
|
+
>
|
|
1220
|
+
> When a comment’s `belongs_to` has both `counter_cache:` and `touch:`, Rails’ `no_touching` still touches the article, since the time is set in the counter’s `UPDATE`. Here the article is only counted. Inside the block, Rails’ `touch` returns `nil`, and here it resolves to `false`. Rails also loads each comment’s article for its touch, then leaves it alone. Here the touch doesn’t load it, though a required `belongsTo` still checks that its article exists.
|
|
1221
|
+
|
|
1222
|
+
## Touching the record it has
|
|
1223
|
+
|
|
1224
|
+
To set a profile’s `updatedAt` whenever its user changes, declare `touch: true` on the user’s `hasOne`:
|
|
1225
|
+
|
|
1226
|
+
```ts
|
|
1227
|
+
import { hasOne, Model } from "@forestfuture/active-record";
|
|
1228
|
+
|
|
1229
|
+
export class User extends Model.define({
|
|
1230
|
+
id: { type: "integer", null: false },
|
|
1231
|
+
name: { type: "string", null: false },
|
|
1232
|
+
updatedAt: "datetime",
|
|
1233
|
+
}) {
|
|
1234
|
+
profile = hasOne(Profile, { touch: true });
|
|
1235
|
+
}
|
|
1236
|
+
```
|
|
1237
|
+
|
|
1238
|
+
Updating or destroying a user then touches its profile, in the same atomic batch as the user. So does calling `touch()` on the user:
|
|
1239
|
+
|
|
1240
|
+
```ts
|
|
1241
|
+
const user = await User.find(id);
|
|
1242
|
+
await user.update({ name: "Ada" }); // sets the profile's updatedAt
|
|
1243
|
+
await user.touch(); // and again
|
|
1244
|
+
```
|
|
1245
|
+
|
|
1246
|
+
A save with nothing to write doesn’t touch the profile. A `hasOne` through another touches the record it reaches.
|
|
1247
|
+
|
|
1248
|
+
The profile is touched as [a `belongsTo`’s record is](#running-the-articles-callbacks). It takes the names of datetime attributes to set, runs its `afterTouch` and update commit callbacks, and touches its own records in turn. It’s found through the association, so a profile the association’s scope or Profile’s default scope hides isn’t touched. Inside [`Profile.noTouching`](#turning-touches-off), it isn’t loaded or touched.
|
|
1249
|
+
|
|
1250
|
+
The profile isn’t touched when:
|
|
1251
|
+
|
|
1252
|
+
- **The user is new.** A profile built with `user.profile.build()` is inserted with the user, and its insert sets its `updatedAt`.
|
|
1253
|
+
- **The user’s own save writes it**, such as a profile built through the user, or a changed one with `autosave: true`. Its own save sets its `updatedAt`.
|
|
1254
|
+
- **The user’s `dependent` removes it**, with `"destroy"` or `"delete"`. With `"nullify"`, it’s touched once it no longer points at the user.
|
|
1255
|
+
|
|
1256
|
+
A profile saved as its own entry in the user’s batch is still touched, whether it comes before or after the user.
|
|
1257
|
+
|
|
1258
|
+
> **Compared with Rails**
|
|
1259
|
+
>
|
|
1260
|
+
> Rails’ `has_one … touch:` takes `true` or one column. Here it also takes a list of attributes.
|
|
1179
1261
|
>
|
|
1180
|
-
> Rails
|
|
1262
|
+
> Rails touches a changed profile before its autosave saves it, so its `after_touch` runs too. Here only its save writes it.
|
|
1263
|
+
>
|
|
1264
|
+
> After a user is created, Rails finds and touches a profile that already points at the new user’s key. Here a new user touches nothing, so a create sends no query for it.
|
|
1181
1265
|
|
|
1182
1266
|
## Writing many rows
|
|
1183
1267
|
|
|
@@ -1211,8 +1295,6 @@ These features aren’t in Active Record yet. The code shows the shape they’re
|
|
|
1211
1295
|
# Bulk writes and batches
|
|
1212
1296
|
Source: https://active-record.forestfuture.dev/batches
|
|
1213
1297
|
|
|
1214
|
-
Bulk writes change many rows in one SQL statement. A batch sends several writes to D1 at once, and they’re all written, or none of them.
|
|
1215
|
-
|
|
1216
1298
|
## Writing many rows
|
|
1217
1299
|
|
|
1218
1300
|
Call a bulk write on a Relation. It runs straight away, without validations or callbacks:
|
|
@@ -1378,11 +1460,9 @@ await batch((b) => [
|
|
|
1378
1460
|
# Callbacks
|
|
1379
1461
|
Source: https://active-record.forestfuture.dev/callbacks
|
|
1380
1462
|
|
|
1381
|
-
Callbacks run your code at points in a record’s lifecycle, such as before it’s validated or after it’s saved.
|
|
1382
|
-
|
|
1383
1463
|
## Registering callbacks
|
|
1384
1464
|
|
|
1385
|
-
Register callbacks in a Model’s `static {}` block. Each receives the record, and may be async:
|
|
1465
|
+
Register callbacks in a Model’s `static {}` block. Each receives the record, and may be async, except the [callbacks for a record built or loaded](#running-code-when-a-record-is-built-or-loaded):
|
|
1386
1466
|
|
|
1387
1467
|
```ts
|
|
1388
1468
|
import { abort, Model } from "@forestfuture/active-record";
|
|
@@ -1439,22 +1519,30 @@ Once a Model has been used, registering another callback throws `InvalidModel`,
|
|
|
1439
1519
|
| 1 | `beforeValidation` | Before the validators, on every save, and on `isValid()` | Stops the save |
|
|
1440
1520
|
| 2 | `afterValidation` | After the validators | Stops the save |
|
|
1441
1521
|
| 3 | `beforeSave` | Before every write, new or persisted | Stops the save |
|
|
1442
|
-
| 4 | `
|
|
1443
|
-
|
|
|
1522
|
+
| 4 | `aroundSave` | Its first part, before `next()` | Stops the save |
|
|
1523
|
+
| 5 | `beforeCreate` | Before inserting a new record | Stops the save |
|
|
1524
|
+
| 5 | `beforeUpdate` | Before updating a persisted record | Stops the save |
|
|
1525
|
+
| 6 | `aroundCreate` | Its first part, before `next()` | Stops the save |
|
|
1526
|
+
| 6 | `aroundUpdate` | Its first part, before `next()` | Stops the save |
|
|
1444
1527
|
| | _The write to D1_ | Skipped when a persisted record has no changes | |
|
|
1445
|
-
|
|
|
1446
|
-
|
|
|
1447
|
-
|
|
|
1448
|
-
|
|
|
1449
|
-
|
|
|
1450
|
-
|
|
|
1451
|
-
|
|
|
1528
|
+
| 7 | `aroundCreate` | Its last part, once `next()` resolves | Too late: `AbortAfterPersistence` |
|
|
1529
|
+
| 7 | `aroundUpdate` | Its last part, once `next()` resolves | Too late: `AbortAfterPersistence` |
|
|
1530
|
+
| 8 | `afterCreate` | After inserting a new record | Too late: `AbortAfterPersistence` |
|
|
1531
|
+
| 8 | `afterUpdate` | After updating a persisted record | Too late: `AbortAfterPersistence` |
|
|
1532
|
+
| 9 | `aroundSave` | Its last part, once `next()` resolves | Too late: `AbortAfterPersistence` |
|
|
1533
|
+
| 10 | `afterSave` | After every successful save | Too late: `AbortAfterPersistence` |
|
|
1534
|
+
| 11 | `afterCommit` | Last, after every after-callback | Too late: `AbortAfterPersistence` |
|
|
1535
|
+
| 11 | `afterCreateCommit` | Last, after inserting a new record | Too late: `AbortAfterPersistence` |
|
|
1536
|
+
| 11 | `afterUpdateCommit` | Last, after updating a persisted record | Too late: `AbortAfterPersistence` |
|
|
1537
|
+
| 11 | `afterSaveCommit` | Last, after every successful save | Too late: `AbortAfterPersistence` |
|
|
1452
1538
|
| **Destroying** | | | |
|
|
1453
1539
|
| 1 | `beforeDestroy` | Before the `dependent` strategies and the DELETE | Stops the destroy |
|
|
1540
|
+
| 2 | `aroundDestroy` | Its first part, before `next()` | Stops the destroy |
|
|
1454
1541
|
| | _The delete in D1_ | With the dependents, in one batch | |
|
|
1455
|
-
|
|
|
1456
|
-
|
|
|
1457
|
-
|
|
|
1542
|
+
| 3 | `aroundDestroy` | Its last part, once `next()` resolves | Too late: `AbortAfterPersistence` |
|
|
1543
|
+
| 4 | `afterDestroy` | After the record is destroyed | Too late: `AbortAfterPersistence` |
|
|
1544
|
+
| 5 | `afterCommit` | Last, after every after-callback | Too late: `AbortAfterPersistence` |
|
|
1545
|
+
| 5 | `afterDestroyCommit` | Last, after the record is destroyed | Too late: `AbortAfterPersistence` |
|
|
1458
1546
|
| **Touching** | | | |
|
|
1459
1547
|
| | _The write to D1_ | `updatedAt`, and any attributes named | |
|
|
1460
1548
|
| 1 | `afterTouch` | After `touch()` writes the record’s timestamps | Too late: `AbortAfterPersistence` |
|
|
@@ -1463,6 +1551,9 @@ Once a Model has been used, registering another callback throws `InvalidModel`,
|
|
|
1463
1551
|
| 2 | `afterSaveCommit` | Last, when `touch()` wrote a row | Too late: `AbortAfterPersistence` |
|
|
1464
1552
|
| **Refused** | | | |
|
|
1465
1553
|
| 1 | `afterRollback` | When the database refuses the save or destroy | Nothing to stop |
|
|
1554
|
+
| **Loading** | | | |
|
|
1555
|
+
| 1 | `afterFind` | After a record is loaded | Nothing to stop |
|
|
1556
|
+
| 2 | `afterInitialize` | After a record is loaded, or built | Nothing to stop |
|
|
1466
1557
|
|
|
1467
1558
|
A save runs either the create pair or the update pair, never both.
|
|
1468
1559
|
|
|
@@ -1474,6 +1565,34 @@ A save runs either the create pair or the update pair, never both.
|
|
|
1474
1565
|
The database has kept a save’s writes before any after-callback runs. An error thrown by an after-callback or a commit callback reaches the caller, but the record stays saved. The callbacks after it don’t run. In a batch, that includes the other records’ callbacks.
|
|
1475
1566
|
:::
|
|
1476
1567
|
|
|
1568
|
+
## Wrapping a save or destroy
|
|
1569
|
+
|
|
1570
|
+
An around callback runs code on both sides of a write. Call `next()` to run the rest of the save, and await it:
|
|
1571
|
+
|
|
1572
|
+
```ts
|
|
1573
|
+
this.aroundSave(async (order, next) => {
|
|
1574
|
+
const started = Date.now();
|
|
1575
|
+
await next();
|
|
1576
|
+
console.info(`Saved order ${order.id} in ${Date.now() - started} ms`);
|
|
1577
|
+
});
|
|
1578
|
+
```
|
|
1579
|
+
|
|
1580
|
+
- **`aroundSave`** runs after `beforeSave`. Its `next()` runs `beforeCreate` or `beforeUpdate`, the write, and `afterCreate` or `afterUpdate`. `afterSave` runs once the callback finishes.
|
|
1581
|
+
- **`aroundCreate`**, **`aroundUpdate`**, and **`aroundDestroy`** wrap only the write, between the matching before- and after-callbacks.
|
|
1582
|
+
- **Several around callbacks of one kind** nest. The first one declared is the outermost.
|
|
1583
|
+
|
|
1584
|
+
`next()` returns a promise with no value. It resolves once the database has kept the write. A save sends its writes together, so in a [batch](/batches#batching-records), every record’s first part runs before the batch is written. Then each record’s last part runs in turn.
|
|
1585
|
+
|
|
1586
|
+
### Stopping a wrapped write
|
|
1587
|
+
|
|
1588
|
+
- **Not calling `next()`** stops the save, as `abort()` does. `save()` resolves to `false`, and nothing is written.
|
|
1589
|
+
- **An `abort()` before `next()`** stops the save. After `next()`, the write has happened, so `abort()` throws `AbortAfterPersistence`.
|
|
1590
|
+
- **When the database refuses the write**, `afterRollback` runs, then `next()` rejects with the database’s error. The save throws it even if you catch it.
|
|
1591
|
+
- **When the save ends without sending the write**, `next()` rejects with the error the save ends with. That happens when another record in the save or batch is refused before the write is sent.
|
|
1592
|
+
- **When an earlier record’s after-callback throws**, the write is kept. This record’s after-callbacks are skipped, and `next()` rejects with that error.
|
|
1593
|
+
|
|
1594
|
+
To release something you hold during the write, put `await next()` in a `try` block, and release it in `finally`.
|
|
1595
|
+
|
|
1477
1596
|
## Running code after the commit
|
|
1478
1597
|
|
|
1479
1598
|
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:
|
|
@@ -1507,6 +1626,8 @@ this.afterTouch(async (article) => {
|
|
|
1507
1626
|
- **`savedChanges()`** holds only the touched attributes, so `hasSavedChangeTo("email")` is `false` in a touch’s callbacks.
|
|
1508
1627
|
- **A refused touch** runs `afterRollback`, and the record stays as it was.
|
|
1509
1628
|
|
|
1629
|
+
A `belongsTo` declared with [`touch`](/associations#touching-the-record-it-belongs-to) touches its record the same way. Saving a comment can run its article’s `afterTouch` and commit callbacks.
|
|
1630
|
+
|
|
1510
1631
|
`touchAll` and the counters’ `touch` option run no callbacks.
|
|
1511
1632
|
|
|
1512
1633
|
:::warning[A touch runs the update commit callbacks]
|
|
@@ -1533,6 +1654,34 @@ The record keeps its unsaved state, and no after-callback or commit callback run
|
|
|
1533
1654
|
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.
|
|
1534
1655
|
:::
|
|
1535
1656
|
|
|
1657
|
+
## Running code when a record is built or loaded
|
|
1658
|
+
|
|
1659
|
+
`afterInitialize` runs for every record you build and every record you load. `afterFind` runs for every record you load, just before `afterInitialize`:
|
|
1660
|
+
|
|
1661
|
+
```ts
|
|
1662
|
+
this.afterInitialize((invoice) => {
|
|
1663
|
+
if (invoice.isNewRecord()) invoice.currency ??= currencyFor(invoice.country);
|
|
1664
|
+
});
|
|
1665
|
+
```
|
|
1666
|
+
|
|
1667
|
+
- **`build` and `create`** run `afterInitialize` after their `init` function, so it sees what `init` set. Building through a `hasMany` or `hasOne` runs it once the record points at its owner. Building through a `through` association runs the join record’s `afterInitialize` once it points at the record.
|
|
1668
|
+
- **Every load** runs `afterFind`, then `afterInitialize`: a query, an association read, a preload, and `reload()`. Preloaded associations aren’t attached yet when they run.
|
|
1669
|
+
- **Saving a record** runs neither, and neither does `new Invoice()`.
|
|
1670
|
+
|
|
1671
|
+
Both callbacks run synchronously, since `build` can’t wait for them. An `async` one is a type error. An error thrown by either reaches the caller, and the query returns no records.
|
|
1672
|
+
|
|
1673
|
+
### Handling partial records
|
|
1674
|
+
|
|
1675
|
+
A record loaded with [`select`](/querying#selecting-attributes) runs both callbacks too, and reading an attribute it left out throws `MissingAttribute`. Check with `hasAttribute` first:
|
|
1676
|
+
|
|
1677
|
+
```ts
|
|
1678
|
+
this.afterFind((invoice) => {
|
|
1679
|
+
if (invoice.hasAttribute("total") && invoice.total > 10_000) {
|
|
1680
|
+
console.info(`Large invoice ${invoice.id} loaded`);
|
|
1681
|
+
}
|
|
1682
|
+
});
|
|
1683
|
+
```
|
|
1684
|
+
|
|
1536
1685
|
## Stopping a save
|
|
1537
1686
|
|
|
1538
1687
|
Throw `abort(reason)` from a before-callback to stop a save or destroy:
|
|
@@ -1555,13 +1704,6 @@ Only `abort()` stops a save. Returning `false` does nothing, and any other error
|
|
|
1555
1704
|
In an after-callback, the write has already happened, so `abort()` throws `AbortAfterPersistence`, naming the callback.
|
|
1556
1705
|
:::
|
|
1557
1706
|
|
|
1558
|
-
## Not built yet
|
|
1559
|
-
|
|
1560
|
-
These callbacks aren’t in Active Record yet. The code shows the shape they’re likely to take.
|
|
1561
|
-
|
|
1562
|
-
- **Around callbacks** ([#48](https://github.com/forestfuture/active-record/issues/48)): `this.aroundSave(async (record, proceed) => { …; await proceed(); … })`, and `aroundCreate`, `aroundUpdate`, and `aroundDestroy`.
|
|
1563
|
-
- **`afterInitialize` and `afterFind`** ([#49](https://github.com/forestfuture/active-record/issues/49)): for every record built or loaded, and every record loaded.
|
|
1564
|
-
|
|
1565
1707
|
> **Compared with Rails**
|
|
1566
1708
|
>
|
|
1567
1709
|
> `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.
|
|
@@ -1570,6 +1712,10 @@ These callbacks aren’t in Active Record yet. The code shows the shape they’r
|
|
|
1570
1712
|
>
|
|
1571
1713
|
> `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.
|
|
1572
1714
|
>
|
|
1715
|
+
> `around_save`, `around_create`, `around_update`, and `around_destroy` are `aroundSave`, `aroundCreate`, `aroundUpdate`, and `aroundDestroy`, and `yield` is `await next()`. Rails wraps each record’s own SQL in its transaction. Here, `next()` waits for the whole save’s batch. A Rails `around_save` can rescue the database’s error and carry on; here the save still throws it. Rails saves a `has_many`’s autosaved records inside the owner’s `around_save`. Here, the owner’s `aroundSave` finishes before their after-callbacks run. When an inner `around_save` doesn’t `yield`, Rails resumes the outer one after its `yield`. Here, the outer one’s `next()` rejects, and nothing is saved.
|
|
1716
|
+
>
|
|
1717
|
+
> `after_initialize` and `after_find` are `afterInitialize` and `afterFind`, and run in the same order. Here they can’t be async. `new Invoice()` doesn’t run `afterInitialize`, where Rails’ `new` does: build records through the Model instead, with `Invoice.build()`. `reload()` runs both on the record itself, where Rails runs them on a fresh copy and takes its attributes. `has_attribute?` is `hasAttribute`.
|
|
1718
|
+
>
|
|
1573
1719
|
> Rails’ `if:` and `unless:` options for callbacks aren’t needed: write the condition inside the callback.
|
|
1574
1720
|
|
|
1575
1721
|
---
|
|
@@ -1577,7 +1723,9 @@ These callbacks aren’t in Active Record yet. The code shows the shape they’r
|
|
|
1577
1723
|
# Schema changes
|
|
1578
1724
|
Source: https://active-record.forestfuture.dev/change-a-table
|
|
1579
1725
|
|
|
1580
|
-
|
|
1726
|
+
:::note
|
|
1727
|
+
Wrangler applies each migration once, in order. The schema is regenerated after each change, so a Model’s attributes follow its table.
|
|
1728
|
+
:::
|
|
1581
1729
|
|
|
1582
1730
|
## Adding a column
|
|
1583
1731
|
|
|
@@ -1670,7 +1818,9 @@ Wrangler backs up the database before applying migrations to it.
|
|
|
1670
1818
|
# Coming from Rails
|
|
1671
1819
|
Source: https://active-record.forestfuture.dev/coming-from-rails
|
|
1672
1820
|
|
|
1673
|
-
|
|
1821
|
+
:::tip
|
|
1822
|
+
Models, validations, callbacks, associations, scopes, and dirty tracking all follow Rails’ Active Record, down to the default error messages.
|
|
1823
|
+
:::
|
|
1674
1824
|
|
|
1675
1825
|
## Querying from the Model
|
|
1676
1826
|
|
|
@@ -1773,7 +1923,9 @@ The generators follow `rails generate model` and `rails generate migration`. A c
|
|
|
1773
1923
|
# Command line
|
|
1774
1924
|
Source: https://active-record.forestfuture.dev/command-line
|
|
1775
1925
|
|
|
1776
|
-
|
|
1926
|
+
## Running the command
|
|
1927
|
+
|
|
1928
|
+
The `active-record` command comes with `@forestfuture/active-record`, and `ffar` is its short name. Run it from your project’s folder:
|
|
1777
1929
|
|
|
1778
1930
|
```sh
|
|
1779
1931
|
npx active-record --help
|
|
@@ -2124,10 +2276,350 @@ Every command exits with `0` on success, and `1` when anything was refused or fa
|
|
|
2124
2276
|
|
|
2125
2277
|
---
|
|
2126
2278
|
|
|
2279
|
+
# Conditions
|
|
2280
|
+
Source: https://active-record.forestfuture.dev/conditions
|
|
2281
|
+
|
|
2282
|
+
## At a glance
|
|
2283
|
+
|
|
2284
|
+
| To match | Write | SQL |
|
|
2285
|
+
| ----------------------------- | -------------------------------------- | --------------------------- |
|
|
2286
|
+
| equal values | `where({ role: "admin" })` | `role = ?` |
|
|
2287
|
+
| NULL | `where({ role: null })` | `role IS NULL` |
|
|
2288
|
+
| any value in a list | `where({ role: ["admin", "editor"] })` | `role IN (…)` |
|
|
2289
|
+
| anything but a value | `whereNot({ role: "admin" })` | `NOT (role = ?)` |
|
|
2290
|
+
| either of two queries | `where(a).or(User.where(b))` | `(…) OR (…)` |
|
|
2291
|
+
| a comparison | `where({ createdAt: gte(date) })` | `created_at >= ?` |
|
|
2292
|
+
| a range | `where({ createdAt: between(a, b) })` | both ends included |
|
|
2293
|
+
| anything else | ``where(sql`…`)`` | your SQL, with values bound |
|
|
2294
|
+
| a replacement for a condition | `rewhere({ role: "admin" })` | drops the old `role = ?` |
|
|
2295
|
+
| fewer parts of a query | `unscope("order")`, `only("where")` | drops the parts named |
|
|
2296
|
+
| all but some records | `excluding(record)` | leaves those records out |
|
|
2297
|
+
|
|
2298
|
+
## The Model
|
|
2299
|
+
|
|
2300
|
+
The examples use this Model and table:
|
|
2301
|
+
|
|
2302
|
+
**Model**
|
|
2303
|
+
|
|
2304
|
+
```ts
|
|
2305
|
+
import { Model } from "@forestfuture/active-record";
|
|
2306
|
+
|
|
2307
|
+
export class User extends Model.define({
|
|
2308
|
+
id: { type: "string", null: false, generateId: true },
|
|
2309
|
+
email: { type: "string", null: false },
|
|
2310
|
+
role: "string",
|
|
2311
|
+
isActive: "boolean",
|
|
2312
|
+
createdAt: { type: "datetime", null: false },
|
|
2313
|
+
updatedAt: { type: "datetime", null: false },
|
|
2314
|
+
}) {}
|
|
2315
|
+
```
|
|
2316
|
+
|
|
2317
|
+
**D1**
|
|
2318
|
+
|
|
2319
|
+
```sql
|
|
2320
|
+
CREATE TABLE users (
|
|
2321
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
2322
|
+
email TEXT NOT NULL,
|
|
2323
|
+
role TEXT,
|
|
2324
|
+
is_active BOOLEAN,
|
|
2325
|
+
created_at DATETIME NOT NULL,
|
|
2326
|
+
updated_at DATETIME NOT NULL
|
|
2327
|
+
);
|
|
2328
|
+
```
|
|
2329
|
+
|
|
2330
|
+
**Postgres**
|
|
2331
|
+
|
|
2332
|
+
```sql
|
|
2333
|
+
CREATE TABLE users (
|
|
2334
|
+
id UUID PRIMARY KEY,
|
|
2335
|
+
email TEXT NOT NULL,
|
|
2336
|
+
role TEXT,
|
|
2337
|
+
is_active BOOLEAN,
|
|
2338
|
+
created_at TIMESTAMPTZ NOT NULL,
|
|
2339
|
+
updated_at TIMESTAMPTZ NOT NULL
|
|
2340
|
+
);
|
|
2341
|
+
```
|
|
2342
|
+
|
|
2343
|
+
## Matching values
|
|
2344
|
+
|
|
2345
|
+
Pass `where` an object of attributes that must all match:
|
|
2346
|
+
|
|
2347
|
+
```ts twoslash
|
|
2348
|
+
// @filename: models.ts
|
|
2349
|
+
import { Model } from "@forestfuture/active-record";
|
|
2350
|
+
|
|
2351
|
+
export class User extends Model.define({
|
|
2352
|
+
id: { type: "string", null: false, generateId: true },
|
|
2353
|
+
email: { type: "string", null: false },
|
|
2354
|
+
role: "string",
|
|
2355
|
+
isActive: "boolean",
|
|
2356
|
+
createdAt: { type: "datetime", null: false },
|
|
2357
|
+
updatedAt: { type: "datetime", null: false },
|
|
2358
|
+
}) {}
|
|
2359
|
+
|
|
2360
|
+
// @filename: example.ts
|
|
2361
|
+
// ---cut---
|
|
2362
|
+
import { User } from "./models";
|
|
2363
|
+
|
|
2364
|
+
const admins = await User.where({ role: "admin", isActive: true }).toArray();
|
|
2365
|
+
|
|
2366
|
+
User.where({ role: null }); // role IS NULL
|
|
2367
|
+
User.where({ role: ["admin", "editor"] }); // role IN (…), any number of values
|
|
2368
|
+
```
|
|
2369
|
+
|
|
2370
|
+
- `null` matches NULL. An array matches any of its values, and is bound as one value, so it can be any length.
|
|
2371
|
+
- Values are [cast to the attribute’s type](/models#casting-assigned-values), so text from a query string works as it is: `where({ isActive: "false" })` finds inactive users. A value that can’t be cast matches nothing: `findBy` resolves to `null`, and `find` throws `RecordNotFound`.
|
|
2372
|
+
- `undefined` throws `TypeError`. Leave the key out, or use `null`.
|
|
2373
|
+
|
|
2374
|
+
Attribute names are checked when you compile, and a misspelled one that gets past the compiler throws `UnknownAttribute`:
|
|
2375
|
+
|
|
2376
|
+
```ts twoslash
|
|
2377
|
+
// @noErrorValidation
|
|
2378
|
+
// @filename: models.ts
|
|
2379
|
+
import { Model } from "@forestfuture/active-record";
|
|
2380
|
+
|
|
2381
|
+
export class User extends Model.define({
|
|
2382
|
+
id: { type: "string", null: false, generateId: true },
|
|
2383
|
+
email: { type: "string", null: false },
|
|
2384
|
+
role: "string",
|
|
2385
|
+
isActive: "boolean",
|
|
2386
|
+
createdAt: { type: "datetime", null: false },
|
|
2387
|
+
updatedAt: { type: "datetime", null: false },
|
|
2388
|
+
}) {}
|
|
2389
|
+
|
|
2390
|
+
// @filename: example.ts
|
|
2391
|
+
// ---cut---
|
|
2392
|
+
import { User } from "./models";
|
|
2393
|
+
|
|
2394
|
+
User.where({ rol: "admin" });
|
|
2395
|
+
```
|
|
2396
|
+
|
|
2397
|
+
## Negating conditions
|
|
2398
|
+
|
|
2399
|
+
Negate a condition with `whereNot`, or combine two queries with `or`:
|
|
2400
|
+
|
|
2401
|
+
```ts twoslash
|
|
2402
|
+
// @filename: models.ts
|
|
2403
|
+
import { Model } from "@forestfuture/active-record";
|
|
2404
|
+
|
|
2405
|
+
export class User extends Model.define({
|
|
2406
|
+
id: { type: "string", null: false, generateId: true },
|
|
2407
|
+
email: { type: "string", null: false },
|
|
2408
|
+
role: "string",
|
|
2409
|
+
isActive: "boolean",
|
|
2410
|
+
createdAt: { type: "datetime", null: false },
|
|
2411
|
+
updatedAt: { type: "datetime", null: false },
|
|
2412
|
+
}) {}
|
|
2413
|
+
|
|
2414
|
+
// @filename: example.ts
|
|
2415
|
+
// ---cut---
|
|
2416
|
+
import { User } from "./models";
|
|
2417
|
+
|
|
2418
|
+
const others = await User.whereNot({ role: "admin" }).toArray();
|
|
2419
|
+
const either = await User.where({ role: "admin" })
|
|
2420
|
+
.or(User.where({ isActive: false }))
|
|
2421
|
+
.toArray();
|
|
2422
|
+
```
|
|
2423
|
+
|
|
2424
|
+
- `whereNot` negates the whole condition. As in SQL, `whereNot({ role: "admin" })` also leaves out users whose role is NULL.
|
|
2425
|
+
- `or` combines two Relations of the same Model that differ only in their conditions.
|
|
2426
|
+
|
|
2427
|
+
:::note
|
|
2428
|
+
In a list, values that can’t be cast are left out. So `whereNot({ id: "abc" })` on an integer key excludes nothing.
|
|
2429
|
+
:::
|
|
2430
|
+
|
|
2431
|
+
## Comparing values
|
|
2432
|
+
|
|
2433
|
+
Pass a comparison helper as a value:
|
|
2434
|
+
|
|
2435
|
+
```ts twoslash
|
|
2436
|
+
// @filename: models.ts
|
|
2437
|
+
import { Model } from "@forestfuture/active-record";
|
|
2438
|
+
|
|
2439
|
+
export class User extends Model.define({
|
|
2440
|
+
id: { type: "string", null: false, generateId: true },
|
|
2441
|
+
email: { type: "string", null: false },
|
|
2442
|
+
role: "string",
|
|
2443
|
+
isActive: "boolean",
|
|
2444
|
+
createdAt: { type: "datetime", null: false },
|
|
2445
|
+
updatedAt: { type: "datetime", null: false },
|
|
2446
|
+
}) {}
|
|
2447
|
+
|
|
2448
|
+
// @filename: example.ts
|
|
2449
|
+
// ---cut---
|
|
2450
|
+
import { between, gte, lt } from "@forestfuture/active-record";
|
|
2451
|
+
import { User } from "./models";
|
|
2452
|
+
|
|
2453
|
+
const since = new Date("2026-01-01");
|
|
2454
|
+
const until = new Date("2026-02-01");
|
|
2455
|
+
|
|
2456
|
+
User.where({ createdAt: gte(since) }); // created_at >= ?
|
|
2457
|
+
User.where({ createdAt: lt(since) }); // created_at < ?
|
|
2458
|
+
User.where({ createdAt: between(since, until) }); // both ends included
|
|
2459
|
+
User.where({ createdAt: between(since, until, { excludeEnd: true }) });
|
|
2460
|
+
```
|
|
2461
|
+
|
|
2462
|
+
`gt`, `gte`, `lt`, `lte`, and `between` work on number, string, and datetime attributes, and dates compare by time. `between` includes both ends, unless you pass `{ excludeEnd: true }`.
|
|
2463
|
+
|
|
2464
|
+
## Writing SQL fragments
|
|
2465
|
+
|
|
2466
|
+
Write anything else as an `sql` tagged template, with `column()` for an attribute’s column:
|
|
2467
|
+
|
|
2468
|
+
```ts twoslash
|
|
2469
|
+
// @filename: models.ts
|
|
2470
|
+
import { Model } from "@forestfuture/active-record";
|
|
2471
|
+
|
|
2472
|
+
export class User extends Model.define({
|
|
2473
|
+
id: { type: "string", null: false, generateId: true },
|
|
2474
|
+
email: { type: "string", null: false },
|
|
2475
|
+
role: "string",
|
|
2476
|
+
isActive: "boolean",
|
|
2477
|
+
createdAt: { type: "datetime", null: false },
|
|
2478
|
+
updatedAt: { type: "datetime", null: false },
|
|
2479
|
+
}) {}
|
|
2480
|
+
|
|
2481
|
+
// @filename: example.ts
|
|
2482
|
+
// ---cut---
|
|
2483
|
+
import { column, sql } from "@forestfuture/active-record";
|
|
2484
|
+
import { User } from "./models";
|
|
2485
|
+
|
|
2486
|
+
const email = "Ada@Example.com";
|
|
2487
|
+
const ada = await User.findBy(sql`lower(${column("email")}) = lower(${email})`);
|
|
2488
|
+
```
|
|
2489
|
+
|
|
2490
|
+
Values are always bound, as they are, so a `Date` is ISO text. To write a value the way its attribute stores it, use `column(name).value(v)`:
|
|
2491
|
+
|
|
2492
|
+
```ts twoslash
|
|
2493
|
+
// @filename: models.ts
|
|
2494
|
+
import { Model } from "@forestfuture/active-record";
|
|
2495
|
+
|
|
2496
|
+
export class User extends Model.define({
|
|
2497
|
+
id: { type: "string", null: false, generateId: true },
|
|
2498
|
+
email: { type: "string", null: false },
|
|
2499
|
+
role: "string",
|
|
2500
|
+
isActive: "boolean",
|
|
2501
|
+
createdAt: { type: "datetime", null: false },
|
|
2502
|
+
updatedAt: { type: "datetime", null: false },
|
|
2503
|
+
}) {}
|
|
2504
|
+
|
|
2505
|
+
// @filename: example.ts
|
|
2506
|
+
// ---cut---
|
|
2507
|
+
import { column, sql } from "@forestfuture/active-record";
|
|
2508
|
+
import { User } from "./models";
|
|
2509
|
+
|
|
2510
|
+
const createdAt = column("createdAt");
|
|
2511
|
+
const newcomers = await User.where(
|
|
2512
|
+
sql`${createdAt} >= ${createdAt.value(new Date("2026-01-01"))}`,
|
|
2513
|
+
).toArray();
|
|
2514
|
+
```
|
|
2515
|
+
|
|
2516
|
+
`value` works for any attribute, and writes a boolean as 0 or 1 and a JSON value as text. It casts as assigning would, 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.
|
|
2517
|
+
|
|
2518
|
+
:::warning[Datetimes stored as Unix time]
|
|
2519
|
+
For a datetime [stored as a Unix time](/adopt-a-database#reading-unix-timestamps), a bare `Date`, or an ISO datetime string, beside its column throws `TypeError`. Inside an expression, such as `abs(${column("publishedAt")} - ${date})`, or an `IN` list, nothing can tell, and the integer is compared with text: `>` matches nothing and `<` matches every row. Use `value` there.
|
|
2520
|
+
:::
|
|
2521
|
+
|
|
2522
|
+
## Replacing conditions
|
|
2523
|
+
|
|
2524
|
+
Replace the conditions on some attributes with `rewhere`:
|
|
2525
|
+
|
|
2526
|
+
```ts twoslash
|
|
2527
|
+
// @filename: models.ts
|
|
2528
|
+
import { Model } from "@forestfuture/active-record";
|
|
2529
|
+
|
|
2530
|
+
export class User extends Model.define({
|
|
2531
|
+
id: { type: "string", null: false, generateId: true },
|
|
2532
|
+
email: { type: "string", null: false },
|
|
2533
|
+
role: "string",
|
|
2534
|
+
isActive: "boolean",
|
|
2535
|
+
createdAt: { type: "datetime", null: false },
|
|
2536
|
+
updatedAt: { type: "datetime", null: false },
|
|
2537
|
+
}) {}
|
|
2538
|
+
|
|
2539
|
+
// @filename: example.ts
|
|
2540
|
+
// ---cut---
|
|
2541
|
+
import { User } from "./models";
|
|
2542
|
+
|
|
2543
|
+
const members = User.where({ role: "member", isActive: true });
|
|
2544
|
+
const activeAdmins = await members.rewhere({ role: "admin" }).toArray(); // is_active = ? AND role = ?
|
|
2545
|
+
```
|
|
2546
|
+
|
|
2547
|
+
Conditions on other attributes stay, and so do `sql` fragments. A default scope’s condition on the attribute is replaced too. A `whereNot` or `or` is replaced only if it names no other attributes.
|
|
2548
|
+
|
|
2549
|
+
Drop parts of a query with `unscope`, or keep only some with `only`:
|
|
2550
|
+
|
|
2551
|
+
```ts twoslash
|
|
2552
|
+
// @filename: models.ts
|
|
2553
|
+
import { Model } from "@forestfuture/active-record";
|
|
2554
|
+
|
|
2555
|
+
export class User extends Model.define({
|
|
2556
|
+
id: { type: "string", null: false, generateId: true },
|
|
2557
|
+
email: { type: "string", null: false },
|
|
2558
|
+
role: "string",
|
|
2559
|
+
isActive: "boolean",
|
|
2560
|
+
createdAt: { type: "datetime", null: false },
|
|
2561
|
+
updatedAt: { type: "datetime", null: false },
|
|
2562
|
+
}) {}
|
|
2563
|
+
|
|
2564
|
+
// @filename: example.ts
|
|
2565
|
+
// ---cut---
|
|
2566
|
+
import { User } from "./models";
|
|
2567
|
+
|
|
2568
|
+
const recent = User.where({ role: "admin" }).order({ createdAt: "desc" }).limit(10);
|
|
2569
|
+
recent.unscope("order", "limit"); // every admin, unordered
|
|
2570
|
+
recent.unscope({ where: "role" }); // the 10 newest users
|
|
2571
|
+
recent.only("where"); // every admin
|
|
2572
|
+
```
|
|
2573
|
+
|
|
2574
|
+
- The parts are `"where"`, `"order"`, `"limit"`, `"offset"`, `"select"`, `"distinct"`, `"includes"`, `"joins"`, `"leftJoins"`, and `"createWith"`. `{ where: "role" }` drops only the conditions on those attributes.
|
|
2575
|
+
- A default scope’s parts are dropped too. To start without the default scope, use [`unscoped()`](/querying#defining-a-default-scope).
|
|
2576
|
+
- 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.
|
|
2577
|
+
- Merging a Relation built with `unscope` drops those parts from the Relation it’s merged into.
|
|
2578
|
+
- A join can’t be dropped while a merged condition or order uses it. That throws `IncompatibleRelation`.
|
|
2579
|
+
|
|
2580
|
+
## Leaving records out
|
|
2581
|
+
|
|
2582
|
+
Leave out records you already have with `excluding`:
|
|
2583
|
+
|
|
2584
|
+
```ts twoslash
|
|
2585
|
+
// @filename: models.ts
|
|
2586
|
+
import { Model } from "@forestfuture/active-record";
|
|
2587
|
+
|
|
2588
|
+
export class User extends Model.define({
|
|
2589
|
+
id: { type: "string", null: false, generateId: true },
|
|
2590
|
+
email: { type: "string", null: false },
|
|
2591
|
+
role: "string",
|
|
2592
|
+
isActive: "boolean",
|
|
2593
|
+
createdAt: { type: "datetime", null: false },
|
|
2594
|
+
updatedAt: { type: "datetime", null: false },
|
|
2595
|
+
}) {}
|
|
2596
|
+
|
|
2597
|
+
// @filename: example.ts
|
|
2598
|
+
// ---cut---
|
|
2599
|
+
import { User } from "./models";
|
|
2600
|
+
|
|
2601
|
+
const me = await User.findByOrThrow({ email: "ada@example.com" });
|
|
2602
|
+
const everyoneElse = await User.excluding(me).toArray();
|
|
2603
|
+
```
|
|
2604
|
+
|
|
2605
|
+
It takes records of the Relation’s Model, or arrays of them. A record that isn’t saved yet leaves nothing out.
|
|
2606
|
+
|
|
2607
|
+
> **Compared with Rails**
|
|
2608
|
+
>
|
|
2609
|
+
> `rewhere`, `unscope`, `only`, and `excluding` 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. `invert_where` and `without` aren’t offered, and scopes cover `extending`.
|
|
2610
|
+
|
|
2611
|
+
> **Beyond Rails**
|
|
2612
|
+
>
|
|
2613
|
+
> 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.
|
|
2614
|
+
|
|
2615
|
+
---
|
|
2616
|
+
|
|
2127
2617
|
# Connections
|
|
2128
2618
|
Source: https://active-record.forestfuture.dev/connecting
|
|
2129
2619
|
|
|
2130
|
-
|
|
2620
|
+
## At a glance
|
|
2621
|
+
|
|
2622
|
+
Most apps only use the binding.
|
|
2131
2623
|
|
|
2132
2624
|
| | How | Use it for |
|
|
2133
2625
|
| -------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------- |
|
|
@@ -2180,7 +2672,7 @@ export default {
|
|
|
2180
2672
|
Every query started from a Model inside it, and everything it awaits, uses that database instead of the binding.
|
|
2181
2673
|
|
|
2182
2674
|
:::warning[Node.js compatibility]
|
|
2183
|
-
`withDatabase` uses Workers’ `AsyncLocalStorage`. It’s on by default for compatibility dates from 2026-08-04. For an earlier date, add `"compatibility_flags": ["nodejs_compat"]` to your Wrangler config, or `withDatabase` throws `NoDatabase`.
|
|
2675
|
+
`withDatabase` uses Workers’ `AsyncLocalStorage`. It’s on by default for compatibility dates from 2026-08-04. For an earlier date, add `"compatibility_flags": ["nodejs_compat"]` to your Wrangler config, or `withDatabase` throws `NoDatabase`. On D1, only `withDatabase` and [`noTouching`](/associations#turning-touches-off) need it. On Postgres, `pg` needs it too.
|
|
2184
2676
|
:::
|
|
2185
2677
|
|
|
2186
2678
|
These pages use a request’s database:
|
|
@@ -2235,7 +2727,9 @@ await batch((b) => [b.save(user), b.save(post), b.deleteAll(Post.where({ userId:
|
|
|
2235
2727
|
# Console
|
|
2236
2728
|
Source: https://active-record.forestfuture.dev/console
|
|
2237
2729
|
|
|
2238
|
-
|
|
2730
|
+
## Opening the console
|
|
2731
|
+
|
|
2732
|
+
Run the console from your project’s folder. It opens your local database, or your remote one with [`--remote`](#opening-your-remote-database):
|
|
2239
2733
|
|
|
2240
2734
|
```sh
|
|
2241
2735
|
npx active-record console
|
|
@@ -2435,8 +2929,6 @@ The console runs your project’s code: your Models, and the `wrangler` and `@fo
|
|
|
2435
2929
|
# Custom types
|
|
2436
2930
|
Source: https://active-record.forestfuture.dev/custom-types
|
|
2437
2931
|
|
|
2438
|
-
A custom type holds a value the built-in types don’t, such as money or a list of sizes. Its values are stored in their column as one of the built-in types.
|
|
2439
|
-
|
|
2440
2932
|
## Defining a type
|
|
2441
2933
|
|
|
2442
2934
|
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:
|
|
@@ -2575,7 +3067,9 @@ An equal value in another object, such as a new `Money` of the same cents, isn
|
|
|
2575
3067
|
# D1
|
|
2576
3068
|
Source: https://active-record.forestfuture.dev/d1
|
|
2577
3069
|
|
|
2578
|
-
|
|
3070
|
+
## Installing
|
|
3071
|
+
|
|
3072
|
+
The D1 adapter comes with `@forestfuture/active-record`, as its `/d1` entry:
|
|
2579
3073
|
|
|
2580
3074
|
```sh
|
|
2581
3075
|
npm install @forestfuture/active-record
|
|
@@ -2654,6 +3148,8 @@ SQLite stores a [`decimal`](/models#storing-exact-numbers-days-and-times) as a n
|
|
|
2654
3148
|
# Errors
|
|
2655
3149
|
Source: https://active-record.forestfuture.dev/errors
|
|
2656
3150
|
|
|
3151
|
+
## Checking for Active Record’s errors
|
|
3152
|
+
|
|
2657
3153
|
Every error Active Record throws extends `ActiveRecordError`, so one check separates them from anything else:
|
|
2658
3154
|
|
|
2659
3155
|
```ts
|
|
@@ -2743,7 +3239,9 @@ Every method throws them, `save()` as well as `saveOrThrow()`. The record keeps
|
|
|
2743
3239
|
# Generators
|
|
2744
3240
|
Source: https://active-record.forestfuture.dev/generators
|
|
2745
3241
|
|
|
2746
|
-
|
|
3242
|
+
:::note
|
|
3243
|
+
Each migration is written in your database’s own SQL. [Command line](/command-line#column-syntax) lists the types on D1 and on Postgres, and every option.
|
|
3244
|
+
:::
|
|
2747
3245
|
|
|
2748
3246
|
## Adding a table
|
|
2749
3247
|
|
|
@@ -2872,8 +3370,6 @@ npx active-record schema
|
|
|
2872
3370
|
# Getting started
|
|
2873
3371
|
Source: https://active-record.forestfuture.dev/getting-started
|
|
2874
3372
|
|
|
2875
|
-
Active Record turns each table in your [D1](https://developers.cloudflare.com/d1/) database into a Model, so your [Worker](https://developers.cloudflare.com/workers/) works with records instead of rows. In this tutorial you’ll build the start of a small blog: users, and the posts they write.
|
|
2876
|
-
|
|
2877
3373
|
:::warning[Version 0.x]
|
|
2878
3374
|
Active Record is before 1.0. Its behavior is tested against real D1, but the API may still change. A breaking change ships in a new minor version, so `^0.7.0` never takes one.
|
|
2879
3375
|
:::
|
|
@@ -3089,7 +3585,9 @@ The list includes Ada, with her email lowercased by `beforeSave`. Sign her up ag
|
|
|
3089
3585
|
# Logging
|
|
3090
3586
|
Source: https://active-record.forestfuture.dev/logging
|
|
3091
3587
|
|
|
3092
|
-
|
|
3588
|
+
## Receiving each query
|
|
3589
|
+
|
|
3590
|
+
An `onQuery` listener is called once for every statement, writes and batches included, with:
|
|
3093
3591
|
|
|
3094
3592
|
| Field | |
|
|
3095
3593
|
| --------------- | ---------------------------------------------------------------- |
|
|
@@ -3282,8 +3780,6 @@ A bare value inside an `sql` fragment has no attribute, so it’s logged as give
|
|
|
3282
3780
|
# Models
|
|
3283
3781
|
Source: https://active-record.forestfuture.dev/models
|
|
3284
3782
|
|
|
3285
|
-
A Model describes one table. Its attributes come from your migrations, through the generated schema, so the Model only declares behavior.
|
|
3286
|
-
|
|
3287
3783
|
## Defining Models
|
|
3288
3784
|
|
|
3289
3785
|
### Generating `ApplicationRecord`
|
|
@@ -3943,7 +4439,7 @@ import { column, sql } from "@forestfuture/active-record";
|
|
|
3943
4439
|
const recent = await User.where(sql`${column("createdAt")} > ${since}`).toArray();
|
|
3944
4440
|
```
|
|
3945
4441
|
|
|
3946
|
-
A plain string is rejected. To write a `Date`, boolean, or JSON value the way an attribute stores it, see [Writing SQL fragments](/
|
|
4442
|
+
A plain string is rejected. To write a `Date`, boolean, or JSON value the way an attribute stores it, see [Writing SQL fragments](/conditions#writing-sql-fragments).
|
|
3947
4443
|
|
|
3948
4444
|
## Serializing records
|
|
3949
4445
|
|
|
@@ -4080,7 +4576,9 @@ After that, a Model’s declarations are fixed, so request code can’t change t
|
|
|
4080
4576
|
# Moving to Postgres
|
|
4081
4577
|
Source: https://active-record.forestfuture.dev/move-to-postgres
|
|
4082
4578
|
|
|
4083
|
-
|
|
4579
|
+
## Planning the move
|
|
4580
|
+
|
|
4581
|
+
The examples move the app from [Getting started](/getting-started).
|
|
4084
4582
|
|
|
4085
4583
|
| What changes | How |
|
|
4086
4584
|
| --------------------- | -------------------------------------------------------- |
|
|
@@ -4334,8 +4832,6 @@ Your queries, validations, callbacks, and associations work the same on Postgres
|
|
|
4334
4832
|
# Persistence
|
|
4335
4833
|
Source: https://active-record.forestfuture.dev/persistence
|
|
4336
4834
|
|
|
4337
|
-
Records are saved, updated, and destroyed with `save`, `create`, `update`, and `destroy`.
|
|
4338
|
-
|
|
4339
4835
|
## Saving records
|
|
4340
4836
|
|
|
4341
4837
|
Save a record with `save`. It validates the record, runs its callbacks, and resolves to `true` or `false`:
|
|
@@ -4458,7 +4954,9 @@ await Article.where({ isPinned: true }).touchAll(); // every pinned article, in
|
|
|
4458
4954
|
|
|
4459
4955
|
`touch` skips validations and the save callbacks, and the record’s other unsaved changes stay unsaved. It runs `afterTouch`, then the commit callbacks for an update. See [Running code after a touch](/callbacks#running-code-after-a-touch).
|
|
4460
4956
|
|
|
4461
|
-
`touch` resolves to `true`, or `false` when the row is gone. A record that was never saved throws `RecordNotSaved`. On a Model with no `updatedAt`, name at least one attribute.
|
|
4957
|
+
`touch` resolves to `true`, or `false` when the row is gone. A record that was never saved throws `RecordNotSaved`. On a Model with no `updatedAt`, name at least one attribute. Inside a [`noTouching` block](/associations#turning-touches-off) for its Model, `touch` writes nothing and resolves to `false`.
|
|
4958
|
+
|
|
4959
|
+
To touch the record a record belongs to whenever it changes, declare `touch` on its `belongsTo`. See [Touching the record it belongs to](/associations#touching-the-record-it-belongs-to).
|
|
4462
4960
|
|
|
4463
4961
|
### Updating counters
|
|
4464
4962
|
|
|
@@ -4552,7 +5050,7 @@ const news = await Label.createOrFindBy({ name: "news" }); // created, or found
|
|
|
4552
5050
|
|
|
4553
5051
|
- **Leave out a `uniqueness` validation on those attributes.** It refuses the duplicate before the insert, so `createOrFindBy` resolves to the invalid record, not the existing one. The UNIQUE index alone keeps the column unique.
|
|
4554
5052
|
- **Save the record alone.** When `init` builds or sets records through its associations, a refusal may be theirs, so `createOrFindBy` throws the `RecordNotUnique` instead of finding.
|
|
4555
|
-
- **It throws `RecordNotFound` when there’s nothing to find:** when the index refused a value in an attribute you didn’t pass, when the existing row isn’t linked to the owner of an [association through another](/
|
|
5053
|
+
- **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](/through-associations), or when a [D1 Session](/read-your-own-writes) reads from a replica that the other request’s row hasn’t reached yet.
|
|
4556
5054
|
|
|
4557
5055
|
:::
|
|
4558
5056
|
|
|
@@ -4679,7 +5177,9 @@ To insert, update, or delete many rows at once, without validations and callback
|
|
|
4679
5177
|
# PostgreSQL
|
|
4680
5178
|
Source: https://active-record.forestfuture.dev/postgresql
|
|
4681
5179
|
|
|
4682
|
-
|
|
5180
|
+
## Installing
|
|
5181
|
+
|
|
5182
|
+
The PostgreSQL adapter comes with `@forestfuture/active-record`, as its `/postgresql` entry. Install the library with `pg`, and PGlite for reading your schema:
|
|
4683
5183
|
|
|
4684
5184
|
```sh
|
|
4685
5185
|
npm install @forestfuture/active-record pg
|
|
@@ -4829,8 +5329,6 @@ A `jsonb` column keeps a JSON value, not the text you wrote. A raw query reads i
|
|
|
4829
5329
|
# Database resolution
|
|
4830
5330
|
Source: https://active-record.forestfuture.dev/query-databases
|
|
4831
5331
|
|
|
4832
|
-
`Product.find(id)` works with no setup, because a Model knows its binding. But a Worker isn’t a long-running server, and that shapes how a query finds its database.
|
|
4833
|
-
|
|
4834
5332
|
## One isolate, many requests
|
|
4835
5333
|
|
|
4836
5334
|
A Worker runs in an **isolate** that serves many requests at the same time, and a Model class is shared by all of them. So anything stored on a class is shared by every request in flight. That rules out storing a connection on a class: some of what a connection carries belongs to one request only.
|
|
@@ -4874,6 +5372,8 @@ For the options themselves, see [Connections](/connecting).
|
|
|
4874
5372
|
# Querying
|
|
4875
5373
|
Source: https://active-record.forestfuture.dev/querying
|
|
4876
5374
|
|
|
5375
|
+
## Building a Relation
|
|
5376
|
+
|
|
4877
5377
|
A query is a **Relation**. Each method that narrows, orders, or pages it returns a new Relation, and nothing runs until you ask for results:
|
|
4878
5378
|
|
|
4879
5379
|
```ts
|
|
@@ -4896,130 +5396,7 @@ A query runs on the current database: the request’s, if it was opened with `wi
|
|
|
4896
5396
|
|
|
4897
5397
|
## Adding conditions
|
|
4898
5398
|
|
|
4899
|
-
|
|
4900
|
-
|
|
4901
|
-
```ts
|
|
4902
|
-
import { User } from "./models";
|
|
4903
|
-
|
|
4904
|
-
User.where({ role: "admin", isActive: true }); // role = ? AND is_active = ?
|
|
4905
|
-
User.where({ role: null }); // role IS NULL
|
|
4906
|
-
User.where({ role: ["admin", "editor"] }); // role IN (…), any number of values
|
|
4907
|
-
User.whereNot({ role: "admin" }); // NOT (role = ?)
|
|
4908
|
-
User.where({ role: "admin" }).or(User.where({ isActive: false }));
|
|
4909
|
-
```
|
|
4910
|
-
|
|
4911
|
-
- `null` matches NULL, and an array matches any of its values. The list is bound as one value, so it can be any length.
|
|
4912
|
-
- `whereNot` negates the whole condition. As in SQL, `whereNot({ role: "admin" })` also leaves out users whose role is NULL.
|
|
4913
|
-
- `or` combines two Relations of the same Model that differ only in their conditions.
|
|
4914
|
-
- `undefined` throws `TypeError`. Leave the key out, or use `null`.
|
|
4915
|
-
|
|
4916
|
-
Values are [cast to the attribute’s type](/models#casting-assigned-values), so `where({ quantity: "42" })` finds 42. A value that can’t be cast matches nothing: `findBy` resolves to `null`, and `find` throws `RecordNotFound`.
|
|
4917
|
-
|
|
4918
|
-
:::note
|
|
4919
|
-
In a list, values that can’t be cast are left out. So `whereNot({ id: "abc" })` on an integer key excludes nothing.
|
|
4920
|
-
:::
|
|
4921
|
-
|
|
4922
|
-
### Comparing values
|
|
4923
|
-
|
|
4924
|
-
Pass a comparison helper as a value:
|
|
4925
|
-
|
|
4926
|
-
```ts
|
|
4927
|
-
import { between, gte, lt } from "@forestfuture/active-record";
|
|
4928
|
-
import { Post, User } from "./models";
|
|
4929
|
-
|
|
4930
|
-
Post.where({ publishedAt: gte(since) }); // published_at >= since
|
|
4931
|
-
User.where({ createdAt: lt(since) }); // created_at < since
|
|
4932
|
-
User.where({ createdAt: between(since, until) }); // both ends included
|
|
4933
|
-
User.where({ createdAt: between(since, until, { excludeEnd: true }) });
|
|
4934
|
-
```
|
|
4935
|
-
|
|
4936
|
-
`gt`, `gte`, `lt`, `lte`, and `between` work on number, string, and datetime attributes, and dates compare by time. `between` includes both ends. Pass `{ excludeEnd: true }` to leave out the end.
|
|
4937
|
-
|
|
4938
|
-
### Writing SQL fragments
|
|
4939
|
-
|
|
4940
|
-
For anything else, write an `sql` tagged template. Values are always bound, and `column()` looks up an attribute’s column:
|
|
4941
|
-
|
|
4942
|
-
```ts
|
|
4943
|
-
import { column, sql } from "@forestfuture/active-record";
|
|
4944
|
-
import { User } from "./models";
|
|
4945
|
-
|
|
4946
|
-
const email = "Ada@Example.com";
|
|
4947
|
-
User.where(sql`lower(${column("email")}) = lower(${email})`);
|
|
4948
|
-
```
|
|
4949
|
-
|
|
4950
|
-
:::warning[Integer datetimes]
|
|
4951
|
-
A value in a fragment is bound as it is, so a `Date` is ISO text. If the attribute is a datetime [stored as a Unix time](/adopt-a-database#reading-unix-timestamps), compare it with `column("publishedAt").value(date)`, which writes the `Date` as the attribute stores it. A bare `Date` (or an ISO datetime string) beside that column in a comparison throws `TypeError`. In an expression, such as `abs(${column("publishedAt")} - ${date})`, or in an `IN` list, Active Record can’t tell what you meant: you’re comparing an integer with text, which SQLite always orders the same way, so `>` matches nothing and `<` matches every row. Check which form the expression needs, and use `value` when it needs the stored one.
|
|
4952
|
-
:::
|
|
4953
|
-
|
|
4954
|
-
```ts
|
|
4955
|
-
import { column, sql } from "@forestfuture/active-record";
|
|
4956
|
-
|
|
4957
|
-
export function publishedBefore(before: Date) {
|
|
4958
|
-
const publishedAt = column("publishedAt");
|
|
4959
|
-
return Article.where(sql`${publishedAt} < ${publishedAt.value(before)}`);
|
|
4960
|
-
}
|
|
4961
|
-
```
|
|
4962
|
-
|
|
4963
|
-
`value` works for any attribute, and writes a boolean as 0 or 1 and a JSON value as text. The value is cast as an assigned one, so a value the attribute can’t hold throws `TypeError` naming the attribute, when `where` is given the fragment. A filtered attribute’s value is hidden from `onQuery`, as it is anywhere else.
|
|
4964
|
-
|
|
4965
|
-
### Replacing conditions
|
|
4966
|
-
|
|
4967
|
-
Replace the conditions on some attributes with `rewhere`:
|
|
4968
|
-
|
|
4969
|
-
```ts
|
|
4970
|
-
import { User } from "./models";
|
|
4971
|
-
|
|
4972
|
-
const members = User.where({ role: "member", isActive: true });
|
|
4973
|
-
members.rewhere({ role: "admin" }); // is_active = ? AND role = ?
|
|
4974
|
-
```
|
|
4975
|
-
|
|
4976
|
-
Conditions on other attributes stay, and so do `sql` fragments. A default scope’s condition on the attribute is replaced too.
|
|
4977
|
-
|
|
4978
|
-
:::note
|
|
4979
|
-
A `whereNot` or `or` that names only those attributes is replaced. One that names other attributes too stays.
|
|
4980
|
-
:::
|
|
4981
|
-
|
|
4982
|
-
Drop parts of a query with `unscope`, or keep only some with `only`:
|
|
4983
|
-
|
|
4984
|
-
```ts
|
|
4985
|
-
import { User } from "./models";
|
|
4986
|
-
|
|
4987
|
-
const recent = User.where({ role: "admin" }).order({ createdAt: "desc" }).limit(10);
|
|
4988
|
-
recent.unscope("order", "limit"); // every admin, unordered
|
|
4989
|
-
recent.unscope({ where: "role" }); // the 10 newest users
|
|
4990
|
-
recent.only("where"); // every admin
|
|
4991
|
-
```
|
|
4992
|
-
|
|
4993
|
-
- The parts are `"where"`, `"order"`, `"limit"`, `"offset"`, `"select"`, `"distinct"`, `"includes"`, `"joins"`, `"leftJoins"`, and `"createWith"`. `{ where: "role" }` drops only the conditions on those attributes.
|
|
4994
|
-
- A default scope’s parts are dropped too. To start without the default scope, use [`unscoped()`](#defining-a-default-scope).
|
|
4995
|
-
- On an association, the link to its owner stays. `user.posts().unscope("where")` is still the user’s posts, and so is `rewhere({ userId })`. Start from `Post` to read past the owner.
|
|
4996
|
-
- Merging a Relation built with `unscope` drops those parts from the Relation it’s merged into.
|
|
4997
|
-
- A join can’t be dropped while conditions or an order merged onto it use it. That throws `IncompatibleRelation`.
|
|
4998
|
-
|
|
4999
|
-
> **Compared with Rails**
|
|
5000
|
-
>
|
|
5001
|
-
> `rewhere`, `unscope`, and `only` work as Rails’ do, with the parts named as strings. `group` and `having` aren’t parts, since a grouped Relation is a type of its own. Rails’ `invert_where` and `extending` aren’t offered. Scopes cover `extending`.
|
|
5002
|
-
|
|
5003
|
-
> **Beyond Rails**
|
|
5004
|
-
>
|
|
5005
|
-
> On an association, Rails’ `unscope(:where)` drops the link to its owner, so a read can reach records that `create` wouldn’t link to it. Here no rewrite drops the link, so reads and writes agree.
|
|
5006
|
-
|
|
5007
|
-
## Leaving records out
|
|
5008
|
-
|
|
5009
|
-
Leave out records you already have with `excluding`:
|
|
5010
|
-
|
|
5011
|
-
```ts
|
|
5012
|
-
import { User } from "./models";
|
|
5013
|
-
|
|
5014
|
-
const current = await User.firstOrThrow();
|
|
5015
|
-
const others = await User.where({ role: "admin" }).excluding(current).toArray();
|
|
5016
|
-
```
|
|
5017
|
-
|
|
5018
|
-
It takes records of the Relation’s Model, or arrays of them. A record that isn’t saved yet leaves nothing out.
|
|
5019
|
-
|
|
5020
|
-
> **Compared with Rails**
|
|
5021
|
-
>
|
|
5022
|
-
> `excluding` is Rails’ `excluding`. Its alias `without` isn’t offered.
|
|
5399
|
+
Narrow a query with `where`, `whereNot`, `or`, comparisons such as `gte` and `between`, and `sql` fragments. Replace them with `rewhere`, drop parts with `unscope`, and leave records out with `excluding`. See [Conditions](/conditions).
|
|
5023
5400
|
|
|
5024
5401
|
## Using raw statements
|
|
5025
5402
|
|
|
@@ -5409,7 +5786,7 @@ console.log(partial[0]?.id); // the primary key is always loaded too
|
|
|
5409
5786
|
const roles = await User.select("role").distinct().pluck("role");
|
|
5410
5787
|
```
|
|
5411
5788
|
|
|
5412
|
-
- Reading an attribute that wasn’t loaded throws `MissingAttribute`, including from a validator or callback.
|
|
5789
|
+
- Reading an attribute that wasn’t loaded throws `MissingAttribute`, including from a validator or callback. `record.hasAttribute("email")` says whether it was loaded.
|
|
5413
5790
|
- Saving a partial record writes only what changed. `reload()` loads the whole row.
|
|
5414
5791
|
- After `distinct()`, the primary key isn’t added, since it would make every row distinct, so those records can’t be saved.
|
|
5415
5792
|
|
|
@@ -5521,7 +5898,7 @@ const draft = Product.build({ name: "Pen" }); // available: 1, from the default
|
|
|
5521
5898
|
- `insert`, `insertAll`, `upsert`, and `upsertAll` write its conditions’ values over the values you give. `build` and `create` use the values you give.
|
|
5522
5899
|
- Several default scopes all apply. A subclass adds its own to its parent’s.
|
|
5523
5900
|
- An order in a default scope is the Relation’s order. `reorder` replaces it.
|
|
5524
|
-
- `rewhere` replaces its condition on an attribute, and [`unscope`](#replacing-conditions) drops its parts.
|
|
5901
|
+
- `rewhere` replaces its condition on an attribute, and [`unscope`](/conditions#replacing-conditions) drops its parts.
|
|
5525
5902
|
|
|
5526
5903
|
To leave the default scope out, start from `unscoped()`:
|
|
5527
5904
|
|
|
@@ -5637,7 +6014,9 @@ A polymorphic `belongsTo` can’t be joined, because its records may be in sever
|
|
|
5637
6014
|
# Read replicas
|
|
5638
6015
|
Source: https://active-record.forestfuture.dev/read-your-own-writes
|
|
5639
6016
|
|
|
5640
|
-
|
|
6017
|
+
:::note
|
|
6018
|
+
[D1 read replication](https://developers.cloudflare.com/d1/best-practices/read-replication/) serves reads from a nearby replica, which may be a moment behind. A D1 **Session** keeps each user’s reads at least as new as their own writes.
|
|
6019
|
+
:::
|
|
5641
6020
|
|
|
5642
6021
|
## Opening a Session for each request
|
|
5643
6022
|
|
|
@@ -5712,8 +6091,6 @@ After the first query, each query reads data at least as new as the one before,
|
|
|
5712
6091
|
# Schema and ApplicationRecord
|
|
5713
6092
|
Source: https://active-record.forestfuture.dev/schema
|
|
5714
6093
|
|
|
5715
|
-
In Rails, a migration describes a table, and the model never repeats it: Rails reads the columns from the database when the app runs. Active Record keeps that idea, with one change TypeScript requires: it reads the columns when you **generate** the schema, not when your Worker runs.
|
|
5716
|
-
|
|
5717
6094
|
## Migrations are the source of truth
|
|
5718
6095
|
|
|
5719
6096
|
Tables are created and changed by **migrations**: numbered SQL files that Wrangler applies in order, recording each one in the database (in a `d1_migrations` table), so each runs once. Cloudflare’s [D1 migrations](https://developers.cloudflare.com/d1/reference/migrations/) guide covers Wrangler’s side. Active Record’s generators write migrations for you, but any migration Wrangler can apply works, however it was written.
|
|
@@ -5753,10 +6130,6 @@ A Model can still declare its attributes itself, with `define`, for a view or a
|
|
|
5753
6130
|
# Security
|
|
5754
6131
|
Source: https://active-record.forestfuture.dev/security
|
|
5755
6132
|
|
|
5756
|
-
Whatever a request sends can reach a query or a record through Active Record, so a mistake in it is a mistake in every app that uses it. Here’s what it protects against, what it leaves to your app, the tests that check each guarantee, how releases are built, and the security reviews it has had.
|
|
5757
|
-
|
|
5758
|
-
These are the project’s own reviews, not an independent audit. Each says what it covered and what it didn’t.
|
|
5759
|
-
|
|
5760
6133
|
## What Active Record protects against
|
|
5761
6134
|
|
|
5762
6135
|
- **SQL injection.** Every value is bound as a parameter, never written into SQL text. Identifiers come only from a Model’s declared attributes, and are quoted. Raw SQL is only possible through the `sql` tagged template, which binds every value it’s given.
|
|
@@ -5803,7 +6176,7 @@ The library’s guarantees are tested against a real D1 database (through Minifl
|
|
|
5803
6176
|
|
|
5804
6177
|
## Review log
|
|
5805
6178
|
|
|
5806
|
-
Each security review adds an entry here: what it covered, how, what it found, and what it didn’t cover.
|
|
6179
|
+
Each security review adds an entry here: what it covered, how, what it found, and what it didn’t cover. These are the project’s own reviews, not an independent audit.
|
|
5807
6180
|
|
|
5808
6181
|
### 2026-10-04: the library, its command line, and CI
|
|
5809
6182
|
|
|
@@ -5877,8 +6250,6 @@ Please report a security problem privately, as the [security policy](https://git
|
|
|
5877
6250
|
# Multiple databases
|
|
5878
6251
|
Source: https://active-record.forestfuture.dev/several-databases
|
|
5879
6252
|
|
|
5880
|
-
A Worker can bind several D1 databases, or a D1 database and a Postgres one. Each gets its own schema file and base class, and each Model queries the database its base class names.
|
|
5881
|
-
|
|
5882
6253
|
## Binding the databases
|
|
5883
6254
|
|
|
5884
6255
|
Add each database to your Wrangler config, with its own `migrations_dir`:
|
|
@@ -6154,8 +6525,6 @@ npx active-record migrate --database HYPERDRIVE
|
|
|
6154
6525
|
# Shared behavior
|
|
6155
6526
|
Source: https://active-record.forestfuture.dev/shared-behavior
|
|
6156
6527
|
|
|
6157
|
-
Every Model extends your app’s `ApplicationRecord`, so whatever you write on it, every Model has.
|
|
6158
|
-
|
|
6159
6528
|
## Sharing methods, callbacks, and scopes
|
|
6160
6529
|
|
|
6161
6530
|
Write them on `ApplicationRecord`, in `src/models/application-record.ts`:
|
|
@@ -6259,7 +6628,9 @@ See [Multiple databases](/several-databases).
|
|
|
6259
6628
|
# Testing
|
|
6260
6629
|
Source: https://active-record.forestfuture.dev/testing
|
|
6261
6630
|
|
|
6262
|
-
|
|
6631
|
+
## Installing
|
|
6632
|
+
|
|
6633
|
+
[Miniflare](https://developers.cloudflare.com/workers/testing/miniflare/) runs Cloudflare’s runtime, D1 included, inside Node:
|
|
6263
6634
|
|
|
6264
6635
|
```sh
|
|
6265
6636
|
npm install --save-dev vitest miniflare@4
|
|
@@ -6350,11 +6721,466 @@ To run tests inside the Workers runtime itself, use Cloudflare’s [Vitest integ
|
|
|
6350
6721
|
|
|
6351
6722
|
---
|
|
6352
6723
|
|
|
6724
|
+
# Through associations
|
|
6725
|
+
Source: https://active-record.forestfuture.dev/through-associations
|
|
6726
|
+
|
|
6727
|
+
## At a glance
|
|
6728
|
+
|
|
6729
|
+
| To | Write |
|
|
6730
|
+
| --------------------------------------- | ------------------------------------------------------------ |
|
|
6731
|
+
| declare a many-to-many association | `hasMany(Article, { through: "taggings" })` |
|
|
6732
|
+
| follow an association with another name | `hasMany(Author, { through: "articles", source: "author" })` |
|
|
6733
|
+
| reach one record | `hasOne(Author, { through: "article" })` |
|
|
6734
|
+
| read the records | `tag.articles()`, a Relation |
|
|
6735
|
+
| preload them | `Tag.includes("articles")` |
|
|
6736
|
+
| link a record | `tag.articles().push(article)` |
|
|
6737
|
+
| create a record and link it | `tag.articles().create({ … })` |
|
|
6738
|
+
| unlink a record | `tag.articles().delete(article)` |
|
|
6739
|
+
|
|
6740
|
+
### Options
|
|
6741
|
+
|
|
6742
|
+
| Prop | Type | Default | Description |
|
|
6743
|
+
| - | - | - | - |
|
|
6744
|
+
| `through` | `string` | - | The association to go through. |
|
|
6745
|
+
| `source?` | `string` | - | The join Model’s association to follow. Defaults to this association’s name, singular or plural. |
|
|
6746
|
+
| `scope?` | `(q) => Relation` | - | Narrows or orders the records, as on any association. |
|
|
6747
|
+
| `dependent?` | `"destroy" \| "deleteAll"` | - | What destroying the owner does to the join records. hasMany only. |
|
|
6748
|
+
|
|
6749
|
+
`scope` works as it does on any association. See [Scoping associations](/associations#scoping-associations).
|
|
6750
|
+
|
|
6751
|
+
## The Models
|
|
6752
|
+
|
|
6753
|
+
The examples use these Models and tables:
|
|
6754
|
+
|
|
6755
|
+
**Models**
|
|
6756
|
+
|
|
6757
|
+
```ts
|
|
6758
|
+
import { belongsTo, hasMany, hasOne, Model } from "@forestfuture/active-record";
|
|
6759
|
+
|
|
6760
|
+
export class Author extends Model.define({
|
|
6761
|
+
id: { type: "string", null: false, generateId: true },
|
|
6762
|
+
name: { type: "string", null: false },
|
|
6763
|
+
}) {
|
|
6764
|
+
articles = hasMany(Article);
|
|
6765
|
+
}
|
|
6766
|
+
|
|
6767
|
+
export class Article extends Model.define({
|
|
6768
|
+
id: { type: "string", null: false, generateId: true },
|
|
6769
|
+
authorId: { type: "string", null: false },
|
|
6770
|
+
title: { type: "string", null: false },
|
|
6771
|
+
}) {
|
|
6772
|
+
author = belongsTo(Author);
|
|
6773
|
+
taggings = hasMany(Tagging);
|
|
6774
|
+
tags = hasMany(Tag, { through: "taggings" }); // each tagging's tag
|
|
6775
|
+
}
|
|
6776
|
+
|
|
6777
|
+
export class Tag extends Model.define({
|
|
6778
|
+
id: { type: "integer", null: false },
|
|
6779
|
+
name: { type: "string", null: false },
|
|
6780
|
+
}) {
|
|
6781
|
+
taggings = hasMany(Tagging);
|
|
6782
|
+
articles = hasMany(Article, { through: "taggings" }); // each tagging's article
|
|
6783
|
+
writers = hasMany(Author, { through: "articles", source: "author" }); // each article's author
|
|
6784
|
+
}
|
|
6785
|
+
|
|
6786
|
+
export class Tagging extends Model.define({
|
|
6787
|
+
id: { type: "integer", null: false },
|
|
6788
|
+
articleId: { type: "string", null: false },
|
|
6789
|
+
tagId: { type: "integer", null: false },
|
|
6790
|
+
}) {
|
|
6791
|
+
article = belongsTo(Article);
|
|
6792
|
+
tag = belongsTo(Tag);
|
|
6793
|
+
author = hasOne(Author, { through: "article" }); // the article's author
|
|
6794
|
+
}
|
|
6795
|
+
```
|
|
6796
|
+
|
|
6797
|
+
**D1**
|
|
6798
|
+
|
|
6799
|
+
```sql
|
|
6800
|
+
CREATE TABLE authors (
|
|
6801
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
6802
|
+
name TEXT NOT NULL
|
|
6803
|
+
);
|
|
6804
|
+
CREATE TABLE articles (
|
|
6805
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
6806
|
+
author_id TEXT NOT NULL REFERENCES authors (id),
|
|
6807
|
+
title TEXT NOT NULL
|
|
6808
|
+
);
|
|
6809
|
+
CREATE TABLE tags (
|
|
6810
|
+
id INTEGER PRIMARY KEY,
|
|
6811
|
+
name TEXT NOT NULL
|
|
6812
|
+
);
|
|
6813
|
+
CREATE TABLE taggings (
|
|
6814
|
+
id INTEGER PRIMARY KEY,
|
|
6815
|
+
article_id TEXT NOT NULL REFERENCES articles (id),
|
|
6816
|
+
tag_id INTEGER NOT NULL REFERENCES tags (id)
|
|
6817
|
+
);
|
|
6818
|
+
```
|
|
6819
|
+
|
|
6820
|
+
**Postgres**
|
|
6821
|
+
|
|
6822
|
+
```sql
|
|
6823
|
+
CREATE TABLE authors (
|
|
6824
|
+
id UUID PRIMARY KEY,
|
|
6825
|
+
name TEXT NOT NULL
|
|
6826
|
+
);
|
|
6827
|
+
CREATE TABLE articles (
|
|
6828
|
+
id UUID PRIMARY KEY,
|
|
6829
|
+
author_id UUID NOT NULL REFERENCES authors (id),
|
|
6830
|
+
title TEXT NOT NULL
|
|
6831
|
+
);
|
|
6832
|
+
CREATE TABLE tags (
|
|
6833
|
+
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
|
6834
|
+
name TEXT NOT NULL
|
|
6835
|
+
);
|
|
6836
|
+
CREATE TABLE taggings (
|
|
6837
|
+
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
|
6838
|
+
article_id UUID NOT NULL REFERENCES articles (id),
|
|
6839
|
+
tag_id BIGINT NOT NULL REFERENCES tags (id)
|
|
6840
|
+
);
|
|
6841
|
+
```
|
|
6842
|
+
|
|
6843
|
+
## Reading records
|
|
6844
|
+
|
|
6845
|
+
Read a through association as you would any `hasMany`:
|
|
6846
|
+
|
|
6847
|
+
```ts twoslash
|
|
6848
|
+
// @filename: models.ts
|
|
6849
|
+
import { belongsTo, hasMany, hasOne, Model } from "@forestfuture/active-record";
|
|
6850
|
+
|
|
6851
|
+
export class Author extends Model.define({
|
|
6852
|
+
id: { type: "string", null: false, generateId: true },
|
|
6853
|
+
name: { type: "string", null: false },
|
|
6854
|
+
}) {
|
|
6855
|
+
articles = hasMany(Article);
|
|
6856
|
+
}
|
|
6857
|
+
|
|
6858
|
+
export class Article extends Model.define({
|
|
6859
|
+
id: { type: "string", null: false, generateId: true },
|
|
6860
|
+
authorId: { type: "string", null: false },
|
|
6861
|
+
title: { type: "string", null: false },
|
|
6862
|
+
}) {
|
|
6863
|
+
author = belongsTo(Author);
|
|
6864
|
+
taggings = hasMany(Tagging);
|
|
6865
|
+
tags = hasMany(Tag, { through: "taggings" }); // each tagging's tag
|
|
6866
|
+
}
|
|
6867
|
+
|
|
6868
|
+
export class Tag extends Model.define({
|
|
6869
|
+
id: { type: "integer", null: false },
|
|
6870
|
+
name: { type: "string", null: false },
|
|
6871
|
+
}) {
|
|
6872
|
+
taggings = hasMany(Tagging);
|
|
6873
|
+
articles = hasMany(Article, { through: "taggings" }); // each tagging's article
|
|
6874
|
+
writers = hasMany(Author, { through: "articles", source: "author" }); // each article's author
|
|
6875
|
+
}
|
|
6876
|
+
|
|
6877
|
+
export class Tagging extends Model.define({
|
|
6878
|
+
id: { type: "integer", null: false },
|
|
6879
|
+
articleId: { type: "string", null: false },
|
|
6880
|
+
tagId: { type: "integer", null: false },
|
|
6881
|
+
}) {
|
|
6882
|
+
article = belongsTo(Article);
|
|
6883
|
+
tag = belongsTo(Tag);
|
|
6884
|
+
author = hasOne(Author, { through: "article" }); // the article's author
|
|
6885
|
+
}
|
|
6886
|
+
|
|
6887
|
+
// @filename: example.ts
|
|
6888
|
+
// ---cut---
|
|
6889
|
+
import { Article, Tag } from "./models";
|
|
6890
|
+
|
|
6891
|
+
const tag = await Tag.findByOrThrow({ name: "essays" });
|
|
6892
|
+
const articles = await tag.articles().order({ title: "asc" }).toArray(); // one query
|
|
6893
|
+
|
|
6894
|
+
const article = await Article.findByOrThrow({ title: "Engines" });
|
|
6895
|
+
const tags = await article.tags().toArray(); // the other way, through the same taggings
|
|
6896
|
+
```
|
|
6897
|
+
|
|
6898
|
+
- `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`.
|
|
6899
|
+
- `tag.articles()` is a Relation, with every Relation method, read in one query. Its writes go to the taggings, as [below](#writing-through-it).
|
|
6900
|
+
- Each record comes back once, however many join records point at it.
|
|
6901
|
+
- The scopes of both associations it goes through apply, and so does its own `scope`.
|
|
6902
|
+
|
|
6903
|
+
## Preloading records
|
|
6904
|
+
|
|
6905
|
+
Preload the records for every tag with `includes`:
|
|
6906
|
+
|
|
6907
|
+
```ts twoslash
|
|
6908
|
+
// @filename: models.ts
|
|
6909
|
+
import { belongsTo, hasMany, hasOne, Model } from "@forestfuture/active-record";
|
|
6910
|
+
|
|
6911
|
+
export class Author extends Model.define({
|
|
6912
|
+
id: { type: "string", null: false, generateId: true },
|
|
6913
|
+
name: { type: "string", null: false },
|
|
6914
|
+
}) {
|
|
6915
|
+
articles = hasMany(Article);
|
|
6916
|
+
}
|
|
6917
|
+
|
|
6918
|
+
export class Article extends Model.define({
|
|
6919
|
+
id: { type: "string", null: false, generateId: true },
|
|
6920
|
+
authorId: { type: "string", null: false },
|
|
6921
|
+
title: { type: "string", null: false },
|
|
6922
|
+
}) {
|
|
6923
|
+
author = belongsTo(Author);
|
|
6924
|
+
taggings = hasMany(Tagging);
|
|
6925
|
+
tags = hasMany(Tag, { through: "taggings" }); // each tagging's tag
|
|
6926
|
+
}
|
|
6927
|
+
|
|
6928
|
+
export class Tag extends Model.define({
|
|
6929
|
+
id: { type: "integer", null: false },
|
|
6930
|
+
name: { type: "string", null: false },
|
|
6931
|
+
}) {
|
|
6932
|
+
taggings = hasMany(Tagging);
|
|
6933
|
+
articles = hasMany(Article, { through: "taggings" }); // each tagging's article
|
|
6934
|
+
writers = hasMany(Author, { through: "articles", source: "author" }); // each article's author
|
|
6935
|
+
}
|
|
6936
|
+
|
|
6937
|
+
export class Tagging extends Model.define({
|
|
6938
|
+
id: { type: "integer", null: false },
|
|
6939
|
+
articleId: { type: "string", null: false },
|
|
6940
|
+
tagId: { type: "integer", null: false },
|
|
6941
|
+
}) {
|
|
6942
|
+
article = belongsTo(Article);
|
|
6943
|
+
tag = belongsTo(Tag);
|
|
6944
|
+
author = hasOne(Author, { through: "article" }); // the article's author
|
|
6945
|
+
}
|
|
6946
|
+
|
|
6947
|
+
// @filename: example.ts
|
|
6948
|
+
// ---cut---
|
|
6949
|
+
import { Tag } from "./models";
|
|
6950
|
+
|
|
6951
|
+
const everyTag = await Tag.includes("articles").toArray(); // tags, taggings, and articles
|
|
6952
|
+
for (const each of everyTag) console.log(each.name, each.loaded("articles").length);
|
|
6953
|
+
```
|
|
6954
|
+
|
|
6955
|
+
The join records and the articles load with the tags’ own query, in one round trip on D1. The join records aren’t kept as `taggings` unless you include them too.
|
|
6956
|
+
|
|
6957
|
+
## Naming the source
|
|
6958
|
+
|
|
6959
|
+
If the join Model’s association has another name, pass it as `source`, as `writers` does to follow each article’s `author`:
|
|
6960
|
+
|
|
6961
|
+
```ts twoslash
|
|
6962
|
+
// @filename: models.ts
|
|
6963
|
+
import { belongsTo, hasMany, hasOne, Model } from "@forestfuture/active-record";
|
|
6964
|
+
|
|
6965
|
+
export class Author extends Model.define({
|
|
6966
|
+
id: { type: "string", null: false, generateId: true },
|
|
6967
|
+
name: { type: "string", null: false },
|
|
6968
|
+
}) {
|
|
6969
|
+
articles = hasMany(Article);
|
|
6970
|
+
}
|
|
6971
|
+
|
|
6972
|
+
export class Article extends Model.define({
|
|
6973
|
+
id: { type: "string", null: false, generateId: true },
|
|
6974
|
+
authorId: { type: "string", null: false },
|
|
6975
|
+
title: { type: "string", null: false },
|
|
6976
|
+
}) {
|
|
6977
|
+
author = belongsTo(Author);
|
|
6978
|
+
taggings = hasMany(Tagging);
|
|
6979
|
+
tags = hasMany(Tag, { through: "taggings" }); // each tagging's tag
|
|
6980
|
+
}
|
|
6981
|
+
|
|
6982
|
+
export class Tag extends Model.define({
|
|
6983
|
+
id: { type: "integer", null: false },
|
|
6984
|
+
name: { type: "string", null: false },
|
|
6985
|
+
}) {
|
|
6986
|
+
taggings = hasMany(Tagging);
|
|
6987
|
+
articles = hasMany(Article, { through: "taggings" }); // each tagging's article
|
|
6988
|
+
writers = hasMany(Author, { through: "articles", source: "author" }); // each article's author
|
|
6989
|
+
}
|
|
6990
|
+
|
|
6991
|
+
export class Tagging extends Model.define({
|
|
6992
|
+
id: { type: "integer", null: false },
|
|
6993
|
+
articleId: { type: "string", null: false },
|
|
6994
|
+
tagId: { type: "integer", null: false },
|
|
6995
|
+
}) {
|
|
6996
|
+
article = belongsTo(Article);
|
|
6997
|
+
tag = belongsTo(Tag);
|
|
6998
|
+
author = hasOne(Author, { through: "article" }); // the article's author
|
|
6999
|
+
}
|
|
7000
|
+
|
|
7001
|
+
// @filename: example.ts
|
|
7002
|
+
// ---cut---
|
|
7003
|
+
import { Tag } from "./models";
|
|
7004
|
+
|
|
7005
|
+
const tag = await Tag.findByOrThrow({ name: "essays" });
|
|
7006
|
+
const writers = await tag.writers().toArray(); // each author once
|
|
7007
|
+
```
|
|
7008
|
+
|
|
7009
|
+
`writers` goes through `articles`, which goes through `taggings`. An association can go through any number of others this way.
|
|
7010
|
+
|
|
7011
|
+
## Going through a belongsTo or a hasOne
|
|
7012
|
+
|
|
7013
|
+
A `hasOne` can go through a `belongsTo`, as a tagging’s `author` does through its `article`:
|
|
7014
|
+
|
|
7015
|
+
```ts twoslash
|
|
7016
|
+
// @filename: models.ts
|
|
7017
|
+
import { belongsTo, hasMany, hasOne, Model } from "@forestfuture/active-record";
|
|
7018
|
+
|
|
7019
|
+
export class Author extends Model.define({
|
|
7020
|
+
id: { type: "string", null: false, generateId: true },
|
|
7021
|
+
name: { type: "string", null: false },
|
|
7022
|
+
}) {
|
|
7023
|
+
articles = hasMany(Article);
|
|
7024
|
+
}
|
|
7025
|
+
|
|
7026
|
+
export class Article extends Model.define({
|
|
7027
|
+
id: { type: "string", null: false, generateId: true },
|
|
7028
|
+
authorId: { type: "string", null: false },
|
|
7029
|
+
title: { type: "string", null: false },
|
|
7030
|
+
}) {
|
|
7031
|
+
author = belongsTo(Author);
|
|
7032
|
+
taggings = hasMany(Tagging);
|
|
7033
|
+
tags = hasMany(Tag, { through: "taggings" }); // each tagging's tag
|
|
7034
|
+
}
|
|
7035
|
+
|
|
7036
|
+
export class Tag extends Model.define({
|
|
7037
|
+
id: { type: "integer", null: false },
|
|
7038
|
+
name: { type: "string", null: false },
|
|
7039
|
+
}) {
|
|
7040
|
+
taggings = hasMany(Tagging);
|
|
7041
|
+
articles = hasMany(Article, { through: "taggings" }); // each tagging's article
|
|
7042
|
+
writers = hasMany(Author, { through: "articles", source: "author" }); // each article's author
|
|
7043
|
+
}
|
|
7044
|
+
|
|
7045
|
+
export class Tagging extends Model.define({
|
|
7046
|
+
id: { type: "integer", null: false },
|
|
7047
|
+
articleId: { type: "string", null: false },
|
|
7048
|
+
tagId: { type: "integer", null: false },
|
|
7049
|
+
}) {
|
|
7050
|
+
article = belongsTo(Article);
|
|
7051
|
+
tag = belongsTo(Tag);
|
|
7052
|
+
author = hasOne(Author, { through: "article" }); // the article's author
|
|
7053
|
+
}
|
|
7054
|
+
|
|
7055
|
+
// @filename: example.ts
|
|
7056
|
+
// ---cut---
|
|
7057
|
+
import { Tagging } from "./models";
|
|
7058
|
+
|
|
7059
|
+
const tagging = await Tagging.firstOrThrow();
|
|
7060
|
+
const author = await tagging.author();
|
|
7061
|
+
```
|
|
7062
|
+
|
|
7063
|
+
`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`.
|
|
7064
|
+
|
|
7065
|
+
## Writing through it
|
|
7066
|
+
|
|
7067
|
+
Add records with `push`, `build`, and `create`, which each make the join record that links the owner to the record:
|
|
7068
|
+
|
|
7069
|
+
```ts twoslash
|
|
7070
|
+
// @filename: models.ts
|
|
7071
|
+
import { belongsTo, hasMany, hasOne, Model } from "@forestfuture/active-record";
|
|
7072
|
+
|
|
7073
|
+
export class Author extends Model.define({
|
|
7074
|
+
id: { type: "string", null: false, generateId: true },
|
|
7075
|
+
name: { type: "string", null: false },
|
|
7076
|
+
}) {
|
|
7077
|
+
articles = hasMany(Article);
|
|
7078
|
+
}
|
|
7079
|
+
|
|
7080
|
+
export class Article extends Model.define({
|
|
7081
|
+
id: { type: "string", null: false, generateId: true },
|
|
7082
|
+
authorId: { type: "string", null: false },
|
|
7083
|
+
title: { type: "string", null: false },
|
|
7084
|
+
}) {
|
|
7085
|
+
author = belongsTo(Author);
|
|
7086
|
+
taggings = hasMany(Tagging);
|
|
7087
|
+
tags = hasMany(Tag, { through: "taggings" }); // each tagging's tag
|
|
7088
|
+
}
|
|
7089
|
+
|
|
7090
|
+
export class Tag extends Model.define({
|
|
7091
|
+
id: { type: "integer", null: false },
|
|
7092
|
+
name: { type: "string", null: false },
|
|
7093
|
+
}) {
|
|
7094
|
+
taggings = hasMany(Tagging);
|
|
7095
|
+
articles = hasMany(Article, { through: "taggings" }); // each tagging's article
|
|
7096
|
+
writers = hasMany(Author, { through: "articles", source: "author" }); // each article's author
|
|
7097
|
+
}
|
|
7098
|
+
|
|
7099
|
+
export class Tagging extends Model.define({
|
|
7100
|
+
id: { type: "integer", null: false },
|
|
7101
|
+
articleId: { type: "string", null: false },
|
|
7102
|
+
tagId: { type: "integer", null: false },
|
|
7103
|
+
}) {
|
|
7104
|
+
article = belongsTo(Article);
|
|
7105
|
+
tag = belongsTo(Tag);
|
|
7106
|
+
author = hasOne(Author, { through: "article" }); // the article's author
|
|
7107
|
+
}
|
|
7108
|
+
|
|
7109
|
+
// @filename: example.ts
|
|
7110
|
+
// ---cut---
|
|
7111
|
+
import { Article, Tag } from "./models";
|
|
7112
|
+
|
|
7113
|
+
const tag = await Tag.findByOrThrow({ name: "essays" });
|
|
7114
|
+
const article = await Article.findByOrThrow({ title: "Engines" });
|
|
7115
|
+
|
|
7116
|
+
await tag.articles().push(article); // saves a tagging that links them
|
|
7117
|
+
const draft = await tag.articles().create({ authorId: article.authorId, title: "Draft" });
|
|
7118
|
+
|
|
7119
|
+
await tag.articles().delete(article); // deletes the tagging; the article stays
|
|
7120
|
+
```
|
|
7121
|
+
|
|
7122
|
+
- `push(article)` saves a tagging for each article, in one write. A new article is saved first.
|
|
7123
|
+
- `build(attributes)` builds the article and its tagging. Saving the tag saves both. Saving the article on its own saves no tagging.
|
|
7124
|
+
- `create(attributes)` saves the article, then its tagging. An invalid article comes back unsaved, and nothing is written.
|
|
7125
|
+
|
|
7126
|
+
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`.
|
|
7127
|
+
|
|
7128
|
+
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.
|
|
7129
|
+
|
|
7130
|
+
## Removing records
|
|
7131
|
+
|
|
7132
|
+
Removing records through the association removes their join records. The records themselves stay:
|
|
7133
|
+
|
|
7134
|
+
| Method | Does |
|
|
7135
|
+
| ------------------ | --------------------------------------------------------------------------------------------------- |
|
|
7136
|
+
| `delete(article)` | Deletes the tag’s taggings to the article, without callbacks |
|
|
7137
|
+
| `destroy(article)` | Destroys those taggings, running their callbacks, in one write |
|
|
7138
|
+
| `clear()` | Deletes every tagging to the tag’s articles, without callbacks. The tag then has no articles loaded |
|
|
7139
|
+
| `deleteAll()` | Deletes the same taggings, and resolves to how many it deleted |
|
|
7140
|
+
| `destroyAll()` | Destroys the same taggings, running their callbacks, and resolves to the articles |
|
|
7141
|
+
|
|
7142
|
+
An article the tag doesn’t reach removes nothing. To remove an article itself, destroy it: `await article.destroy()`. In a batch, pass the association to the write: `b.deleteAll(tag.articles())` deletes the tag’s taggings.
|
|
7143
|
+
|
|
7144
|
+
:::warning[A narrowed deleteAll or destroyAll removes the records themselves]
|
|
7145
|
+
`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.
|
|
7146
|
+
:::
|
|
7147
|
+
|
|
7148
|
+
### Removing join records with dependent
|
|
7149
|
+
|
|
7150
|
+
A `hasMany` through a join Model takes `dependent: "destroy"` or `dependent: "deleteAll"`, which acts on its join records:
|
|
7151
|
+
|
|
7152
|
+
- With `"destroy"`, destroying the tag destroys its taggings, running their callbacks, and `delete` destroys them too.
|
|
7153
|
+
- With `"deleteAll"`, destroying the tag deletes them without callbacks.
|
|
7154
|
+
- `clear` and `deleteAll` always delete them without callbacks.
|
|
7155
|
+
|
|
7156
|
+
## Setting a hasOne through another
|
|
7157
|
+
|
|
7158
|
+
A `hasOne` that goes through another `hasOne` has `set`, and no `build` or `create`:
|
|
7159
|
+
|
|
7160
|
+
- `set(record)` points the owner’s join record at the record, or creates the join record if there isn’t one, with the equality values of the join association’s `scope`.
|
|
7161
|
+
- `set(null)` destroys the join record.
|
|
7162
|
+
|
|
7163
|
+
## Spotting read-only associations
|
|
7164
|
+
|
|
7165
|
+
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` is read-only, since it goes through `articles`, which goes through `taggings`.
|
|
7166
|
+
|
|
7167
|
+
`insert`, `insertAll`, `upsert`, and `upsertAll` throw `ReadonlyAssociation` on any association through another, since they write no join records.
|
|
7168
|
+
|
|
7169
|
+
:::note
|
|
7170
|
+
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)).
|
|
7171
|
+
:::
|
|
7172
|
+
|
|
7173
|
+
> **Compared with Rails**
|
|
7174
|
+
>
|
|
7175
|
+
> `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.
|
|
7176
|
+
>
|
|
7177
|
+
> 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.
|
|
7178
|
+
|
|
7179
|
+
---
|
|
7180
|
+
|
|
6353
7181
|
# Untrusted input
|
|
6354
7182
|
Source: https://active-record.forestfuture.dev/untrusted-input
|
|
6355
7183
|
|
|
6356
|
-
A request can send any fields it likes. Pick the ones you want before they reach a Model.
|
|
6357
|
-
|
|
6358
7184
|
## Permitting fields
|
|
6359
7185
|
|
|
6360
7186
|
Only permit the fields you want from a request:
|
|
@@ -6452,8 +7278,6 @@ An association’s link to its owner always stays. `user.posts().rewhere({ userI
|
|
|
6452
7278
|
# Upgrading
|
|
6453
7279
|
Source: https://active-record.forestfuture.dev/upgrading
|
|
6454
7280
|
|
|
6455
|
-
Each section moves an app up one release. Start from the release you’re on.
|
|
6456
|
-
|
|
6457
7281
|
## Upgrading from 0.7 to 0.8
|
|
6458
7282
|
|
|
6459
7283
|
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.
|
|
@@ -6669,8 +7493,6 @@ It also applies migrations through your project’s Wrangler, with `npx active-r
|
|
|
6669
7493
|
# Validations
|
|
6670
7494
|
Source: https://active-record.forestfuture.dev/validations
|
|
6671
7495
|
|
|
6672
|
-
Validations check a record before it’s saved. An invalid record isn’t saved, and its `errors` say why.
|
|
6673
|
-
|
|
6674
7496
|
## Declaring validations
|
|
6675
7497
|
|
|
6676
7498
|
Declare validations in a Model’s `static {}` block with `this.validates`:
|
|
@@ -7053,6 +7875,8 @@ export class Product extends ApplicationRecord {
|
|
|
7053
7875
|
Each message is looked up when you read it:
|
|
7054
7876
|
|
|
7055
7877
|
```ts
|
|
7878
|
+
import { Product } from "./models";
|
|
7879
|
+
|
|
7056
7880
|
const product = Product.build({ name: "", priceCents: 0 });
|
|
7057
7881
|
await product.isValid(); // false
|
|
7058
7882
|
|