@forestfuture/active-record 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -4
- package/config-schema.json +56 -0
- package/dist/{adapter-BSvFhTDf.d.mts → adapter-AGKp6wfO.d.mts} +42 -9
- package/dist/adapter.d.mts +3 -2
- package/dist/adapter.mjs +4 -3
- package/dist/{batch-DBeYk5wx.mjs → batch-BS_WseLf.mjs} +128 -44
- package/dist/cli.d.mts +176 -28
- package/dist/cli.mjs +3 -2
- package/dist/command.mjs +746 -432
- package/dist/d1.d.mts +68 -0
- package/dist/d1.mjs +0 -0
- package/dist/for-adapters-Ch6CoHD4.mjs +240 -0
- package/dist/for-adapters-D_Iu0gS_.mjs +33 -0
- package/dist/for-adapters-t3-LukJQ.d.mts +21 -0
- package/dist/{generated-model-CfDggoVN.mjs → generated-model-Cnt0Ot9q.mjs} +4 -0
- package/dist/index-CyCJuM96.d.mts +149 -0
- package/dist/index.d.mts +3 -143
- package/dist/index.mjs +3 -2
- package/dist/plugin-Cyoej7qV.mjs +600 -0
- package/dist/plugin-XOHYndhP.mjs +939 -0
- package/dist/postgresql.d.mts +72 -0
- package/dist/postgresql.mjs +588 -0
- package/dist/src-la_KkjCS.mjs +1 -0
- package/dist/storage-override-CpbkdIqE.mjs +187 -0
- package/llms-full.txt +837 -201
- package/package.json +25 -2
- package/skills/active-record/SKILL.md +4 -4
- package/dist/storage-override-BYBYP8Mj.mjs +0 -91
package/llms-full.txt
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Active Record
|
|
2
2
|
|
|
3
|
-
> A Rails-inspired Active Record for Cloudflare Workers
|
|
3
|
+
> A Rails-inspired Active Record for Cloudflare Workers, on D1 or Postgres.
|
|
4
4
|
|
|
5
|
-
# Active Record for Cloudflare
|
|
6
|
-
Source: https://
|
|
5
|
+
# Active Record for Cloudflare Workers
|
|
6
|
+
Source: https://active-record.forestfuture.dev/
|
|
7
7
|
|
|
8
8
|
```package-install
|
|
9
|
-
npm install @forestfuture/active-record
|
|
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
|
+
|
|
12
14
|
**[Get started](/getting-started)**
|
|
13
15
|
|
|
14
16
|
From an empty Worker to two related Models in about ten minutes.
|
|
@@ -17,7 +19,7 @@ Read the tutorial
|
|
|
17
19
|
|
|
18
20
|
**[Coming from Rails](/coming-from-rails)**
|
|
19
21
|
|
|
20
|
-
What carries over from
|
|
22
|
+
What carries over from Rails, and what’s different.
|
|
21
23
|
|
|
22
24
|
See what’s different
|
|
23
25
|
|
|
@@ -107,17 +109,22 @@ N+1. Hand-written SQL goes through a tagged template, so values are always bound
|
|
|
107
109
|
`save`, `create`, `update`, and `destroy` run validations and callbacks in a predictable order,
|
|
108
110
|
with dirty tracking and dependent strategies. Methods that throw end in `OrThrow`.
|
|
109
111
|
|
|
110
|
-
**[Atomic
|
|
112
|
+
**[Atomic batches](/batches)**
|
|
113
|
+
|
|
114
|
+
`batch` writes a set of statements and records all at once, or not at all, on D1 and on
|
|
115
|
+
Postgres. Keys generated in code let a whole graph save in one batch.
|
|
116
|
+
|
|
117
|
+
**[One API, two databases](/move-to-postgres)**
|
|
111
118
|
|
|
112
|
-
D1
|
|
113
|
-
|
|
119
|
+
Start on D1 and move to Postgres with your Models and code unchanged. Each adapter lists what
|
|
120
|
+
works differently on its database.
|
|
114
121
|
|
|
115
122
|
---
|
|
116
123
|
|
|
117
124
|
# Existing databases
|
|
118
|
-
Source: https://
|
|
125
|
+
Source: https://active-record.forestfuture.dev/adopt-a-database
|
|
119
126
|
|
|
120
|
-
|
|
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.
|
|
121
128
|
|
|
122
129
|
## Using Drizzle’s migrations
|
|
123
130
|
|
|
@@ -134,7 +141,7 @@ Drizzle writes its migrations to `drizzle/`, its `out` setting. Tell Wrangler wh
|
|
|
134
141
|
}
|
|
135
142
|
```
|
|
136
143
|
|
|
137
|
-
Drizzle’s own schema often lives at `src/db/schema.ts` or in `src/db/schema/`, where
|
|
144
|
+
Drizzle’s own schema often lives at `src/db/schema.ts` or in `src/db/schema/`, where Active Record writes its schema by default. Generate Active Record’s elsewhere:
|
|
138
145
|
|
|
139
146
|
```sh
|
|
140
147
|
npx active-record schema --out src/db/d1-record.ts
|
|
@@ -145,22 +152,22 @@ If `src/models/application-record.ts` already exists, point it at the new file w
|
|
|
145
152
|
Pass `--out` to every later `schema` and `g` command, or keep it in a `package.json` script.
|
|
146
153
|
|
|
147
154
|
:::note
|
|
148
|
-
Without `--out`,
|
|
155
|
+
Without `--out`, Active Record refuses to write over a file it didn’t write, or beside a folder of the same name, so Drizzle’s schema is safe.
|
|
149
156
|
:::
|
|
150
157
|
|
|
151
158
|
## Using Prisma’s migrations
|
|
152
159
|
|
|
153
160
|
With D1, Prisma’s migrations are usually Wrangler’s own: files in `migrations/`, written by `prisma migrate diff`. `npx active-record schema` reads them as they are.
|
|
154
161
|
|
|
155
|
-
Prisma names tables after its models, such as `User`, and columns in camelCase, such as `createdAt`.
|
|
162
|
+
Prisma names tables after its models, such as `User`, and columns in camelCase, such as `createdAt`. Active Record keeps both names, so the Model sets its table, `static override table = "User"`, and has attributes such as `createdAt`.
|
|
156
163
|
|
|
157
164
|
:::warning[Two date formats in one column]
|
|
158
|
-
Prisma writes a `DateTime` as `2026-10-12T06:38:30.325+00:00`, and a `DEFAULT CURRENT_TIMESTAMP` fills `2026-10-12 06:38:30`.
|
|
165
|
+
Prisma writes a `DateTime` as `2026-10-12T06:38:30.325+00:00`, and a `DEFAULT CURRENT_TIMESTAMP` fills `2026-10-12 06:38:30`. Active Record reads both as UTC, but SQLite compares dates as text, so a column with both needs the steps in [Comparing dates in two forms](#comparing-dates-in-two-forms).
|
|
159
166
|
:::
|
|
160
167
|
|
|
161
168
|
## Comparing dates in two forms
|
|
162
169
|
|
|
163
|
-
A column can hold SQLite’s own date text (`2026-10-12 06:38:30`, from a `DEFAULT CURRENT_TIMESTAMP`) beside ISO text (`2026-10-12T06:38:30.000Z`).
|
|
170
|
+
A column can hold SQLite’s own date text (`2026-10-12 06:38:30`, from a `DEFAULT CURRENT_TIMESTAMP`) beside ISO text (`2026-10-12T06:38:30.000Z`). Active Record reads both as UTC, but SQLite compares them as text. On a column with both, `order` and `between` can misplace values within a day, and a condition on one instant misses the row written in the other form.
|
|
164
171
|
|
|
165
172
|
To make the rows match, rewrite them once in a migration, with your own table and column:
|
|
166
173
|
|
|
@@ -170,7 +177,7 @@ SET created_at = strftime('%Y-%m-%dT%H:%M:%fZ', created_at)
|
|
|
170
177
|
WHERE strftime('%Y-%m-%dT%H:%M:%fZ', created_at) <> created_at;
|
|
171
178
|
```
|
|
172
179
|
|
|
173
|
-
It writes
|
|
180
|
+
It writes Active Record’s form for every row SQLite can read as a date, and leaves NULLs and anything else as they were. Running it again changes nothing. The rewrite is permanent, so export the table first. Conditions on the column then use its index.
|
|
174
181
|
|
|
175
182
|
If another tool still writes the other form, compare through `strftime` in a fragment instead:
|
|
176
183
|
|
|
@@ -190,7 +197,7 @@ export function oldestFirst() {
|
|
|
190
197
|
}
|
|
191
198
|
```
|
|
192
199
|
|
|
193
|
-
`strftime` reads every form SQLite knows and writes
|
|
200
|
+
`strftime` reads every form SQLite knows and writes Active Record’s ISO text, so rows in either form compare and sort as the times they are.
|
|
194
201
|
|
|
195
202
|
:::note
|
|
196
203
|
A wrapped column can’t use its index for that condition, so SQLite reads the whole table.
|
|
@@ -270,12 +277,12 @@ In a raw `env.DB.prepare(...)` statement, bind `Article.typeForAttribute("publis
|
|
|
270
277
|
:::
|
|
271
278
|
|
|
272
279
|
:::note
|
|
273
|
-
Prisma’s dates need no override. On D1, Prisma writes a `DateTime` as ISO text, which
|
|
280
|
+
Prisma’s dates need no override. On D1, Prisma writes a `DateTime` as ISO text, which Active Record reads as it is.
|
|
274
281
|
:::
|
|
275
282
|
|
|
276
283
|
> **Beyond Rails**
|
|
277
284
|
>
|
|
278
|
-
>
|
|
285
|
+
> Rails has no option for a date kept as an integer; there it takes a custom attribute type. Here it’s a `storage` on the `datetime`.
|
|
279
286
|
|
|
280
287
|
## Fixing cells of the wrong type
|
|
281
288
|
|
|
@@ -305,23 +312,23 @@ SQLite converts a value to the column’s declared type only when it can: `'42'`
|
|
|
305
312
|
---
|
|
306
313
|
|
|
307
314
|
# AI agents
|
|
308
|
-
Source: https://
|
|
315
|
+
Source: https://active-record.forestfuture.dev/ai-agents
|
|
309
316
|
|
|
310
317
|
Coding agents follow Active Record’s conventions best with its guide at hand and its rules in context. The agent skill brings both, 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.
|
|
311
318
|
|
|
312
319
|
## Giving your agent the docs
|
|
313
320
|
|
|
314
|
-
| Resource
|
|
315
|
-
|
|
|
316
|
-
| [`llms.txt`](https://
|
|
317
|
-
| [`llms-full.txt`](https://
|
|
318
|
-
| Any page + `.md`
|
|
319
|
-
| [The agent skill](https://
|
|
320
|
-
| `node_modules/@forestfuture/active-record/llms-full.txt`
|
|
321
|
+
| Resource | What it is |
|
|
322
|
+
| --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
323
|
+
| [`llms.txt`](https://active-record.forestfuture.dev/llms.txt) | An index of the guide, each page with what it covers, following [llmstxt.org](https://llmstxt.org). Start here when an agent can fetch pages. |
|
|
324
|
+
| [`llms-full.txt`](https://active-record.forestfuture.dev/llms-full.txt) | The whole guide in one Markdown file, about 55K tokens. |
|
|
325
|
+
| Any page + `.md` | Every page as Markdown: [`/associations.md`](https://active-record.forestfuture.dev/associations.md). |
|
|
326
|
+
| [The agent skill](https://active-record.forestfuture.dev/.well-known/agent-skills/active-record/SKILL.md) | The skill below, published where agents look for a site’s skills. |
|
|
327
|
+
| `node_modules/@forestfuture/active-record/llms-full.txt` | The same guide, shipped in the package. It matches the version you’ve installed, and an agent can read it without fetching anything. |
|
|
321
328
|
|
|
322
329
|
## Installing the agent skill
|
|
323
330
|
|
|
324
|
-
Install the library’s [agent skill](https://github.com/forestfuture/active-record/blob/main/packages/active-record/skills/active-record/SKILL.md): its rules, the shapes of a Model and a Worker, and the mistakes to watch for, with pointers into the guide. Agents that support skills, such as Claude Code, Cursor, Codex, and [others](https://skills.sh), load it when they work on
|
|
331
|
+
Install the library’s [agent skill](https://github.com/forestfuture/active-record/blob/main/packages/active-record/skills/active-record/SKILL.md): its rules, the shapes of a Model and a Worker, and the mistakes to watch for, with pointers into the guide. Agents that support skills, such as Claude Code, Cursor, Codex, and [others](https://skills.sh), load it when they work on Active Record code:
|
|
325
332
|
|
|
326
333
|
```sh
|
|
327
334
|
npx skills add forestfuture/active-record
|
|
@@ -342,7 +349,7 @@ The skills CLI marks `experimental_sync` as experimental, so its name may change
|
|
|
342
349
|
Agents read `AGENTS.md`, or `CLAUDE.md` for Claude Code, at the start of every task, while a skill loads only when the agent decides it applies. To make sure the guide is always in reach, add one line to yours:
|
|
343
350
|
|
|
344
351
|
```md
|
|
345
|
-
Before writing code with `@forestfuture/active-record
|
|
352
|
+
Before writing code with `@forestfuture/active-record`, read the part of `node_modules/@forestfuture/active-record/llms-full.txt` for the task.
|
|
346
353
|
```
|
|
347
354
|
|
|
348
355
|
The line names the guide shipped with your installed version, so it stays correct after an upgrade.
|
|
@@ -353,7 +360,7 @@ Skip this section if you’ve installed the skill: the block below is the skill
|
|
|
353
360
|
|
|
354
361
|
```md
|
|
355
362
|
|
|
356
|
-
Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for Cloudflare Workers, with an adapter per database: `@forestfuture/
|
|
363
|
+
Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for Cloudflare Workers, with an adapter per database inside it: `@forestfuture/active-record/d1` for D1, and `@forestfuture/active-record/postgresql` for Postgres, which needs the app's own `pg`. Import Models, Relations, and errors from the core, and what opens a database from its adapter's entry: `connect`, `withSession`, `NoSession`, and `d1` from `/d1`; `connect` and `postgresql` from `/postgresql`. Every `active-record` command reads `active-record.jsonc`, which names each database's adapter: run `npx active-record init` to write it, never `--adapter`. Its guide for the installed version is `node_modules/@forestfuture/active-record/llms-full.txt`, one Markdown file with a `#` heading per page: read the part for the task before writing code with it.
|
|
357
364
|
|
|
358
365
|
- Create tables with the generators, never by hand-declaring attributes: `npx active-record g model Post user:references 'title:string!'` writes the migration and the Model; `npx active-record g migration AddSlugToPosts slug:string:unique` writes a change. Apply them with `npx active-record migrate`. After a hand-written migration, run `npx active-record schema`. Never edit the generated `src/db/schema.ts`.
|
|
359
366
|
- A Model extends the app's base class: `class Post extends ApplicationRecord {}`. Its table comes from its class name (`Post` → `posts`), or `static override table = "…"`, and its attributes from the schema, so it declares only behavior. Run `npx active-record schema` after adding or renaming a Model, as after a migration: a Model it hasn't seen throws `InvalidModel`. Change how a column is read with an override in the class, `static override attributes = { metadata: "json" } as const`, never by editing the schema. An `INTEGER` holding a Unix time (Drizzle's `timestamp` modes) is `{ type: "datetime", storage: "unixSeconds" }` or `"unixMilliseconds"`. A cell that isn't its attribute's type (a number in an ISO `datetime`, text in an `integer`) fails the load with a `TypeError` naming the attribute: correct the override, don't catch it.
|
|
@@ -376,7 +383,7 @@ Copy it again after upgrading Active Record, since the rules can change.
|
|
|
376
383
|
---
|
|
377
384
|
|
|
378
385
|
# Associations
|
|
379
|
-
Source: https://
|
|
386
|
+
Source: https://active-record.forestfuture.dev/associations
|
|
380
387
|
|
|
381
388
|
Associations connect Models: `belongsTo`, `hasMany`, and `hasOne`.
|
|
382
389
|
|
|
@@ -526,7 +533,7 @@ const latest = await author?.articles().first();
|
|
|
526
533
|
|
|
527
534
|
> **Beyond Rails**
|
|
528
535
|
>
|
|
529
|
-
> After `author.articles().where({ title: "Untitled" }).deleteAll()`, you’d expect `author.articles()` not to hold the untitled articles any more, and here it doesn’t. In Rails it still does, until you reload: only a write on the association itself (`author.articles.delete_all`) resets what it has loaded, while a write after `where`, `or`, `merge` or a scope runs on a separate relation. In
|
|
536
|
+
> After `author.articles().where({ title: "Untitled" }).deleteAll()`, you’d expect `author.articles()` not to hold the untitled articles any more, and here it doesn’t. In Rails it still does, until you reload: only a write on the association itself (`author.articles.delete_all`) resets what it has loaded, while a write after `where`, `or`, `merge` or a scope runs on a separate relation. In Active Record any write built from `author.articles()` clears it, at the cost of one query on the next read.
|
|
530
537
|
|
|
531
538
|
:::note
|
|
532
539
|
A `belongsTo` whose foreign key is `null`, or an association on an unsaved owner, reads without a query.
|
|
@@ -548,7 +555,7 @@ for (const each of authors) {
|
|
|
548
555
|
|
|
549
556
|
Nest with an object: `includes({ articles: "comments" })` or `includes({ articles: ["comments", "tags"] })`.
|
|
550
557
|
|
|
551
|
-
The
|
|
558
|
+
The example above sends four queries, however many authors there are. On D1, the whole tree goes [in one round trip](/d1#sending-queries-in-one-round-trip) with the authors’ own query.
|
|
552
559
|
|
|
553
560
|
:::note
|
|
554
561
|
With a `limit` or `offset`, `includes` ends the order with the primary key, so the preloads find the same records the query loads.
|
|
@@ -556,7 +563,7 @@ With a `limit` or `offset`, `includes` ends the order with the primary key, so t
|
|
|
556
563
|
|
|
557
564
|
> **Beyond Rails**
|
|
558
565
|
>
|
|
559
|
-
> Rails sends each association’s preload query on its own, so every association adds a round trip.
|
|
566
|
+
> Rails sends each association’s preload query on its own, so every association adds a round trip. On D1, the whole tree takes one.
|
|
560
567
|
|
|
561
568
|
:::note
|
|
562
569
|
`hasMany` and `hasOne` find their records by the foreign key, both with `includes` and when you read one record’s association, such as `author.articles()`. Add an index to the foreign key column. Otherwise D1 reads every row of the table for each lookup, and bills you for each row it reads. A `references` column from the [generators](/generators) is indexed already, and you can add an index to any other foreign key yourself:
|
|
@@ -672,7 +679,7 @@ await article.comments().deleteAll(); // one DELETE for the article's comments
|
|
|
672
679
|
|
|
673
680
|
## Not built yet
|
|
674
681
|
|
|
675
|
-
These features aren’t in
|
|
682
|
+
These features aren’t in Active Record yet. The code shows the shape they’re likely to take.
|
|
676
683
|
|
|
677
684
|
- **Associations through another** ([#59](https://github.com/forestfuture/active-record/issues/59)): `projects = hasMany(Project, { through: "assignments" })`, a user’s projects reached through their assignments.
|
|
678
685
|
- **Polymorphic associations** ([#60](https://github.com/forestfuture/active-record/issues/60)): `commentable = belongsTo([Post, Photo])`, with `comments = hasMany(Comment, { as: "commentable" })` on each.
|
|
@@ -682,7 +689,7 @@ These features aren’t in d1-record yet. The code shows the shape they’re lik
|
|
|
682
689
|
---
|
|
683
690
|
|
|
684
691
|
# Bulk writes and batches
|
|
685
|
-
Source: https://
|
|
692
|
+
Source: https://active-record.forestfuture.dev/batches
|
|
686
693
|
|
|
687
694
|
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.
|
|
688
695
|
|
|
@@ -826,7 +833,7 @@ await batch([
|
|
|
826
833
|
---
|
|
827
834
|
|
|
828
835
|
# Callbacks
|
|
829
|
-
Source: https://
|
|
836
|
+
Source: https://active-record.forestfuture.dev/callbacks
|
|
830
837
|
|
|
831
838
|
Callbacks run your code at points in a record’s lifecycle, such as before it’s validated or after it’s saved.
|
|
832
839
|
|
|
@@ -923,7 +930,7 @@ In an after-callback, the write has already happened, so `abort()` throws `Abort
|
|
|
923
930
|
|
|
924
931
|
## Not built yet
|
|
925
932
|
|
|
926
|
-
These callbacks aren’t in
|
|
933
|
+
These callbacks aren’t in Active Record yet. The code shows the shape they’re likely to take.
|
|
927
934
|
|
|
928
935
|
- **Around callbacks** ([#48](https://github.com/forestfuture/active-record/issues/48)): `this.aroundSave(async (record, proceed) => { …; await proceed(); … })`, and `aroundCreate`, `aroundUpdate`, and `aroundDestroy`.
|
|
929
936
|
- **`afterInitialize` and `afterFind`** ([#49](https://github.com/forestfuture/active-record/issues/49)): for every record built or loaded, and every record loaded.
|
|
@@ -939,7 +946,7 @@ These callbacks aren’t in d1-record yet. The code shows the shape they’re li
|
|
|
939
946
|
---
|
|
940
947
|
|
|
941
948
|
# Schema changes
|
|
942
|
-
Source: https://
|
|
949
|
+
Source: https://active-record.forestfuture.dev/change-a-table
|
|
943
950
|
|
|
944
951
|
Change a table with a new migration. Wrangler applies each migration once, in order. The schema is regenerated after each change, so a Model’s attributes follow its table.
|
|
945
952
|
|
|
@@ -952,7 +959,7 @@ npx active-record g migration AddBioToUsers bio:string
|
|
|
952
959
|
npx active-record migrate
|
|
953
960
|
```
|
|
954
961
|
|
|
955
|
-
```sql migrations/
|
|
962
|
+
```sql migrations/20261108100000_add_bio_to_users.sql
|
|
956
963
|
ALTER TABLE users ADD COLUMN bio TEXT;
|
|
957
964
|
```
|
|
958
965
|
|
|
@@ -968,7 +975,7 @@ Generate an empty migration, and write the rename:
|
|
|
968
975
|
npx active-record g migration RenameBioToAbout
|
|
969
976
|
```
|
|
970
977
|
|
|
971
|
-
```sql migrations/
|
|
978
|
+
```sql migrations/20261108100500_rename_bio_to_about.sql
|
|
972
979
|
ALTER TABLE users RENAME COLUMN bio TO about;
|
|
973
980
|
```
|
|
974
981
|
|
|
@@ -1006,7 +1013,7 @@ Remove a `references` column the same way, with `RemoveUserFromPosts user:refere
|
|
|
1006
1013
|
|
|
1007
1014
|
SQLite can’t change a column’s type in place. Write a migration that builds a new table, copies the rows, and swaps the tables, as [SQLite describes](https://www.sqlite.org/lang_altertable.html#otheralter):
|
|
1008
1015
|
|
|
1009
|
-
```sql migrations/
|
|
1016
|
+
```sql migrations/20261108101000_make_price_cents_an_integer.sql
|
|
1010
1017
|
PRAGMA defer_foreign_keys = true;
|
|
1011
1018
|
|
|
1012
1019
|
CREATE TABLE products_new (
|
|
@@ -1032,7 +1039,7 @@ Wrangler backs up the database before applying migrations to it.
|
|
|
1032
1039
|
---
|
|
1033
1040
|
|
|
1034
1041
|
# Coming from Rails
|
|
1035
|
-
Source: https://
|
|
1042
|
+
Source: https://active-record.forestfuture.dev/coming-from-rails
|
|
1036
1043
|
|
|
1037
1044
|
Models, validations, callbacks, associations, scopes, and dirty tracking all follow Active Record, down to the default error messages. Here’s what’s different.
|
|
1038
1045
|
|
|
@@ -1128,17 +1135,82 @@ Default scopes, `has_many :through`, polymorphic associations, single-table inhe
|
|
|
1128
1135
|
---
|
|
1129
1136
|
|
|
1130
1137
|
# Command line
|
|
1131
|
-
Source: https://
|
|
1138
|
+
Source: https://active-record.forestfuture.dev/command-line
|
|
1132
1139
|
|
|
1133
|
-
The `active-record` command generates `src/db/schema.ts` from your migrations, writes new migrations and Models, and applies migrations. It comes with `@forestfuture/active-record`, and `ffar` is its short name. Run it from
|
|
1140
|
+
The `active-record` command generates `src/db/schema.ts` from your migrations, writes new migrations and Models, and applies migrations. It comes with `@forestfuture/active-record`, and `ffar` is its short name. Run it from your project’s folder:
|
|
1134
1141
|
|
|
1135
1142
|
```sh
|
|
1136
1143
|
npx active-record --help
|
|
1137
1144
|
```
|
|
1138
1145
|
|
|
1139
|
-
|
|
1146
|
+
Every command reads your databases, and the adapter each one uses, from `active-record.jsonc`. `active-record init` writes it.
|
|
1147
|
+
|
|
1148
|
+
It needs Node.js 22.5 or later. On D1, it needs 22.13 or later, for Node’s built-in SQLite. [Generators](/generators) shows it step by step.
|
|
1149
|
+
|
|
1150
|
+
## `active-record init`
|
|
1151
|
+
|
|
1152
|
+
Write `active-record.jsonc` for your project:
|
|
1153
|
+
|
|
1154
|
+
```sh
|
|
1155
|
+
npx active-record init
|
|
1156
|
+
```
|
|
1157
|
+
|
|
1158
|
+
It reads your Wrangler config. Each database in its `d1_databases` gets a D1 entry. Each Hyperdrive binding gets a PostgreSQL entry, whose `url` is the binding’s `localConnectionString`.
|
|
1159
|
+
|
|
1160
|
+
Run it again after you add a database to your Wrangler config. It adds each database the file doesn’t name yet, and leaves the rest of the file as you wrote it, comments included:
|
|
1161
|
+
|
|
1162
|
+
```text
|
|
1163
|
+
Added LOGS to active-record.jsonc (on d1)
|
|
1164
|
+
```
|
|
1165
|
+
|
|
1166
|
+
| Option | |
|
|
1167
|
+
| ------------------ | ---------------------------------------------------------------------------------- |
|
|
1168
|
+
| `--adapter <name>` | The adapter, `d1` or `postgresql`, when your Wrangler config has both, or neither. |
|
|
1169
|
+
| `--config <file>` | Write this file, in place of `active-record.jsonc`. |
|
|
1170
|
+
|
|
1171
|
+
With `--adapter postgresql` and no Hyperdrive binding, it writes a `DATABASE_URL` entry, with a guess at your local database’s `url` for you to correct.
|
|
1172
|
+
|
|
1173
|
+
## Declaring your databases
|
|
1174
|
+
|
|
1175
|
+
`active-record.jsonc` sits beside your `package.json`. It names each of your databases by its binding, and the adapter it uses:
|
|
1176
|
+
|
|
1177
|
+
```jsonc
|
|
1178
|
+
{
|
|
1179
|
+
"$schema": "./node_modules/@forestfuture/active-record/config-schema.json",
|
|
1180
|
+
"databases": {
|
|
1181
|
+
"DB": { "adapter": "d1" },
|
|
1182
|
+
},
|
|
1183
|
+
}
|
|
1184
|
+
```
|
|
1185
|
+
|
|
1186
|
+
Your generated schema names each database by its binding. The `$schema` line lets your editor complete and check the file. A project’s databases all use one adapter.
|
|
1187
|
+
|
|
1188
|
+
On D1, the rest of a database’s settings stay in your Wrangler config’s `d1_databases`, which must have its binding. A D1 database there that the file doesn’t name is left out, and every command notes it. On Postgres, the file holds a database’s settings:
|
|
1189
|
+
|
|
1190
|
+
```jsonc
|
|
1191
|
+
{
|
|
1192
|
+
"databases": {
|
|
1193
|
+
"HYPERDRIVE": {
|
|
1194
|
+
"adapter": "postgresql",
|
|
1195
|
+
"migrationsDir": "migrations",
|
|
1196
|
+
"url": "postgres://localhost/shop_development",
|
|
1197
|
+
"remoteUrl": "${PRODUCTION_DATABASE_URL}",
|
|
1198
|
+
},
|
|
1199
|
+
},
|
|
1200
|
+
}
|
|
1201
|
+
```
|
|
1202
|
+
|
|
1203
|
+
| Setting | |
|
|
1204
|
+
| --------------- | ------------------------------------------------------------------------- |
|
|
1205
|
+
| `adapter` | `d1` or `postgresql`. |
|
|
1206
|
+
| `migrationsDir` | Its migrations folder, relative to the file (`migrations` by default). |
|
|
1207
|
+
| `url` | The local database: what `migrate` and the console use. |
|
|
1208
|
+
| `remoteUrl` | The real database, for `--remote`. |
|
|
1209
|
+
| `schemaUrl` | A server the schema may be read on, for an extension PGlite doesn’t have. |
|
|
1210
|
+
|
|
1211
|
+
`${NAME}` reads a variable from the environment, so a password stays out of the file. The command never prints a connection string, only its database and host. `--config` names another file.
|
|
1140
1212
|
|
|
1141
|
-
|
|
1213
|
+
On Postgres, the command needs `pg` installed, and PGlite to read your schema. It says what to install when either is missing.
|
|
1142
1214
|
|
|
1143
1215
|
## `active-record schema`
|
|
1144
1216
|
|
|
@@ -1148,19 +1220,18 @@ Generate the schema file from your migrations:
|
|
|
1148
1220
|
npx active-record schema
|
|
1149
1221
|
```
|
|
1150
1222
|
|
|
1151
|
-
It applies your migrations, in order, to an in-memory
|
|
1223
|
+
It applies your migrations, in order, to an in-memory database, and writes each table’s columns to `src/db/schema.ts`. On D1 that’s SQLite. On Postgres it’s [PGlite](https://pglite.dev), so it needs no server.
|
|
1152
1224
|
|
|
1153
|
-
| Option |
|
|
1154
|
-
| -------------------- |
|
|
1155
|
-
| `--check` | Write nothing: fail (exit 1) if the schema file is out of date. For CI.
|
|
1156
|
-
| `--watch` | Regenerate whenever a migration or a Model file changes.
|
|
1157
|
-
| `--out <file>` | Write the schema here instead. With several databases, a folder for one file each.
|
|
1158
|
-
| `--migrations <dir>` | Read migrations from here instead of the
|
|
1159
|
-
| `--models <dir>` | Where your Models and `application-record.ts` are (`src/models/` by default).
|
|
1160
|
-
| `--config <file>` | Use this
|
|
1161
|
-
| `--adapter <name>` | The adapter (`d1`), when the project has several installed. |
|
|
1225
|
+
| Option | |
|
|
1226
|
+
| -------------------- | ---------------------------------------------------------------------------------- |
|
|
1227
|
+
| `--check` | Write nothing: fail (exit 1) if the schema file is out of date. For CI. |
|
|
1228
|
+
| `--watch` | Regenerate whenever a migration or a Model file changes. |
|
|
1229
|
+
| `--out <file>` | Write the schema here instead. With several databases, a folder for one file each. |
|
|
1230
|
+
| `--migrations <dir>` | Read migrations from here instead of the config’s folder (one database only). |
|
|
1231
|
+
| `--models <dir>` | Where your Models and `application-record.ts` are (`src/models/` by default). |
|
|
1232
|
+
| `--config <file>` | Use this config file, in place of `active-record.jsonc`. |
|
|
1162
1233
|
|
|
1163
|
-
**What it reads:** each entry
|
|
1234
|
+
**What it reads:** each database in `active-record.jsonc`. On Postgres, from its `migrationsDir`. On D1, from its entry in the Wrangler config’s `d1_databases`, with its `binding`, `migrations_dir` (default `migrations/`), `migrations_pattern` (for migrations in folders), and `migrations_table` (left out of the schema). Migrations apply in the order of the numbers their names start with (`9_…` before `10_…`), as Wrangler applies them. It also loads the Model files in `--models`, using your project’s own `@forestfuture/active-record`, to find each Model and its table, so code at a Model file’s top level runs.
|
|
1164
1235
|
|
|
1165
1236
|
**What it writes:**
|
|
1166
1237
|
|
|
@@ -1177,11 +1248,11 @@ It applies your migrations, in order, to an in-memory SQLite database, and write
|
|
|
1177
1248
|
- A file it didn’t write (one without its “Generated by” header), such as a Drizzle schema.
|
|
1178
1249
|
- A file beside a folder of the same name (`src/db/schema.ts` next to `src/db/schema/`), which would take over that folder’s imports.
|
|
1179
1250
|
- Two bindings whose names would give the same base class (`DB` and `db`).
|
|
1180
|
-
- A migration
|
|
1251
|
+
- A migration the database rejects: the error names the file, and the last good schema is kept.
|
|
1181
1252
|
- A Model whose table the migrations don’t make, a Model file that fails to load, or a Model exported as `default`. The error names the file, and the last good schema is kept.
|
|
1182
1253
|
|
|
1183
1254
|
:::warning[Coming from Drizzle or Prisma?]
|
|
1184
|
-
Their schemas often live at `src/db/schema.ts` or `src/db/schema/`. Write
|
|
1255
|
+
Their schemas often live at `src/db/schema.ts` or `src/db/schema/`. Write Active Record’s somewhere else, with `--out src/db/d1-record.ts`, and, if `application-record.ts` already exists, point its `import { schema }` at it (a new one is written importing the right file).
|
|
1185
1256
|
:::
|
|
1186
1257
|
|
|
1187
1258
|
## `active-record console`
|
|
@@ -1192,24 +1263,23 @@ Open your database with your Models in a console, or `active-record c` for short
|
|
|
1192
1263
|
npx active-record console
|
|
1193
1264
|
```
|
|
1194
1265
|
|
|
1195
|
-
| Option |
|
|
1196
|
-
| ------------------- |
|
|
1197
|
-
| `--database <name>` | The
|
|
1198
|
-
| `--models <path>` | Where the Models are: a folder (`src/models`) or one file (`src/models.ts`).
|
|
1199
|
-
| `--config <file>` | Use this
|
|
1200
|
-
| `--
|
|
1201
|
-
| `--
|
|
1202
|
-
|
|
|
1203
|
-
|
|
|
1204
|
-
| `--
|
|
1205
|
-
| `--
|
|
1206
|
-
| `--history` | Keep what you type in a remote session, which isn’t kept unless you ask. |
|
|
1266
|
+
| Option | |
|
|
1267
|
+
| ------------------- | ------------------------------------------------------------------------------------- |
|
|
1268
|
+
| `--database <name>` | The database to open, by its binding, when the config has several. |
|
|
1269
|
+
| `--models <path>` | Where the Models are: a folder (`src/models`) or one file (`src/models.ts`). |
|
|
1270
|
+
| `--config <file>` | Use this config file, in place of `active-record.jsonc`. |
|
|
1271
|
+
| `--no-history` | Don’t keep what you type (in `.wrangler/` on D1, `node_modules/.cache/` on Postgres). |
|
|
1272
|
+
| `--verbose` | Print each statement a line runs. `.verbose` turns it on and off in the console. |
|
|
1273
|
+
| `-e, --eval <code>` | Run this code, print its result (alone, on stdout), and exit; a failure exits 1. |
|
|
1274
|
+
| `--remote` | Open your remote database instead, after you type its name. |
|
|
1275
|
+
| `--yes` | With `--remote`, don’t ask first (also how to open it without a terminal). |
|
|
1276
|
+
| `--history` | Keep what you type in a remote session, which isn’t kept unless you ask. |
|
|
1207
1277
|
|
|
1208
|
-
It reads TypeScript Models and uses your project’s own
|
|
1278
|
+
It reads TypeScript Models and uses your project’s own `@forestfuture/active-record` and its adapter. On D1, it opens the database through your project’s `wrangler`. On Postgres, it opens a connection to the database’s `url`, or with `--remote` its `remoteUrl`, and closes it when you leave. It refuses, printing why, when there’s no config, with several databases and no `--database`, with no Models, or with the library not installed. On D1, it also refuses without `wrangler` installed, or with `--remote` when the binding has no `database_id`. On Postgres, it refuses when the database has no `url` (or, with `--remote`, no `remoteUrl`), or names a variable that isn’t set. With `--remote`, it refuses when you don’t confirm it, or aren’t on a terminal and didn’t pass `--yes`. `--yes` only goes with `--remote`, `--history` can’t be combined with `--no-history`, and `-e` takes one piece of code, once.
|
|
1209
1279
|
|
|
1210
1280
|
## `active-record migrate`
|
|
1211
1281
|
|
|
1212
|
-
Apply your pending migrations to the local database
|
|
1282
|
+
Apply your pending migrations to the local database:
|
|
1213
1283
|
|
|
1214
1284
|
```sh
|
|
1215
1285
|
npx active-record migrate
|
|
@@ -1220,14 +1290,30 @@ npx active-record migrate
|
|
|
1220
1290
|
| `--database <name>` | The database to migrate, when the config has several. |
|
|
1221
1291
|
| `--remote` | Migrate your remote database instead, after you type its name. |
|
|
1222
1292
|
| `--yes` | With `--remote`, don’t ask first (also how to migrate it without a terminal). |
|
|
1223
|
-
| `--config <file>` | Use this
|
|
1224
|
-
|
|
1293
|
+
| `--config <file>` | Use this config file. |
|
|
1294
|
+
|
|
1295
|
+
On D1, it runs your project’s `wrangler d1 migrations apply` for the database, `--local` or `--remote`, and prints what Wrangler prints. It exits with Wrangler’s code.
|
|
1296
|
+
|
|
1297
|
+
On Postgres, it applies them itself, to the database’s `url`, or with `--remote` its `remoteUrl`. It runs the migrations folder’s `.sql` files in the order of their versions and records each one’s version in `schema_migrations`. A version is the number a file’s name starts with:
|
|
1225
1298
|
|
|
1226
|
-
|
|
1299
|
+
```text
|
|
1300
|
+
Local database HYPERDRIVE (shop_development on localhost)
|
|
1301
|
+
Applied 20261108090503_create_products.sql
|
|
1302
|
+
Applied 20261108090504_add_sku_to_products.sql
|
|
1303
|
+
```
|
|
1304
|
+
|
|
1305
|
+
- **Each migration runs in a transaction** with its version, so one that fails is rolled back whole, and the ones after it don’t run. A statement Postgres can’t run in a transaction, such as `CREATE INDEX CONCURRENTLY`, fails.
|
|
1306
|
+
- **A second run at the same time is refused**, through an advisory lock, so each migration runs once. Run it again once the first is done.
|
|
1307
|
+
- **A file whose name doesn’t start with a number** is refused before any migration runs, as are two files with the same number.
|
|
1308
|
+
- **A migration with its own `BEGIN`, `COMMIT` or `ROLLBACK`** is refused too, since it would end the transaction the migration runs in. A function’s `BEGIN … END` is fine.
|
|
1309
|
+
|
|
1310
|
+
:::note[Migrating the real database on Postgres]
|
|
1311
|
+
On D1, `--remote` reaches your database through Cloudflare, signed in with Wrangler. On Postgres, it connects to the database itself, so the machine that runs it needs the `remoteUrl`’s variable, password included, and a network route to the server. That’s usually your CI, with the URL as a secret. If the database is only reachable through a Cloudflare Tunnel, open a local port to it with `cloudflared access tcp --hostname db.example.com --url localhost:5433`, and point `remoteUrl` at `localhost:5433`.
|
|
1312
|
+
:::
|
|
1227
1313
|
|
|
1228
1314
|
## Mapping columns to attributes
|
|
1229
1315
|
|
|
1230
|
-
|
|
1316
|
+
On D1, each column becomes an attribute by the first of these that applies:
|
|
1231
1317
|
|
|
1232
1318
|
1. **An override in the Model:** `static override attributes = { available: "boolean" } as const`.
|
|
1233
1319
|
2. **The column’s declared type:**
|
|
@@ -1261,9 +1347,37 @@ Also:
|
|
|
1261
1347
|
- an `INTEGER` read as a `boolean` from its name;
|
|
1262
1348
|
- for migrations written by Drizzle or Prisma (recognized by their config files or the lines they write): a note naming the tool, then one for each column worth checking, such as an `INTEGER` named `…_at` that may hold a Unix timestamp (the note shows the [`storage` override](/adopt-a-database#reading-unix-timestamps) for it), or a `TEXT` named like JSON without a `json_valid` check;
|
|
1263
1349
|
- a `DATETIME` column whose default is a number or `unixepoch()`, with the [`storage` override](/adopt-a-database#reading-unix-timestamps);
|
|
1264
|
-
- for migrations written by Drizzle or Prisma, a `DATETIME` column whose default is `CURRENT_TIMESTAMP` or `datetime('now')`, since it writes a different date text from
|
|
1350
|
+
- for migrations written by Drizzle or Prisma, a `DATETIME` column whose default is `CURRENT_TIMESTAMP` or `datetime('now')`, since it writes a different date text from Active Record’s and the two [compare as text](/adopt-a-database#comparing-dates-in-two-forms);
|
|
1265
1351
|
- migrations in folders with no `migrations_pattern` to find them.
|
|
1266
1352
|
|
|
1353
|
+
### Mapping Postgres’s columns
|
|
1354
|
+
|
|
1355
|
+
On Postgres, an override in the Model still comes first. Otherwise each column’s type decides, since Postgres’s types are real:
|
|
1356
|
+
|
|
1357
|
+
| Type | Attribute |
|
|
1358
|
+
| ---------------------------------------------------- | ------------------------------------------------------------- |
|
|
1359
|
+
| `smallint`, `integer`, `bigint` | `integer` |
|
|
1360
|
+
| `real`, `double precision` | `real` |
|
|
1361
|
+
| `boolean` | `boolean` |
|
|
1362
|
+
| `timestamptz`, `timestamp`, `date` | `datetime` |
|
|
1363
|
+
| `json`, `jsonb` | `json` |
|
|
1364
|
+
| `text`, `varchar`, `char`, `citext`, `uuid`, an enum | `string` |
|
|
1365
|
+
| `numeric` | An error: store money as integer cents (`price_cents BIGINT`) |
|
|
1366
|
+
| `bytea`, an array | An error: not supported |
|
|
1367
|
+
| anything else (`inet`, `interval`) | `string`, with a note |
|
|
1368
|
+
|
|
1369
|
+
A domain maps as the type it’s built on. Names, `NOT NULL`, and keys work as on D1. A string key gets `generateId: true` unless it has a literal default, even when Postgres has a default such as `gen_random_uuid()`. Literal defaults (`'draft'`, `0`, `true`, `'{}'::jsonb`) are copied, and functions such as `now()` are left to Postgres. Views, other schemas, and `schema_migrations` are left out.
|
|
1370
|
+
|
|
1371
|
+
**Extensions:** a migration can `CREATE EXTENSION` any of the extensions PGlite has its own build of, such as `citext`, `uuid-ossp`, `pg_trgm`, `pgcrypto`, `hstore`, and `ltree`. For any other, such as PostGIS, set `schemaUrl` to a Postgres server that has it, such as a local one. The schema is then read there, in a database of its own:
|
|
1372
|
+
|
|
1373
|
+
```jsonc
|
|
1374
|
+
{ "databases": { "HYPERDRIVE": { "schemaUrl": "postgres://localhost/postgres" } } }
|
|
1375
|
+
```
|
|
1376
|
+
|
|
1377
|
+
The migrations run in one transaction that’s rolled back, and the database is dropped afterwards, so a `CREATE ROLE` leaves nothing behind. It needs permission to create databases. A note says which server was read. Without `schemaUrl`, the command says to set one, and never uses `url` for it.
|
|
1378
|
+
|
|
1379
|
+
Stopping the command with Ctrl-C drops the database too. A command killed outright can leave one behind, named `active_record_schema_…`, which you can drop yourself.
|
|
1380
|
+
|
|
1267
1381
|
## `active-record g model` and `g migration`
|
|
1268
1382
|
|
|
1269
1383
|
```sh
|
|
@@ -1275,49 +1389,58 @@ npx active-record g migration <Name> [columns] [options]
|
|
|
1275
1389
|
|
|
1276
1390
|
| Option | |
|
|
1277
1391
|
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------- |
|
|
1278
|
-
| `--id integer\|text` | `integer`:
|
|
1392
|
+
| `--id integer\|text` | `integer`: a key the database generates. `text` (the default): a key generated in code. |
|
|
1279
1393
|
| `--no-timestamps` | Leave out `created_at` and `updated_at`. |
|
|
1280
1394
|
| `--models <path>` | Write Models in this folder (importing `application-record.ts` from it), or append them to one file (`src/models.ts`). |
|
|
1281
|
-
| `--database <binding>` | The
|
|
1395
|
+
| `--database <binding>` | The database to use, when the config has several. |
|
|
1282
1396
|
| `--out <file>` | The schema file to regenerate, as for `active-record schema` (for a Drizzle project’s `src/db/d1-record.ts`, say). |
|
|
1283
|
-
| `--config <file>` | Use this
|
|
1284
|
-
| `--adapter <name>` | The adapter (`d1`), when the project has several installed. |
|
|
1397
|
+
| `--config <file>` | Use this config file. |
|
|
1285
1398
|
|
|
1286
1399
|
### Column syntax
|
|
1287
1400
|
|
|
1288
1401
|
`name[:type][!][=value][:unique|:index]`
|
|
1289
1402
|
|
|
1290
|
-
| Type |
|
|
1291
|
-
| ---------------------- |
|
|
1292
|
-
| `string` (the default) | `TEXT`
|
|
1293
|
-
| `integer` | `INTEGER`
|
|
1294
|
-
| `real` | `REAL`
|
|
1295
|
-
| `boolean` | `BOOLEAN`
|
|
1296
|
-
| `datetime` | `DATETIME`
|
|
1297
|
-
| `json` | `TEXT CHECK (json_valid(column))`
|
|
1298
|
-
|
|
1403
|
+
| Type | D1 | Postgres |
|
|
1404
|
+
| ---------------------- | --------------------------------- | ------------------ |
|
|
1405
|
+
| `string` (the default) | `TEXT` | `TEXT` |
|
|
1406
|
+
| `integer` | `INTEGER` | `BIGINT` |
|
|
1407
|
+
| `real` | `REAL` | `DOUBLE PRECISION` |
|
|
1408
|
+
| `boolean` | `BOOLEAN` | `BOOLEAN` |
|
|
1409
|
+
| `datetime` | `DATETIME` | `TIMESTAMPTZ` |
|
|
1410
|
+
| `json` | `TEXT CHECK (json_valid(column))` | `JSONB` |
|
|
1411
|
+
|
|
1412
|
+
A `references` column is `<name>_id`, typed like the referenced table’s key, with `REFERENCES <plural> (id)` and an index.
|
|
1413
|
+
|
|
1414
|
+
The key `g model` writes:
|
|
1415
|
+
|
|
1416
|
+
| Key | D1 | Postgres |
|
|
1417
|
+
| ------------------- | ------------------------------ | -------------------------------------------------------- |
|
|
1418
|
+
| generated in code | `id TEXT PRIMARY KEY NOT NULL` | `id UUID PRIMARY KEY` |
|
|
1419
|
+
| with `--id integer` | `id INTEGER PRIMARY KEY` | `id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY` |
|
|
1420
|
+
|
|
1421
|
+
Timestamps are `created_at` and `updated_at`, `NOT NULL`, as `DATETIME` on D1 and `TIMESTAMPTZ` on Postgres.
|
|
1299
1422
|
|
|
1300
1423
|
- **`!`** makes the column `NOT NULL`. A `references` column is `NOT NULL` in a new table, and can be `NULL` when added to an existing one.
|
|
1301
1424
|
- **`=value`** is a literal default, for `string`, `integer`, `real`, and `boolean` columns (`=draft`, `=0`, `=1.5`, `=true`).
|
|
1302
1425
|
- **`:unique`** adds a unique index, and **`:index`** an index, named like `index_products_on_sku`.
|
|
1303
|
-
- **Names** can be written `priceCents` or `price_cents`; columns are always snake_case. Names
|
|
1426
|
+
- **Names** can be written `priceCents` or `price_cents`; columns are always snake_case. Names the database reserves (`order`, `group`, and on Postgres `user`) are quoted.
|
|
1304
1427
|
|
|
1305
1428
|
> **Beyond Rails**
|
|
1306
1429
|
>
|
|
1307
|
-
> `=value` is
|
|
1430
|
+
> `=value` is Active Record’s own addition: Rails’ generators can’t give a column a default.
|
|
1308
1431
|
|
|
1309
1432
|
### Migration names
|
|
1310
1433
|
|
|
1311
|
-
| Name | Writes
|
|
1312
|
-
| ----------------------------- |
|
|
1313
|
-
| `Create<Table>` | `CREATE TABLE`, as `g model` does
|
|
1314
|
-
| `Add<Anything>To<Table>` | `ADD COLUMN` for each column, then their indexes
|
|
1315
|
-
| `Remove<Anything>From<Table>` | `DROP INDEX IF EXISTS` for
|
|
1316
|
-
| anything else | An empty migration, to write yourself
|
|
1434
|
+
| Name | Writes |
|
|
1435
|
+
| ----------------------------- | ------------------------------------------------------------------------- |
|
|
1436
|
+
| `Create<Table>` | `CREATE TABLE`, as `g model` does |
|
|
1437
|
+
| `Add<Anything>To<Table>` | `ADD COLUMN` for each column, then their indexes |
|
|
1438
|
+
| `Remove<Anything>From<Table>` | `DROP COLUMN`, after `DROP INDEX IF EXISTS` for its generated index on D1 |
|
|
1439
|
+
| anything else | An empty migration, to write yourself |
|
|
1317
1440
|
|
|
1318
1441
|
A name can be written `AddSkuToProducts` or `add_sku_to_products`, and the table in it is made plural (`CreateWidget` creates `widgets`). A Model’s name is made singular, with a note (`g model line_items` writes `LineItem`). Names are letters, digits, and `_`, starting with a letter.
|
|
1319
1442
|
|
|
1320
|
-
**File names**
|
|
1443
|
+
**File names** start with the UTC time they’re written, to the second (`20261108090503_add_sku_to_products.sql`), so migrations written on two branches don’t clash. Files numbered `0001_…` still run first.
|
|
1321
1444
|
|
|
1322
1445
|
### What’s checked first
|
|
1323
1446
|
|
|
@@ -1327,7 +1450,7 @@ Nothing is written unless all of these hold:
|
|
|
1327
1450
|
- the Model’s file doesn’t exist yet (or, with one models file, doesn’t have the class yet);
|
|
1328
1451
|
- the config’s `migrations_pattern`, if it has one, would match the new file, so Wrangler would apply it;
|
|
1329
1452
|
- the schema file can be written (see [What it refuses](#active-record-schema));
|
|
1330
|
-
- it isn’t a required column added without a default.
|
|
1453
|
+
- on D1, it isn’t a required column added without a default, which SQLite can’t add.
|
|
1331
1454
|
|
|
1332
1455
|
Then the generator writes the files, regenerates the schema, and prints the next step: `npx active-record migrate`.
|
|
1333
1456
|
|
|
@@ -1338,9 +1461,9 @@ Every command exits with `0` on success, and `1` when anything was refused or fa
|
|
|
1338
1461
|
---
|
|
1339
1462
|
|
|
1340
1463
|
# Connections
|
|
1341
|
-
Source: https://
|
|
1464
|
+
Source: https://active-record.forestfuture.dev/connecting
|
|
1342
1465
|
|
|
1343
|
-
A query finds its
|
|
1466
|
+
A query finds its database in one of three ways. Most apps only use the first.
|
|
1344
1467
|
|
|
1345
1468
|
| | How | Use it for |
|
|
1346
1469
|
| -------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------- |
|
|
@@ -1350,9 +1473,13 @@ A query finds its D1 database in one of three ways. Most apps only use the first
|
|
|
1350
1473
|
|
|
1351
1474
|
[Database resolution](/query-databases) explains why there are three, and [which one you need](/query-databases#which-do-i-need).
|
|
1352
1475
|
|
|
1476
|
+
:::note
|
|
1477
|
+
The examples use D1’s `connect`, from `@forestfuture/active-record/d1`. On Postgres, `connect` comes from `@forestfuture/active-record/postgresql` and takes your Hyperdrive binding. See [PostgreSQL](/postgresql#connecting).
|
|
1478
|
+
:::
|
|
1479
|
+
|
|
1353
1480
|
## Using the binding
|
|
1354
1481
|
|
|
1355
|
-
Each Model names the
|
|
1482
|
+
Each Model names the binding it queries, so a Model queries by itself during any request:
|
|
1356
1483
|
|
|
1357
1484
|
```ts
|
|
1358
1485
|
import { Post, User } from "./models";
|
|
@@ -1362,7 +1489,7 @@ const user = await User.findByOrThrow({ email: "ada@example.com" });
|
|
|
1362
1489
|
const posts = await Post.where({ userId: user.id }).order({ id: "desc" }).toArray();
|
|
1363
1490
|
```
|
|
1364
1491
|
|
|
1365
|
-
`active-record schema` writes the binding into the generated schema your app’s base class holds
|
|
1492
|
+
`active-record schema` writes the binding into the generated schema your app’s base class holds. On D1 it comes from your Wrangler config’s `d1_databases`, and on Postgres from your `active-record.jsonc`.
|
|
1366
1493
|
|
|
1367
1494
|
Records remember their database, so `user.save()` and `user.posts()` use the same one later. Build records with `User.build(…)`: a record made with `new User()` has no database, and throws `NoDatabase` when it needs one.
|
|
1368
1495
|
|
|
@@ -1376,7 +1503,7 @@ Some things belong to one request, such as a D1 Session that reads its own write
|
|
|
1376
1503
|
|
|
1377
1504
|
```ts
|
|
1378
1505
|
import { withDatabase } from "@forestfuture/active-record";
|
|
1379
|
-
import { connect } from "@forestfuture/
|
|
1506
|
+
import { connect } from "@forestfuture/active-record/d1";
|
|
1380
1507
|
|
|
1381
1508
|
export default {
|
|
1382
1509
|
fetch(request, env) {
|
|
@@ -1389,7 +1516,7 @@ export default {
|
|
|
1389
1516
|
Every query started from a Model inside it, and everything it awaits, uses that database instead of the binding.
|
|
1390
1517
|
|
|
1391
1518
|
:::warning[Node.js compatibility]
|
|
1392
|
-
`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`.
|
|
1519
|
+
`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`. Nothing else on D1 needs it. On Postgres, `pg` needs it too.
|
|
1393
1520
|
:::
|
|
1394
1521
|
|
|
1395
1522
|
These pages use a request’s database:
|
|
@@ -1404,7 +1531,7 @@ These pages use a request’s database:
|
|
|
1404
1531
|
Start a query from a database you hold with `db.model`. It ignores `withDatabase`:
|
|
1405
1532
|
|
|
1406
1533
|
```ts
|
|
1407
|
-
import { connect } from "@forestfuture/
|
|
1534
|
+
import { connect } from "@forestfuture/active-record/d1";
|
|
1408
1535
|
import { User } from "./models";
|
|
1409
1536
|
|
|
1410
1537
|
const db = connect(env.DB);
|
|
@@ -1442,14 +1569,16 @@ Entries from a Model’s statics use the current database. `db.batch([...])` use
|
|
|
1442
1569
|
---
|
|
1443
1570
|
|
|
1444
1571
|
# Console
|
|
1445
|
-
Source: https://
|
|
1572
|
+
Source: https://active-record.forestfuture.dev/console
|
|
1446
1573
|
|
|
1447
|
-
Open a console on your local database, with your Models loaded, to try a query or fix a record by hand, or on your remote one with [`--remote`](#opening-your-remote-database). Run it from
|
|
1574
|
+
Open a console on your local database, with your Models loaded, to try a query or fix a record by hand, or on your remote one with [`--remote`](#opening-your-remote-database). Run it from your project’s folder:
|
|
1448
1575
|
|
|
1449
1576
|
```sh
|
|
1450
1577
|
npx active-record console
|
|
1451
1578
|
```
|
|
1452
1579
|
|
|
1580
|
+
On Postgres, it opens the `url` your [`active-record.jsonc`](/command-line#declaring-your-databases) declares, or with `--remote` its `remoteUrl`. The rest of this page shows D1.
|
|
1581
|
+
|
|
1453
1582
|
It prints which database and Models it opened, then waits for a line:
|
|
1454
1583
|
|
|
1455
1584
|
```text
|
|
@@ -1492,7 +1621,7 @@ Reloaded: Post, User
|
|
|
1492
1621
|
If a file fails to load, say a syntax error in the middle of an edit, the console names the file and keeps the Models you had.
|
|
1493
1622
|
|
|
1494
1623
|
:::note
|
|
1495
|
-
Only files in your project’s folder are read again. Your database connection and `@forestfuture/
|
|
1624
|
+
Only files in your project’s folder are read again. Your database connection and `@forestfuture/active-record` stay as they are.
|
|
1496
1625
|
:::
|
|
1497
1626
|
|
|
1498
1627
|
## Seeing the SQL
|
|
@@ -1535,7 +1664,7 @@ It opens your remote database only when you ask with `--remote`, and never for a
|
|
|
1535
1664
|
|
|
1536
1665
|
It starts only that D1 binding. The rest of your Wrangler config (Durable Objects, services, `vars`, and the secrets in `.dev.vars`) isn’t started, so it can’t warn or fail on them, and your Models can’t reach them either.
|
|
1537
1666
|
|
|
1538
|
-
On a terminal, what you type is kept in `.wrangler/
|
|
1667
|
+
On a terminal, what you type is kept in `.wrangler/active-record-history`, which Wrangler projects already ignore. A line can hold a token or an email, so add `--no-history` when you’d rather it wasn’t kept.
|
|
1539
1668
|
|
|
1540
1669
|
## Opening your remote database
|
|
1541
1670
|
|
|
@@ -1575,7 +1704,7 @@ There’s no one to type the name unless both your input and output are a termin
|
|
|
1575
1704
|
echo 'await User.count()' | npx active-record console --remote --yes
|
|
1576
1705
|
```
|
|
1577
1706
|
|
|
1578
|
-
What you type isn’t kept unless you add `--history`, and then it goes in `.wrangler/
|
|
1707
|
+
What you type isn’t kept unless you add `--history`, and then it goes in `.wrangler/active-record-history-remote`, a file of its own, so the up arrow never offers a local session a line you typed against the real database.
|
|
1579
1708
|
|
|
1580
1709
|
:::note
|
|
1581
1710
|
The binding needs a `database_id`. If it also has a `preview_database_id`, Wrangler opens that one in place of `database_id`, and the console says so: `Remote preview database DB (…)`.
|
|
@@ -1622,11 +1751,11 @@ echo 'await User.count()' | npx active-record console
|
|
|
1622
1751
|
That prints the same transcript a session does (the database, a prompt before each line, `#=> ` before each result) and exits 0 even when a line fails. For a script that checks the result or the exit code, use `-e`.
|
|
1623
1752
|
|
|
1624
1753
|
:::note
|
|
1625
|
-
The console reads your TypeScript Models directly, including extensionless imports and `tsconfig.json` paths, so it works in TypeScript projects. It needs Node.js 22.13 or later, and `wrangler` and `@forestfuture/
|
|
1754
|
+
The console reads your TypeScript Models directly, including extensionless imports and `tsconfig.json` paths, so it works in TypeScript projects. It needs Node.js 22.13 or later, and `wrangler` and `@forestfuture/active-record` installed in your project. It uses your copies, so your Models and the console share one library.
|
|
1626
1755
|
:::
|
|
1627
1756
|
|
|
1628
1757
|
:::warning[Only in projects you trust]
|
|
1629
|
-
The console runs your project’s code: your Models, and the `wrangler` and `@forestfuture/
|
|
1758
|
+
The console runs your project’s code: your Models, and the `wrangler` and `@forestfuture/active-record` in its `node_modules`. Run it in a project you’d run `wrangler dev` in.
|
|
1630
1759
|
:::
|
|
1631
1760
|
|
|
1632
1761
|
> **Compared with Rails**
|
|
@@ -1639,21 +1768,49 @@ The console runs your project’s code: your Models, and the `wrangler` and `@fo
|
|
|
1639
1768
|
|
|
1640
1769
|
---
|
|
1641
1770
|
|
|
1642
|
-
# D1
|
|
1643
|
-
Source: https://
|
|
1771
|
+
# D1
|
|
1772
|
+
Source: https://active-record.forestfuture.dev/d1
|
|
1773
|
+
|
|
1774
|
+
The D1 adapter runs your Models on [Cloudflare D1](https://developers.cloudflare.com/d1/). It comes with `@forestfuture/active-record`, as its `/d1` entry:
|
|
1644
1775
|
|
|
1645
|
-
|
|
1776
|
+
```sh
|
|
1777
|
+
npm install @forestfuture/active-record
|
|
1778
|
+
```
|
|
1779
|
+
|
|
1780
|
+
## Binding a database
|
|
1781
|
+
|
|
1782
|
+
Bind your D1 database in your Wrangler config:
|
|
1783
|
+
|
|
1784
|
+
```jsonc wrangler.jsonc
|
|
1785
|
+
{
|
|
1786
|
+
"d1_databases": [{ "binding": "DB", "database_name": "my-app-db", "database_id": "…" }],
|
|
1787
|
+
}
|
|
1788
|
+
```
|
|
1789
|
+
|
|
1790
|
+
Then run `npx active-record init`, which names it in your [`active-record.jsonc`](/command-line#declaring-your-databases) as a D1 database. `active-record schema` reads its migrations through your Wrangler config, and your generated schema names it with `adapter: d1({ binding: "DB" })`. Your Models then query it with nothing to set up. `connect(env.DB)` opens it yourself, for [a request’s database](/connecting#using-the-requests-database) or [an explicit one](/connecting#using-an-explicit-database). `active-record migrate` applies your migrations through Wrangler.
|
|
1791
|
+
|
|
1792
|
+
## Reading your own writes
|
|
1793
|
+
|
|
1794
|
+
With read replication, wrap each request in [`withSession`](/read-your-own-writes), from `@forestfuture/active-record/d1`. It opens a D1 Session, so the request reads its own writes, and carries its bookmark to the user’s next request.
|
|
1795
|
+
|
|
1796
|
+
## Sending queries in one round trip
|
|
1797
|
+
|
|
1798
|
+
D1 sends a batch of queries in one round trip. A [preload](/associations#preloading-associations) sends its whole tree that way, with the records’ own query, so `includes({ articles: "comments" })` is three queries in one round trip. A [page](/querying#paginating) sends its `COUNT` and its records together, with their preloads.
|
|
1799
|
+
|
|
1800
|
+
A batch runs as one transaction, so every query in it reads the same data. A preload’s nested query that would bind more than 100 values waits for the records above it, and takes one more round trip.
|
|
1801
|
+
|
|
1802
|
+
D1 also differs in these ways.
|
|
1646
1803
|
|
|
1647
1804
|
## No interactive transactions
|
|
1648
1805
|
|
|
1649
1806
|
D1 can’t hold a transaction open while your Worker awaits, so there’s no `transaction(async (tx) => …)`. You can’t read, decide, then write atomically.
|
|
1650
1807
|
|
|
1651
|
-
What you can make atomic is a set of writes prepared in advance: [`batch([...])`](/batches#batching-writes) sends statements and records together, and D1 writes all of them or none.
|
|
1808
|
+
What you can make atomic is a set of writes prepared in advance: [`batch([...])`](/batches#batching-writes) sends statements and records together, and D1 writes all of them or none. Active Record uses the same batches itself:
|
|
1652
1809
|
|
|
1653
1810
|
- A destroy’s [`dependent` strategies](/associations#destroying-dependent-records) are written in one batch with the owner’s DELETE.
|
|
1654
1811
|
- A record [autosaved](/associations#autosaving) with its owner joins the owner’s batch when the owner’s key is known in advance.
|
|
1655
1812
|
|
|
1656
|
-
##
|
|
1813
|
+
## Generating keys in code
|
|
1657
1814
|
|
|
1658
1815
|
Rows in a batch can only point at each other through keys that exist before it’s sent. Generated `TEXT` keys are made in code by [`generateId`](/models#generating-ids), so records have their key from `build()`. Then:
|
|
1659
1816
|
|
|
@@ -1662,10 +1819,6 @@ Rows in a batch can only point at each other through keys that exist before it
|
|
|
1662
1819
|
|
|
1663
1820
|
When D1 generates the key (`INTEGER PRIMARY KEY`), it doesn’t exist until the row is written. An owner is written first, then the records built through it in the next batch, a level at a time, and the batches aren’t atomic together. See [Autosaving](/associations#autosaving).
|
|
1664
1821
|
|
|
1665
|
-
## Read replicas
|
|
1666
|
-
|
|
1667
|
-
With read replication, a read can come from a replica that’s slightly behind. Wrap each request in [`withSession`](/read-your-own-writes). It opens a Session for the request, so the request reads its own writes. It also carries the Session’s bookmark to the user’s next request, so a user never sees data older than their last write.
|
|
1668
|
-
|
|
1669
1822
|
## Uniqueness is checked twice
|
|
1670
1823
|
|
|
1671
1824
|
The `uniqueness` validation asks D1 before saving, which gives a friendly error, but two requests can both pass it at once. Only a UNIQUE index guarantees uniqueness. Declare both, and handle [`RecordNotUnique`](/errors#constraint-errors) where a race matters.
|
|
@@ -1674,7 +1827,7 @@ The `uniqueness` validation asks D1 before saving, which gives a friendly error,
|
|
|
1674
1827
|
|
|
1675
1828
|
## Bound parameters
|
|
1676
1829
|
|
|
1677
|
-
D1 allows 100 bound values in one statement.
|
|
1830
|
+
D1 allows 100 bound values in one statement. The adapter binds lists as one JSON value (`json_each`), so `where({ id: [...] })`, `find([...])`, preloads, and `insertAll` work with any number of values. A single value can be up to 2 MB.
|
|
1678
1831
|
|
|
1679
1832
|
## Foreign keys are enforced
|
|
1680
1833
|
|
|
@@ -1687,15 +1840,15 @@ Once D1 has accepted a write, it’s done. An error thrown by an after-callback
|
|
|
1687
1840
|
---
|
|
1688
1841
|
|
|
1689
1842
|
# Errors
|
|
1690
|
-
Source: https://
|
|
1843
|
+
Source: https://active-record.forestfuture.dev/errors
|
|
1691
1844
|
|
|
1692
|
-
Every error
|
|
1845
|
+
Every error Active Record throws extends `ActiveRecordError`, so one check separates them from anything else:
|
|
1693
1846
|
|
|
1694
1847
|
```ts
|
|
1695
1848
|
import { ActiveRecordError } from "@forestfuture/active-record";
|
|
1696
1849
|
|
|
1697
1850
|
if (error instanceof ActiveRecordError) {
|
|
1698
|
-
// one of
|
|
1851
|
+
// one of Active Record's own
|
|
1699
1852
|
}
|
|
1700
1853
|
```
|
|
1701
1854
|
|
|
@@ -1774,9 +1927,9 @@ Every method throws them, `save()` as well as `saveOrThrow()`. The record keeps
|
|
|
1774
1927
|
---
|
|
1775
1928
|
|
|
1776
1929
|
# Generators
|
|
1777
|
-
Source: https://
|
|
1930
|
+
Source: https://active-record.forestfuture.dev/generators
|
|
1778
1931
|
|
|
1779
|
-
Generators write a table’s migration and its Model from a short description, then regenerate `src/db/schema.ts`.
|
|
1932
|
+
Generators write a table’s migration and its Model from a short description, then regenerate `src/db/schema.ts`. Each migration is written in your database’s own SQL: the [Command line](/command-line#column-syntax) reference lists the types on D1 and on Postgres, and every option.
|
|
1780
1933
|
|
|
1781
1934
|
## Adding a table
|
|
1782
1935
|
|
|
@@ -1787,7 +1940,7 @@ npx active-record g model Product 'name:string!' 'priceCents:integer!=0' user:re
|
|
|
1787
1940
|
```
|
|
1788
1941
|
|
|
1789
1942
|
```
|
|
1790
|
-
Wrote migrations/
|
|
1943
|
+
Wrote migrations/20261108093000_create_products.sql
|
|
1791
1944
|
Wrote src/models/product.ts
|
|
1792
1945
|
Wrote src/db/schema.ts (3 tables) from migrations/
|
|
1793
1946
|
Next: npx active-record migrate
|
|
@@ -1830,7 +1983,7 @@ Quote columns that contain `!`, so bash and zsh leave it alone.
|
|
|
1830
1983
|
|
|
1831
1984
|
> **Beyond Rails**
|
|
1832
1985
|
>
|
|
1833
|
-
> Rails’ generators have no syntax for a column’s default.
|
|
1986
|
+
> Rails’ generators have no syntax for a column’s default. Active Record adds `=value` (`=0`, `=true`, `=draft`), because SQLite can’t add a required (`NOT NULL`) column to an existing table without one.
|
|
1834
1987
|
|
|
1835
1988
|
## Changing a table
|
|
1836
1989
|
|
|
@@ -1902,12 +2055,12 @@ npx active-record schema
|
|
|
1902
2055
|
---
|
|
1903
2056
|
|
|
1904
2057
|
# Getting started
|
|
1905
|
-
Source: https://
|
|
2058
|
+
Source: https://active-record.forestfuture.dev/getting-started
|
|
1906
2059
|
|
|
1907
2060
|
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.
|
|
1908
2061
|
|
|
1909
2062
|
:::warning[Version 0.x]
|
|
1910
|
-
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.
|
|
2063
|
+
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.
|
|
1911
2064
|
:::
|
|
1912
2065
|
|
|
1913
2066
|
## Prerequisites
|
|
@@ -1929,10 +2082,31 @@ You’ll need:
|
|
|
1929
2082
|
|
|
1930
2083
|
## Installing Active Record
|
|
1931
2084
|
|
|
1932
|
-
Install
|
|
2085
|
+
Install Active Record. Its D1 adapter comes with it:
|
|
2086
|
+
|
|
2087
|
+
```sh
|
|
2088
|
+
npm install @forestfuture/active-record
|
|
2089
|
+
```
|
|
2090
|
+
|
|
2091
|
+
## Naming your database
|
|
2092
|
+
|
|
2093
|
+
Tell Active Record about your database:
|
|
1933
2094
|
|
|
1934
2095
|
```sh
|
|
1935
|
-
|
|
2096
|
+
npx active-record init
|
|
2097
|
+
```
|
|
2098
|
+
|
|
2099
|
+
It writes `active-record.jsonc`, which names `DB` as a D1 database. Every `active-record` command reads it:
|
|
2100
|
+
|
|
2101
|
+
```jsonc active-record.jsonc
|
|
2102
|
+
{
|
|
2103
|
+
"$schema": "./node_modules/@forestfuture/active-record/config-schema.json",
|
|
2104
|
+
"databases": {
|
|
2105
|
+
"DB": {
|
|
2106
|
+
"adapter": "d1",
|
|
2107
|
+
},
|
|
2108
|
+
},
|
|
2109
|
+
}
|
|
1936
2110
|
```
|
|
1937
2111
|
|
|
1938
2112
|
## Generating the Models
|
|
@@ -1948,16 +2122,16 @@ Each column is `name:type`. A `!` makes it required, `=true` sets a default, `:u
|
|
|
1948
2122
|
|
|
1949
2123
|
The generator writes these files:
|
|
1950
2124
|
|
|
1951
|
-
| File
|
|
1952
|
-
|
|
|
1953
|
-
| `migrations/
|
|
1954
|
-
| `src/db/schema.ts`
|
|
1955
|
-
| `src/models/application-record.ts`
|
|
1956
|
-
| `src/models/user.ts`, `post.ts`
|
|
2125
|
+
| File | What it is |
|
|
2126
|
+
| ------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
|
|
2127
|
+
| `migrations/20261108090503_create_users.sql`, `20261108090504_create_posts.sql` | The SQL that creates each table |
|
|
2128
|
+
| `src/db/schema.ts` | Every table’s columns, generated from the migrations. Don’t edit it. |
|
|
2129
|
+
| `src/models/application-record.ts` | Your app’s base class. It’s yours to edit. |
|
|
2130
|
+
| `src/models/user.ts`, `post.ts` | One Model per table |
|
|
1957
2131
|
|
|
1958
2132
|
Here’s the migration for posts:
|
|
1959
2133
|
|
|
1960
|
-
```sql migrations/
|
|
2134
|
+
```sql migrations/20261108090504_create_posts.sql
|
|
1961
2135
|
CREATE TABLE posts (
|
|
1962
2136
|
id TEXT PRIMARY KEY NOT NULL,
|
|
1963
2137
|
user_id TEXT NOT NULL REFERENCES users (id),
|
|
@@ -2052,7 +2226,7 @@ export default {
|
|
|
2052
2226
|
// POST: sign up a user with a first post, saved together.
|
|
2053
2227
|
const { email } = await request.json<{ email: string }>();
|
|
2054
2228
|
const user = User.build({ email });
|
|
2055
|
-
user.posts().build({ title: "Hello,
|
|
2229
|
+
user.posts().build({ title: "Hello, world" });
|
|
2056
2230
|
|
|
2057
2231
|
// save() validates and runs callbacks; false means it wasn't saved, and why is in errors.
|
|
2058
2232
|
if (!(await user.save())) {
|
|
@@ -2092,11 +2266,13 @@ The list includes Ada, with her email lowercased by `beforeSave`. Sign her up ag
|
|
|
2092
2266
|
- **[Associations](/associations):** `hasMany`, `belongsTo`, and `hasOne`.
|
|
2093
2267
|
- **[Generators](/generators):** every way to write columns.
|
|
2094
2268
|
- **[Bulk writes and batches](/batches):** writing several changes at once.
|
|
2269
|
+
- **[D1](/d1):** what’s different on D1, and Sessions for read replicas.
|
|
2270
|
+
- **[Moving to Postgres](/move-to-postgres):** this app on Postgres, with its data.
|
|
2095
2271
|
|
|
2096
2272
|
---
|
|
2097
2273
|
|
|
2098
2274
|
# Logging
|
|
2099
|
-
Source: https://
|
|
2275
|
+
Source: https://active-record.forestfuture.dev/logging
|
|
2100
2276
|
|
|
2101
2277
|
Log the SQL your Worker sends to D1 with an `onQuery` listener. It’s called once for every statement, writes and batches included, with:
|
|
2102
2278
|
|
|
@@ -2125,7 +2301,7 @@ Set `onQuery` on your app’s base class, in `application-record.ts`, to see eve
|
|
|
2125
2301
|
|
|
2126
2302
|
```ts
|
|
2127
2303
|
import { Model } from "@forestfuture/active-record";
|
|
2128
|
-
import { type QueryListener } from "@forestfuture/
|
|
2304
|
+
import { type QueryListener } from "@forestfuture/active-record/d1";
|
|
2129
2305
|
import { schema } from "../db/schema";
|
|
2130
2306
|
|
|
2131
2307
|
// src/models/application-record.ts: every query, from every Model, whichever database runs it.
|
|
@@ -2146,7 +2322,7 @@ To group a request’s queries, open its database with a listener that knows the
|
|
|
2146
2322
|
|
|
2147
2323
|
```ts
|
|
2148
2324
|
import { withDatabase } from "@forestfuture/active-record";
|
|
2149
|
-
import { connect } from "@forestfuture/
|
|
2325
|
+
import { connect } from "@forestfuture/active-record/d1";
|
|
2150
2326
|
|
|
2151
2327
|
// src/worker.ts: one request's queries, tagged with its ID, as JSON lines for Workers Logs.
|
|
2152
2328
|
// `app` stands for what your app exports as its Worker today: a framework's handler, or your own.
|
|
@@ -2185,7 +2361,7 @@ Check a variable that only `.dev.vars` sets, such as `LOG_SQL=1`. For one reques
|
|
|
2185
2361
|
|
|
2186
2362
|
```ts
|
|
2187
2363
|
import { withDatabase } from "@forestfuture/active-record";
|
|
2188
|
-
import { connect, type QueryListener } from "@forestfuture/
|
|
2364
|
+
import { connect, type QueryListener } from "@forestfuture/active-record/d1";
|
|
2189
2365
|
|
|
2190
2366
|
// LOG_SQL=1 in .dev.vars: logging in development only, nothing in production.
|
|
2191
2367
|
const onQuery: QueryListener | undefined = env.LOG_SQL
|
|
@@ -2199,7 +2375,7 @@ The app-wide listener reads the variable from `cloudflare:workers` when a query
|
|
|
2199
2375
|
|
|
2200
2376
|
```ts
|
|
2201
2377
|
import { Model } from "@forestfuture/active-record";
|
|
2202
|
-
import { type QueryListener } from "@forestfuture/
|
|
2378
|
+
import { type QueryListener } from "@forestfuture/active-record/d1";
|
|
2203
2379
|
import { env as workerEnv } from "cloudflare:workers";
|
|
2204
2380
|
import { schema } from "../db/schema";
|
|
2205
2381
|
|
|
@@ -2221,7 +2397,7 @@ To see a request’s database time in the browser’s developer tools, add it up
|
|
|
2221
2397
|
|
|
2222
2398
|
```ts
|
|
2223
2399
|
import { withDatabase } from "@forestfuture/active-record";
|
|
2224
|
-
import { connect } from "@forestfuture/
|
|
2400
|
+
import { connect } from "@forestfuture/active-record/d1";
|
|
2225
2401
|
import { User } from "./models";
|
|
2226
2402
|
|
|
2227
2403
|
let queries = 0;
|
|
@@ -2284,12 +2460,12 @@ A bare value inside an `sql` fragment has no attribute, so it’s logged as give
|
|
|
2284
2460
|
|
|
2285
2461
|
> **Compared with Rails**
|
|
2286
2462
|
>
|
|
2287
|
-
> Rails filters by its app-wide `filter_parameters`, against parameter and column names.
|
|
2463
|
+
> Rails filters by its app-wide `filter_parameters`, against parameter and column names. Active Record keeps the list on the Model (`static filterAttributes`, inherited from your base class), and matches each entry against the attribute’s snake_case name, so `"_key"` filters `apiKey`. A RegExp may match either form. It also hides filtered values in cast errors and in `RecordNotFound`, which Rails’ filter doesn’t cover.
|
|
2288
2464
|
|
|
2289
2465
|
---
|
|
2290
2466
|
|
|
2291
2467
|
# Models
|
|
2292
|
-
Source: https://
|
|
2468
|
+
Source: https://active-record.forestfuture.dev/models
|
|
2293
2469
|
|
|
2294
2470
|
A Model describes one table. Its attributes come from your migrations, through the generated schema, so the Model only declares behavior.
|
|
2295
2471
|
|
|
@@ -2549,7 +2725,7 @@ Conditions are cast the same way, so `where({ quantity: "42" })` finds 42. A con
|
|
|
2549
2725
|
|
|
2550
2726
|
> **Beyond Rails**
|
|
2551
2727
|
>
|
|
2552
|
-
> Rails casts leniently: `"12abc"` becomes `12`, `1.7` becomes `1`, any other text is `true`, and `""` is `nil`.
|
|
2728
|
+
> Rails casts leniently: `"12abc"` becomes `12`, `1.7` becomes `1`, any other text is `true`, and `""` is `nil`. Active Record refuses each, so `isAdmin=no` from a form can’t save `true`, and an empty field can’t silently become `null`.
|
|
2553
2729
|
|
|
2554
2730
|
## Building records
|
|
2555
2731
|
|
|
@@ -2734,7 +2910,7 @@ A name a Model doesn’t have throws `InvalidModel` when the Model is first used
|
|
|
2734
2910
|
|
|
2735
2911
|
> **Beyond Rails**
|
|
2736
2912
|
>
|
|
2737
|
-
> Rails’ `serializable_hash(except:)` is per call, and `filter_attributes` only covers logs and inspection.
|
|
2913
|
+
> Rails’ `serializable_hash(except:)` is per call, and `filter_attributes` only covers logs and inspection. Active Record keeps a class-level list, so `Response.json(user)` is safe without each call site remembering to strip the attribute.
|
|
2738
2914
|
|
|
2739
2915
|
## Filtering attributes
|
|
2740
2916
|
|
|
@@ -2792,7 +2968,7 @@ Printing shows attributes only, so it never loads an association. [Hidden attrib
|
|
|
2792
2968
|
|
|
2793
2969
|
> **Beyond Rails**
|
|
2794
2970
|
>
|
|
2795
|
-
> Rails doesn’t mark unsaved changes when it prints a record.
|
|
2971
|
+
> Rails doesn’t mark unsaved changes when it prints a record. Active Record does, so a pending edit is visible in the console before you save it.
|
|
2796
2972
|
|
|
2797
2973
|
## Sharing behavior
|
|
2798
2974
|
|
|
@@ -2815,8 +2991,261 @@ After that, a Model’s declarations are fixed, so request code can’t change t
|
|
|
2815
2991
|
|
|
2816
2992
|
---
|
|
2817
2993
|
|
|
2994
|
+
# Moving to Postgres
|
|
2995
|
+
Source: https://active-record.forestfuture.dev/move-to-postgres
|
|
2996
|
+
|
|
2997
|
+
Move your app from D1 to Postgres by changing its migrations, its schema, its config, and its data. Your Models and the code that uses them stay as they are. The examples move the app from [Getting started](/getting-started).
|
|
2998
|
+
|
|
2999
|
+
| What changes | How |
|
|
3000
|
+
| --------------------- | -------------------------------------------------------- |
|
|
3001
|
+
| Packages | Add `pg`, and PGlite for reading your schema. |
|
|
3002
|
+
| `active-record.jsonc` | It names your Postgres database in place of the D1 one. |
|
|
3003
|
+
| `migrations/` | Rewritten in Postgres’s types, with the same file names. |
|
|
3004
|
+
| `src/db/schema.ts` | Regenerated, so it names the PostgreSQL adapter. |
|
|
3005
|
+
| Your Wrangler config | A Hyperdrive binding in place of the D1 one. |
|
|
3006
|
+
| Your data | Copied from D1 to Postgres. |
|
|
3007
|
+
|
|
3008
|
+
You’ll need `sqlite3` and `psql` on your machine to copy the data.
|
|
3009
|
+
|
|
3010
|
+
## Installing pg
|
|
3011
|
+
|
|
3012
|
+
The PostgreSQL adapter comes with `@forestfuture/active-record`. Install `pg`, which it connects with, and PGlite, which `active-record schema` reads your schema with:
|
|
3013
|
+
|
|
3014
|
+
```sh
|
|
3015
|
+
npm install pg
|
|
3016
|
+
npm install --save-dev @electric-sql/pglite
|
|
3017
|
+
```
|
|
3018
|
+
|
|
3019
|
+
## Declaring the database
|
|
3020
|
+
|
|
3021
|
+
Replace the D1 database in your `active-record.jsonc` with your Postgres one:
|
|
3022
|
+
|
|
3023
|
+
```jsonc active-record.jsonc
|
|
3024
|
+
{
|
|
3025
|
+
"$schema": "./node_modules/@forestfuture/active-record/config-schema.json",
|
|
3026
|
+
"databases": {
|
|
3027
|
+
"HYPERDRIVE": {
|
|
3028
|
+
"adapter": "postgresql",
|
|
3029
|
+
"url": "postgres://user:password@localhost:5432/my_app",
|
|
3030
|
+
"remoteUrl": "${PRODUCTION_DATABASE_URL}",
|
|
3031
|
+
},
|
|
3032
|
+
},
|
|
3033
|
+
}
|
|
3034
|
+
```
|
|
3035
|
+
|
|
3036
|
+
`HYPERDRIVE` is the binding your Worker will reach Postgres through. `url` is your local database, and `remoteUrl` your real one, read here from the environment. Every `active-record` command now works on Postgres. See [Declaring your databases](/command-line#declaring-your-databases).
|
|
3037
|
+
|
|
3038
|
+
:::note
|
|
3039
|
+
Hyperdrive needs a password in a local connection string, even for a server that asks for none.
|
|
3040
|
+
:::
|
|
3041
|
+
|
|
3042
|
+
## Rewriting the migrations
|
|
3043
|
+
|
|
3044
|
+
Rewrite each migration in Postgres’s types, and keep its file name. Here are the app’s users:
|
|
3045
|
+
|
|
3046
|
+
```sql migrations/20261108090503_create_users.sql
|
|
3047
|
+
CREATE TABLE users (
|
|
3048
|
+
id UUID PRIMARY KEY,
|
|
3049
|
+
email TEXT NOT NULL,
|
|
3050
|
+
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
|
3051
|
+
created_at TIMESTAMPTZ NOT NULL,
|
|
3052
|
+
updated_at TIMESTAMPTZ NOT NULL
|
|
3053
|
+
);
|
|
3054
|
+
CREATE UNIQUE INDEX index_users_on_email ON users (email);
|
|
3055
|
+
```
|
|
3056
|
+
|
|
3057
|
+
And its posts:
|
|
3058
|
+
|
|
3059
|
+
```sql migrations/20261108090504_create_posts.sql
|
|
3060
|
+
CREATE TABLE posts (
|
|
3061
|
+
id UUID PRIMARY KEY,
|
|
3062
|
+
user_id UUID NOT NULL REFERENCES users (id),
|
|
3063
|
+
title TEXT NOT NULL,
|
|
3064
|
+
published_at TIMESTAMPTZ,
|
|
3065
|
+
created_at TIMESTAMPTZ NOT NULL,
|
|
3066
|
+
updated_at TIMESTAMPTZ NOT NULL
|
|
3067
|
+
);
|
|
3068
|
+
CREATE INDEX index_posts_on_user_id ON posts (user_id);
|
|
3069
|
+
```
|
|
3070
|
+
|
|
3071
|
+
These are the files `g model` writes on Postgres for the same commands. Change each type this way:
|
|
3072
|
+
|
|
3073
|
+
| On D1 | On Postgres |
|
|
3074
|
+
| ----------------------------------- | -------------------------------------------------------- |
|
|
3075
|
+
| `id TEXT PRIMARY KEY`, made in code | `id UUID PRIMARY KEY` |
|
|
3076
|
+
| `id INTEGER PRIMARY KEY` | `id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY` |
|
|
3077
|
+
| `INTEGER` | `BIGINT` |
|
|
3078
|
+
| `REAL` | `DOUBLE PRECISION` |
|
|
3079
|
+
| `DATETIME` | `TIMESTAMPTZ` |
|
|
3080
|
+
| `BOOLEAN`, `TEXT` | The same |
|
|
3081
|
+
| `TEXT` holding JSON | `JSONB` |
|
|
3082
|
+
|
|
3083
|
+
If your `generateId` makes keys that aren’t UUIDs, keep those keys `TEXT`, and their foreign keys too.
|
|
3084
|
+
|
|
3085
|
+
A datetime kept as a Unix time has a `storage` override. It can stay `BIGINT`, and keep the override. To store it as `TIMESTAMPTZ` instead, add a migration that converts it after you copy the data. Then remove the override from your Model:
|
|
3086
|
+
|
|
3087
|
+
```sql
|
|
3088
|
+
ALTER TABLE payments ALTER COLUMN paid_at TYPE TIMESTAMPTZ USING to_timestamp(paid_at);
|
|
3089
|
+
```
|
|
3090
|
+
|
|
3091
|
+
For milliseconds, convert `to_timestamp(paid_at / 1000.0)`.
|
|
3092
|
+
|
|
3093
|
+
Then create the tables in your local database:
|
|
3094
|
+
|
|
3095
|
+
```sh
|
|
3096
|
+
npx active-record migrate
|
|
3097
|
+
```
|
|
3098
|
+
|
|
3099
|
+
## Regenerating the schema
|
|
3100
|
+
|
|
3101
|
+
Regenerate your schema from the new migrations:
|
|
3102
|
+
|
|
3103
|
+
```sh
|
|
3104
|
+
npx active-record schema
|
|
3105
|
+
```
|
|
3106
|
+
|
|
3107
|
+
Its attributes come out the same as on D1. Only its adapter changes:
|
|
3108
|
+
|
|
3109
|
+
```ts src/db/schema.ts
|
|
3110
|
+
import { postgresql } from "@forestfuture/active-record/postgresql";
|
|
3111
|
+
|
|
3112
|
+
export const schema = {
|
|
3113
|
+
adapter: postgresql({ binding: "HYPERDRIVE" }),
|
|
3114
|
+
// …
|
|
3115
|
+
};
|
|
3116
|
+
```
|
|
3117
|
+
|
|
3118
|
+
## Copying the data
|
|
3119
|
+
|
|
3120
|
+
Copy your rows with this script. It exports your D1 database through Wrangler, writes each table as CSV with `sqlite3`, and loads them into Postgres with `psql`, all in one transaction:
|
|
3121
|
+
|
|
3122
|
+
```sh copy-data.sh
|
|
3123
|
+
#!/bin/sh
|
|
3124
|
+
# Copies rows from the D1 database bound as DB to the Postgres database DATABASE_URL names.
|
|
3125
|
+
#
|
|
3126
|
+
# DATABASE_URL=postgres://… sh copy-data.sh --remote users posts
|
|
3127
|
+
#
|
|
3128
|
+
# Name each table after the tables its foreign keys point at. Use --local for your local D1.
|
|
3129
|
+
set -eu
|
|
3130
|
+
|
|
3131
|
+
fail() {
|
|
3132
|
+
echo "copy-data.sh: $1" >&2
|
|
3133
|
+
exit 1
|
|
3134
|
+
}
|
|
3135
|
+
|
|
3136
|
+
d1=$1 # --remote or --local
|
|
3137
|
+
shift
|
|
3138
|
+
# Names go into SQL, so each must be letters, digits and underscores.
|
|
3139
|
+
for table in "$@"; do
|
|
3140
|
+
case $table in
|
|
3141
|
+
"" | [0-9]* | *[!A-Za-z0-9_]*) fail "can't copy a table named '$table'" ;;
|
|
3142
|
+
esac
|
|
3143
|
+
done
|
|
3144
|
+
|
|
3145
|
+
work=$(mktemp -d)
|
|
3146
|
+
trap 'rm -rf "$work"' EXIT
|
|
3147
|
+
# dash runs no EXIT trap on Ctrl-C, so exit first, and the copies of your data go too.
|
|
3148
|
+
trap 'exit 1' INT TERM HUP
|
|
3149
|
+
|
|
3150
|
+
# D1's tables and rows, as SQL, loaded into a SQLite file of your own.
|
|
3151
|
+
npx wrangler d1 export DB "$d1" --output "$work/d1.sql"
|
|
3152
|
+
sqlite3 "$work/d1.db" < "$work/d1.sql"
|
|
3153
|
+
|
|
3154
|
+
# Each table as CSV. sqlite3 quotes empty text and leaves NULL unquoted, as Postgres reads them.
|
|
3155
|
+
for table in "$@"; do
|
|
3156
|
+
info="FROM pragma_table_info('$table')"
|
|
3157
|
+
odd=$(sqlite3 "$work/d1.db" "SELECT count(*) $info WHERE name GLOB '[0-9]*' OR name GLOB '*[^A-Za-z0-9_]*'")
|
|
3158
|
+
[ "$odd" = 0 ] || fail "$table has a column whose name isn't letters, digits and underscores"
|
|
3159
|
+
columns=$(sqlite3 "$work/d1.db" "SELECT group_concat('\"' || name || '\"', ', ') $info")
|
|
3160
|
+
[ -n "$columns" ] || fail "D1 has no table named $table"
|
|
3161
|
+
sqlite3 -csv -header "$work/d1.db" "SELECT $columns FROM \"$table\"" > "$work/$table.csv"
|
|
3162
|
+
# Postgres folds an unquoted migration's names to lowercase, so they're named that way here.
|
|
3163
|
+
pg_table=$(printf '%s' "$table" | tr '[:upper:]' '[:lower:]')
|
|
3164
|
+
pg_columns=$(printf '%s' "$columns" | tr '[:upper:]' '[:lower:]')
|
|
3165
|
+
printf '%s\n' "\\copy \"$pg_table\" ($pg_columns) FROM '$work/$table.csv' WITH (FORMAT csv, HEADER true)" >> "$work/copy.sql"
|
|
3166
|
+
done
|
|
3167
|
+
|
|
3168
|
+
# Every table in one transaction, so a failure copies nothing.
|
|
3169
|
+
psql "$DATABASE_URL" --single-transaction -v ON_ERROR_STOP=1 --quiet --file "$work/copy.sql"
|
|
3170
|
+
```
|
|
3171
|
+
|
|
3172
|
+
Copy your local data to your local database:
|
|
3173
|
+
|
|
3174
|
+
```sh
|
|
3175
|
+
DATABASE_URL=postgres://user:password@localhost:5432/my_app sh copy-data.sh --local users posts
|
|
3176
|
+
```
|
|
3177
|
+
|
|
3178
|
+
Name each table after the tables it points at, so `users` comes before `posts`.
|
|
3179
|
+
|
|
3180
|
+
:::note
|
|
3181
|
+
If a table has integer keys, set its identity past the keys you copied, so the next row Postgres makes doesn’t take one of them:
|
|
3182
|
+
|
|
3183
|
+
```sql
|
|
3184
|
+
SELECT setval(pg_get_serial_sequence('comments', 'id'), (SELECT max(id) FROM comments));
|
|
3185
|
+
```
|
|
3186
|
+
|
|
3187
|
+
:::
|
|
3188
|
+
|
|
3189
|
+
## Switching the binding to Hyperdrive
|
|
3190
|
+
|
|
3191
|
+
Create a Hyperdrive config for your real database:
|
|
3192
|
+
|
|
3193
|
+
```sh
|
|
3194
|
+
npx wrangler hyperdrive create my-app --connection-string="$PRODUCTION_DATABASE_URL"
|
|
3195
|
+
```
|
|
3196
|
+
|
|
3197
|
+
Then bind it in your Wrangler config, with the `nodejs_compat` flag `pg` needs. Keep your D1 binding there too:
|
|
3198
|
+
|
|
3199
|
+
```jsonc wrangler.jsonc
|
|
3200
|
+
{
|
|
3201
|
+
"name": "my-app",
|
|
3202
|
+
"main": "src/index.ts",
|
|
3203
|
+
"compatibility_date": "2026-09-01",
|
|
3204
|
+
"compatibility_flags": ["nodejs_compat"],
|
|
3205
|
+
"hyperdrive": [
|
|
3206
|
+
{
|
|
3207
|
+
"binding": "HYPERDRIVE",
|
|
3208
|
+
"id": "<the id it printed>",
|
|
3209
|
+
"localConnectionString": "postgres://user:password@localhost:5432/my_app",
|
|
3210
|
+
},
|
|
3211
|
+
],
|
|
3212
|
+
// copy-data.sh exports D1 through this binding. Remove it once you've copied your real data.
|
|
3213
|
+
"d1_databases": [{ "binding": "DB", "database_name": "my-app-db", "database_id": "…" }],
|
|
3214
|
+
}
|
|
3215
|
+
```
|
|
3216
|
+
|
|
3217
|
+
`npx wrangler dev` now runs your app on your local Postgres.
|
|
3218
|
+
|
|
3219
|
+
## Going live
|
|
3220
|
+
|
|
3221
|
+
:::warning[Stop writes before you copy]
|
|
3222
|
+
A write that reaches D1 after you copy its data never reaches Postgres. Stop writes first, for example with a deploy that answers them with a 503.
|
|
3223
|
+
:::
|
|
3224
|
+
|
|
3225
|
+
:::note
|
|
3226
|
+
While it copies, `psql` shows its connection string to anyone on your machine who lists its processes. Copy from a machine only you use. To check your server’s certificate, add `sslmode=verify-full&sslrootcert=system` to the URL you copy to (libpq 16 or later).
|
|
3227
|
+
:::
|
|
3228
|
+
|
|
3229
|
+
Then create your tables on the real database, copy the data, and deploy:
|
|
3230
|
+
|
|
3231
|
+
```sh
|
|
3232
|
+
npx active-record migrate --remote
|
|
3233
|
+
DATABASE_URL="$PRODUCTION_DATABASE_URL" sh copy-data.sh --remote users posts
|
|
3234
|
+
npx wrangler deploy
|
|
3235
|
+
```
|
|
3236
|
+
|
|
3237
|
+
## Removing the D1 database
|
|
3238
|
+
|
|
3239
|
+
Once your app runs on Postgres, remove the `d1_databases` entry from your Wrangler config.
|
|
3240
|
+
|
|
3241
|
+
:::tip
|
|
3242
|
+
Your queries, validations, callbacks, and associations work the same on Postgres. A few things work differently, such as how NULLs and text sort, and `sql` fragments that use SQLite’s own functions. [PostgreSQL](/postgresql) lists each one.
|
|
3243
|
+
:::
|
|
3244
|
+
|
|
3245
|
+
---
|
|
3246
|
+
|
|
2818
3247
|
# Persistence
|
|
2819
|
-
Source: https://
|
|
3248
|
+
Source: https://active-record.forestfuture.dev/persistence
|
|
2820
3249
|
|
|
2821
3250
|
Records are saved, updated, and destroyed with `save`, `create`, `update`, and `destroy`.
|
|
2822
3251
|
|
|
@@ -2939,10 +3368,158 @@ To insert, update, or delete many rows at once, without validations and callback
|
|
|
2939
3368
|
|
|
2940
3369
|
---
|
|
2941
3370
|
|
|
3371
|
+
# PostgreSQL
|
|
3372
|
+
Source: https://active-record.forestfuture.dev/postgresql
|
|
3373
|
+
|
|
3374
|
+
The PostgreSQL adapter runs your Models on Postgres, in a Worker through [Hyperdrive](https://developers.cloudflare.com/hyperdrive/) or on Node. It comes with `@forestfuture/active-record`, as its `/postgresql` entry. Install the library with `pg`, and PGlite for reading your schema:
|
|
3375
|
+
|
|
3376
|
+
```sh
|
|
3377
|
+
npm install @forestfuture/active-record pg
|
|
3378
|
+
npm install --save-dev @electric-sql/pglite
|
|
3379
|
+
```
|
|
3380
|
+
|
|
3381
|
+
Then name your database in [`active-record.jsonc`](/command-line#declaring-your-databases), with `npx active-record init --adapter postgresql`.
|
|
3382
|
+
|
|
3383
|
+
A Worker on Postgres needs `"compatibility_flags": ["nodejs_compat"]` in its Wrangler config, for `pg`. To move an app from D1, see [Moving to Postgres](/move-to-postgres).
|
|
3384
|
+
|
|
3385
|
+
Your Models, queries, and callbacks work the same on Postgres. The sections after [Connecting](#connecting) are the places Postgres works differently from D1.
|
|
3386
|
+
|
|
3387
|
+
## Connecting
|
|
3388
|
+
|
|
3389
|
+
`connect` takes a Hyperdrive binding, a connection string, or a `pg` Pool. Open the request’s database from your Hyperdrive binding:
|
|
3390
|
+
|
|
3391
|
+
```ts
|
|
3392
|
+
import { withDatabase } from "@forestfuture/active-record";
|
|
3393
|
+
import { connect } from "@forestfuture/active-record/postgresql";
|
|
3394
|
+
|
|
3395
|
+
export default {
|
|
3396
|
+
fetch(request, env) {
|
|
3397
|
+
const db = connect(env.HYPERDRIVE);
|
|
3398
|
+
return withDatabase(db, () => app.fetch(request, env));
|
|
3399
|
+
},
|
|
3400
|
+
};
|
|
3401
|
+
```
|
|
3402
|
+
|
|
3403
|
+
The first query inside `withDatabase` opens a client, and the rest of the request shares it. It closes when `withDatabase` finishes. Each `withDatabase` call gets its own client, so a Database your Worker opens once can serve every request. Without `withDatabase`, each query opens a client of its own and closes it when it’s done. So does work that outlives the request, such as a save in `ctx.waitUntil`.
|
|
3404
|
+
|
|
3405
|
+
Your schema names the binding with `adapter: postgresql({ binding: "HYPERDRIVE" })`, so `User.find(id)` works in a Worker with nothing to set up. Declare it in your [`active-record.jsonc`](/command-line#declaring-your-databases), where the command finds your databases.
|
|
3406
|
+
|
|
3407
|
+
`connect(env.DATABASE_URL)` takes a connection string the same way.
|
|
3408
|
+
|
|
3409
|
+
:::tip
|
|
3410
|
+
On Workers, use Hyperdrive. It pools connections, so a new client doesn’t mean a new connection to Postgres.
|
|
3411
|
+
:::
|
|
3412
|
+
|
|
3413
|
+
On Node, pass your own Pool, which your app ends when it shuts down:
|
|
3414
|
+
|
|
3415
|
+
```ts
|
|
3416
|
+
import pg from "pg";
|
|
3417
|
+
import { connect } from "@forestfuture/active-record/postgresql";
|
|
3418
|
+
|
|
3419
|
+
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
|
|
3420
|
+
const db = connect(pool);
|
|
3421
|
+
```
|
|
3422
|
+
|
|
3423
|
+
Outside a Worker there’s no binding, so wrap each request in `withDatabase(db, …)` for your Models’ statics.
|
|
3424
|
+
|
|
3425
|
+
Opening a client from a binding or a connection string waits up to 10 seconds for Postgres to answer. After that, the query fails with `Error: timeout expired`. Each query waiting for that client tries again, and can wait as long. To change the limit, set `connect_timeout` to a number of seconds:
|
|
3426
|
+
|
|
3427
|
+
```ts
|
|
3428
|
+
import { connect } from "@forestfuture/active-record/postgresql";
|
|
3429
|
+
|
|
3430
|
+
const db = connect("postgres://app@db.example.com/app?connect_timeout=5");
|
|
3431
|
+
```
|
|
3432
|
+
|
|
3433
|
+
If you want no limit, set `connect_timeout=0`.
|
|
3434
|
+
|
|
3435
|
+
:::note
|
|
3436
|
+
A Hyperdrive binding’s connection string isn’t yours to change, so it always waits up to 10 seconds. A Pool uses its own `connectionTimeoutMillis`.
|
|
3437
|
+
:::
|
|
3438
|
+
|
|
3439
|
+
> **Compared with Rails**
|
|
3440
|
+
>
|
|
3441
|
+
> Rails sets no limit, so opening a connection waits as long as it takes unless you set `connect_timeout`. Here the limit is 10 seconds unless you set one.
|
|
3442
|
+
|
|
3443
|
+
## Batches are transactions
|
|
3444
|
+
|
|
3445
|
+
[`batch([...])`](/batches#batching-writes) writes all its entries or none, as on D1. On Postgres it runs them between `BEGIN` and `COMMIT`, on a client of its own. A query your request sends while the batch runs stays outside the transaction, so a failed batch never rolls it back.
|
|
3446
|
+
|
|
3447
|
+
## Reads run one after another
|
|
3448
|
+
|
|
3449
|
+
On D1, a [preload](/associations#preloading-associations) or a [page](/querying#paginating) sends all its queries [in one round trip](/d1#sending-queries-in-one-round-trip). On Postgres they run one after another, on one client. A page’s `total` comes from its own query, so a write between the two can make it disagree with the page’s records for a moment.
|
|
3450
|
+
|
|
3451
|
+
Queries you send at once with `Promise.all` inside one `withDatabase` call also run one after another, on that call’s client.
|
|
3452
|
+
|
|
3453
|
+
## Large integers
|
|
3454
|
+
|
|
3455
|
+
A `bigint` column reads as a number. A value past `Number.MAX_SAFE_INTEGER` throws a `TypeError` naming its attribute, rather than reading as a number that’s slightly wrong.
|
|
3456
|
+
|
|
3457
|
+
## Placeholders
|
|
3458
|
+
|
|
3459
|
+
`onQuery` and `toSql()` show the SQL Postgres runs, with `$1`, `$2`, and so on where D1 shows `?`.
|
|
3460
|
+
|
|
3461
|
+
## Raw SQL stays on its database
|
|
3462
|
+
|
|
3463
|
+
An [`sql` fragment](/querying#using-raw-statements) is sent as you wrote it. A fragment that uses SQLite’s functions fails on Postgres, and one that uses Postgres’s fails on D1.
|
|
3464
|
+
|
|
3465
|
+
## Sorting
|
|
3466
|
+
|
|
3467
|
+
Postgres sorts NULL after every value: last in ascending order, and first in descending order. D1 sorts it first in ascending order. Place NULLs yourself to sort them the same on both:
|
|
3468
|
+
|
|
3469
|
+
```ts
|
|
3470
|
+
User.order({ role: { direction: "asc", nulls: "last" } });
|
|
3471
|
+
```
|
|
3472
|
+
|
|
3473
|
+
Postgres sorts text by your database’s collation, usually its locale’s, where capitals and lowercase letters interleave. D1 sorts by code point, so every capital comes before every lowercase letter.
|
|
3474
|
+
|
|
3475
|
+
## Distinct records ordered by another column
|
|
3476
|
+
|
|
3477
|
+
Postgres refuses to order `distinct()` records by a column they don’t select, and throws its own error. Select the column, or order by one you select.
|
|
3478
|
+
|
|
3479
|
+
## NUL characters
|
|
3480
|
+
|
|
3481
|
+
Postgres text, and strings in a `jsonb` value, can’t hold the NUL character (`\u0000`). A value with one fails with Postgres’s own error.
|
|
3482
|
+
|
|
3483
|
+
## Keys written by hand
|
|
3484
|
+
|
|
3485
|
+
A key you set yourself doesn’t move a Postgres identity column. The next key Postgres makes can then be one you’ve already used, which fails as a duplicate.
|
|
3486
|
+
|
|
3487
|
+
## Constraint errors name their table
|
|
3488
|
+
|
|
3489
|
+
Postgres’s constraint errors name their table and columns. So a batch’s foreign-key failure has `.table` and `.columns`, where D1’s has `.table` `null` when the batch writes to several tables.
|
|
3490
|
+
|
|
3491
|
+
## Migrations are applied by the command
|
|
3492
|
+
|
|
3493
|
+
On D1, `active-record migrate` runs Wrangler, which records each migration by its file name. On Postgres, the command applies them itself. It records each one’s version in a `schema_migrations` table. A version is the number a file’s name starts with, so every file’s name needs one. Renaming the rest of the name doesn’t run the migration again.
|
|
3494
|
+
|
|
3495
|
+
Each migration runs in a transaction. One that fails leaves nothing behind, since Postgres can undo a `CREATE TABLE` or an `ALTER TABLE`. A statement that can’t run in a transaction, such as `CREATE INDEX CONCURRENTLY`, fails.
|
|
3496
|
+
|
|
3497
|
+
[Migrating the real database](/command-line#active-record-migrate) needs its connection string and a route to its server.
|
|
3498
|
+
|
|
3499
|
+
## Reading the schema
|
|
3500
|
+
|
|
3501
|
+
`active-record schema` reads your schema by applying your migrations to [PGlite](https://pglite.dev), Postgres in memory, so it needs no server. A migration that creates an extension PGlite doesn’t have, such as PostGIS, is read on the server your [`schemaUrl`](/command-line#mapping-postgress-columns) names instead.
|
|
3502
|
+
|
|
3503
|
+
Postgres’s column types decide the attributes. Unlike on D1, a column’s name never does, so an `is_active BIGINT` is an integer.
|
|
3504
|
+
|
|
3505
|
+
## Adding a required column
|
|
3506
|
+
|
|
3507
|
+
A generated migration can add a `NOT NULL` column without a default, which SQLite refuses. Postgres runs it on an empty table, and refuses it on a table with rows.
|
|
3508
|
+
|
|
3509
|
+
## Migrations in folders
|
|
3510
|
+
|
|
3511
|
+
The command reads a Postgres database’s migrations from its folder, not from folders inside it. Migrations a tool writes in folders, such as `migrations/0000_init/migration.sql`, aren’t read.
|
|
3512
|
+
|
|
3513
|
+
## jsonb keeps the value
|
|
3514
|
+
|
|
3515
|
+
A `jsonb` column keeps a JSON value, not the text you wrote. A raw query reads it back with Postgres’s own spacing and key order. Your Models read the same value either way.
|
|
3516
|
+
|
|
3517
|
+
---
|
|
3518
|
+
|
|
2942
3519
|
# Database resolution
|
|
2943
|
-
Source: https://
|
|
3520
|
+
Source: https://active-record.forestfuture.dev/query-databases
|
|
2944
3521
|
|
|
2945
|
-
`Product.find(id)` works with no setup, because a Model knows its
|
|
3522
|
+
`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.
|
|
2946
3523
|
|
|
2947
3524
|
## One isolate, many requests
|
|
2948
3525
|
|
|
@@ -2985,7 +3562,7 @@ For the options themselves, see [Connections](/connecting).
|
|
|
2985
3562
|
---
|
|
2986
3563
|
|
|
2987
3564
|
# Querying
|
|
2988
|
-
Source: https://
|
|
3565
|
+
Source: https://active-record.forestfuture.dev/querying
|
|
2989
3566
|
|
|
2990
3567
|
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:
|
|
2991
3568
|
|
|
@@ -3061,7 +3638,7 @@ User.where(sql`lower(${column("email")}) = lower(${email})`);
|
|
|
3061
3638
|
```
|
|
3062
3639
|
|
|
3063
3640
|
:::warning[Integer datetimes]
|
|
3064
|
-
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,
|
|
3641
|
+
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.
|
|
3065
3642
|
:::
|
|
3066
3643
|
|
|
3067
3644
|
```ts
|
|
@@ -3119,7 +3696,7 @@ For a cache key, or the value a test expects of a raw row, `serialize` gives the
|
|
|
3119
3696
|
|
|
3120
3697
|
> **Compared with Rails**
|
|
3121
3698
|
>
|
|
3122
|
-
> `typeForAttribute` is `type_for_attribute`, with the same `cast`, `serialize`, and `deserialize`.
|
|
3699
|
+
> `typeForAttribute` is `type_for_attribute`, with the same `cast`, `serialize`, and `deserialize`. Active Record’s are strict: a value the attribute can’t hold throws, where Rails casts it leniently.
|
|
3123
3700
|
|
|
3124
3701
|
## Ordering and paging
|
|
3125
3702
|
|
|
@@ -3139,12 +3716,12 @@ User.order({ createdAt: "desc" }).limit(20).offset(40); // page 3
|
|
|
3139
3716
|
Calling `order` again adds more keys. `reorder` replaces the order so far, and `reorder()` removes it. To get a page with its total, use [`paginate`](#paginating).
|
|
3140
3717
|
|
|
3141
3718
|
:::note
|
|
3142
|
-
NULLs sort first in ascending order,
|
|
3719
|
+
On D1, NULLs sort first in ascending order, and on Postgres last. Place them with `nulls: "first"` or `nulls: "last"` to sort them the same on both.
|
|
3143
3720
|
:::
|
|
3144
3721
|
|
|
3145
3722
|
## Paginating
|
|
3146
3723
|
|
|
3147
|
-
`paginate` resolves to one page of records and the total they’re a page of
|
|
3724
|
+
`paginate` resolves to one page of records and the total they’re a page of:
|
|
3148
3725
|
|
|
3149
3726
|
```ts
|
|
3150
3727
|
import { Post } from "./models";
|
|
@@ -3159,7 +3736,8 @@ export async function listPosts(request: Request): Promise<Response> {
|
|
|
3159
3736
|
- `page` and `perPage` take numbers, or text from a query string. Missing, `null`, or empty, they mean the first page and the default size. Anything that isn’t a whole number from 1 throws `TypeError`.
|
|
3160
3737
|
- Pages sort by the Relation’s order, then by the primary key, so records that tie keep their pages between requests.
|
|
3161
3738
|
- A page past the last has no records, but still has the real `total`.
|
|
3162
|
-
- `includes()` preloads the page’s associations
|
|
3739
|
+
- `includes()` preloads the page’s associations, with one more query per association.
|
|
3740
|
+
- On D1, the count, the records, and their preloads take [one round trip](/d1#sending-queries-in-one-round-trip).
|
|
3163
3741
|
- A Relation with its own `limit` or `offset` throws `IncompatibleRelation`.
|
|
3164
3742
|
|
|
3165
3743
|
### Skipping the count
|
|
@@ -3194,7 +3772,7 @@ D1 limits neither the rows a query returns nor the size of its response. `maxPer
|
|
|
3194
3772
|
|
|
3195
3773
|
> **Beyond Rails**
|
|
3196
3774
|
>
|
|
3197
|
-
> Rails leaves pagination to gems such as Kaminari and Pagy.
|
|
3775
|
+
> Rails leaves pagination to gems such as Kaminari and Pagy. Active Record builds it in, and on D1 sends the count and the page together.
|
|
3198
3776
|
|
|
3199
3777
|
## Getting results
|
|
3200
3778
|
|
|
@@ -3339,16 +3917,16 @@ const admins = await User.where({ role: "admin" }).merge(recent).toArray();
|
|
|
3339
3917
|
|
|
3340
3918
|
> **Compared with Rails**
|
|
3341
3919
|
>
|
|
3342
|
-
> Rails adds the argument’s order to the receiver’s.
|
|
3920
|
+
> Rails adds the argument’s order to the receiver’s. Active Record replaces it.
|
|
3343
3921
|
|
|
3344
3922
|
## Preloading associations
|
|
3345
3923
|
|
|
3346
|
-
`includes` loads associations for every record, with one query per association
|
|
3924
|
+
`includes` loads associations for every record, with one query per association. See [Associations](/associations#preloading-associations).
|
|
3347
3925
|
|
|
3348
3926
|
---
|
|
3349
3927
|
|
|
3350
3928
|
# Read replicas
|
|
3351
|
-
Source: https://
|
|
3929
|
+
Source: https://active-record.forestfuture.dev/read-your-own-writes
|
|
3352
3930
|
|
|
3353
3931
|
With [D1 read replication](https://developers.cloudflare.com/d1/best-practices/read-replication/), reads can come from a nearby replica that may be a moment behind. A D1 **Session** keeps each user’s reads at least as new as their own writes.
|
|
3354
3932
|
|
|
@@ -3357,7 +3935,7 @@ With [D1 read replication](https://developers.cloudflare.com/d1/best-practices/r
|
|
|
3357
3935
|
Wrap each request in `withSession`, passing it the request and your D1 binding:
|
|
3358
3936
|
|
|
3359
3937
|
```ts
|
|
3360
|
-
import { withSession } from "@forestfuture/
|
|
3938
|
+
import { withSession } from "@forestfuture/active-record/d1";
|
|
3361
3939
|
|
|
3362
3940
|
// src/worker.ts: each request reads at least as new as this browser's last write, from any replica.
|
|
3363
3941
|
export default {
|
|
@@ -3386,7 +3964,7 @@ For a second D1 database, call `withSession` again inside the first one. Give ea
|
|
|
3386
3964
|
If your clients aren’t browsers, carry the bookmark in a header instead:
|
|
3387
3965
|
|
|
3388
3966
|
```ts
|
|
3389
|
-
import { withSession } from "@forestfuture/
|
|
3967
|
+
import { withSession } from "@forestfuture/active-record/d1";
|
|
3390
3968
|
|
|
3391
3969
|
// An API's clients send back the x-d1-bookmark header of the response before.
|
|
3392
3970
|
export const api = {
|
|
@@ -3423,13 +4001,13 @@ After the first query, each query reads data at least as new as the one before,
|
|
|
3423
4001
|
---
|
|
3424
4002
|
|
|
3425
4003
|
# Schema and ApplicationRecord
|
|
3426
|
-
Source: https://
|
|
4004
|
+
Source: https://active-record.forestfuture.dev/schema
|
|
3427
4005
|
|
|
3428
|
-
In Rails, a migration describes a table, and the model never repeats it:
|
|
4006
|
+
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.
|
|
3429
4007
|
|
|
3430
4008
|
## Migrations are the source of truth
|
|
3431
4009
|
|
|
3432
|
-
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.
|
|
4010
|
+
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.
|
|
3433
4011
|
|
|
3434
4012
|
A Model never redeclares its columns. If it did, the migration and the Model would say the same thing twice (`price_cents INTEGER NOT NULL`, then `priceCents: { type: "integer", null: false }`), and could drift apart.
|
|
3435
4013
|
|
|
@@ -3437,7 +4015,7 @@ A Model never redeclares its columns. If it did, the migration and the Model wou
|
|
|
3437
4015
|
|
|
3438
4016
|
TypeScript needs to know a Model’s attributes before your code runs, to type `product.priceCents` and check `Product.where({ … })`. And a Worker shouldn’t ask D1 for its tables on every request. So instead of reading the database at runtime, `active-record schema` applies your migrations to an in-memory SQLite database, reads each table’s columns, and writes them to `src/db/schema.ts`.
|
|
3439
4017
|
|
|
3440
|
-
That file is to
|
|
4018
|
+
That file is to Active Record what `db/schema.rb` is to Rails: a document of every table, regenerated after each migration, never edited by hand, and committed, so each schema change shows up as a readable diff next to its migration. Each table names the migration that last changed it. In CI, `active-record schema --check` catches a schema someone forgot to regenerate.
|
|
3441
4019
|
|
|
3442
4020
|
After the tables, the file holds `schema`: the D1 binding, every table, and the list of your Models. Last come type declarations that add each table’s attributes to its Model’s class. They’re types only, so the file still imports nothing when your Worker runs.
|
|
3443
4021
|
|
|
@@ -3464,13 +4042,13 @@ A Model can still declare its attributes itself, with `define`, for a view or a
|
|
|
3464
4042
|
---
|
|
3465
4043
|
|
|
3466
4044
|
# Security
|
|
3467
|
-
Source: https://
|
|
4045
|
+
Source: https://active-record.forestfuture.dev/security
|
|
3468
4046
|
|
|
3469
|
-
Whatever a request sends can reach a query or a record through
|
|
4047
|
+
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.
|
|
3470
4048
|
|
|
3471
4049
|
These are the project’s own reviews, not an independent audit. Each says what it covered and what it didn’t.
|
|
3472
4050
|
|
|
3473
|
-
## What
|
|
4051
|
+
## What Active Record protects against
|
|
3474
4052
|
|
|
3475
4053
|
- **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.
|
|
3476
4054
|
- **Values that aren’t what TypeScript says.** A value from JSON, a form, or a query string is cast to its attribute’s type when it’s assigned or used in a condition, and anything ambiguous is refused: `"false"` can’t save `true`. See [Models](/models#casting-assigned-values).
|
|
@@ -3507,7 +4085,7 @@ The library’s guarantees are tested against a real D1 database (through Minifl
|
|
|
3507
4085
|
|
|
3508
4086
|
## Supply chain
|
|
3509
4087
|
|
|
3510
|
-
- **No runtime dependencies in your Worker.** The library
|
|
4088
|
+
- **No runtime dependencies in your Worker.** The library is one package, `@forestfuture/active-record`, with its adapters inside it. On D1 it imports no other package, so no other package’s compromise can reach your Worker through it. On Postgres it imports `pg`, the driver your app installs itself. The command line, a development tool, depends on `jiti` to load your Models; installing the library installs it, and your Worker doesn’t bundle it.
|
|
3511
4089
|
- **The command line runs your Model files.** `active-record schema`, the generators, and the console load them to find your Models, so code at a Model file’s top level runs each time, `active-record schema --check` in CI included.
|
|
3512
4090
|
- **Releases are built by CI.** The npm package is built and published by the repository’s release workflow, never from a laptop, so what’s on npm is what’s in the repository. Publishing uses npm’s trusted publishing, so no npm token is stored anywhere, and each version carries a provenance attestation linking it to its commit. Version 0.1.0 was published before that was set up, with a one-time token, and has no attestation ([#109](https://github.com/forestfuture/active-record/issues/109)); 0.1.1 and later do.
|
|
3513
4091
|
- **CI is pinned.** Every third-party GitHub Action is pinned to a commit, not a tag that could be moved, because a moved tag would run someone else’s code in the job that publishes. A test fails if one isn’t.
|
|
@@ -3588,7 +4166,7 @@ Please report a security problem privately, as the [security policy](https://git
|
|
|
3588
4166
|
---
|
|
3589
4167
|
|
|
3590
4168
|
# Multiple databases
|
|
3591
|
-
Source: https://
|
|
4169
|
+
Source: https://active-record.forestfuture.dev/several-databases
|
|
3592
4170
|
|
|
3593
4171
|
A Worker can bind several D1 databases. Each gets its own schema file and base class, and each Model queries the database its base class names.
|
|
3594
4172
|
|
|
@@ -3687,7 +4265,7 @@ The second write can still fail after the first one succeeds. A batch can’t jo
|
|
|
3687
4265
|
With read replication, give each database its own Session. Nest a `withSession` call for each, and give each its own cookie name:
|
|
3688
4266
|
|
|
3689
4267
|
```ts
|
|
3690
|
-
import { withSession } from "@forestfuture/
|
|
4268
|
+
import { withSession } from "@forestfuture/active-record/d1";
|
|
3691
4269
|
|
|
3692
4270
|
// src/worker.ts: each database's bookmark travels in its own cookie.
|
|
3693
4271
|
export const replicas = {
|
|
@@ -3705,7 +4283,7 @@ To pass per-request options without Sessions, such as `onQuery`, open the databa
|
|
|
3705
4283
|
|
|
3706
4284
|
```ts
|
|
3707
4285
|
import { withDatabase } from "@forestfuture/active-record";
|
|
3708
|
-
import { connect, type Database, type QueryListener } from "@forestfuture/
|
|
4286
|
+
import { connect, type Database, type QueryListener } from "@forestfuture/active-record/d1";
|
|
3709
4287
|
|
|
3710
4288
|
const onQuery: QueryListener = ({ sql }) => console.log(sql);
|
|
3711
4289
|
const databases: Database[] = [connect(env.DB, { onQuery }), connect(env.LOGS, { onQuery })];
|
|
@@ -3716,13 +4294,13 @@ return withDatabase(databases, handle); // each Model uses the one on its bindin
|
|
|
3716
4294
|
|
|
3717
4295
|
## Testing with several databases
|
|
3718
4296
|
|
|
3719
|
-
Outside a Worker, a Model can’t look up its binding. Give your tests the bindings by mocking `cloudflare:workers`. First, let Vitest’s mocks reach
|
|
4297
|
+
Outside a Worker, a Model can’t look up its binding. Give your tests the bindings by mocking `cloudflare:workers`. First, let Vitest’s mocks reach Active Record:
|
|
3720
4298
|
|
|
3721
4299
|
```ts vitest.config.ts
|
|
3722
4300
|
import { defineConfig } from "vitest/config";
|
|
3723
4301
|
|
|
3724
4302
|
export default defineConfig({
|
|
3725
|
-
test: { server: { deps: { inline: ["@forestfuture/
|
|
4303
|
+
test: { server: { deps: { inline: ["@forestfuture/active-record"] } } },
|
|
3726
4304
|
});
|
|
3727
4305
|
```
|
|
3728
4306
|
|
|
@@ -3753,7 +4331,7 @@ test("signing in logs an entry", async () => {
|
|
|
3753
4331
|
Each Model now finds its own database, as it does in a Worker. Call your Worker’s `fetch` without `withDatabase`.
|
|
3754
4332
|
|
|
3755
4333
|
:::note
|
|
3756
|
-
Assign the bindings onto the mocked `env` object, as above.
|
|
4334
|
+
Assign the bindings onto the mocked `env` object, as above. Active Record reads `env` the first time a Model needs its binding, so it never sees an object assigned later.
|
|
3757
4335
|
:::
|
|
3758
4336
|
|
|
3759
4337
|
## Opening one in the console
|
|
@@ -3767,7 +4345,7 @@ npx active-record console --database LOGS
|
|
|
3767
4345
|
---
|
|
3768
4346
|
|
|
3769
4347
|
# Shared behavior
|
|
3770
|
-
Source: https://
|
|
4348
|
+
Source: https://active-record.forestfuture.dev/shared-behavior
|
|
3771
4349
|
|
|
3772
4350
|
Every Model extends your app’s `ApplicationRecord`, so whatever you write on it, every Model has.
|
|
3773
4351
|
|
|
@@ -3872,7 +4450,7 @@ See [Multiple databases](/several-databases).
|
|
|
3872
4450
|
---
|
|
3873
4451
|
|
|
3874
4452
|
# Testing
|
|
3875
|
-
Source: https://
|
|
4453
|
+
Source: https://active-record.forestfuture.dev/testing
|
|
3876
4454
|
|
|
3877
4455
|
Test your Models and Worker against a real D1 database, with your migrations applied. [Miniflare](https://developers.cloudflare.com/workers/testing/miniflare/) runs Cloudflare’s runtime, D1 included, inside Node:
|
|
3878
4456
|
|
|
@@ -3911,7 +4489,7 @@ Outside a Worker there’s no binding, so run the test’s code inside `withData
|
|
|
3911
4489
|
|
|
3912
4490
|
```ts test/users.test.ts
|
|
3913
4491
|
import { withDatabase } from "@forestfuture/active-record";
|
|
3914
|
-
import { connect } from "@forestfuture/
|
|
4492
|
+
import { connect } from "@forestfuture/active-record/d1";
|
|
3915
4493
|
import { afterAll, beforeAll, expect, test } from "vitest";
|
|
3916
4494
|
import { User } from "../src/models/user";
|
|
3917
4495
|
import { testDatabase } from "./d1";
|
|
@@ -3936,7 +4514,7 @@ Call your Worker’s `fetch` handler inside `withDatabase` too, and its queries
|
|
|
3936
4514
|
|
|
3937
4515
|
```ts test/worker.test.ts
|
|
3938
4516
|
import { withDatabase } from "@forestfuture/active-record";
|
|
3939
|
-
import { connect } from "@forestfuture/
|
|
4517
|
+
import { connect } from "@forestfuture/active-record/d1";
|
|
3940
4518
|
import { afterAll, beforeAll, expect, test } from "vitest";
|
|
3941
4519
|
import worker from "../src/index";
|
|
3942
4520
|
import { testDatabase } from "./d1";
|
|
@@ -3966,7 +4544,7 @@ To run tests inside the Workers runtime itself, use Cloudflare’s [Vitest integ
|
|
|
3966
4544
|
---
|
|
3967
4545
|
|
|
3968
4546
|
# Untrusted input
|
|
3969
|
-
Source: https://
|
|
4547
|
+
Source: https://active-record.forestfuture.dev/untrusted-input
|
|
3970
4548
|
|
|
3971
4549
|
A request can send any fields it likes. Pick the ones you want before they reach a Model.
|
|
3972
4550
|
|
|
@@ -3987,7 +4565,7 @@ Permitted values are cast to their attribute’s types, so `"42"` becomes `42` f
|
|
|
3987
4565
|
|
|
3988
4566
|
> **Beyond Rails**
|
|
3989
4567
|
>
|
|
3990
|
-
> Rails’ `params.permit` only filters keys.
|
|
4568
|
+
> Rails’ `params.permit` only filters keys. Active Record’s also casts each value, and checks that each name is an attribute.
|
|
3991
4569
|
|
|
3992
4570
|
## Using a schema library
|
|
3993
4571
|
|
|
@@ -4048,12 +4626,70 @@ A value that can’t be cast matches nothing, so `whereNot({ id: "abc" })` exclu
|
|
|
4048
4626
|
|
|
4049
4627
|
---
|
|
4050
4628
|
|
|
4051
|
-
# Upgrading
|
|
4052
|
-
Source: https://
|
|
4629
|
+
# Upgrading
|
|
4630
|
+
Source: https://active-record.forestfuture.dev/upgrading
|
|
4631
|
+
|
|
4632
|
+
Each section moves an app up one release. Start from the release you’re on.
|
|
4633
|
+
|
|
4634
|
+
## Upgrading from 0.6 to 0.7
|
|
4635
|
+
|
|
4636
|
+
In 0.7, the adapters ship inside `@forestfuture/active-record`, so an app on D1 installs one package. Upgrade in four steps.
|
|
4637
|
+
|
|
4638
|
+
### Replacing the D1 package
|
|
4639
|
+
|
|
4640
|
+
Remove the D1 package, then update the core:
|
|
4641
|
+
|
|
4642
|
+
```sh
|
|
4643
|
+
npm uninstall @forestfuture/d1-record
|
|
4644
|
+
npm install @forestfuture/active-record@^0.7.0
|
|
4645
|
+
```
|
|
4646
|
+
|
|
4647
|
+
### Changing imports
|
|
4648
|
+
|
|
4649
|
+
Import what opens D1 from the core’s `/d1` entry:
|
|
4650
|
+
|
|
4651
|
+
```ts
|
|
4652
|
+
import { connect, d1, withSession } from "@forestfuture/active-record/d1";
|
|
4653
|
+
```
|
|
4654
|
+
|
|
4655
|
+
Everything else still comes from `@forestfuture/active-record`. If your Vitest config inlines the D1 adapter (`server.deps.inline`), inline `@forestfuture/active-record` instead.
|
|
4656
|
+
|
|
4657
|
+
### Writing `active-record.jsonc`
|
|
4658
|
+
|
|
4659
|
+
Run `init` in your project’s folder:
|
|
4660
|
+
|
|
4661
|
+
```sh
|
|
4662
|
+
npx active-record init
|
|
4663
|
+
```
|
|
4664
|
+
|
|
4665
|
+
It writes `active-record.jsonc`, naming each database in your Wrangler config’s `d1_databases` and its adapter:
|
|
4666
|
+
|
|
4667
|
+
```jsonc
|
|
4668
|
+
{
|
|
4669
|
+
"$schema": "./node_modules/@forestfuture/active-record/config-schema.json",
|
|
4670
|
+
"databases": {
|
|
4671
|
+
"DB": { "adapter": "d1" },
|
|
4672
|
+
},
|
|
4673
|
+
}
|
|
4674
|
+
```
|
|
4675
|
+
|
|
4676
|
+
Every `active-record` command reads it. Each database’s migrations folder stays in your Wrangler config. `--adapter` is gone, and `--config` now names this file.
|
|
4677
|
+
|
|
4678
|
+
### Regenerating the schema
|
|
4679
|
+
|
|
4680
|
+
Regenerate your schema:
|
|
4681
|
+
|
|
4682
|
+
```sh
|
|
4683
|
+
npx active-record schema
|
|
4684
|
+
```
|
|
4685
|
+
|
|
4686
|
+
Its import changes to `@forestfuture/active-record/d1`. Until you regenerate it, `active-record schema --check` reports it as out of date.
|
|
4687
|
+
|
|
4688
|
+
## Upgrading from d1-record 0.5 to 0.6
|
|
4053
4689
|
|
|
4054
4690
|
In 0.6, the library is two packages. `@forestfuture/active-record` is the core: Models, Relations, validations, callbacks, and associations. `@forestfuture/d1-record` is its adapter for D1. Upgrade in four steps.
|
|
4055
4691
|
|
|
4056
|
-
|
|
4692
|
+
### Installing both packages
|
|
4057
4693
|
|
|
4058
4694
|
Install the core beside the adapter:
|
|
4059
4695
|
|
|
@@ -4063,7 +4699,7 @@ npm install @forestfuture/active-record@^0.6.0 @forestfuture/d1-record@^0.6.0
|
|
|
4063
4699
|
|
|
4064
4700
|
Both packages share a version, so keep them on the same one.
|
|
4065
4701
|
|
|
4066
|
-
|
|
4702
|
+
### Changing imports
|
|
4067
4703
|
|
|
4068
4704
|
Import from the core everything that isn’t about D1. Import from the adapter what opens D1:
|
|
4069
4705
|
|
|
@@ -4086,7 +4722,7 @@ import { connect, d1, withSession } from "@forestfuture/d1-record";
|
|
|
4086
4722
|
|
|
4087
4723
|
`d1-record` re-exports nothing of the core, so an import of `Model` from it fails.
|
|
4088
4724
|
|
|
4089
|
-
|
|
4725
|
+
### Regenerating the schema
|
|
4090
4726
|
|
|
4091
4727
|
Run the schema command under its new name:
|
|
4092
4728
|
|
|
@@ -4096,7 +4732,7 @@ npx active-record schema
|
|
|
4096
4732
|
|
|
4097
4733
|
The generated schema now names its adapter, `adapter: d1({ binding: "DB" })`, where it named only the binding. Your base class needs no change.
|
|
4098
4734
|
|
|
4099
|
-
|
|
4735
|
+
### Running `active-record`
|
|
4100
4736
|
|
|
4101
4737
|
The command is now `active-record`, or `ffar` for short. Swap it in your scripts and CI:
|
|
4102
4738
|
|
|
@@ -4108,7 +4744,7 @@ The command is now `active-record`, or `ffar` for short. Swap it in your scripts
|
|
|
4108
4744
|
|
|
4109
4745
|
It also applies migrations through your project’s Wrangler, with `npx active-record migrate`. See [Command line](/command-line#active-record-migrate).
|
|
4110
4746
|
|
|
4111
|
-
|
|
4747
|
+
### Updating for the other changes
|
|
4112
4748
|
|
|
4113
4749
|
- **Write results:** `insert`, `insertAll`, `upsert`, and `upsertAll` resolve to `{ rowsAffected, rows }`, where they resolved to D1’s `meta`. `rows` holds each written row’s primary key, or the attributes its `returning` option names. Use `rowsAffected` for `meta.changes`, and `rows[0]?.id` for `meta.last_row_id`. A statement in `batch` resolves to the same.
|
|
4114
4750
|
- **The base error** is `ActiveRecordError`, where it was `D1RecordError`.
|
|
@@ -4119,7 +4755,7 @@ It also applies migrations through your project’s Wrangler, with `npx active-r
|
|
|
4119
4755
|
---
|
|
4120
4756
|
|
|
4121
4757
|
# Validations
|
|
4122
|
-
Source: https://
|
|
4758
|
+
Source: https://active-record.forestfuture.dev/validations
|
|
4123
4759
|
|
|
4124
4760
|
Validations check a record before it’s saved. An invalid record isn’t saved, and its `errors` say why.
|
|
4125
4761
|
|
|
@@ -4394,4 +5030,4 @@ With a count of 1, the three `length` messages say “1 character”. `restrictD
|
|
|
4394
5030
|
|
|
4395
5031
|
> **Compared with Rails**
|
|
4396
5032
|
>
|
|
4397
|
-
> Rails looks messages up in its locale files, in nearly the same order: the Model’s, then its ancestors’, then the shared ones. Among the shared ones, Rails tries a message for the type before one for the attribute. Your base class tries the attribute’s first, as every class does.
|
|
5033
|
+
> Rails looks messages up in its locale files, in nearly the same order: the Model’s, then its ancestors’, then the shared ones. Among the shared ones, Rails tries a message for the type before one for the attribute. Your base class tries the attribute’s first, as every class does. Active Record keeps messages on the classes instead, so a Model’s messages sit next to its validations. Their keys are Active Record’s error types, in camelCase. Rails shows “Translation missing” for a type with no message, where Active Record throws when the error is added. Messages in other languages aren’t here yet.
|