@forestfuture/active-record 0.0.0 → 0.6.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/LICENSE +21 -0
- package/README.md +26 -2
- package/dist/adapter-BSvFhTDf.d.mts +1293 -0
- package/dist/adapter.d.mts +2 -0
- package/dist/adapter.mjs +3 -0
- package/dist/batch-DBeYk5wx.mjs +4171 -0
- package/dist/cli.d.mts +197 -0
- package/dist/cli.mjs +3 -0
- package/dist/command.d.mts +1 -0
- package/dist/command.mjs +2157 -0
- package/dist/epoch-storage-o2aoOH7H.mjs +112 -0
- package/dist/generated-model-CfDggoVN.mjs +1853 -0
- package/dist/index.d.mts +143 -0
- package/dist/index.mjs +3 -0
- package/dist/storage-override-BYBYP8Mj.mjs +91 -0
- package/llms-full.txt +4397 -0
- package/package.json +42 -4
- package/skills/active-record/SKILL.md +88 -0
package/llms-full.txt
ADDED
|
@@ -0,0 +1,4397 @@
|
|
|
1
|
+
# d1-record
|
|
2
|
+
|
|
3
|
+
> A Rails-inspired Active Record for Cloudflare Workers and D1.
|
|
4
|
+
|
|
5
|
+
# Active Record for Cloudflare D1
|
|
6
|
+
Source: https://d1-record.forestfuture.dev/
|
|
7
|
+
|
|
8
|
+
```package-install
|
|
9
|
+
npm install @forestfuture/active-record @forestfuture/d1-record
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
**[Get started](/getting-started)**
|
|
13
|
+
|
|
14
|
+
From an empty Worker to two related Models in about ten minutes.
|
|
15
|
+
|
|
16
|
+
Read the tutorial
|
|
17
|
+
|
|
18
|
+
**[Coming from Rails](/coming-from-rails)**
|
|
19
|
+
|
|
20
|
+
What carries over from Active Record, and what D1 changes.
|
|
21
|
+
|
|
22
|
+
See what’s different
|
|
23
|
+
|
|
24
|
+
## A Model and its queries
|
|
25
|
+
|
|
26
|
+
```ts Model
|
|
27
|
+
import { hasMany } from "@forestfuture/active-record";
|
|
28
|
+
import { ApplicationRecord } from "./application-record";
|
|
29
|
+
import { Post } from "./post";
|
|
30
|
+
|
|
31
|
+
export class User extends ApplicationRecord {
|
|
32
|
+
posts = hasMany(Post, { dependent: "destroy" }); // posts.user_id points here
|
|
33
|
+
|
|
34
|
+
static active = this.scope((q) => q.where({ isActive: true }));
|
|
35
|
+
|
|
36
|
+
static {
|
|
37
|
+
this.validates("email", { presence: true, uniqueness: true });
|
|
38
|
+
this.beforeSave((user) => {
|
|
39
|
+
user.email = user.email.toLowerCase();
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
```ts Querying
|
|
46
|
+
import { User } from "./models";
|
|
47
|
+
|
|
48
|
+
User.where({ role: "admin", isActive: true }); // role = ? AND is_active = ?
|
|
49
|
+
User.where({ role: null }); // role IS NULL
|
|
50
|
+
User.where({ role: ["admin", "editor"] }); // role IN (…), any number of values
|
|
51
|
+
User.whereNot({ role: "admin" }); // NOT (role = ?)
|
|
52
|
+
User.where({ role: "admin" }).or(User.where({ isActive: false }));
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
```ts Saving
|
|
56
|
+
import { User } from "./models";
|
|
57
|
+
|
|
58
|
+
const user = User.build({ email: "ada@example.com" });
|
|
59
|
+
if (await user.save()) {
|
|
60
|
+
// saved: user.isPersisted() is true
|
|
61
|
+
} else {
|
|
62
|
+
console.log(user.errors.fullMessages()); // ["Email has already been taken"]
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const created = await User.create({ email: "grace@example.com" }); // saved, or not
|
|
66
|
+
await created.update({ isActive: false }); // true or false
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
```ts Batches
|
|
70
|
+
import { batch } from "@forestfuture/active-record";
|
|
71
|
+
import { Article, Author } from "./models";
|
|
72
|
+
|
|
73
|
+
const authorId = crypto.randomUUID(); // generated in code, so rows can point at it
|
|
74
|
+
await batch([
|
|
75
|
+
Author.toInsert({ id: authorId, name: "Grace" }),
|
|
76
|
+
Article.toInsert({ authorId, title: "Hello" }),
|
|
77
|
+
Article.where({ authorId: "author-1" }).toDeleteAll(),
|
|
78
|
+
]);
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
```sql Table
|
|
82
|
+
CREATE TABLE posts (
|
|
83
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
84
|
+
user_id TEXT NOT NULL REFERENCES users (id),
|
|
85
|
+
title TEXT NOT NULL,
|
|
86
|
+
published_at DATETIME,
|
|
87
|
+
created_at DATETIME NOT NULL,
|
|
88
|
+
updated_at DATETIME NOT NULL
|
|
89
|
+
);
|
|
90
|
+
CREATE INDEX index_posts_on_user_id ON posts (user_id);
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## What’s inside
|
|
94
|
+
|
|
95
|
+
**[Models, declared once](/models)**
|
|
96
|
+
|
|
97
|
+
Typed attributes come from your tables, camelCase in your code and snake_case in SQL, with
|
|
98
|
+
defaults, timestamps, dates, and JSON converted both ways.
|
|
99
|
+
|
|
100
|
+
**[Lazy, composable queries](/querying)**
|
|
101
|
+
|
|
102
|
+
Conditions, ordering, pagination, scopes, and preloading with one query per association, never
|
|
103
|
+
N+1. Hand-written SQL goes through a tagged template, so values are always bound.
|
|
104
|
+
|
|
105
|
+
**[A predictable lifecycle](/persistence)**
|
|
106
|
+
|
|
107
|
+
`save`, `create`, `update`, and `destroy` run validations and callbacks in a predictable order,
|
|
108
|
+
with dirty tracking and dependent strategies. Methods that throw end in `OrThrow`.
|
|
109
|
+
|
|
110
|
+
**[Atomic where D1 allows](/batches)**
|
|
111
|
+
|
|
112
|
+
D1 can’t hold a transaction open across awaits, so `batch` writes a set of statements and
|
|
113
|
+
records all at once, or not at all. Keys generated in code let a whole graph save in one batch.
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
# Existing databases
|
|
118
|
+
Source: https://d1-record.forestfuture.dev/adopt-a-database
|
|
119
|
+
|
|
120
|
+
d1-record reads a database’s tables from its migrations. If your database already has migrations, from Drizzle, Prisma, or Wrangler, point d1-record at them. If it doesn’t, start from a snapshot of its schema.
|
|
121
|
+
|
|
122
|
+
## Using Drizzle’s migrations
|
|
123
|
+
|
|
124
|
+
Drizzle writes its migrations to `drizzle/`, its `out` setting. Tell Wrangler where they are:
|
|
125
|
+
|
|
126
|
+
```jsonc wrangler.jsonc
|
|
127
|
+
{
|
|
128
|
+
"d1_databases": [
|
|
129
|
+
// Migrations as drizzle/0000_name.sql:
|
|
130
|
+
{ "binding": "DB", "database_name": "my-app-db", "migrations_dir": "drizzle" },
|
|
131
|
+
// Or, as drizzle/<timestamp>_name/migration.sql:
|
|
132
|
+
// { …, "migrations_pattern": "drizzle/*/migration.sql" },
|
|
133
|
+
],
|
|
134
|
+
}
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Drizzle’s own schema often lives at `src/db/schema.ts` or in `src/db/schema/`, where d1-record writes its schema by default. Generate d1-record’s elsewhere:
|
|
138
|
+
|
|
139
|
+
```sh
|
|
140
|
+
npx active-record schema --out src/db/d1-record.ts
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
If `src/models/application-record.ts` already exists, point it at the new file with `import { tables } from "../db/d1-record";`. A new one imports it already.
|
|
144
|
+
|
|
145
|
+
Pass `--out` to every later `schema` and `g` command, or keep it in a `package.json` script.
|
|
146
|
+
|
|
147
|
+
:::note
|
|
148
|
+
Without `--out`, d1-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
|
+
:::
|
|
150
|
+
|
|
151
|
+
## Using Prisma’s migrations
|
|
152
|
+
|
|
153
|
+
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
|
+
|
|
155
|
+
Prisma names tables after its models, such as `User`, and columns in camelCase, such as `createdAt`. d1-record keeps both names, so the Model sets its table, `static override table = "User"`, and has attributes such as `createdAt`.
|
|
156
|
+
|
|
157
|
+
:::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`. d1-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
|
+
:::
|
|
160
|
+
|
|
161
|
+
## Comparing dates in two forms
|
|
162
|
+
|
|
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`). d1-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
|
+
|
|
165
|
+
To make the rows match, rewrite them once in a migration, with your own table and column:
|
|
166
|
+
|
|
167
|
+
```sql
|
|
168
|
+
UPDATE reminders
|
|
169
|
+
SET created_at = strftime('%Y-%m-%dT%H:%M:%fZ', created_at)
|
|
170
|
+
WHERE strftime('%Y-%m-%dT%H:%M:%fZ', created_at) <> created_at;
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
It writes d1-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
|
+
|
|
175
|
+
If another tool still writes the other form, compare through `strftime` in a fragment instead:
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
import { column, sql } from "@forestfuture/active-record";
|
|
179
|
+
|
|
180
|
+
export function createdSince(since: Date) {
|
|
181
|
+
const createdAt = column("createdAt");
|
|
182
|
+
return Reminder.where(
|
|
183
|
+
sql`strftime('%Y-%m-%dT%H:%M:%fZ', ${createdAt}) >= ${createdAt.value(since)}`,
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export function oldestFirst() {
|
|
188
|
+
const createdAt = column("createdAt");
|
|
189
|
+
return Reminder.order(sql`strftime('%Y-%m-%dT%H:%M:%fZ', ${createdAt})`);
|
|
190
|
+
}
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
`strftime` reads every form SQLite knows and writes d1-record’s ISO text, so rows in either form compare and sort as the times they are.
|
|
194
|
+
|
|
195
|
+
:::note
|
|
196
|
+
A wrapped column can’t use its index for that condition, so SQLite reads the whole table.
|
|
197
|
+
:::
|
|
198
|
+
|
|
199
|
+
## Starting with no migrations
|
|
200
|
+
|
|
201
|
+
For a database built by hand, or by `drizzle-kit push`, export a snapshot of its schema as the first migration, and mark it as applied:
|
|
202
|
+
|
|
203
|
+
```sh
|
|
204
|
+
# The tables, without their data, as a first migration:
|
|
205
|
+
npx wrangler d1 export my-app-db --remote --no-data --output migrations/0001_baseline.sql
|
|
206
|
+
|
|
207
|
+
# Create Wrangler's record of applied migrations, and mark the snapshot as applied,
|
|
208
|
+
# so Wrangler never runs it against the database it came from:
|
|
209
|
+
npx wrangler d1 migrations list my-app-db --remote
|
|
210
|
+
npx wrangler d1 execute my-app-db --remote --command "INSERT INTO d1_migrations (name) VALUES ('0001_baseline.sql')"
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
From then on, change tables with new migrations. See [Schema changes](/change-a-table).
|
|
214
|
+
|
|
215
|
+
## Checking the generated attributes
|
|
216
|
+
|
|
217
|
+
Other tools can store values differently, so a column can become the wrong attribute type, and fail when it’s read. When `active-record schema` recognizes Drizzle’s or Prisma’s migrations, it prints a note for each column worth checking:
|
|
218
|
+
|
|
219
|
+
```
|
|
220
|
+
Note: these migrations look like Drizzle's. Some columns may convert to the wrong type and fail when read, especially numeric timestamps: check the generated types (…)
|
|
221
|
+
Note: posts.metadata: read as a string; if it holds JSON, override it as "json" in its Model
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
Fix a column’s type with an override in its Model. It changes how the column is read and written, never the table:
|
|
225
|
+
|
|
226
|
+
```ts
|
|
227
|
+
export class Post extends ApplicationRecord {
|
|
228
|
+
static override attributes = {
|
|
229
|
+
metadata: "json", // text({ mode: "json" }): JSON in a plain TEXT column
|
|
230
|
+
archived: "boolean", // integer({ mode: "boolean" }): 0 or 1
|
|
231
|
+
legacyNotes: false, // a column this app no longer uses: never read or written
|
|
232
|
+
} as const;
|
|
233
|
+
}
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
## Reading Unix timestamps
|
|
237
|
+
|
|
238
|
+
Read a Unix timestamp column as a `Date` by overriding it as a `datetime` with the matching `storage`. Drizzle’s `integer({ mode: "timestamp" })` stores seconds, and `"timestamp_ms"` stores milliseconds:
|
|
239
|
+
|
|
240
|
+
```ts
|
|
241
|
+
import { gte } from "@forestfuture/active-record";
|
|
242
|
+
|
|
243
|
+
export class Article extends ApplicationRecord {
|
|
244
|
+
static override attributes = {
|
|
245
|
+
publishedAt: { type: "datetime", storage: "unixSeconds" }, // timestamp: seconds
|
|
246
|
+
updatedAt: { type: "datetime", storage: "unixMilliseconds" }, // timestamp_ms: milliseconds
|
|
247
|
+
} as const;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export function publishedSince(since: Date) {
|
|
251
|
+
return Article.where({ publishedAt: gte(since) });
|
|
252
|
+
}
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
| Drizzle mode | `storage` |
|
|
256
|
+
| ---------------- | -------------------- |
|
|
257
|
+
| `"timestamp"` | `"unixSeconds"` |
|
|
258
|
+
| `"timestamp_ms"` | `"unixMilliseconds"` |
|
|
259
|
+
|
|
260
|
+
The column stays an `INTEGER`. `createdAt` and `updatedAt` declared this way are written as integers too, and `where` and `between` take `Date`s.
|
|
261
|
+
|
|
262
|
+
Under `unixSeconds`, a `Date` is stored to the second, so a condition such as `lt(date)` compares to the second too.
|
|
263
|
+
|
|
264
|
+
:::warning[A Date in an sql fragment]
|
|
265
|
+
A `Date` beside that column in a `sql` fragment throws `TypeError`: a fragment has no attribute, so it would bind as ISO text. Use `column("publishedAt").value(date)`, which writes it as the attribute stores it. See [Writing SQL fragments](/querying#writing-sql-fragments).
|
|
266
|
+
:::
|
|
267
|
+
|
|
268
|
+
:::note
|
|
269
|
+
In a raw `env.DB.prepare(...)` statement, bind `Article.typeForAttribute("publishedAt").serialize(date)`, and read a cell with `deserialize`. See [Using raw statements](/querying#using-raw-statements).
|
|
270
|
+
:::
|
|
271
|
+
|
|
272
|
+
:::note
|
|
273
|
+
Prisma’s dates need no override. On D1, Prisma writes a `DateTime` as ISO text, which d1-record reads as it is.
|
|
274
|
+
:::
|
|
275
|
+
|
|
276
|
+
> **Beyond Rails**
|
|
277
|
+
>
|
|
278
|
+
> Active Record has no option for a date kept as an integer; there it takes a custom attribute type. In d1-record it’s a `storage` on the `datetime`.
|
|
279
|
+
|
|
280
|
+
## Fixing cells of the wrong type
|
|
281
|
+
|
|
282
|
+
A cell that isn’t the attribute’s type fails when the record loads or `pluck` reads it, naming the Model and attribute:
|
|
283
|
+
|
|
284
|
+
```text
|
|
285
|
+
TypeError: Article: 1767323045 isn't a datetime for "publishedAt"
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
Find the cells by their SQLite type:
|
|
289
|
+
|
|
290
|
+
```sql
|
|
291
|
+
SELECT typeof(published_at), count(*) FROM articles GROUP BY 1;
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
Then fix the cause:
|
|
295
|
+
|
|
296
|
+
- If the column holds Unix times, declare the [`storage`](#reading-unix-timestamps) so they’re read as one.
|
|
297
|
+
- If the attribute’s type is wrong, override it with the type the column holds.
|
|
298
|
+
- If a few rows hold the wrong thing, `UPDATE` them.
|
|
299
|
+
- If the column isn’t used, ignore it with `false` in the override.
|
|
300
|
+
|
|
301
|
+
:::note
|
|
302
|
+
SQLite converts a value to the column’s declared type only when it can: `'42'` in an `INTEGER` column is stored as 42, and `'abc'` stays text.
|
|
303
|
+
:::
|
|
304
|
+
|
|
305
|
+
---
|
|
306
|
+
|
|
307
|
+
# AI agents
|
|
308
|
+
Source: https://d1-record.forestfuture.dev/ai-agents
|
|
309
|
+
|
|
310
|
+
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
|
+
|
|
312
|
+
## Giving your agent the docs
|
|
313
|
+
|
|
314
|
+
| Resource | What it is |
|
|
315
|
+
| ----------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
316
|
+
| [`llms.txt`](https://d1-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. |
|
|
317
|
+
| [`llms-full.txt`](https://d1-record.forestfuture.dev/llms-full.txt) | The whole guide in one Markdown file, about 55K tokens. |
|
|
318
|
+
| Any page + `.md` | Every page as Markdown: [`/associations.md`](https://d1-record.forestfuture.dev/associations.md). |
|
|
319
|
+
| [The agent skill](https://d1-record.forestfuture.dev/.well-known/agent-skills/active-record/SKILL.md) | The skill below, published where agents look for a site’s skills. |
|
|
320
|
+
| `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
|
+
|
|
322
|
+
## Installing the agent skill
|
|
323
|
+
|
|
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 d1-record code:
|
|
325
|
+
|
|
326
|
+
```sh
|
|
327
|
+
npx skills add forestfuture/active-record
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
To install the copy shipped with your installed version, sync skills from `node_modules`:
|
|
331
|
+
|
|
332
|
+
```sh
|
|
333
|
+
npx skills experimental_sync
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
:::note
|
|
337
|
+
The skills CLI marks `experimental_sync` as experimental, so its name may change.
|
|
338
|
+
:::
|
|
339
|
+
|
|
340
|
+
## Pointing AGENTS.md at the guide
|
|
341
|
+
|
|
342
|
+
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
|
+
|
|
344
|
+
```md
|
|
345
|
+
Before writing code with `@forestfuture/active-record` or `@forestfuture/d1-record`, read the part of `node_modules/@forestfuture/active-record/llms-full.txt` for the task.
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
The line names the guide shipped with your installed version, so it stays correct after an upgrade.
|
|
349
|
+
|
|
350
|
+
## Using the rules without a skill
|
|
351
|
+
|
|
352
|
+
Skip this section if you’ve installed the skill: the block below is the skill’s rules, and the agent would read them twice. For an agent that reads only `AGENTS.md` or `CLAUDE.md`, paste it into yours:
|
|
353
|
+
|
|
354
|
+
```md
|
|
355
|
+
|
|
356
|
+
Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for Cloudflare Workers, with an adapter per database: `@forestfuture/d1-record` for D1. Import Models, Relations, and errors from the core, and `connect`, `withSession`, `NoSession`, and `d1` from the 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
|
+
|
|
358
|
+
- 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
|
+
- 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.
|
|
360
|
+
- Start queries and new records from the Model, as in Rails: `User.find(id)`, `User.where(…)`, `User.build(…)`. Each Model queries the binding named in the generated schema its base class holds, during a request. For a D1 Session, wrap the handler in `withSession(request, env.DB, fn)`. For per-request `onQuery`, or tests and scripts outside a Worker, wrap the code once in `withDatabase(connect(env.DB, { … }), fn)`. Records keep the database they came from.
|
|
361
|
+
- Never pass a request's whole body, form or query string to a Model: name the fields, with destructuring or `User.permit(await request.json(), "email", "name")` (it reads `FormData` and `URLSearchParams` too). Assigned values are checked against the attribute's type, but that doesn't stop a user setting `role` or `isAdmin`. Check a request value's type before querying with it: `findBy({ token: null })` matches rows whose token is NULL.
|
|
362
|
+
- Name attributes in camelCase everywhere: `where`, `order`, `pluck`, `foreignKey`. Column names (snake_case) appear only inside `sql` fragments.
|
|
363
|
+
- Write custom SQL as an `sql` tagged template, which binds every value: ``where(sql`lower(${column("email")}) = ${email}`)``. Interpolate an attribute's value with `column("publishedAt").value(date)`, not the bare `Date`, when the attribute is stored as a Unix time: a bare `Date` is ISO text, and it throws `TypeError` when it's compared directly with that column.
|
|
364
|
+
- For a raw `env.DB.prepare(…).bind(…)` statement, bind `Post.typeForAttribute("publishedAt").serialize(date)`, which writes the value as the attribute stores it, and read a cell with `.deserialize(cell)`. A value the attribute can't hold throws `TypeError`.
|
|
365
|
+
- Bulk writes run when called: `await posts.deleteAll()` and `updateAll(…)` resolve to how many rows; `insert(…)`, `insertAll`, `upsert` and `upsertAll` to `{ rowsAffected, rows }`, where `rows` holds each written row's primary key, or the attributes `returning: [...]` names (`returning: false` for none). Make several writes atomic with one `batch([...])` of their `to…` forms (`toInsert`, `toUpdateAll`, `toDeleteAll`, …) and records' `toSave()`/`toDestroy()`. D1 has no interactive transactions, so a read-then-write can't be atomic.
|
|
366
|
+
- Keep the generators' `TEXT` keys, generated in code, for records saved together (`--id integer` gives a key D1 generates instead). An owner whose key is known before its INSERT (generated in code, or already saved) is written in one atomic batch with the records built through it. A key D1 generates exists only after its own write, so each level is then written in a separate batch.
|
|
367
|
+
- To change how those keys are made (UUIDv7, ULID, a prefix), override `static generateId` once on the app's base class; don't give each Model's key a `default`. `generateId` sees only the attribute's name, so a value made from other attributes (a slug) goes in a callback.
|
|
368
|
+
- Declare associations as fields, passing the target class: `posts = hasMany(Post, { dependent: "destroy" })`, `author = belongsTo(User)`. The field's name is the association's name.
|
|
369
|
+
- Change the copy of validation messages with `this.errorMessages({...})` in the `static {}` block of the app's base class (every Model) or a Model (`attributes: { email: { taken: "…" } }` for one attribute), and attribute names with `this.humanAttributeNames({...})`, rather than a `message` on every `validates`. For a custom error, `errors.add("endsAt", { type: "afterStart" })` and give `afterStart` a message there.
|
|
370
|
+
- Check what writes return. `save()` and `update()` resolve to `false` when validation fails (reasons in `record.errors`) or a callback aborts (`record.abortReason`). `destroy()` resolves to `false` when a callback aborts, or a `restrictWithError` association refuses (reason in `record.errors`). The `…OrThrow` methods throw instead. Constraint errors, such as `RecordNotUnique`, always throw.
|
|
371
|
+
|
|
372
|
+
```
|
|
373
|
+
|
|
374
|
+
Copy it again after upgrading Active Record, since the rules can change.
|
|
375
|
+
|
|
376
|
+
---
|
|
377
|
+
|
|
378
|
+
# Associations
|
|
379
|
+
Source: https://d1-record.forestfuture.dev/associations
|
|
380
|
+
|
|
381
|
+
Associations connect Models: `belongsTo`, `hasMany`, and `hasOne`.
|
|
382
|
+
|
|
383
|
+
## Defining associations
|
|
384
|
+
|
|
385
|
+
Declare each association as a field, passing the target Model’s class. The field’s name is the association’s name:
|
|
386
|
+
|
|
387
|
+
```ts
|
|
388
|
+
import { belongsTo, hasMany, hasOne, Model } from "@forestfuture/active-record";
|
|
389
|
+
|
|
390
|
+
export class Author extends Model.define({
|
|
391
|
+
id: { type: "string", null: false, generateId: true },
|
|
392
|
+
name: { type: "string", null: false },
|
|
393
|
+
}) {
|
|
394
|
+
articles = hasMany(Article, { dependent: "destroy" }); // Article's authorId
|
|
395
|
+
profile = hasOne(Profile, { dependent: "delete" }); // Profile's authorId
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
export class Article extends Model.define({
|
|
399
|
+
id: { type: "string", null: false, generateId: true },
|
|
400
|
+
authorId: { type: "string", null: false },
|
|
401
|
+
title: { type: "string", null: false },
|
|
402
|
+
}) {
|
|
403
|
+
author = belongsTo(Author); // its own authorId
|
|
404
|
+
comments = hasMany(Comment, { dependent: "deleteAll" }); // Comment's articleId
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
export class Profile extends Model.define({
|
|
408
|
+
id: { type: "integer", null: false },
|
|
409
|
+
authorId: { type: "string", null: false },
|
|
410
|
+
bio: "string",
|
|
411
|
+
}) {}
|
|
412
|
+
|
|
413
|
+
export class Comment extends Model.define({
|
|
414
|
+
id: { type: "integer", null: false },
|
|
415
|
+
articleId: { type: "string", null: false },
|
|
416
|
+
body: { type: "string", null: false },
|
|
417
|
+
}) {}
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
Models can refer to each other in any order. A subclass inherits its parent’s associations, and can redeclare one to change it.
|
|
421
|
+
|
|
422
|
+
## belongsTo
|
|
423
|
+
|
|
424
|
+
Use `belongsTo` on the Model whose table holds the foreign key. A post belongs to its author:
|
|
425
|
+
|
|
426
|
+
```ts
|
|
427
|
+
const article = await Article.find(articleId);
|
|
428
|
+
const author = await article.author(); // an Author, or null
|
|
429
|
+
|
|
430
|
+
article.author.set(editor); // points it at another author: written when the article is saved
|
|
431
|
+
await article.save();
|
|
432
|
+
```
|
|
433
|
+
|
|
434
|
+
- **`await record.author()`** reads the associated record, or `null`.
|
|
435
|
+
- **`record.author.set(user)`** points the record at another record, and `set(null)` clears it. It’s written when the record is saved.
|
|
436
|
+
- **`record.author.build(attrs)`** builds a record to point at. It’s validated with the record, and saved before it, so the foreign key can be filled in.
|
|
437
|
+
- **`record.author.create(attrs)`** and **`createOrThrow(attrs)`** save a new record at once, and point at it. The record itself isn’t saved.
|
|
438
|
+
|
|
439
|
+
| Option | Does |
|
|
440
|
+
| ------------ | ------------------------------------------------------------------------------------------- |
|
|
441
|
+
| `foreignKey` | The attribute on this record that holds the link. Defaults to the association’s name + `Id` |
|
|
442
|
+
| `primaryKey` | The attribute on the target it points at. Defaults to the target’s primary key |
|
|
443
|
+
| `scope` | Narrows the target, `(q) => q.where(…)`. See [Scoping associations](#scoping-associations) |
|
|
444
|
+
|
|
445
|
+
## hasMany
|
|
446
|
+
|
|
447
|
+
Use `hasMany` on the Model the other table’s foreign key points at. A user has many posts:
|
|
448
|
+
|
|
449
|
+
```ts
|
|
450
|
+
const author = await Author.find(authorId);
|
|
451
|
+
const articles = await author.articles().toArray(); // a Relation of the author's articles
|
|
452
|
+
|
|
453
|
+
author.articles().build({ title: "Untitled" }); // saved with the author, with its key
|
|
454
|
+
await author.save();
|
|
455
|
+
|
|
456
|
+
await author.articles().where({ title: "Untitled" }).deleteAll(); // bulk writes, scoped to the author
|
|
457
|
+
```
|
|
458
|
+
|
|
459
|
+
- **`record.posts()`** is a Relation of the associated records, with every Relation method and the target’s scopes.
|
|
460
|
+
- **`record.posts().build(attrs)`** builds a record with the owner’s key, saved with the owner. See [Autosaving](#autosaving).
|
|
461
|
+
- **`record.posts().create(attrs)`** and **`createOrThrow(attrs)`** save a new record at once. The owner must already be saved.
|
|
462
|
+
- **`insert`, `updateAll`, and `deleteAll`** write to the owner’s records. See [Writing many rows](#writing-many-rows).
|
|
463
|
+
|
|
464
|
+
| Option | Does |
|
|
465
|
+
| ------------ | ---------------------------------------------------------------------------------------------------------------- |
|
|
466
|
+
| `foreignKey` | The attribute on the target’s records that holds the link. Defaults to this Model’s class name + `Id` |
|
|
467
|
+
| `primaryKey` | The attribute on this record the foreign key points at. Defaults to the primary key |
|
|
468
|
+
| `scope` | Narrows or orders the records, `(q) => q.order(…)`. See [Scoping associations](#scoping-associations) |
|
|
469
|
+
| `dependent` | What destroying the owner does to the records. See [Destroying dependent records](#destroying-dependent-records) |
|
|
470
|
+
|
|
471
|
+
## hasOne
|
|
472
|
+
|
|
473
|
+
Use `hasOne` like `hasMany`, when there’s at most one record. A user has one profile:
|
|
474
|
+
|
|
475
|
+
```ts
|
|
476
|
+
const author = await Author.find(authorId);
|
|
477
|
+
const profile = await author.profile(); // a Profile, or null
|
|
478
|
+
|
|
479
|
+
if (profile === null) await author.profile.create({ bio: "Writer" }); // saved at once
|
|
480
|
+
```
|
|
481
|
+
|
|
482
|
+
- **`await record.profile()`** reads the associated record, or `null`. If several records point at the owner, it’s the first by the scope’s order, then the primary key.
|
|
483
|
+
- **`record.profile.build(attrs)`** builds a record with the owner’s key, saved with the owner.
|
|
484
|
+
- **`record.profile.create(attrs)`** and **`createOrThrow(attrs)`** save a new record at once. The owner must already be saved.
|
|
485
|
+
|
|
486
|
+
`hasOne` takes the same options as `hasMany`.
|
|
487
|
+
|
|
488
|
+
## Naming foreign keys
|
|
489
|
+
|
|
490
|
+
A foreign key names an attribute, such as `authorId`, rather than a column. By default, it’s inferred:
|
|
491
|
+
|
|
492
|
+
- **`belongsTo`** uses the association’s name + `Id`. `author = belongsTo(Author)` uses the record’s own `authorId`.
|
|
493
|
+
- **`hasMany` and `hasOne`** use the Model’s class name + `Id`, on the target. `Author`’s associations use `authorId`, `BlogPost`’s use `blogPostId`, and `APIKey`’s use `apiKeyId`.
|
|
494
|
+
|
|
495
|
+
If the name doesn’t follow the convention, pass `foreignKey`:
|
|
496
|
+
|
|
497
|
+
```ts
|
|
498
|
+
import { belongsTo } from "@forestfuture/active-record";
|
|
499
|
+
|
|
500
|
+
export class Post extends ApplicationRecord {
|
|
501
|
+
author = belongsTo(User, { foreignKey: "userId" });
|
|
502
|
+
}
|
|
503
|
+
```
|
|
504
|
+
|
|
505
|
+
Keys are checked the first time a Model is used, and a missing attribute throws `InvalidModel`.
|
|
506
|
+
|
|
507
|
+
**Bundlers and class names**
|
|
508
|
+
|
|
509
|
+
Wrangler keeps class names by default, even when minifying. If a bundler renames `Author` to `e`, the inferred `eId` doesn’t exist, and the first use of the Model throws `InvalidModel`, saying where the key came from. Pass `foreignKey`, or keep class names in your bundler’s settings.
|
|
510
|
+
|
|
511
|
+
## Caching loaded records
|
|
512
|
+
|
|
513
|
+
A loaded association is cached on the record. Reading `author()` again doesn’t query, and neither does `articles().toArray()` once the collection is loaded:
|
|
514
|
+
|
|
515
|
+
```ts
|
|
516
|
+
const article = await Article.find(articleId);
|
|
517
|
+
const author = await article.author(); // an Author, or null
|
|
518
|
+
const profile = await author?.profile(); // a Profile, or null
|
|
519
|
+
const latest = await author?.articles().first();
|
|
520
|
+
```
|
|
521
|
+
|
|
522
|
+
- Changing a foreign key makes the next read query again.
|
|
523
|
+
- `reload()` clears the cache, and `await record.reloadAssociation("articles")` reloads one association.
|
|
524
|
+
- A write through a `hasMany` clears its loaded collection: `insert`, `upsert`, `updateAll` and `deleteAll`, alone or in `db.batch`, even after `where` or `order`, or with the association joined by `or()`, `merge()` or a scope. `create` through the association itself adds the new record instead, so the next read still doesn’t query.
|
|
525
|
+
- A write made another way, such as `Article.where({ authorId: author.id }).deleteAll()`, doesn’t touch a loaded collection: reload the association to see it.
|
|
526
|
+
|
|
527
|
+
> **Beyond Rails**
|
|
528
|
+
>
|
|
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 d1-record any write built from `author.articles()` clears it, at the cost of one query on the next read.
|
|
530
|
+
|
|
531
|
+
:::note
|
|
532
|
+
A `belongsTo` whose foreign key is `null`, or an association on an unsaved owner, reads without a query.
|
|
533
|
+
:::
|
|
534
|
+
|
|
535
|
+
## Preloading associations
|
|
536
|
+
|
|
537
|
+
Load an association for every record at once with `includes`, with one query per association however many records there are:
|
|
538
|
+
|
|
539
|
+
```ts
|
|
540
|
+
const authors = await Author.includes("profile", { articles: "comments" }) // 4 queries in 3 round trips, however many authors
|
|
541
|
+
.toArray();
|
|
542
|
+
|
|
543
|
+
for (const each of authors) {
|
|
544
|
+
const articles = await each.articles().toArray(); // no query: already loaded
|
|
545
|
+
console.log(each.name, articles.length, each.loaded("profile")?.bio);
|
|
546
|
+
}
|
|
547
|
+
```
|
|
548
|
+
|
|
549
|
+
Nest with an object: `includes({ articles: "comments" })` or `includes({ articles: ["comments", "tags"] })`.
|
|
550
|
+
|
|
551
|
+
The whole tree goes to D1 with the authors’ own query, in one round trip. The example above sends four queries. A nested query that would bind more than D1’s 100 values waits for the records above it, and takes one more round trip.
|
|
552
|
+
|
|
553
|
+
:::note
|
|
554
|
+
With a `limit` or `offset`, `includes` ends the order with the primary key, so the preloads find the same records the query loads.
|
|
555
|
+
:::
|
|
556
|
+
|
|
557
|
+
> **Beyond Rails**
|
|
558
|
+
>
|
|
559
|
+
> Rails sends each association’s preload query on its own, so every association adds a round trip. Here the whole tree takes one.
|
|
560
|
+
|
|
561
|
+
:::note
|
|
562
|
+
`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:
|
|
563
|
+
|
|
564
|
+
```sql
|
|
565
|
+
CREATE INDEX index_articles_on_author_id ON articles (author_id);
|
|
566
|
+
```
|
|
567
|
+
|
|
568
|
+
`includes` also runs the query’s own conditions again for each association it preloads. With a `limit` or `offset`, it runs the query’s order again as well. Index the columns the query filters and sorts by, too. Otherwise D1 reads those rows again for every association, and bills you each time.
|
|
569
|
+
|
|
570
|
+
:::
|
|
571
|
+
|
|
572
|
+
`record.loaded("profile")` reads a preloaded association synchronously, and throws `AssociationNotLoaded` if it wasn’t loaded, so a template never sends a query. `record.isLoaded("profile")` checks first.
|
|
573
|
+
|
|
574
|
+
## Creating related records
|
|
575
|
+
|
|
576
|
+
Records built or created through a `hasMany` get the owner’s key:
|
|
577
|
+
|
|
578
|
+
```ts
|
|
579
|
+
const comment = await article.comments().create({ body: "Lovely." }); // articleId filled in
|
|
580
|
+
```
|
|
581
|
+
|
|
582
|
+
### Autosaving
|
|
583
|
+
|
|
584
|
+
A record built through an association is saved with its owner. Build a whole graph, then save the owner:
|
|
585
|
+
|
|
586
|
+
```ts
|
|
587
|
+
const ada = Author.build({ name: "Ada" });
|
|
588
|
+
ada.articles().build({ title: "Notes on the Analytical Engine" });
|
|
589
|
+
ada.articles().build({ title: "Sketch of the Engine" });
|
|
590
|
+
ada.profile.build({ bio: "Mathematician" });
|
|
591
|
+
await ada.saveOrThrow(); // the author, both articles and the profile, in one batch
|
|
592
|
+
```
|
|
593
|
+
|
|
594
|
+
The built records are validated with the owner. An invalid article makes the author invalid (“Articles is invalid”), with its own errors on the article.
|
|
595
|
+
|
|
596
|
+
When the owner’s key is generated in code, as here, everything is written in one atomic batch.
|
|
597
|
+
|
|
598
|
+
:::warning[Keys D1 generates]
|
|
599
|
+
When D1 generates the key, with an `INTEGER PRIMARY KEY`, the key doesn’t exist until the owner is written. So the owner is written first, and its records follow in the next batch, a level at a time. The batches aren’t atomic together: if a record fails at the second level, the save throws with the owner already saved. Generate keys in code wherever a graph must save all at once.
|
|
600
|
+
:::
|
|
601
|
+
|
|
602
|
+
## Scoping associations
|
|
603
|
+
|
|
604
|
+
Narrow or order an association’s records with `scope`:
|
|
605
|
+
|
|
606
|
+
```ts
|
|
607
|
+
import { hasMany, Model } from "@forestfuture/active-record";
|
|
608
|
+
|
|
609
|
+
export class Blog extends Model.define({ id: { type: "integer", null: false } }) {
|
|
610
|
+
// A scope for the association, as Rails' `has_many :posts, -> { … }`.
|
|
611
|
+
recentPosts = hasMany(BlogPost, {
|
|
612
|
+
scope: (q) => q.order({ createdAt: "desc" }).where({ draft: false }),
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
```
|
|
616
|
+
|
|
617
|
+
The scope applies to reads and preloads alike, and records created through the association take its equality values. `q` is the target’s Relation, with its attributes and scopes.
|
|
618
|
+
|
|
619
|
+
:::note
|
|
620
|
+
A scope that uses `limit`, `offset`, or `distinct` can’t be preloaded, since it would apply to every owner’s records together. `includes` throws `IncompatibleRelation` before it sends any preload.
|
|
621
|
+
:::
|
|
622
|
+
|
|
623
|
+
**A Model’s association to itself, scoped with its own scopes**
|
|
624
|
+
|
|
625
|
+
TypeScript can’t infer this one case: `children = hasMany(Category, { scope: (q) => q.top() })` inside `Category`, where `top` is one of `Category`’s scopes. Write the field’s type out:
|
|
626
|
+
|
|
627
|
+
```ts
|
|
628
|
+
import { belongsTo, hasMany, Model, type HasMany } from "@forestfuture/active-record";
|
|
629
|
+
|
|
630
|
+
export class Category extends Model.define({
|
|
631
|
+
id: { type: "integer", null: false },
|
|
632
|
+
parentId: "integer",
|
|
633
|
+
}) {
|
|
634
|
+
static top = this.scope((q) => q.where({ parentId: null }));
|
|
635
|
+
|
|
636
|
+
// Written out: TypeScript can't infer a field whose scope uses its own Model's scopes.
|
|
637
|
+
children: HasMany<typeof Category> = hasMany(Category, {
|
|
638
|
+
foreignKey: "parentId",
|
|
639
|
+
scope: (q) => q.top(),
|
|
640
|
+
});
|
|
641
|
+
parent = belongsTo(Category, { foreignKey: "parentId" });
|
|
642
|
+
}
|
|
643
|
+
```
|
|
644
|
+
|
|
645
|
+
## Destroying dependent records
|
|
646
|
+
|
|
647
|
+
Set what destroying the owner does to its records with `dependent`:
|
|
648
|
+
|
|
649
|
+
| Strategy | What happens |
|
|
650
|
+
| -------------------------- | --------------------------------------------------------------------------------------- |
|
|
651
|
+
| `"destroy"` | Each record is destroyed with its own callbacks and dependents |
|
|
652
|
+
| `"deleteAll"` / `"delete"` | The records are deleted in one statement, without callbacks (`"delete"` for a `hasOne`) |
|
|
653
|
+
| `"nullify"` | Their foreign keys are set to `NULL` |
|
|
654
|
+
| `"restrictWithException"` | The destroy throws `DeleteRestriction` while there are records |
|
|
655
|
+
| `"restrictWithError"` | The destroy returns `false`, with an error on the owner’s `base` |
|
|
656
|
+
|
|
657
|
+
Everything a destroy does, the owner’s DELETE included, is written in one atomic batch. Strategies run after the owner’s `beforeDestroy` callbacks, so an `abort()` leaves the records alone.
|
|
658
|
+
|
|
659
|
+
:::note
|
|
660
|
+
Without a strategy, it’s up to the database. If the table declares the foreign key with `REFERENCES`, destroying an owner whose records still point at it throws `InvalidForeignKey`.
|
|
661
|
+
:::
|
|
662
|
+
|
|
663
|
+
## Writing many rows
|
|
664
|
+
|
|
665
|
+
`insert`, `updateAll`, and `deleteAll` work through a `hasMany`, scoped to the owner’s records, and so do their `to…` forms for a batch:
|
|
666
|
+
|
|
667
|
+
```ts
|
|
668
|
+
await article.comments().deleteAll(); // one DELETE for the article's comments
|
|
669
|
+
```
|
|
670
|
+
|
|
671
|
+
`deleteAll()` on the association follows its `dependent` strategy: it deletes the records for `"destroy"` or `"deleteAll"`, and otherwise sets their foreign keys to `NULL`. See [Bulk writes and batches](/batches).
|
|
672
|
+
|
|
673
|
+
## Not built yet
|
|
674
|
+
|
|
675
|
+
These features aren’t in d1-record yet. The code shows the shape they’re likely to take.
|
|
676
|
+
|
|
677
|
+
- **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
|
+
- **Polymorphic associations** ([#60](https://github.com/forestfuture/active-record/issues/60)): `commentable = belongsTo([Post, Photo])`, with `comments = hasMany(Comment, { as: "commentable" })` on each.
|
|
679
|
+
- **Counter caches** ([#61](https://github.com/forestfuture/active-record/issues/61)): `post = belongsTo(Post, { counterCache: true })`, keeping a `commentsCount` on each post, updated in the same atomic batch as the write.
|
|
680
|
+
- **Inverse associations** ([#62](https://github.com/forestfuture/active-record/issues/62)): after `await post.comments().toArray()`, each `comment.post()` returns that same post, without a query.
|
|
681
|
+
|
|
682
|
+
---
|
|
683
|
+
|
|
684
|
+
# Bulk writes and batches
|
|
685
|
+
Source: https://d1-record.forestfuture.dev/batches
|
|
686
|
+
|
|
687
|
+
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
|
+
|
|
689
|
+
## Writing many rows
|
|
690
|
+
|
|
691
|
+
Call a bulk write on a Relation. It runs straight away, without validations or callbacks:
|
|
692
|
+
|
|
693
|
+
```ts
|
|
694
|
+
import { column, sql } from "@forestfuture/active-record";
|
|
695
|
+
import { Article, Comment } from "./models";
|
|
696
|
+
|
|
697
|
+
const deleted = await Comment.where({ articleId }).deleteAll(); // how many
|
|
698
|
+
await Article.where({ id: articleId }).updateAll({ title: "Edited" });
|
|
699
|
+
await Article.where({ id: articleId }).updateAll(
|
|
700
|
+
sql`${column("title")} = upper(${column("title")})`,
|
|
701
|
+
);
|
|
702
|
+
const { rowsAffected, rows } = await Comment.insert({ articleId, body: "First!" });
|
|
703
|
+
console.log(deleted, rowsAffected, rows[0]?.id); // the new comment's key
|
|
704
|
+
```
|
|
705
|
+
|
|
706
|
+
- **`updateAll(changes)`** takes attributes or an `sql` fragment, and resolves to the number of rows updated. It leaves `updatedAt` alone. With a `limit` or `offset`, the Relation’s order picks which rows are written.
|
|
707
|
+
- **`deleteAll()`** resolves to the number of rows deleted. On `none()`, both send nothing and resolve to `0`.
|
|
708
|
+
- **`insert(attrs)`** writes one row. It resolves to `{ rowsAffected, rows }`, and `rows` holds the new row’s primary key. Declared defaults, timestamps, and a Relation’s equality conditions fill what isn’t given.
|
|
709
|
+
|
|
710
|
+
### Inserting many rows
|
|
711
|
+
|
|
712
|
+
Insert many rows in one statement with `insertAll`:
|
|
713
|
+
|
|
714
|
+
```ts
|
|
715
|
+
import { Author, Comment } from "./models";
|
|
716
|
+
|
|
717
|
+
await Comment.insertAll([
|
|
718
|
+
{ articleId, body: "One" },
|
|
719
|
+
{ articleId, body: "Two" },
|
|
720
|
+
]);
|
|
721
|
+
await Author.upsert({ id: "author-1", name: "Ada" }); // insert, or update the name
|
|
722
|
+
await Author.insert({ id: "author-1", name: "Ada" }, { onDuplicate: "skip" });
|
|
723
|
+
```
|
|
724
|
+
|
|
725
|
+
- **`insertAll(rows)`** inserts every row, however many, up to D1’s 2 MB per bound value. Every row must have the same attributes. A duplicate throws and writes nothing.
|
|
726
|
+
- **`{ onDuplicate: "skip" }`** skips rows that clash with a unique index.
|
|
727
|
+
- **`upsert(attrs)`** and **`upsertAll(rows)`** update a row that clashes with the primary key, or with the unique index named by `uniqueBy`. Only the attributes you give are updated, and `updatedAt` is set.
|
|
728
|
+
|
|
729
|
+
### Returning attributes
|
|
730
|
+
|
|
731
|
+
Inserts and upserts return the primary key of each row they write. Name other attributes with `returning`:
|
|
732
|
+
|
|
733
|
+
```ts
|
|
734
|
+
import { Comment } from "./models";
|
|
735
|
+
|
|
736
|
+
const { rows } = await Comment.insertAll(
|
|
737
|
+
[
|
|
738
|
+
{ articleId, body: "One" },
|
|
739
|
+
{ articleId, body: "Two" },
|
|
740
|
+
],
|
|
741
|
+
{ returning: ["id", "body"] },
|
|
742
|
+
);
|
|
743
|
+
for (const { id, body } of rows) console.log(id, body);
|
|
744
|
+
await Comment.insert({ articleId, body: "Three" }, { returning: false });
|
|
745
|
+
```
|
|
746
|
+
|
|
747
|
+
- **`rows`** has one entry for each row written, typed from the attributes you name. A row skipped as a duplicate isn’t in it.
|
|
748
|
+
- **`returning: false`** returns no rows.
|
|
749
|
+
- **Order:** the rows come back in no set order.
|
|
750
|
+
|
|
751
|
+
> **Compared with Rails**
|
|
752
|
+
>
|
|
753
|
+
> These are Rails’ `insert_all`, `upsert_all`, `update_all`, and `delete_all`, with two differences. Declared defaults fill what an insert isn’t given, since on D1 defaults are where keys are generated. And skipping duplicates is something you opt in to, so a duplicate is never silently lost. The `returning` option works as Rails’ does.
|
|
754
|
+
|
|
755
|
+
## Batching writes
|
|
756
|
+
|
|
757
|
+
Each bulk write has a `to…` form that prepares it instead of running it: `toInsert`, `toInsertAll`, `toUpsert`, `toUpsertAll`, `toUpdateAll`, and `toDeleteAll`. Pass them to `batch` to write them atomically:
|
|
758
|
+
|
|
759
|
+
```ts
|
|
760
|
+
import { batch } from "@forestfuture/active-record";
|
|
761
|
+
import { Article, Author } from "./models";
|
|
762
|
+
|
|
763
|
+
const authorId = crypto.randomUUID(); // generated in code, so rows can point at it
|
|
764
|
+
await batch([
|
|
765
|
+
Author.toInsert({ id: authorId, name: "Grace" }),
|
|
766
|
+
Article.toInsert({ authorId, title: "Hello" }),
|
|
767
|
+
Article.where({ authorId: "author-1" }).toDeleteAll(),
|
|
768
|
+
]);
|
|
769
|
+
```
|
|
770
|
+
|
|
771
|
+
`batch` resolves to each entry’s result, in order. A prepared write gives the same `{ rowsAffected, rows }` it resolves to when it runs alone, and `rows` is empty for `toUpdateAll` and `toDeleteAll`.
|
|
772
|
+
|
|
773
|
+
- **Keys:** rows in one batch can only point at each other through keys that exist before it’s sent, so generate keys in code, with [`generateId`](/models#generating-ids).
|
|
774
|
+
- **Inspecting:** a prepared write’s `toSql()` shows the SQL and values it will send, [without sending them](/querying#seeing-a-querys-sql).
|
|
775
|
+
- **Databases:** a batch runs on the database its entries were built on. Entries from two databases throw `IncompatibleRelation`.
|
|
776
|
+
|
|
777
|
+
:::note
|
|
778
|
+
D1 can’t keep a transaction open across `await`s, so there’s no `transaction()` block. A batch is how you make writes atomic.
|
|
779
|
+
:::
|
|
780
|
+
|
|
781
|
+
## Batching records
|
|
782
|
+
|
|
783
|
+
Add a record’s save or destroy to a batch with `toSave()` and `toDestroy()`. Its validations and callbacks still run:
|
|
784
|
+
|
|
785
|
+
```ts
|
|
786
|
+
import { batch } from "@forestfuture/active-record";
|
|
787
|
+
import { Article, Author, Comment } from "./models";
|
|
788
|
+
|
|
789
|
+
const article = await Article.find(articleId);
|
|
790
|
+
article.title = "Final";
|
|
791
|
+
const author = Author.build({ name: "Hedy" });
|
|
792
|
+
const old = await Author.find(oldAuthorId);
|
|
793
|
+
|
|
794
|
+
const [savedArticle, savedAuthor] = await batch([
|
|
795
|
+
article.toSave(),
|
|
796
|
+
author.toSave(),
|
|
797
|
+
old.toDestroy(), // with its dependents
|
|
798
|
+
Comment.where({ articleId }).toDeleteAll(),
|
|
799
|
+
]);
|
|
800
|
+
```
|
|
801
|
+
|
|
802
|
+
When the batch runs:
|
|
803
|
+
|
|
804
|
+
1. Each record, in order, is validated and runs its before-callbacks. The first that’s invalid or aborts throws `RecordInvalid`, `RecordNotSaved`, or `RecordNotDestroyed`, and nothing is sent.
|
|
805
|
+
2. Every write goes to D1 as one atomic batch. If D1 refuses it with a constraint error, nothing is written, and every record keeps its unsaved state.
|
|
806
|
+
3. Each record takes its saved state, then its after-callbacks run.
|
|
807
|
+
|
|
808
|
+
A record’s autosaved associations and `dependent` strategies join the same batch. A record listed twice, or already saved by its owner’s autosave, is written once.
|
|
809
|
+
|
|
810
|
+
> **Compared with Rails**
|
|
811
|
+
>
|
|
812
|
+
> In a Rails transaction, one record’s `after_save` runs before the next record’s `before_save`. In a batch, every before-callback runs first.
|
|
813
|
+
|
|
814
|
+
Statements and records mix in one batch. From the [Getting started](/getting-started) project, this publishes every draft and destroys a user with their posts:
|
|
815
|
+
|
|
816
|
+
```ts
|
|
817
|
+
import { batch } from "@forestfuture/active-record";
|
|
818
|
+
import { Post } from "./models";
|
|
819
|
+
|
|
820
|
+
await batch([
|
|
821
|
+
Post.where({ publishedAt: null }).toUpdateAll({ publishedAt: new Date() }),
|
|
822
|
+
user.toDestroy(), // and the user's posts, since posts are dependent: "destroy"
|
|
823
|
+
]);
|
|
824
|
+
```
|
|
825
|
+
|
|
826
|
+
---
|
|
827
|
+
|
|
828
|
+
# Callbacks
|
|
829
|
+
Source: https://d1-record.forestfuture.dev/callbacks
|
|
830
|
+
|
|
831
|
+
Callbacks run your code at points in a record’s lifecycle, such as before it’s validated or after it’s saved.
|
|
832
|
+
|
|
833
|
+
## Registering callbacks
|
|
834
|
+
|
|
835
|
+
Register callbacks in a Model’s `static {}` block. Each receives the record, and may be async:
|
|
836
|
+
|
|
837
|
+
```ts
|
|
838
|
+
import { abort, Model } from "@forestfuture/active-record";
|
|
839
|
+
|
|
840
|
+
export class Order extends Model.define({
|
|
841
|
+
id: { type: "integer", null: false },
|
|
842
|
+
status: { type: "string", null: false, default: () => "pending" },
|
|
843
|
+
email: { type: "string", null: false },
|
|
844
|
+
totalCents: { type: "integer", null: false },
|
|
845
|
+
suspended: "boolean",
|
|
846
|
+
placedAt: "datetime",
|
|
847
|
+
}) {
|
|
848
|
+
static {
|
|
849
|
+
this.beforeValidation((order) => {
|
|
850
|
+
order.email = order.email.trim().toLowerCase();
|
|
851
|
+
});
|
|
852
|
+
this.beforeCreate((order) => {
|
|
853
|
+
order.placedAt = new Date();
|
|
854
|
+
});
|
|
855
|
+
this.beforeSave((order) => {
|
|
856
|
+
if (order.suspended) throw abort("Orders can't change while suspended");
|
|
857
|
+
});
|
|
858
|
+
this.afterSave(async (order) => {
|
|
859
|
+
if (order.hasSavedChangeTo("status", { to: "shipped" })) {
|
|
860
|
+
await notifyShipped(order.email);
|
|
861
|
+
}
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
```
|
|
866
|
+
|
|
867
|
+
Callbacks of one kind run in the order declared. A subclass runs its parent’s callbacks, then its own.
|
|
868
|
+
|
|
869
|
+
:::note
|
|
870
|
+
Once a Model has been used, registering another callback throws `InvalidModel`, so request code can’t add one that leaks into later requests.
|
|
871
|
+
:::
|
|
872
|
+
|
|
873
|
+
## Callback order
|
|
874
|
+
|
|
875
|
+
| Order | Callback | Runs | `abort()` |
|
|
876
|
+
| -------------- | ------------------ | -------------------------------------------------------- | --------------------------------- |
|
|
877
|
+
| **Saving** | | | |
|
|
878
|
+
| 1 | `beforeValidation` | Before the validators, on every save, and on `isValid()` | Stops the save |
|
|
879
|
+
| 2 | `afterValidation` | After the validators | Stops the save |
|
|
880
|
+
| 3 | `beforeSave` | Before every write, new or persisted | Stops the save |
|
|
881
|
+
| 4 | `beforeCreate` | Before inserting a new record | Stops the save |
|
|
882
|
+
| 4 | `beforeUpdate` | Before updating a persisted record | Stops the save |
|
|
883
|
+
| | _The write to D1_ | Skipped when a persisted record has no changes | |
|
|
884
|
+
| 5 | `afterCreate` | After inserting a new record | Too late: `AbortAfterPersistence` |
|
|
885
|
+
| 5 | `afterUpdate` | After updating a persisted record | Too late: `AbortAfterPersistence` |
|
|
886
|
+
| 6 | `afterSave` | After every successful save | Too late: `AbortAfterPersistence` |
|
|
887
|
+
| **Destroying** | | | |
|
|
888
|
+
| 1 | `beforeDestroy` | Before the `dependent` strategies and the DELETE | Stops the destroy |
|
|
889
|
+
| | _The delete in D1_ | With the dependents, in one batch | |
|
|
890
|
+
| 2 | `afterDestroy` | After the record is destroyed | Too late: `AbortAfterPersistence` |
|
|
891
|
+
|
|
892
|
+
A save runs either the create pair or the update pair, never both.
|
|
893
|
+
|
|
894
|
+
- **After-callbacks** run after every successful save, even one with no changes to write.
|
|
895
|
+
- **A before-callback that changes an attribute** makes the record dirty, and the change is written.
|
|
896
|
+
- **An after-callback that changes an attribute** leaves the record dirty. Nothing is written again.
|
|
897
|
+
|
|
898
|
+
:::warning[Nothing is rolled back]
|
|
899
|
+
D1 has committed a save’s writes before any after-callback runs. An error thrown by an after-callback reaches the caller, but the record stays saved.
|
|
900
|
+
:::
|
|
901
|
+
|
|
902
|
+
## Stopping a save
|
|
903
|
+
|
|
904
|
+
Throw `abort(reason)` from a before-callback to stop a save or destroy:
|
|
905
|
+
|
|
906
|
+
```ts
|
|
907
|
+
import { abort } from "@forestfuture/active-record";
|
|
908
|
+
|
|
909
|
+
this.beforeSave((order) => {
|
|
910
|
+
if (order.suspended) throw abort("Orders can't change while suspended");
|
|
911
|
+
});
|
|
912
|
+
```
|
|
913
|
+
|
|
914
|
+
- **`save()`** resolves to `false` and writes nothing. The record keeps its changes, and `record.abortReason` holds the reason.
|
|
915
|
+
- **`saveOrThrow()`** throws `RecordNotSaved` with the reason.
|
|
916
|
+
- **`destroy()`** resolves to `false`, and **`destroyOrThrow()`** throws `RecordNotDestroyed`.
|
|
917
|
+
|
|
918
|
+
Only `abort()` stops a save. Returning `false` does nothing, and any other error reaches the caller as it is.
|
|
919
|
+
|
|
920
|
+
:::note
|
|
921
|
+
In an after-callback, the write has already happened, so `abort()` throws `AbortAfterPersistence`, naming the callback.
|
|
922
|
+
:::
|
|
923
|
+
|
|
924
|
+
## Not built yet
|
|
925
|
+
|
|
926
|
+
These callbacks aren’t in d1-record yet. The code shows the shape they’re likely to take.
|
|
927
|
+
|
|
928
|
+
- **Around callbacks** ([#48](https://github.com/forestfuture/active-record/issues/48)): `this.aroundSave(async (record, proceed) => { …; await proceed(); … })`, and `aroundCreate`, `aroundUpdate`, and `aroundDestroy`.
|
|
929
|
+
- **`afterInitialize` and `afterFind`** ([#49](https://github.com/forestfuture/active-record/issues/49)): for every record built or loaded, and every record loaded.
|
|
930
|
+
- **`record.touch()` and `afterTouch`** ([#50](https://github.com/forestfuture/active-record/issues/50)): sets `updatedAt` without a full save.
|
|
931
|
+
- **`on: "create"` and `on: "update"`** ([#51](https://github.com/forestfuture/active-record/issues/51)): `this.validates("password", { presence: true, on: "create" })`. Until then, check `record.isNewRecord()` in an `if` option or a callback.
|
|
932
|
+
|
|
933
|
+
> **Compared with Rails**
|
|
934
|
+
>
|
|
935
|
+
> There’s no `after_commit` or `after_rollback`. In Rails, `after_save` runs before the save’s transaction commits. Here, D1 has already committed before any after-callback runs, so every after-callback is already “after commit”. In a [batch](/batches#batching-records), they run once the whole batch is written. When D1 refuses a write, nothing was written, and the save throws the [constraint error](/errors#constraint-errors).
|
|
936
|
+
>
|
|
937
|
+
> Rails’ `if:` and `unless:` options for callbacks aren’t needed: write the condition inside the callback.
|
|
938
|
+
|
|
939
|
+
---
|
|
940
|
+
|
|
941
|
+
# Schema changes
|
|
942
|
+
Source: https://d1-record.forestfuture.dev/change-a-table
|
|
943
|
+
|
|
944
|
+
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
|
+
|
|
946
|
+
## Adding a column
|
|
947
|
+
|
|
948
|
+
Generate the migration, then apply it:
|
|
949
|
+
|
|
950
|
+
```sh
|
|
951
|
+
npx active-record g migration AddBioToUsers bio:string
|
|
952
|
+
npx active-record migrate
|
|
953
|
+
```
|
|
954
|
+
|
|
955
|
+
```sql migrations/0003_add_bio_to_users.sql
|
|
956
|
+
ALTER TABLE users ADD COLUMN bio TEXT;
|
|
957
|
+
```
|
|
958
|
+
|
|
959
|
+
`user.bio` is there straight away, typed as `string | null`. A required column needs a default for the existing rows: `'role:string!=member'`.
|
|
960
|
+
|
|
961
|
+
To deploy, apply the migration with `--remote` first, then deploy the code that uses the column. The code already deployed keeps working, since it only writes the attributes it knows.
|
|
962
|
+
|
|
963
|
+
## Renaming a column
|
|
964
|
+
|
|
965
|
+
Generate an empty migration, and write the rename:
|
|
966
|
+
|
|
967
|
+
```sh
|
|
968
|
+
npx active-record g migration RenameBioToAbout
|
|
969
|
+
```
|
|
970
|
+
|
|
971
|
+
```sql migrations/0004_rename_bio_to_about.sql
|
|
972
|
+
ALTER TABLE users RENAME COLUMN bio TO about;
|
|
973
|
+
```
|
|
974
|
+
|
|
975
|
+
The attribute follows the column, so `bio` becomes `about`. Update the code that uses it, then apply the migration and deploy together, since the old code reads a column that’s gone.
|
|
976
|
+
|
|
977
|
+
:::note
|
|
978
|
+
Keeping the old attribute name for a renamed column is planned in [#65](https://github.com/forestfuture/active-record/issues/65).
|
|
979
|
+
:::
|
|
980
|
+
|
|
981
|
+
## Removing a column
|
|
982
|
+
|
|
983
|
+
Remove a column in the opposite order to adding one, so the code stops using it before it goes:
|
|
984
|
+
|
|
985
|
+
1. Ignore the column in the Model, remove the code that uses it, and deploy:
|
|
986
|
+
|
|
987
|
+
```ts
|
|
988
|
+
import { ApplicationRecord } from "./application-record";
|
|
989
|
+
|
|
990
|
+
export class User extends ApplicationRecord {
|
|
991
|
+
static override attributes = { bio: false } as const;
|
|
992
|
+
}
|
|
993
|
+
```
|
|
994
|
+
|
|
995
|
+
2. Generate the migration, and apply it with `--remote`:
|
|
996
|
+
|
|
997
|
+
```sh
|
|
998
|
+
npx active-record g migration RemoveBioFromUsers bio
|
|
999
|
+
```
|
|
1000
|
+
|
|
1001
|
+
3. Remove `{ bio: false }`, now that the schema no longer has the column.
|
|
1002
|
+
|
|
1003
|
+
Remove a `references` column the same way, with `RemoveUserFromPosts user:references`. Its index is dropped first, then the column.
|
|
1004
|
+
|
|
1005
|
+
## Changing a column’s type
|
|
1006
|
+
|
|
1007
|
+
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
|
+
|
|
1009
|
+
```sql migrations/0005_make_price_cents_an_integer.sql
|
|
1010
|
+
PRAGMA defer_foreign_keys = true;
|
|
1011
|
+
|
|
1012
|
+
CREATE TABLE products_new (
|
|
1013
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
1014
|
+
name TEXT NOT NULL,
|
|
1015
|
+
price_cents INTEGER NOT NULL,
|
|
1016
|
+
created_at DATETIME NOT NULL,
|
|
1017
|
+
updated_at DATETIME NOT NULL
|
|
1018
|
+
);
|
|
1019
|
+
INSERT INTO products_new SELECT id, name, CAST(price_cents AS INTEGER), created_at, updated_at FROM products;
|
|
1020
|
+
DROP TABLE products;
|
|
1021
|
+
ALTER TABLE products_new RENAME TO products;
|
|
1022
|
+
```
|
|
1023
|
+
|
|
1024
|
+
- **`PRAGMA defer_foreign_keys = true`** lets the swap happen while other tables point at this one, [as Cloudflare recommends](https://developers.cloudflare.com/d1/reference/migrations/).
|
|
1025
|
+
- **Indexes** are dropped with the old table, so recreate them after the swap.
|
|
1026
|
+
- **The schema** needs regenerating with `npx active-record schema`, since you wrote this migration by hand.
|
|
1027
|
+
|
|
1028
|
+
:::note
|
|
1029
|
+
Wrangler backs up the database before applying migrations to it.
|
|
1030
|
+
:::
|
|
1031
|
+
|
|
1032
|
+
---
|
|
1033
|
+
|
|
1034
|
+
# Coming from Rails
|
|
1035
|
+
Source: https://d1-record.forestfuture.dev/coming-from-rails
|
|
1036
|
+
|
|
1037
|
+
Models, validations, callbacks, associations, scopes, and dirty tracking all follow Active Record, down to the default error messages. Here’s what’s different.
|
|
1038
|
+
|
|
1039
|
+
## Querying from the Model
|
|
1040
|
+
|
|
1041
|
+
```ts
|
|
1042
|
+
// Rails: User.where(active: true)
|
|
1043
|
+
const users = await User.where({ isActive: true }).toArray();
|
|
1044
|
+
```
|
|
1045
|
+
|
|
1046
|
+
A Model queries by itself. The binding in the generated schema its base class holds plays the part of `connects_to`.
|
|
1047
|
+
|
|
1048
|
+
A Worker serves many requests at once from one isolate, so nothing about a request is stored on the class. For a D1 Session or per-request logging, run the request in [`withDatabase`](/connecting#using-the-requests-database). A record keeps the database it came from.
|
|
1049
|
+
|
|
1050
|
+
## Naming things
|
|
1051
|
+
|
|
1052
|
+
Most names are Rails’ own, in camelCase:
|
|
1053
|
+
|
|
1054
|
+
| Rails | Active Record for Workers |
|
|
1055
|
+
| ---------------------------------------- | ------------------------------------------------- |
|
|
1056
|
+
| `created_at` (attribute) | `createdAt`, mapped to `created_at` |
|
|
1057
|
+
| `foreign_key: :user_id` | `foreignKey: "userId"` |
|
|
1058
|
+
| `save!`, `create!`, `find_by!` | `saveOrThrow`, `createOrThrow`, `findByOrThrow` |
|
|
1059
|
+
| `new_record?`, `persisted?` | `isNewRecord()`, `isPersisted()` |
|
|
1060
|
+
| `empty?`, `any?` | `isEmpty()`, `hasAny()` |
|
|
1061
|
+
| `changed?`, `saved_change_to_email?` | `isChanged()`, `hasSavedChangeTo("email")` |
|
|
1062
|
+
| `rails generate model Post title:string` | `npx active-record g model Post title:string` |
|
|
1063
|
+
| `db/schema.rb`, `rails db:schema:dump` | `src/db/schema.ts`, `npx active-record schema` |
|
|
1064
|
+
| `class Post < ApplicationRecord` | `class Post extends ApplicationRecord` |
|
|
1065
|
+
| `scope :active, -> { … }` | `static active = this.scope((q) => …)` |
|
|
1066
|
+
| `has_many :posts, dependent: :destroy` | `posts = hasMany(Post, { dependent: "destroy" })` |
|
|
1067
|
+
| `post.author = user` | `post.author.set(user)` |
|
|
1068
|
+
| `build_profile` | `user.profile.build()` |
|
|
1069
|
+
| `reload_author` | `post.reloadAssociation("author")` |
|
|
1070
|
+
| `throw :abort` | `throw abort("reason")` |
|
|
1071
|
+
| `to_json` | `toJSON()` |
|
|
1072
|
+
|
|
1073
|
+
Attributes, conditions, and association keys all name attributes, in camelCase. Column names only appear inside `sql` fragments. Foreign keys follow Rails’ conventions, so `User`’s `has_many` uses `userId`.
|
|
1074
|
+
|
|
1075
|
+
## Declaring Models
|
|
1076
|
+
|
|
1077
|
+
Migrations define the columns, and a Model declares only behavior. Where Rails reads the columns when the app runs, this library reads them into `src/db/schema.ts` when you run `active-record schema` or a generator, so TypeScript knows every attribute’s type.
|
|
1078
|
+
|
|
1079
|
+
A Model names its table, since TypeScript can’t derive a class’s types from its name. Scopes are statics, and validations and callbacks go in a `static {}` block:
|
|
1080
|
+
|
|
1081
|
+
```ts
|
|
1082
|
+
import { ApplicationRecord } from "./application-record";
|
|
1083
|
+
|
|
1084
|
+
// Rails:
|
|
1085
|
+
// class Product < ApplicationRecord
|
|
1086
|
+
// scope :in_stock, -> { where(available: true) }
|
|
1087
|
+
// validates :name, presence: true
|
|
1088
|
+
// end
|
|
1089
|
+
export class Product extends ApplicationRecord {
|
|
1090
|
+
static override attributes = { available: "boolean" } as const;
|
|
1091
|
+
static inStock = this.scope((q) => q.where({ available: true }));
|
|
1092
|
+
|
|
1093
|
+
static {
|
|
1094
|
+
this.validates("name", { presence: true });
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
```
|
|
1098
|
+
|
|
1099
|
+
## Writing atomically
|
|
1100
|
+
|
|
1101
|
+
There’s no `transaction do … end`, since D1 can’t keep a transaction open across awaits. Instead, [`batch([...])`](/batches) writes a prepared set of statements and records atomically, with records’ `toSave()` and `toDestroy()`, and bulk writes’ `toUpdateAll()`, `toDeleteAll()`, and so on. Generating keys in code makes whole graphs of new records atomic too. See [D1’s limits](/d1).
|
|
1102
|
+
|
|
1103
|
+
## Primary keys
|
|
1104
|
+
|
|
1105
|
+
:::warning[Keys are UUIDs, not integers]
|
|
1106
|
+
`g model` gives each table a `TEXT` `id` generated in code, which is what makes those batches atomic. `--id integer` gives you integer keys that D1 assigns, without that guarantee.
|
|
1107
|
+
:::
|
|
1108
|
+
|
|
1109
|
+
## Generating code
|
|
1110
|
+
|
|
1111
|
+
The generators follow `rails generate model` and `rails generate migration`. A column can also have a literal default, `count:integer!=0`, which Rails’ generators can’t express. See [Generators](/generators).
|
|
1112
|
+
|
|
1113
|
+
## Smaller differences
|
|
1114
|
+
|
|
1115
|
+
- `insert` and `insertAll` raise on duplicates. Skipping them is opt-in, with `{ onDuplicate: "skip" }`.
|
|
1116
|
+
- `insert` fills in declared defaults, since that’s where keys are generated.
|
|
1117
|
+
- `merge` replaces the order rather than appending to it.
|
|
1118
|
+
- `last()` can’t reverse an `sql` fragment order, and throws `IrreversibleOrder`, rather than trying to parse SQL.
|
|
1119
|
+
- `find(1, 1)` always returns an array, so its return type follows its arguments.
|
|
1120
|
+
- `dependent:` strategies run after the owner’s `beforeDestroy` callbacks, wherever they’re declared, so an `abort()` always protects the records.
|
|
1121
|
+
- Records in a batch run all their before-callbacks before any write, and their after-callbacks after all of them.
|
|
1122
|
+
- Scopes preloaded with `limit` throw, where Rails silently gives wrong results.
|
|
1123
|
+
|
|
1124
|
+
## Not built yet
|
|
1125
|
+
|
|
1126
|
+
Default scopes, `has_many :through`, polymorphic associations, single-table inheritance, counter caches, `destroy_async`, and error messages in other languages.
|
|
1127
|
+
|
|
1128
|
+
---
|
|
1129
|
+
|
|
1130
|
+
# Command line
|
|
1131
|
+
Source: https://d1-record.forestfuture.dev/command-line
|
|
1132
|
+
|
|
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 the folder with your Wrangler config:
|
|
1134
|
+
|
|
1135
|
+
```sh
|
|
1136
|
+
npx active-record --help
|
|
1137
|
+
```
|
|
1138
|
+
|
|
1139
|
+
It finds your database’s adapter from your `package.json`, so it works the same on every database.
|
|
1140
|
+
|
|
1141
|
+
It needs Node.js 22.13 or later, for Node’s built-in SQLite. [Generators](/generators) shows it step by step.
|
|
1142
|
+
|
|
1143
|
+
## `active-record schema`
|
|
1144
|
+
|
|
1145
|
+
Generate the schema file from your migrations:
|
|
1146
|
+
|
|
1147
|
+
```sh
|
|
1148
|
+
npx active-record schema
|
|
1149
|
+
```
|
|
1150
|
+
|
|
1151
|
+
It applies your migrations, in order, to an in-memory SQLite database, and writes each table’s columns to `src/db/schema.ts`.
|
|
1152
|
+
|
|
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 Wrangler config’s folder (one database only). |
|
|
1159
|
+
| `--models <dir>` | Where your Models and `application-record.ts` are (`src/models/` by default). |
|
|
1160
|
+
| `--config <file>` | Use this Wrangler config instead of finding `wrangler.jsonc`, `wrangler.json`, or `wrangler.toml`. |
|
|
1161
|
+
| `--adapter <name>` | The adapter (`d1`), when the project has several installed. |
|
|
1162
|
+
|
|
1163
|
+
**What it reads:** each entry of 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 file-name order, 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
|
+
|
|
1165
|
+
**What it writes:**
|
|
1166
|
+
|
|
1167
|
+
- **The schema file:** each table’s attributes, as a document, with a header naming the migrations and a fingerprint. Then `schema`, with the binding, every table, and your Models, and type declarations adding each table’s attributes to its Model. `--check` compares fingerprints, so formatting the file doesn’t make it stale, but adding or renaming a Model does.
|
|
1168
|
+
- **The base class**, `application-record.ts`, when it’s missing: `abstract class ApplicationRecord extends Model`, holding the schema. It’s never written over, so it’s yours to edit.
|
|
1169
|
+
- **With several databases:** one schema file per binding (`src/db/DB.ts`, `src/db/LOGS.ts`), and one base class each, named after it (`DB` → `DbRecord`, `LOGS` → `LogsRecord`).
|
|
1170
|
+
|
|
1171
|
+
> **Compared with Rails**
|
|
1172
|
+
>
|
|
1173
|
+
> The schema file plays the part of Rails’ `schema.rb`, and each base class is named as Rails names a second database’s.
|
|
1174
|
+
|
|
1175
|
+
**What it refuses**, writing nothing:
|
|
1176
|
+
|
|
1177
|
+
- A file it didn’t write (one without its “Generated by” header), such as a Drizzle schema.
|
|
1178
|
+
- 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
|
+
- Two bindings whose names would give the same base class (`DB` and `db`).
|
|
1180
|
+
- A migration SQLite rejects: the error names the file, and the last good schema is kept.
|
|
1181
|
+
- 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
|
+
|
|
1183
|
+
:::warning[Coming from Drizzle or Prisma?]
|
|
1184
|
+
Their schemas often live at `src/db/schema.ts` or `src/db/schema/`. Write d1-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
|
+
:::
|
|
1186
|
+
|
|
1187
|
+
## `active-record console`
|
|
1188
|
+
|
|
1189
|
+
Open your database with your Models in a console, or `active-record c` for short ([Console](/console) shows a session). It opens the local one unless you pass `--remote`:
|
|
1190
|
+
|
|
1191
|
+
```sh
|
|
1192
|
+
npx active-record console
|
|
1193
|
+
```
|
|
1194
|
+
|
|
1195
|
+
| Option | |
|
|
1196
|
+
| ------------------- | ------------------------------------------------------------------------------------------ |
|
|
1197
|
+
| `--database <name>` | The D1 binding to open, when the config has several. |
|
|
1198
|
+
| `--models <path>` | Where the Models are: a folder (`src/models`) or one file (`src/models.ts`). |
|
|
1199
|
+
| `--config <file>` | Use this Wrangler config instead of finding `wrangler.jsonc`, `wrangler.json`, or `.toml`. |
|
|
1200
|
+
| `--adapter <name>` | The adapter (`d1`), when the project has several installed. |
|
|
1201
|
+
| `--no-history` | Don’t keep what you type in `.wrangler/d1-record-history`. |
|
|
1202
|
+
| `--verbose` | Print each statement a line runs. `.verbose` turns it on and off in the console. |
|
|
1203
|
+
| `-e, --eval <code>` | Run this code, print its result (alone, on stdout), and exit; a failure exits 1. |
|
|
1204
|
+
| `--remote` | Open your remote database instead, after you type its name. |
|
|
1205
|
+
| `--yes` | With `--remote`, don’t ask first (also how to open it without a terminal). |
|
|
1206
|
+
| `--history` | Keep what you type in a remote session, which isn’t kept unless you ask. |
|
|
1207
|
+
|
|
1208
|
+
It reads TypeScript Models and uses your project’s own `wrangler`, `@forestfuture/active-record`, and its adapter. It refuses, printing why, when there’s no Wrangler config, with several databases and no `--database`, with no Models, with `wrangler` or the library not installed, or with `--remote` when the binding has no `database_id`, or 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
|
+
|
|
1210
|
+
## `active-record migrate`
|
|
1211
|
+
|
|
1212
|
+
Apply your pending migrations to the local database, through your project’s own `wrangler`:
|
|
1213
|
+
|
|
1214
|
+
```sh
|
|
1215
|
+
npx active-record migrate
|
|
1216
|
+
```
|
|
1217
|
+
|
|
1218
|
+
| Option | |
|
|
1219
|
+
| ------------------- | ----------------------------------------------------------------------------- |
|
|
1220
|
+
| `--database <name>` | The database to migrate, when the config has several. |
|
|
1221
|
+
| `--remote` | Migrate your remote database instead, after you type its name. |
|
|
1222
|
+
| `--yes` | With `--remote`, don’t ask first (also how to migrate it without a terminal). |
|
|
1223
|
+
| `--config <file>` | Use this Wrangler config. |
|
|
1224
|
+
| `--adapter <name>` | The adapter (`d1`), when the project has several installed. |
|
|
1225
|
+
|
|
1226
|
+
On D1, it runs `wrangler d1 migrations apply` for the database, `--local` or `--remote`, and prints what Wrangler prints. It exits with Wrangler’s code.
|
|
1227
|
+
|
|
1228
|
+
## Mapping columns to attributes
|
|
1229
|
+
|
|
1230
|
+
Each column becomes an attribute by the first of these that applies:
|
|
1231
|
+
|
|
1232
|
+
1. **An override in the Model:** `static override attributes = { available: "boolean" } as const`.
|
|
1233
|
+
2. **The column’s declared type:**
|
|
1234
|
+
|
|
1235
|
+
| Declared as | Attribute |
|
|
1236
|
+
| --------------------------------------------------- | -------------------------------------------------------------- |
|
|
1237
|
+
| `INTEGER`, `INT`, `BIGINT`, … (anything with `INT`) | `integer` |
|
|
1238
|
+
| `TEXT`, `VARCHAR(…)`, `CHAR(…)`, `CLOB` | `string` |
|
|
1239
|
+
| `REAL`, `FLOAT`, `DOUBLE` | `real` |
|
|
1240
|
+
| `BOOLEAN` | `boolean` |
|
|
1241
|
+
| `DATETIME`, `TIMESTAMP`, `DATE` | `datetime` |
|
|
1242
|
+
| `TEXT` with `CHECK (json_valid(column))` | `json` |
|
|
1243
|
+
| `JSON` | `json` |
|
|
1244
|
+
| `NUMERIC`, `DECIMAL` | An error: store money as integer cents (`price_cents INTEGER`) |
|
|
1245
|
+
| `BLOB` | An error: not supported yet |
|
|
1246
|
+
| anything else | `string` |
|
|
1247
|
+
|
|
1248
|
+
3. **The column’s name**, only for a column declared exactly `TEXT` or `INTEGER`: `…_at` `TEXT` is a `datetime`, and `is_…` or `has_…` `INTEGER` is a `boolean` (with a note, since it’s a guess).
|
|
1249
|
+
|
|
1250
|
+
Also:
|
|
1251
|
+
|
|
1252
|
+
- **Names:** `price_cents` becomes `priceCents`. A column whose name doesn’t come back the same from camelCase gets `column: "…"`.
|
|
1253
|
+
- **`NOT NULL`** becomes `null: false`. A primary key is never null.
|
|
1254
|
+
- **Primary keys:** the key column is the Model’s `primaryKey`. A `TEXT` key gets `generateId: true`, so the Model’s [`generateId`](/models#generating-ids) makes it; an `INTEGER PRIMARY KEY` is left to D1. A table with no key, or a key of several columns, is an error.
|
|
1255
|
+
- **Defaults:** literal defaults (numbers, strings, `TRUE`/`FALSE`, JSON) are copied, so a new record shows them before it’s saved. Expressions such as `CURRENT_TIMESTAMP` are left to D1.
|
|
1256
|
+
- **Foreign keys** take the referenced column’s type. They don’t create associations, which are behavior you declare.
|
|
1257
|
+
- **Left out:** SQLite’s own tables, Cloudflare’s (`_cf_…`), the migrations table, and virtual tables.
|
|
1258
|
+
|
|
1259
|
+
**Notes it prints** when the schema is written:
|
|
1260
|
+
|
|
1261
|
+
- an `INTEGER` read as a `boolean` from its name;
|
|
1262
|
+
- 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
|
+
- 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 d1-record’s and the two [compare as text](/adopt-a-database#comparing-dates-in-two-forms);
|
|
1265
|
+
- migrations in folders with no `migrations_pattern` to find them.
|
|
1266
|
+
|
|
1267
|
+
## `active-record g model` and `g migration`
|
|
1268
|
+
|
|
1269
|
+
```sh
|
|
1270
|
+
npx active-record g model <Name> [columns] [options]
|
|
1271
|
+
npx active-record g migration <Name> [columns] [options]
|
|
1272
|
+
```
|
|
1273
|
+
|
|
1274
|
+
`generate` is the same as `g`.
|
|
1275
|
+
|
|
1276
|
+
| Option | |
|
|
1277
|
+
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------- |
|
|
1278
|
+
| `--id integer\|text` | `integer`: an `INTEGER PRIMARY KEY` that D1 generates. `text` (the default): a `TEXT` key generated in code. |
|
|
1279
|
+
| `--no-timestamps` | Leave out `created_at` and `updated_at`. |
|
|
1280
|
+
| `--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 D1 database to use, when the Wrangler config has several. |
|
|
1282
|
+
| `--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 Wrangler config. |
|
|
1284
|
+
| `--adapter <name>` | The adapter (`d1`), when the project has several installed. |
|
|
1285
|
+
|
|
1286
|
+
### Column syntax
|
|
1287
|
+
|
|
1288
|
+
`name[:type][!][=value][:unique|:index]`
|
|
1289
|
+
|
|
1290
|
+
| Type | SQL |
|
|
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
|
+
| `references` | `<name>_id`, typed like the referenced table’s key, `REFERENCES <plural> (id)`, and indexed |
|
|
1299
|
+
|
|
1300
|
+
- **`!`** 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
|
+
- **`=value`** is a literal default, for `string`, `integer`, `real`, and `boolean` columns (`=draft`, `=0`, `=1.5`, `=true`).
|
|
1302
|
+
- **`: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 SQLite reserves (`order`, `group`) are quoted.
|
|
1304
|
+
|
|
1305
|
+
> **Beyond Rails**
|
|
1306
|
+
>
|
|
1307
|
+
> `=value` is d1-record’s own addition: Rails’ generators can’t give a column a default.
|
|
1308
|
+
|
|
1309
|
+
### Migration names
|
|
1310
|
+
|
|
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 each column’s generated index, then `DROP COLUMN` |
|
|
1316
|
+
| anything else | An empty migration, to write yourself |
|
|
1317
|
+
|
|
1318
|
+
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
|
+
|
|
1320
|
+
**File names** are numbered as Wrangler numbers them: the highest number in the migrations folder plus one, in four digits (`0008_add_sku_to_products.sql`).
|
|
1321
|
+
|
|
1322
|
+
### What’s checked first
|
|
1323
|
+
|
|
1324
|
+
Nothing is written unless all of these hold:
|
|
1325
|
+
|
|
1326
|
+
- the new migration applies after the existing ones (in memory, as `active-record schema` applies them);
|
|
1327
|
+
- the Model’s file doesn’t exist yet (or, with one models file, doesn’t have the class yet);
|
|
1328
|
+
- the config’s `migrations_pattern`, if it has one, would match the new file, so Wrangler would apply it;
|
|
1329
|
+
- the schema file can be written (see [What it refuses](#active-record-schema));
|
|
1330
|
+
- it isn’t a required column added without a default.
|
|
1331
|
+
|
|
1332
|
+
Then the generator writes the files, regenerates the schema, and prints the next step: `npx active-record migrate`.
|
|
1333
|
+
|
|
1334
|
+
## Exit codes
|
|
1335
|
+
|
|
1336
|
+
Every command exits with `0` on success, and `1` when anything was refused or failed, or, with `--check`, when the schema is out of date. Messages go to standard output, and say what to do next.
|
|
1337
|
+
|
|
1338
|
+
---
|
|
1339
|
+
|
|
1340
|
+
# Connections
|
|
1341
|
+
Source: https://d1-record.forestfuture.dev/connecting
|
|
1342
|
+
|
|
1343
|
+
A query finds its D1 database in one of three ways. Most apps only use the first.
|
|
1344
|
+
|
|
1345
|
+
| | How | Use it for |
|
|
1346
|
+
| -------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------- |
|
|
1347
|
+
| **The binding** | `User.find(id)`, with nothing to set up | Everyday queries |
|
|
1348
|
+
| **The request’s database** | `withDatabase(connect(env.DB, …), fn)`, once per request | Read replicas with a Session, per-request `onQuery` logging, tests, and scripts |
|
|
1349
|
+
| **An explicit database** | `connect(env.DB).model(User).find(id)` | Code that passes its database around, or uses two at once |
|
|
1350
|
+
|
|
1351
|
+
[Database resolution](/query-databases) explains why there are three, and [which one you need](/query-databases#which-do-i-need).
|
|
1352
|
+
|
|
1353
|
+
## Using the binding
|
|
1354
|
+
|
|
1355
|
+
Each Model names the D1 binding it queries, so a Model queries by itself during any request:
|
|
1356
|
+
|
|
1357
|
+
```ts
|
|
1358
|
+
import { Post, User } from "./models";
|
|
1359
|
+
|
|
1360
|
+
// No setup: each Model queries the binding its generated schema names during the request.
|
|
1361
|
+
const user = await User.findByOrThrow({ email: "ada@example.com" });
|
|
1362
|
+
const posts = await Post.where({ userId: user.id }).order({ id: "desc" }).toArray();
|
|
1363
|
+
```
|
|
1364
|
+
|
|
1365
|
+
`active-record schema` writes the binding into the generated schema your app’s base class holds, from your Wrangler config’s `d1_databases`.
|
|
1366
|
+
|
|
1367
|
+
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
|
+
|
|
1369
|
+
:::note
|
|
1370
|
+
The binding is only there during a request, inside a Worker. Tests and scripts that run in Node get their database from `withDatabase`. See [Testing](/testing).
|
|
1371
|
+
:::
|
|
1372
|
+
|
|
1373
|
+
## Using the request’s database
|
|
1374
|
+
|
|
1375
|
+
Some things belong to one request, such as a D1 Session that reads its own writes, or logging tagged with the request’s ID. Open a database for the request, and run its code inside `withDatabase`:
|
|
1376
|
+
|
|
1377
|
+
```ts
|
|
1378
|
+
import { withDatabase } from "@forestfuture/active-record";
|
|
1379
|
+
import { connect } from "@forestfuture/d1-record";
|
|
1380
|
+
|
|
1381
|
+
export default {
|
|
1382
|
+
fetch(request, env) {
|
|
1383
|
+
const db = connect(env.DB, { onQuery: log });
|
|
1384
|
+
return withDatabase(db, () => app.fetch(request, env));
|
|
1385
|
+
},
|
|
1386
|
+
};
|
|
1387
|
+
```
|
|
1388
|
+
|
|
1389
|
+
Every query started from a Model inside it, and everything it awaits, uses that database instead of the binding.
|
|
1390
|
+
|
|
1391
|
+
:::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`. The rest of d1-record doesn’t need it.
|
|
1393
|
+
:::
|
|
1394
|
+
|
|
1395
|
+
These pages use a request’s database:
|
|
1396
|
+
|
|
1397
|
+
- **[Read replicas](/read-your-own-writes):** a D1 Session per request.
|
|
1398
|
+
- **[Logging](/logging):** one request’s queries, tagged with its ID.
|
|
1399
|
+
- **[Testing](/testing):** a database for Models outside a Worker.
|
|
1400
|
+
- **[Multiple databases](/several-databases):** `withDatabase([...])`, matched to each Model’s binding.
|
|
1401
|
+
|
|
1402
|
+
## Using an explicit database
|
|
1403
|
+
|
|
1404
|
+
Start a query from a database you hold with `db.model`. It ignores `withDatabase`:
|
|
1405
|
+
|
|
1406
|
+
```ts
|
|
1407
|
+
import { connect } from "@forestfuture/d1-record";
|
|
1408
|
+
import { User } from "./models";
|
|
1409
|
+
|
|
1410
|
+
const db = connect(env.DB);
|
|
1411
|
+
const user = await db.model(User).findByOrThrow({ email: "ada@example.com" });
|
|
1412
|
+
```
|
|
1413
|
+
|
|
1414
|
+
To name your Models once, use `db.models`:
|
|
1415
|
+
|
|
1416
|
+
```ts
|
|
1417
|
+
import { Post, User } from "./models";
|
|
1418
|
+
|
|
1419
|
+
const models = db.models({ User, Post });
|
|
1420
|
+
const posts = await models.Post.where({ userId: user.id }).toArray();
|
|
1421
|
+
```
|
|
1422
|
+
|
|
1423
|
+
`connect(env.DB, { session, onQuery })` takes the same options as a request’s database.
|
|
1424
|
+
|
|
1425
|
+
## Batching writes
|
|
1426
|
+
|
|
1427
|
+
`batch` writes statements and records atomically, on the database they were built on:
|
|
1428
|
+
|
|
1429
|
+
```ts
|
|
1430
|
+
import { batch } from "@forestfuture/active-record";
|
|
1431
|
+
import { Post, User } from "./models";
|
|
1432
|
+
|
|
1433
|
+
const user = User.build({ email: "grace@example.com" });
|
|
1434
|
+
const post = Post.build({ userId: user.id, title: "Hello" });
|
|
1435
|
+
|
|
1436
|
+
// Atomic: all written, or none.
|
|
1437
|
+
await batch([user.toSave(), post.toSave(), Post.where({ userId: "old" }).toDeleteAll()]);
|
|
1438
|
+
```
|
|
1439
|
+
|
|
1440
|
+
Entries from a Model’s statics use the current database. `db.batch([...])` uses an explicit one. See [Bulk writes and batches](/batches).
|
|
1441
|
+
|
|
1442
|
+
---
|
|
1443
|
+
|
|
1444
|
+
# Console
|
|
1445
|
+
Source: https://d1-record.forestfuture.dev/console
|
|
1446
|
+
|
|
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 the folder with your Wrangler config:
|
|
1448
|
+
|
|
1449
|
+
```sh
|
|
1450
|
+
npx active-record console
|
|
1451
|
+
```
|
|
1452
|
+
|
|
1453
|
+
It prints which database and Models it opened, then waits for a line:
|
|
1454
|
+
|
|
1455
|
+
```text
|
|
1456
|
+
Local database DB (.wrangler/state)
|
|
1457
|
+
Models: Post, User
|
|
1458
|
+
|
|
1459
|
+
local> const user = await User.find("c5c765b4-b7e1-428e-aa00-88d58f622c71")
|
|
1460
|
+
#=> undefined
|
|
1461
|
+
local> user
|
|
1462
|
+
#=> User { id: 'c5c765b4-b7e1-428e-aa00-88d58f622c71', name: 'Alice', email: [FILTERED] }
|
|
1463
|
+
local> await user.update({ name: "Johnny" })
|
|
1464
|
+
#=> true
|
|
1465
|
+
local> const admins = await User.where({ role: "admin" }).toArray()
|
|
1466
|
+
#=> undefined
|
|
1467
|
+
```
|
|
1468
|
+
|
|
1469
|
+
Leave with `quit`, `exit`, or Ctrl-D. Ctrl-C stops a line that’s still running. `.help` lists the console’s own commands, and `npx active-record c` is the short form.
|
|
1470
|
+
|
|
1471
|
+
## What you can use
|
|
1472
|
+
|
|
1473
|
+
- **Your Models,** by class name, from every file in `src/models`. They query your database, local unless you pass `--remote`, with no `db` to pass.
|
|
1474
|
+
- **`db`,** your connected database, for `db.batch([...])` and `db.model(...)`.
|
|
1475
|
+
- **Top-level `await`,** and `const` and `let`, which last until you leave.
|
|
1476
|
+
|
|
1477
|
+
A record prints as it does in a log: its class and attributes, with a filtered attribute as `[FILTERED]` and an unsaved change next to the value it had. [Printing records](/models#printing-records) has the details.
|
|
1478
|
+
|
|
1479
|
+
An error prints and the console carries on.
|
|
1480
|
+
|
|
1481
|
+
## Reloading your Models
|
|
1482
|
+
|
|
1483
|
+
After you edit a Model, or a file it imports, read them again without leaving:
|
|
1484
|
+
|
|
1485
|
+
```text
|
|
1486
|
+
> reload!
|
|
1487
|
+
Reloaded: Post, User
|
|
1488
|
+
```
|
|
1489
|
+
|
|
1490
|
+
`.reload` does the same. A Model you added appears, and one whose file you removed goes. Records and values you already hold keep their old class, so run the lines that made them again.
|
|
1491
|
+
|
|
1492
|
+
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
|
+
|
|
1494
|
+
:::note
|
|
1495
|
+
Only files in your project’s folder are read again. Your database connection and `@forestfuture/d1-record` stay as they are.
|
|
1496
|
+
:::
|
|
1497
|
+
|
|
1498
|
+
## Seeing the SQL
|
|
1499
|
+
|
|
1500
|
+
Start with `--verbose` to see each statement a line runs, or turn it on and off while you work with `.verbose`:
|
|
1501
|
+
|
|
1502
|
+
```text
|
|
1503
|
+
> .verbose
|
|
1504
|
+
SQL logging on
|
|
1505
|
+
> await User.find(1)
|
|
1506
|
+
User 1.2ms SELECT * FROM "users" WHERE (("id" = ?)) LIMIT ? [ 1, 1 ]
|
|
1507
|
+
#=> User { id: 1, name: 'Alice', email: [FILTERED] }
|
|
1508
|
+
```
|
|
1509
|
+
|
|
1510
|
+
Each line shows the Model, the time, the SQL, and the values it bound. Filtered attributes show as `[FILTERED]`, as they do in `onQuery`. A statement that fails prints `failed` and the reason in place of the time. `verbose!` toggles it too, and `.verbose on` and `.verbose off` set it explicitly.
|
|
1511
|
+
|
|
1512
|
+
:::note
|
|
1513
|
+
The SQL comes from the database’s own `onQuery`, so a listener you set on your base class still runs as well.
|
|
1514
|
+
:::
|
|
1515
|
+
|
|
1516
|
+
## Choosing what to open
|
|
1517
|
+
|
|
1518
|
+
| Option | |
|
|
1519
|
+
| ------------------- | ------------------------------------------------------------------------------------------------------- |
|
|
1520
|
+
| `--database <name>` | The D1 binding to open, when your Wrangler config has several. |
|
|
1521
|
+
| `--models <path>` | Where your Models are: a folder (`src/models` by default) or one file (`src/models.ts`). |
|
|
1522
|
+
| `--config <file>` | Use this Wrangler config instead of finding `wrangler.jsonc`, `wrangler.json`, or `.toml`. |
|
|
1523
|
+
| `--no-history` | Don’t keep what you type in the history file. |
|
|
1524
|
+
| `--verbose` | Print each statement a line runs, to begin with. `.verbose` turns it on and off. |
|
|
1525
|
+
| `-e, --eval <code>` | Run this code, print its result, and exit. See [Running one piece of code](#running-one-piece-of-code). |
|
|
1526
|
+
| `--remote` | Open your remote database instead, after you type its name. See below. |
|
|
1527
|
+
| `--yes` | With `--remote`, don’t ask first. It’s also how to open it without a terminal. |
|
|
1528
|
+
| `--history` | Keep what you type in a remote session, which isn’t kept unless you ask. |
|
|
1529
|
+
|
|
1530
|
+
## Where your data lives
|
|
1531
|
+
|
|
1532
|
+
The console opens the local database in `.wrangler/state`, beside your Wrangler config. It’s the same one `wrangler dev` and `wrangler d1 migrations apply --local` use, so apply your migrations first, and what you change in the console is what your dev server sees.
|
|
1533
|
+
|
|
1534
|
+
It opens your remote database only when you ask with `--remote`, and never for a binding your config marks `remote: true` by itself.
|
|
1535
|
+
|
|
1536
|
+
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
|
+
|
|
1538
|
+
On a terminal, what you type is kept in `.wrangler/d1-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
|
+
|
|
1540
|
+
## Opening your remote database
|
|
1541
|
+
|
|
1542
|
+
`--remote` opens the real database your binding points at, to look at production data or fix one record by hand:
|
|
1543
|
+
|
|
1544
|
+
```sh
|
|
1545
|
+
npx active-record console --remote
|
|
1546
|
+
```
|
|
1547
|
+
|
|
1548
|
+
It names the database and waits for you to type its name. Anything else, including `y`, cancels and opens nothing. Anything you type or paste after the name is dropped, so a pasted block can’t run on the real database before you’ve seen the prompt:
|
|
1549
|
+
|
|
1550
|
+
```text
|
|
1551
|
+
Remote database DB (shop, id 1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d)
|
|
1552
|
+
What you change in the console is changed in this database, not a copy.
|
|
1553
|
+
Type its name to continue, anything else cancels: shop
|
|
1554
|
+
```
|
|
1555
|
+
|
|
1556
|
+
Once it’s open, the prompt says `remote>` (in red on a terminal) where a local session says `local>`, so the two can’t be mistaken for each other:
|
|
1557
|
+
|
|
1558
|
+
```text
|
|
1559
|
+
Remote database DB (shop, id 1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d)
|
|
1560
|
+
Models: Post, User
|
|
1561
|
+
|
|
1562
|
+
remote> await User.count()
|
|
1563
|
+
#=> 42
|
|
1564
|
+
```
|
|
1565
|
+
|
|
1566
|
+
:::warning[Changes can’t be undone]
|
|
1567
|
+
A change is made to the real database, for good. `await user.destroy()` deletes that row from your remote database.
|
|
1568
|
+
:::
|
|
1569
|
+
|
|
1570
|
+
The console signs in with your Wrangler login, or with `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID` in the environment, and takes the account from `account_id` in your Wrangler config when it names one. When Cloudflare refuses, the console prints its reason and how to sign in.
|
|
1571
|
+
|
|
1572
|
+
There’s no one to type the name unless both your input and output are a terminal, so a piped session refuses unless you add `--yes`, which is how a script opens it:
|
|
1573
|
+
|
|
1574
|
+
```sh
|
|
1575
|
+
echo 'await User.count()' | npx active-record console --remote --yes
|
|
1576
|
+
```
|
|
1577
|
+
|
|
1578
|
+
What you type isn’t kept unless you add `--history`, and then it goes in `.wrangler/d1-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
|
+
|
|
1580
|
+
:::note
|
|
1581
|
+
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 (…)`.
|
|
1582
|
+
:::
|
|
1583
|
+
|
|
1584
|
+
:::note
|
|
1585
|
+
A token needs **D1: Edit** and **Workers Scripts: Edit**, and the account needs a `workers.dev` subdomain, as `wrangler dev` needs for a remote binding.
|
|
1586
|
+
:::
|
|
1587
|
+
|
|
1588
|
+
## Running one piece of code
|
|
1589
|
+
|
|
1590
|
+
`-e` runs one piece of code with your Models and `db` in scope, prints its result, and exits, which is how to use the console from a script:
|
|
1591
|
+
|
|
1592
|
+
```sh
|
|
1593
|
+
npx active-record console -e 'await User.count()'
|
|
1594
|
+
```
|
|
1595
|
+
|
|
1596
|
+
```text
|
|
1597
|
+
42
|
|
1598
|
+
```
|
|
1599
|
+
|
|
1600
|
+
- **The result is on stdout.** A string prints as it is, without quotes, so `$(…)` captures it, and anything else prints as the console prints it, without `#=> `. `undefined` prints nothing. What your code logs with `console.log` comes first, and `console.error` goes to stderr, as in `node -e`.
|
|
1601
|
+
- **Everything else is on stderr:** which database and Models it opened, the SQL with `--verbose`, and a refusal to start.
|
|
1602
|
+
- **A failure exits 1.** Its stack goes to stderr, no result goes to stdout, and no statement after it runs. Success exits 0.
|
|
1603
|
+
- **Join statements with `;`.** The last value is the result: `-e 'await User.create({ name: "Dan" }); await User.count()'`.
|
|
1604
|
+
- **It keeps no history,** ignores what is piped to it, and has no time limit: stop it with Ctrl-C, or run it under `timeout`.
|
|
1605
|
+
|
|
1606
|
+
:::note
|
|
1607
|
+
Await every call. `User.find(1)` without `await` prints `Promise { <pending> }`, and a promise you don’t await may not finish before the console exits, and its failure isn’t reported.
|
|
1608
|
+
:::
|
|
1609
|
+
|
|
1610
|
+
:::note
|
|
1611
|
+
Put the code in single quotes, so your shell leaves `$`, `!`, and backticks alone. With `--remote`, `$(…)` makes stdout a pipe, so there is no terminal to ask: add `--yes`, as in `npx active-record console --remote --yes -e 'await User.count()'`.
|
|
1612
|
+
:::
|
|
1613
|
+
|
|
1614
|
+
## Running a few lines at once
|
|
1615
|
+
|
|
1616
|
+
Lines you paste or pipe run in order, each after the one before, and the console finishes them before it exits:
|
|
1617
|
+
|
|
1618
|
+
```sh
|
|
1619
|
+
echo 'await User.count()' | npx active-record console
|
|
1620
|
+
```
|
|
1621
|
+
|
|
1622
|
+
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
|
+
|
|
1624
|
+
:::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/d1-record` installed in your project. It uses your copies, so your Models and the console share one library.
|
|
1626
|
+
:::
|
|
1627
|
+
|
|
1628
|
+
:::warning[Only in projects you trust]
|
|
1629
|
+
The console runs your project’s code: your Models, and the `wrangler` and `@forestfuture/d1-record` in its `node_modules`. Run it in a project you’d run `wrangler dev` in.
|
|
1630
|
+
:::
|
|
1631
|
+
|
|
1632
|
+
> **Compared with Rails**
|
|
1633
|
+
>
|
|
1634
|
+
> This is `rails console` for D1: your Models in scope, and records printed as `inspect` prints them. `-e` is `rails runner` with the last value printed, which `rails runner` leaves to you.
|
|
1635
|
+
|
|
1636
|
+
> **Beyond Rails**
|
|
1637
|
+
>
|
|
1638
|
+
> `rails console` opens whichever environment you start it in, without asking. `--remote` asks you to type the database’s name first, and its prompt says `remote>`.
|
|
1639
|
+
|
|
1640
|
+
---
|
|
1641
|
+
|
|
1642
|
+
# D1’s limits
|
|
1643
|
+
Source: https://d1-record.forestfuture.dev/d1
|
|
1644
|
+
|
|
1645
|
+
d1-record follows Rails wherever D1 allows. These are the places D1 works differently, worth knowing before you design around them.
|
|
1646
|
+
|
|
1647
|
+
## No interactive transactions
|
|
1648
|
+
|
|
1649
|
+
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
|
+
|
|
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. d1-record uses the same batches itself:
|
|
1652
|
+
|
|
1653
|
+
- A destroy’s [`dependent` strategies](/associations#destroying-dependent-records) are written in one batch with the owner’s DELETE.
|
|
1654
|
+
- A record [autosaved](/associations#autosaving) with its owner joins the owner’s batch when the owner’s key is known in advance.
|
|
1655
|
+
|
|
1656
|
+
## Generate keys in code
|
|
1657
|
+
|
|
1658
|
+
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
|
+
|
|
1660
|
+
- A graph of new records built through associations saves in one atomic batch.
|
|
1661
|
+
- A batch can insert rows that point at each other.
|
|
1662
|
+
|
|
1663
|
+
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
|
+
|
|
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
|
+
## Uniqueness is checked twice
|
|
1670
|
+
|
|
1671
|
+
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.
|
|
1672
|
+
|
|
1673
|
+
`caseSensitive: false` compares with SQLite’s `lower()`, which only lowercases ASCII letters, so `"Ä"` and `"ä"` are still different.
|
|
1674
|
+
|
|
1675
|
+
## Bound parameters
|
|
1676
|
+
|
|
1677
|
+
D1 allows 100 bound values in one statement. d1-record 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
|
+
|
|
1679
|
+
## Foreign keys are enforced
|
|
1680
|
+
|
|
1681
|
+
D1 enforces the foreign keys a table declares with `REFERENCES`. Destroying a record whose rows still point at it throws `InvalidForeignKey`, unless the association has a [`dependent` strategy](/associations#destroying-dependent-records) that removes or updates those rows first. A foreign key that isn’t declared in the table isn’t checked at all.
|
|
1682
|
+
|
|
1683
|
+
## Nothing rolls back after a write
|
|
1684
|
+
|
|
1685
|
+
Once D1 has accepted a write, it’s done. An error thrown by an after-callback reaches the caller, but the record stays saved.
|
|
1686
|
+
|
|
1687
|
+
---
|
|
1688
|
+
|
|
1689
|
+
# Errors
|
|
1690
|
+
Source: https://d1-record.forestfuture.dev/errors
|
|
1691
|
+
|
|
1692
|
+
Every error d1-record throws extends `ActiveRecordError`, so one check separates them from anything else:
|
|
1693
|
+
|
|
1694
|
+
```ts
|
|
1695
|
+
import { ActiveRecordError } from "@forestfuture/active-record";
|
|
1696
|
+
|
|
1697
|
+
if (error instanceof ActiveRecordError) {
|
|
1698
|
+
// one of d1-record's own
|
|
1699
|
+
}
|
|
1700
|
+
```
|
|
1701
|
+
|
|
1702
|
+
## Lifecycle errors
|
|
1703
|
+
|
|
1704
|
+
| Error | When |
|
|
1705
|
+
| ----------------------- | ------------------------------------------------------------------------ |
|
|
1706
|
+
| `RecordNotFound` | `find`, `findByOrThrow`, or `reload` found nothing |
|
|
1707
|
+
| `RecordInvalid` | an `OrThrow` save found the record invalid; the record is on `.record` |
|
|
1708
|
+
| `RecordNotSaved` | a save was aborted by a callback, or needs an owner that isn’t saved |
|
|
1709
|
+
| `RecordNotDestroyed` | a destroy was aborted, or restricted by `restrictWithError` |
|
|
1710
|
+
| `RecordDestroyed` | writing to a record that’s already destroyed |
|
|
1711
|
+
| `CallbackAbort` | what `abort()` makes; caught by the lifecycle |
|
|
1712
|
+
| `AbortAfterPersistence` | `abort()` in an after-callback, too late to stop the write (`.callback`) |
|
|
1713
|
+
|
|
1714
|
+
## Usage errors
|
|
1715
|
+
|
|
1716
|
+
A usage error means the code needs to change:
|
|
1717
|
+
|
|
1718
|
+
| Error | When |
|
|
1719
|
+
| ---------------------- | ------------------------------------------------------------------------------- |
|
|
1720
|
+
| `InvalidModel` | a Model’s declaration is wrong, detected the first time it’s used |
|
|
1721
|
+
| `UnknownAttribute` | an attribute that isn’t declared, in `build`, `where`, `update`, … |
|
|
1722
|
+
| `MissingAttribute` | reading an attribute that `select` didn’t load |
|
|
1723
|
+
| `UnknownAssociation` | an association that isn’t declared |
|
|
1724
|
+
| `AssociationNotLoaded` | `loaded()` on an association that wasn’t loaded |
|
|
1725
|
+
| `IncompatibleRelation` | two Relations or writes can’t be used together (below) |
|
|
1726
|
+
| `IrreversibleOrder` | `last()` on a Relation ordered by an `sql` fragment |
|
|
1727
|
+
| `DeleteRestriction` | destroying an owner whose `restrictWithException` association still has records |
|
|
1728
|
+
| `NoDatabase` | using a record made with `new` rather than `build` |
|
|
1729
|
+
| `NoSession` | `db.bookmark()` on a Database opened without a session |
|
|
1730
|
+
|
|
1731
|
+
:::note
|
|
1732
|
+
A name from a request, such as `?include=` or a JSON key, only ever matches the Model’s own attributes and associations; `constructor` and `__proto__` are unknown like any other. Return a 400 for these errors.
|
|
1733
|
+
:::
|
|
1734
|
+
|
|
1735
|
+
### When Relations are incompatible
|
|
1736
|
+
|
|
1737
|
+
`IncompatibleRelation` is thrown for combinations that can’t make a correct query or write:
|
|
1738
|
+
|
|
1739
|
+
- **`or()`, `merge()`, or a scope** with a Relation of another Model, or one that resolves to another database when it runs. `or()` also needs both sides to have the same `select`, order, `limit`, `offset`, `distinct`, and `includes`, since only their conditions can be combined.
|
|
1740
|
+
- **`batch([...])`, `db.batch([...])`, `save()`, or `destroy()`** with statements or records from two databases, such as a `belongsTo` target built on another `connect()`. A write runs on one database. The message names where each database came from.
|
|
1741
|
+
- **`includes`** with `select(...).distinct()`. Preloading needs the keys, and adding them would undo the `distinct`.
|
|
1742
|
+
- **Preloading an association scope** that uses `limit`, `offset`, or `distinct`. One preload query serves every owner, so the limit would apply to all of their records together.
|
|
1743
|
+
- **`updateAll` or `deleteAll`** after `distinct()`: they reject with it, and `toUpdateAll`/`toDeleteAll` throw it.
|
|
1744
|
+
|
|
1745
|
+
## Constraint errors
|
|
1746
|
+
|
|
1747
|
+
When D1 refuses a write because of a constraint, it throws a subclass of `ConstraintViolation`:
|
|
1748
|
+
|
|
1749
|
+
| Error | Constraint |
|
|
1750
|
+
| ------------------- | ----------------------- |
|
|
1751
|
+
| `RecordNotUnique` | `UNIQUE`, `PRIMARY KEY` |
|
|
1752
|
+
| `InvalidForeignKey` | `FOREIGN KEY` |
|
|
1753
|
+
| `NotNullViolation` | `NOT NULL` |
|
|
1754
|
+
| `CheckViolation` | `CHECK` |
|
|
1755
|
+
|
|
1756
|
+
Each has D1’s original error as `cause`, the `table`, and, where D1’s message names them, the `columns` and `attributes`:
|
|
1757
|
+
|
|
1758
|
+
```ts
|
|
1759
|
+
import { RecordNotUnique } from "@forestfuture/active-record";
|
|
1760
|
+
|
|
1761
|
+
try {
|
|
1762
|
+
await user.save();
|
|
1763
|
+
} catch (error) {
|
|
1764
|
+
if (error instanceof RecordNotUnique && error.attributes.includes("email")) {
|
|
1765
|
+
user.errors.add("email", "has already been taken", { type: "taken" });
|
|
1766
|
+
} else {
|
|
1767
|
+
throw error;
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
```
|
|
1771
|
+
|
|
1772
|
+
Every method throws them, `save()` as well as `saveOrThrow()`. The record keeps its changes, so you can fix them and save again.
|
|
1773
|
+
|
|
1774
|
+
---
|
|
1775
|
+
|
|
1776
|
+
# Generators
|
|
1777
|
+
Source: https://d1-record.forestfuture.dev/generators
|
|
1778
|
+
|
|
1779
|
+
Generators write a table’s migration and its Model from a short description, then regenerate `src/db/schema.ts`. The [Command line](/command-line) reference lists every option.
|
|
1780
|
+
|
|
1781
|
+
## Adding a table
|
|
1782
|
+
|
|
1783
|
+
Name the Model, and list its columns, with `g model`:
|
|
1784
|
+
|
|
1785
|
+
```sh
|
|
1786
|
+
npx active-record g model Product 'name:string!' 'priceCents:integer!=0' user:references
|
|
1787
|
+
```
|
|
1788
|
+
|
|
1789
|
+
```
|
|
1790
|
+
Wrote migrations/0003_create_products.sql
|
|
1791
|
+
Wrote src/models/product.ts
|
|
1792
|
+
Wrote src/db/schema.ts (3 tables) from migrations/
|
|
1793
|
+
Next: npx active-record migrate
|
|
1794
|
+
```
|
|
1795
|
+
|
|
1796
|
+
Then apply the migration to your local database:
|
|
1797
|
+
|
|
1798
|
+
```sh
|
|
1799
|
+
npx active-record migrate
|
|
1800
|
+
```
|
|
1801
|
+
|
|
1802
|
+
The table is `products`, with an `id` generated in code, `created_at`, and `updated_at`.
|
|
1803
|
+
|
|
1804
|
+
- **`--id integer`** gives it a key D1 generates instead.
|
|
1805
|
+
- **`--no-timestamps`** leaves out the timestamps.
|
|
1806
|
+
|
|
1807
|
+
> **Compared with Rails**
|
|
1808
|
+
>
|
|
1809
|
+
> Keys are UUIDs, not auto-incrementing integers. With `--id integer`, a record and the records built through it no longer save atomically. See [Autosaving](/associations#autosaving).
|
|
1810
|
+
|
|
1811
|
+
Use `--remote` instead of `--local` when you deploy.
|
|
1812
|
+
|
|
1813
|
+
## Writing columns
|
|
1814
|
+
|
|
1815
|
+
Each column is `name:type`, with optional marks:
|
|
1816
|
+
|
|
1817
|
+
| Column | Means |
|
|
1818
|
+
| ---------------------- | -------------------------------------------------------------------------------- |
|
|
1819
|
+
| `title` | A `string`, the default type |
|
|
1820
|
+
| `email:string!:unique` | Required (`NOT NULL`), with a unique index |
|
|
1821
|
+
| `count:integer!=0` | Required, with a default of `0` |
|
|
1822
|
+
| `settings:json` | JSON, checked by D1 (`CHECK (json_valid(settings))`) |
|
|
1823
|
+
| `user:references` | `user_id`, pointing at `users`, indexed; the Model gets `user = belongsTo(User)` |
|
|
1824
|
+
|
|
1825
|
+
The [column syntax](/command-line#column-syntax) lists every type.
|
|
1826
|
+
|
|
1827
|
+
:::note
|
|
1828
|
+
Quote columns that contain `!`, so bash and zsh leave it alone.
|
|
1829
|
+
:::
|
|
1830
|
+
|
|
1831
|
+
> **Beyond Rails**
|
|
1832
|
+
>
|
|
1833
|
+
> Rails’ generators have no syntax for a column’s default. d1-record adds `=value` (`=0`, `=true`, `=draft`), because SQLite can’t add a required (`NOT NULL`) column to an existing table without one.
|
|
1834
|
+
|
|
1835
|
+
## Changing a table
|
|
1836
|
+
|
|
1837
|
+
Write a migration with `g migration`. It reads what to do from the migration’s name:
|
|
1838
|
+
|
|
1839
|
+
```sh
|
|
1840
|
+
npx active-record g migration AddSlugToPosts slug:string:unique # ADD COLUMN, with a unique index
|
|
1841
|
+
npx active-record g migration RemoveSlugFromPosts slug # DROP COLUMN
|
|
1842
|
+
npx active-record g migration BackfillSlugs # an empty migration to write yourself
|
|
1843
|
+
```
|
|
1844
|
+
|
|
1845
|
+
The name can be written `AddSlugToPosts` or `add_slug_to_posts`. Apply each migration afterwards, as above.
|
|
1846
|
+
|
|
1847
|
+
SQLite can’t add a required column without a default, so the generator refuses one. Give it a default, `slug:string!=draft`, or leave out the `!`.
|
|
1848
|
+
|
|
1849
|
+
:::warning[A default and a unique index don’t mix on a table with rows]
|
|
1850
|
+
`g migration AddSlugToPosts 'slug:string!=draft:unique'` is accepted, but applying it to a table with more than one row fails: every row gets `draft`, which the unique index refuses. Add the column without the index, fill it in, then add the index in a later migration.
|
|
1851
|
+
:::
|
|
1852
|
+
|
|
1853
|
+
## Referencing the same table
|
|
1854
|
+
|
|
1855
|
+
`g model Category parent:references` points `parent_id` at a `parents` table and writes `parent = belongsTo(Parent)`, since it can’t know the parent is another category. Edit both files before applying the migration:
|
|
1856
|
+
|
|
1857
|
+
1. In the migration, point the column at `categories`, and make it optional, since top-level categories have no parent:
|
|
1858
|
+
|
|
1859
|
+
```sql
|
|
1860
|
+
parent_id TEXT REFERENCES categories (id),
|
|
1861
|
+
```
|
|
1862
|
+
|
|
1863
|
+
2. In the Model, use `Category` itself, and add the other direction if you want it.
|
|
1864
|
+
|
|
1865
|
+
```ts
|
|
1866
|
+
import { belongsTo, hasMany } from "@forestfuture/active-record";
|
|
1867
|
+
|
|
1868
|
+
export class Category extends ApplicationRecord {
|
|
1869
|
+
parent = belongsTo(Category); // foreign key: parentId, from the association's name
|
|
1870
|
+
children = hasMany(Category, { foreignKey: "parentId" }); // not the default, categoryId
|
|
1871
|
+
}
|
|
1872
|
+
```
|
|
1873
|
+
|
|
1874
|
+
> **Compared with Rails**
|
|
1875
|
+
>
|
|
1876
|
+
> Rails writes `belongs_to :parent, class_name: "Category", optional: true`. Here the association takes the class itself, so there’s no `class_name`, and whether a parent is required comes from the column: `parentId` can be `null` because the migration allows it.
|
|
1877
|
+
|
|
1878
|
+
## Keeping Models in another folder
|
|
1879
|
+
|
|
1880
|
+
By default, Models and `application-record.ts` go in `src/models/`. To keep them elsewhere, pass `--models` to every command:
|
|
1881
|
+
|
|
1882
|
+
```sh
|
|
1883
|
+
npx active-record schema --models src/app/models
|
|
1884
|
+
npx active-record g model Product 'name:string!' --models src/app/models
|
|
1885
|
+
```
|
|
1886
|
+
|
|
1887
|
+
:::note
|
|
1888
|
+
`active-record schema` writes `application-record.ts` there and reads your Models from there, and the generators write Models that import it, so both need `--models`. A `package.json` script saves retyping it: `"db:schema": "active-record schema --models src/app/models"`.
|
|
1889
|
+
:::
|
|
1890
|
+
|
|
1891
|
+
## Keeping the schema current
|
|
1892
|
+
|
|
1893
|
+
The generators regenerate `src/db/schema.ts` themselves. After writing or editing a migration by hand, or adding or renaming a Model, regenerate it:
|
|
1894
|
+
|
|
1895
|
+
```sh
|
|
1896
|
+
npx active-record schema
|
|
1897
|
+
```
|
|
1898
|
+
|
|
1899
|
+
- **`--watch`** regenerates it whenever a migration or a Model file changes.
|
|
1900
|
+
- **`--check`** fails when the committed schema is out of date. Run it in CI.
|
|
1901
|
+
|
|
1902
|
+
---
|
|
1903
|
+
|
|
1904
|
+
# Getting started
|
|
1905
|
+
Source: https://d1-record.forestfuture.dev/getting-started
|
|
1906
|
+
|
|
1907
|
+
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
|
+
|
|
1909
|
+
:::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.6.0` never takes one.
|
|
1911
|
+
:::
|
|
1912
|
+
|
|
1913
|
+
## Prerequisites
|
|
1914
|
+
|
|
1915
|
+
You’ll need:
|
|
1916
|
+
|
|
1917
|
+
- **A Worker project** with [Wrangler](https://developers.cloudflare.com/workers/wrangler/). `npm create cloudflare@latest` makes one.
|
|
1918
|
+
- **A D1 database bound as `DB`.** Create one with `npx wrangler d1 create my-app-db`, then add the snippet it prints to your Wrangler config:
|
|
1919
|
+
|
|
1920
|
+
```jsonc wrangler.jsonc
|
|
1921
|
+
{
|
|
1922
|
+
"d1_databases": [
|
|
1923
|
+
{ "binding": "DB", "database_name": "my-app-db", "database_id": "<the id it printed>" },
|
|
1924
|
+
],
|
|
1925
|
+
}
|
|
1926
|
+
```
|
|
1927
|
+
|
|
1928
|
+
- **Node.js 22.13 or later**, for the command line.
|
|
1929
|
+
|
|
1930
|
+
## Installing Active Record
|
|
1931
|
+
|
|
1932
|
+
Install the core and its D1 adapter:
|
|
1933
|
+
|
|
1934
|
+
```sh
|
|
1935
|
+
npm install @forestfuture/active-record @forestfuture/d1-record
|
|
1936
|
+
```
|
|
1937
|
+
|
|
1938
|
+
## Generating the Models
|
|
1939
|
+
|
|
1940
|
+
The generator writes a table’s migration and its Model in one step, like `rails generate model`. Generate users first, since each post belongs to a user:
|
|
1941
|
+
|
|
1942
|
+
```sh
|
|
1943
|
+
npx active-record g model User 'email:string!:unique' 'isActive:boolean!=true'
|
|
1944
|
+
npx active-record g model Post user:references 'title:string!' publishedAt:datetime
|
|
1945
|
+
```
|
|
1946
|
+
|
|
1947
|
+
Each column is `name:type`. A `!` makes it required, `=true` sets a default, `:unique` adds a unique index, and `user:references` links each post to a user. The quotes stop your shell from reading the `!`.
|
|
1948
|
+
|
|
1949
|
+
The generator writes these files:
|
|
1950
|
+
|
|
1951
|
+
| File | What it is |
|
|
1952
|
+
| ----------------------------------------------------------- | -------------------------------------------------------------------- |
|
|
1953
|
+
| `migrations/0001_create_users.sql`, `0002_create_posts.sql` | The SQL that creates each table |
|
|
1954
|
+
| `src/db/schema.ts` | Every table’s columns, generated from the migrations. Don’t edit it. |
|
|
1955
|
+
| `src/models/application-record.ts` | Your app’s base class. It’s yours to edit. |
|
|
1956
|
+
| `src/models/user.ts`, `post.ts` | One Model per table |
|
|
1957
|
+
|
|
1958
|
+
Here’s the migration for posts:
|
|
1959
|
+
|
|
1960
|
+
```sql migrations/0002_create_posts.sql
|
|
1961
|
+
CREATE TABLE posts (
|
|
1962
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
1963
|
+
user_id TEXT NOT NULL REFERENCES users (id),
|
|
1964
|
+
title TEXT NOT NULL,
|
|
1965
|
+
published_at DATETIME,
|
|
1966
|
+
created_at DATETIME NOT NULL,
|
|
1967
|
+
updated_at DATETIME NOT NULL
|
|
1968
|
+
);
|
|
1969
|
+
CREATE INDEX index_posts_on_user_id ON posts (user_id);
|
|
1970
|
+
```
|
|
1971
|
+
|
|
1972
|
+
> **Compared with Rails**
|
|
1973
|
+
>
|
|
1974
|
+
> Each `id` is a UUID generated in code, not an auto-incrementing integer, so a user and their posts save together atomically. [Generators](/generators#adding-a-table) covers integer keys.
|
|
1975
|
+
|
|
1976
|
+
## Creating the tables
|
|
1977
|
+
|
|
1978
|
+
Apply the migrations to your local database:
|
|
1979
|
+
|
|
1980
|
+
```sh
|
|
1981
|
+
npx active-record migrate
|
|
1982
|
+
```
|
|
1983
|
+
|
|
1984
|
+
Use `npx active-record migrate --remote` when you deploy.
|
|
1985
|
+
|
|
1986
|
+
## Adding behavior
|
|
1987
|
+
|
|
1988
|
+
A Model’s attributes come from the generated schema, so a Model only declares behavior. The generated `Post` already belongs to a user:
|
|
1989
|
+
|
|
1990
|
+
```ts src/models/post.ts
|
|
1991
|
+
import { belongsTo } from "@forestfuture/active-record";
|
|
1992
|
+
import { ApplicationRecord } from "./application-record";
|
|
1993
|
+
import { User } from "./user";
|
|
1994
|
+
|
|
1995
|
+
export class Post extends ApplicationRecord {
|
|
1996
|
+
user = belongsTo(User);
|
|
1997
|
+
}
|
|
1998
|
+
```
|
|
1999
|
+
|
|
2000
|
+
The generated `User` is one line. Its table, `users`, comes from its class name:
|
|
2001
|
+
|
|
2002
|
+
```ts src/models/user.ts
|
|
2003
|
+
import { ApplicationRecord } from "./application-record";
|
|
2004
|
+
|
|
2005
|
+
export class User extends ApplicationRecord {}
|
|
2006
|
+
```
|
|
2007
|
+
|
|
2008
|
+
Give it posts, a scope for active users, and rules for saving:
|
|
2009
|
+
|
|
2010
|
+
```ts src/models/user.ts
|
|
2011
|
+
import { hasMany } from "@forestfuture/active-record";
|
|
2012
|
+
import { ApplicationRecord } from "./application-record";
|
|
2013
|
+
import { Post } from "./post";
|
|
2014
|
+
|
|
2015
|
+
export class User extends ApplicationRecord {
|
|
2016
|
+
posts = hasMany(Post, { dependent: "destroy" }); // posts.user_id points here
|
|
2017
|
+
|
|
2018
|
+
static active = this.scope((q) => q.where({ isActive: true }));
|
|
2019
|
+
|
|
2020
|
+
static {
|
|
2021
|
+
this.validates("email", { presence: true, uniqueness: true });
|
|
2022
|
+
this.beforeSave((user) => {
|
|
2023
|
+
user.email = user.email.toLowerCase();
|
|
2024
|
+
});
|
|
2025
|
+
}
|
|
2026
|
+
}
|
|
2027
|
+
```
|
|
2028
|
+
|
|
2029
|
+
- `user.posts()` finds the user’s posts, and `dependent: "destroy"` destroys them with the user.
|
|
2030
|
+
- `User.active()` finds active users.
|
|
2031
|
+
- `validates` and `beforeSave` run on every save. An invalid user isn’t saved, and `user.errors` says why.
|
|
2032
|
+
|
|
2033
|
+
## Using the Models
|
|
2034
|
+
|
|
2035
|
+
Queries start from the Model. Each Model uses the `DB` binding, so there’s nothing to connect:
|
|
2036
|
+
|
|
2037
|
+
```ts src/index.ts
|
|
2038
|
+
import { User } from "./models/user";
|
|
2039
|
+
|
|
2040
|
+
export default {
|
|
2041
|
+
async fetch(request: Request): Promise<Response> {
|
|
2042
|
+
// GET: the 20 newest active users, each with their posts.
|
|
2043
|
+
if (request.method === "GET") {
|
|
2044
|
+
const users = await User.active()
|
|
2045
|
+
.includes("posts") // loaded in one extra query, not one per user
|
|
2046
|
+
.order({ createdAt: "desc" })
|
|
2047
|
+
.limit(20)
|
|
2048
|
+
.toArray();
|
|
2049
|
+
return Response.json(users);
|
|
2050
|
+
}
|
|
2051
|
+
|
|
2052
|
+
// POST: sign up a user with a first post, saved together.
|
|
2053
|
+
const { email } = await request.json<{ email: string }>();
|
|
2054
|
+
const user = User.build({ email });
|
|
2055
|
+
user.posts().build({ title: "Hello, D1" });
|
|
2056
|
+
|
|
2057
|
+
// save() validates and runs callbacks; false means it wasn't saved, and why is in errors.
|
|
2058
|
+
if (!(await user.save())) {
|
|
2059
|
+
return Response.json({ errors: user.errors.fullMessages() }, { status: 422 });
|
|
2060
|
+
}
|
|
2061
|
+
return Response.json(user, { status: 201 });
|
|
2062
|
+
},
|
|
2063
|
+
} satisfies ExportedHandler<Env>;
|
|
2064
|
+
```
|
|
2065
|
+
|
|
2066
|
+
- `includes("posts")` loads every user’s posts in one more query.
|
|
2067
|
+
- A post built with `user.posts().build(…)` is saved with its user, in one atomic batch.
|
|
2068
|
+
- `save()` resolves to `false` when validation fails.
|
|
2069
|
+
|
|
2070
|
+
## Trying it
|
|
2071
|
+
|
|
2072
|
+
Start the Worker:
|
|
2073
|
+
|
|
2074
|
+
```sh
|
|
2075
|
+
npx wrangler dev
|
|
2076
|
+
```
|
|
2077
|
+
|
|
2078
|
+
In another terminal, sign up a user, then list the users:
|
|
2079
|
+
|
|
2080
|
+
```sh
|
|
2081
|
+
curl -X POST http://localhost:8787 -d '{"email":"Ada@Example.com"}'
|
|
2082
|
+
curl http://localhost:8787
|
|
2083
|
+
```
|
|
2084
|
+
|
|
2085
|
+
The list includes Ada, with her email lowercased by `beforeSave`. Sign her up again, and you’ll get a `422` with `["Email has already been taken"]`.
|
|
2086
|
+
|
|
2087
|
+
## Next steps
|
|
2088
|
+
|
|
2089
|
+
- **[Models](/models):** attributes, types, and overrides.
|
|
2090
|
+
- **[Querying](/querying):** conditions, ordering, scopes, and preloading.
|
|
2091
|
+
- **[Persistence](/persistence):** saving and destroying records.
|
|
2092
|
+
- **[Associations](/associations):** `hasMany`, `belongsTo`, and `hasOne`.
|
|
2093
|
+
- **[Generators](/generators):** every way to write columns.
|
|
2094
|
+
- **[Bulk writes and batches](/batches):** writing several changes at once.
|
|
2095
|
+
|
|
2096
|
+
---
|
|
2097
|
+
|
|
2098
|
+
# Logging
|
|
2099
|
+
Source: https://d1-record.forestfuture.dev/logging
|
|
2100
|
+
|
|
2101
|
+
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
|
+
|
|
2103
|
+
| Field | |
|
|
2104
|
+
| --------------- | ---------------------------------------------------------------- |
|
|
2105
|
+
| `model` | The Model’s class name, such as `"Product"` |
|
|
2106
|
+
| `sql`, `params` | The statement and its bound values |
|
|
2107
|
+
| `durationMs` | How long it took; in a batch, D1’s own timing for each statement |
|
|
2108
|
+
| `meta` | D1’s result metadata (rows read and written, …) |
|
|
2109
|
+
| `error` | D1’s error, when it failed |
|
|
2110
|
+
|
|
2111
|
+
Send these wherever you like. A listener never changes a query’s outcome: one that throws is logged with `console.error`, and the query’s result stands.
|
|
2112
|
+
|
|
2113
|
+
Set a listener in one of two places:
|
|
2114
|
+
|
|
2115
|
+
| | Where | Knows the request? |
|
|
2116
|
+
| ------------------------- | ----------------------------------------------------- | ------------------ |
|
|
2117
|
+
| **Every query, app-wide** | `static override onQuery` on your app’s base class | No |
|
|
2118
|
+
| **One request’s queries** | `connect(env.DB, { onQuery })`, run in `withDatabase` | Yes |
|
|
2119
|
+
|
|
2120
|
+
If both are set, the request’s listener runs first, then the base class’s.
|
|
2121
|
+
|
|
2122
|
+
## Logging every query
|
|
2123
|
+
|
|
2124
|
+
Set `onQuery` on your app’s base class, in `application-record.ts`, to see every statement of every Model:
|
|
2125
|
+
|
|
2126
|
+
```ts
|
|
2127
|
+
import { Model } from "@forestfuture/active-record";
|
|
2128
|
+
import { type QueryListener } from "@forestfuture/d1-record";
|
|
2129
|
+
import { schema } from "../db/schema";
|
|
2130
|
+
|
|
2131
|
+
// src/models/application-record.ts: every query, from every Model, whichever database runs it.
|
|
2132
|
+
export abstract class ApplicationRecord extends Model {
|
|
2133
|
+
static override schema = schema;
|
|
2134
|
+
|
|
2135
|
+
static override onQuery: QueryListener = ({ model, sql, durationMs, error }) => {
|
|
2136
|
+
console.log(`${model} ${durationMs.toFixed(1)}ms ${sql}`, error ?? "");
|
|
2137
|
+
};
|
|
2138
|
+
}
|
|
2139
|
+
```
|
|
2140
|
+
|
|
2141
|
+
It can’t tell requests apart. A Model can set its own `static override onQuery`, which replaces the base class’s for that Model.
|
|
2142
|
+
|
|
2143
|
+
## Logging one request’s queries
|
|
2144
|
+
|
|
2145
|
+
To group a request’s queries, open its database with a listener that knows the request, and run the request inside `withDatabase`:
|
|
2146
|
+
|
|
2147
|
+
```ts
|
|
2148
|
+
import { withDatabase } from "@forestfuture/active-record";
|
|
2149
|
+
import { connect } from "@forestfuture/d1-record";
|
|
2150
|
+
|
|
2151
|
+
// src/worker.ts: one request's queries, tagged with its ID, as JSON lines for Workers Logs.
|
|
2152
|
+
// `app` stands for what your app exports as its Worker today: a framework's handler, or your own.
|
|
2153
|
+
export const logged = {
|
|
2154
|
+
fetch(request, env, ctx) {
|
|
2155
|
+
const requestId = request.headers.get("cf-ray") ?? crypto.randomUUID();
|
|
2156
|
+
const db = connect(env.DB, {
|
|
2157
|
+
onQuery: ({ model, sql, params, durationMs, error }) =>
|
|
2158
|
+
console.log(
|
|
2159
|
+
JSON.stringify({
|
|
2160
|
+
requestId,
|
|
2161
|
+
model,
|
|
2162
|
+
ms: Math.round(durationMs),
|
|
2163
|
+
sql,
|
|
2164
|
+
params,
|
|
2165
|
+
error: error instanceof Error ? error.message : undefined,
|
|
2166
|
+
}),
|
|
2167
|
+
),
|
|
2168
|
+
});
|
|
2169
|
+
|
|
2170
|
+
// Every query from a Model inside (Product.find, user.save(), …) goes through db.
|
|
2171
|
+
return withDatabase(db, () => app.fetch(request, env, ctx));
|
|
2172
|
+
},
|
|
2173
|
+
} satisfies ExportedHandler<Env>;
|
|
2174
|
+
```
|
|
2175
|
+
|
|
2176
|
+
Logged as JSON, each line can be filtered by `requestId` in [Workers Logs](https://developers.cloudflare.com/workers/observability/logs/workers-logs/). Turn them on with `"observability": { "enabled": true }` in your Wrangler config.
|
|
2177
|
+
|
|
2178
|
+
:::note
|
|
2179
|
+
`withDatabase` needs Node.js compatibility, which is on by default for compatibility dates from 2026-08-04. For an earlier date, add `"compatibility_flags": ["nodejs_compat"]`.
|
|
2180
|
+
:::
|
|
2181
|
+
|
|
2182
|
+
## Logging only in development
|
|
2183
|
+
|
|
2184
|
+
Check a variable that only `.dev.vars` sets, such as `LOG_SQL=1`. For one request’s listener:
|
|
2185
|
+
|
|
2186
|
+
```ts
|
|
2187
|
+
import { withDatabase } from "@forestfuture/active-record";
|
|
2188
|
+
import { connect, type QueryListener } from "@forestfuture/d1-record";
|
|
2189
|
+
|
|
2190
|
+
// LOG_SQL=1 in .dev.vars: logging in development only, nothing in production.
|
|
2191
|
+
const onQuery: QueryListener | undefined = env.LOG_SQL
|
|
2192
|
+
? ({ model, sql, durationMs }) => console.log(`${model} ${durationMs.toFixed(1)}ms ${sql}`)
|
|
2193
|
+
: undefined;
|
|
2194
|
+
|
|
2195
|
+
return withDatabase(connect(env.DB, { onQuery }), () => app.fetch(request, env, ctx));
|
|
2196
|
+
```
|
|
2197
|
+
|
|
2198
|
+
The app-wide listener reads the variable from `cloudflare:workers` when a query runs:
|
|
2199
|
+
|
|
2200
|
+
```ts
|
|
2201
|
+
import { Model } from "@forestfuture/active-record";
|
|
2202
|
+
import { type QueryListener } from "@forestfuture/d1-record";
|
|
2203
|
+
import { env as workerEnv } from "cloudflare:workers";
|
|
2204
|
+
import { schema } from "../db/schema";
|
|
2205
|
+
|
|
2206
|
+
// Logs only when LOG_SQL is set (in .dev.vars), read from the Worker's env when a query runs.
|
|
2207
|
+
export abstract class QuietInProduction extends Model {
|
|
2208
|
+
static override schema = schema;
|
|
2209
|
+
|
|
2210
|
+
static override onQuery: QueryListener = ({ model, sql, durationMs }) => {
|
|
2211
|
+
if ((workerEnv as { LOG_SQL?: string }).LOG_SQL) {
|
|
2212
|
+
console.log(`${model} ${durationMs.toFixed(1)}ms ${sql}`);
|
|
2213
|
+
}
|
|
2214
|
+
};
|
|
2215
|
+
}
|
|
2216
|
+
```
|
|
2217
|
+
|
|
2218
|
+
## Timing queries in the browser
|
|
2219
|
+
|
|
2220
|
+
To see a request’s database time in the browser’s developer tools, add it up, and send it as a `Server-Timing` header:
|
|
2221
|
+
|
|
2222
|
+
```ts
|
|
2223
|
+
import { withDatabase } from "@forestfuture/active-record";
|
|
2224
|
+
import { connect } from "@forestfuture/d1-record";
|
|
2225
|
+
import { User } from "./models";
|
|
2226
|
+
|
|
2227
|
+
let queries = 0;
|
|
2228
|
+
let total = 0;
|
|
2229
|
+
const db = connect(env.DB, {
|
|
2230
|
+
onQuery({ durationMs }) {
|
|
2231
|
+
queries += 1;
|
|
2232
|
+
total += durationMs;
|
|
2233
|
+
},
|
|
2234
|
+
});
|
|
2235
|
+
|
|
2236
|
+
const response = await withDatabase(db, async () =>
|
|
2237
|
+
Response.json(await User.active().toArray()),
|
|
2238
|
+
);
|
|
2239
|
+
// Shown in the browser's developer tools, under the request's Timing.
|
|
2240
|
+
response.headers.append(
|
|
2241
|
+
"server-timing",
|
|
2242
|
+
`d1;dur=${total.toFixed(1)};desc="${queries} queries"`,
|
|
2243
|
+
);
|
|
2244
|
+
return response;
|
|
2245
|
+
```
|
|
2246
|
+
|
|
2247
|
+
## Keeping secrets out of the logs
|
|
2248
|
+
|
|
2249
|
+
Listeners see the values of passwords, tokens, keys, and emails as `"[FILTERED]"`, while D1 still gets the real values. [Models](/models#filtering-attributes) lists the attributes filtered by default, and everywhere their values are hidden.
|
|
2250
|
+
|
|
2251
|
+
### Filtering more attributes
|
|
2252
|
+
|
|
2253
|
+
Name them on your app’s base class, spreading in the defaults:
|
|
2254
|
+
|
|
2255
|
+
```ts
|
|
2256
|
+
import { Model } from "@forestfuture/active-record";
|
|
2257
|
+
|
|
2258
|
+
// src/models/application-record.ts
|
|
2259
|
+
export class Base extends Model {
|
|
2260
|
+
// Rails' defaults, plus an IBAN and a date of birth:
|
|
2261
|
+
static override filterAttributes = [...Model.filterAttributes, "iban", /^dateOfBirth$/];
|
|
2262
|
+
}
|
|
2263
|
+
```
|
|
2264
|
+
|
|
2265
|
+
A string matches any attribute whose snake_case name contains it, so `"iban"` also covers `ibanNumber`. Use a RegExp to match one name exactly.
|
|
2266
|
+
|
|
2267
|
+
### Seeing a filtered attribute
|
|
2268
|
+
|
|
2269
|
+
To see one while debugging, leave it out of the list in development:
|
|
2270
|
+
|
|
2271
|
+
```ts
|
|
2272
|
+
import { Model } from "@forestfuture/active-record";
|
|
2273
|
+
import { schema } from "../db/schema";
|
|
2274
|
+
|
|
2275
|
+
export abstract class ApplicationRecord extends Model {
|
|
2276
|
+
static override schema = schema;
|
|
2277
|
+
static override filterAttributes = Model.filterAttributes.filter((entry) => entry !== "email");
|
|
2278
|
+
}
|
|
2279
|
+
```
|
|
2280
|
+
|
|
2281
|
+
### Filtering `sql` fragments
|
|
2282
|
+
|
|
2283
|
+
A bare value inside an `sql` fragment has no attribute, so it’s logged as given. Write a secret as `column("token").value(token)`, or compare it with a condition such as `where({ token })`, and it’s filtered. Otherwise, leave `params` out of what you log.
|
|
2284
|
+
|
|
2285
|
+
> **Compared with Rails**
|
|
2286
|
+
>
|
|
2287
|
+
> Rails filters by its app-wide `filter_parameters`, against parameter and column names. d1-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
|
+
|
|
2289
|
+
---
|
|
2290
|
+
|
|
2291
|
+
# Models
|
|
2292
|
+
Source: https://d1-record.forestfuture.dev/models
|
|
2293
|
+
|
|
2294
|
+
A Model describes one table. Its attributes come from your migrations, through the generated schema, so the Model only declares behavior.
|
|
2295
|
+
|
|
2296
|
+
## Defining Models
|
|
2297
|
+
|
|
2298
|
+
### Generating `ApplicationRecord`
|
|
2299
|
+
|
|
2300
|
+
The first time you run `active-record schema`, it writes `src/models/application-record.ts`:
|
|
2301
|
+
|
|
2302
|
+
```ts
|
|
2303
|
+
import { Model } from "@forestfuture/active-record";
|
|
2304
|
+
import { schema } from "../db/schema";
|
|
2305
|
+
|
|
2306
|
+
export abstract class ApplicationRecord extends Model {
|
|
2307
|
+
static override schema = schema;
|
|
2308
|
+
}
|
|
2309
|
+
```
|
|
2310
|
+
|
|
2311
|
+
It’s an ordinary class, and yours to edit. The schema it holds gives each Model its attributes and the D1 binding its queries use. Methods, callbacks, and scopes you write on it are every Model’s. See [Shared behavior](/shared-behavior).
|
|
2312
|
+
|
|
2313
|
+
`ApplicationRecord` has no table of its own, so you can’t query it.
|
|
2314
|
+
|
|
2315
|
+
### Extending `ApplicationRecord`
|
|
2316
|
+
|
|
2317
|
+
Define each Model by extending `ApplicationRecord`:
|
|
2318
|
+
|
|
2319
|
+
```ts
|
|
2320
|
+
import { ApplicationRecord } from "./application-record";
|
|
2321
|
+
|
|
2322
|
+
export class Product extends ApplicationRecord {
|
|
2323
|
+
static newest = this.scope((q) => q.order({ createdAt: "desc" }));
|
|
2324
|
+
}
|
|
2325
|
+
```
|
|
2326
|
+
|
|
2327
|
+
The class name names the table, so `Product` reads and writes `products`. The table’s attributes, primary key, and types come from `src/db/schema.ts`.
|
|
2328
|
+
|
|
2329
|
+
[`active-record schema`](/command-line#active-record-schema) writes that file from your migrations and your Models. Run it after you add a Model or a migration. [`active-record g model`](/generators) runs it for you.
|
|
2330
|
+
|
|
2331
|
+
A subclass shares its parent’s table:
|
|
2332
|
+
|
|
2333
|
+
```ts
|
|
2334
|
+
import { Product } from "./models";
|
|
2335
|
+
|
|
2336
|
+
export class FeaturedProduct extends Product {}
|
|
2337
|
+
```
|
|
2338
|
+
|
|
2339
|
+
You can still set `static primaryKey`, as long as it names an attribute.
|
|
2340
|
+
|
|
2341
|
+
### Overriding attributes
|
|
2342
|
+
|
|
2343
|
+
Generated attributes are usually all you need. When a column holds something its type doesn’t say, such as a boolean in a plain `INTEGER`, override the attribute in `static attributes`:
|
|
2344
|
+
|
|
2345
|
+
```ts
|
|
2346
|
+
import { ApplicationRecord } from "./application-record";
|
|
2347
|
+
|
|
2348
|
+
export class Product extends ApplicationRecord {
|
|
2349
|
+
static override attributes = {
|
|
2350
|
+
available: "boolean", // the column is a plain INTEGER: read it as a boolean
|
|
2351
|
+
internalNotes: false, // ignored: never read or written
|
|
2352
|
+
priceCents: { default: () => 100 }, // replaces the column's default, 0
|
|
2353
|
+
} as const;
|
|
2354
|
+
|
|
2355
|
+
static inStock = this.scope((q) => q.where({ available: true }));
|
|
2356
|
+
}
|
|
2357
|
+
```
|
|
2358
|
+
|
|
2359
|
+
Write the object `as const`, so TypeScript keeps each type name. Without it, the class is a compile error.
|
|
2360
|
+
|
|
2361
|
+
An override is one of these:
|
|
2362
|
+
|
|
2363
|
+
| Override | Does |
|
|
2364
|
+
| ----------------------------------------- | ----------------------------------------------------------------------------------------------------- |
|
|
2365
|
+
| `"boolean"` (a type name) | Reads and writes the attribute as that type |
|
|
2366
|
+
| `{ type?, null?, default?, generateId? }` | Replaces those parts of the generated attribute; `null: false` makes it non-null in TypeScript |
|
|
2367
|
+
| `false` | Ignores the column: it’s never typed, read, or written, and queries name their columns instead of `*` |
|
|
2368
|
+
|
|
2369
|
+
An override of an attribute the table doesn’t have throws `InvalidModel`, and `active-record schema` reports it. So does an override that changes a column or ignores the primary key.
|
|
2370
|
+
|
|
2371
|
+
- **Changing a `type`** drops the generated default or `generateId`, so the column’s own default applies unless you give one.
|
|
2372
|
+
- **A `default` and `generateId`** replace each other, so an attribute has one or the other. `generateId` is only for strings.
|
|
2373
|
+
- **A `default`** isn’t type-checked yet ([#74](https://github.com/forestfuture/active-record/issues/74)). One that returns a value the type can’t cast throws `TypeError` when a record is built.
|
|
2374
|
+
- **Ignoring a `NOT NULL` column** without a default makes inserts fail, so give it a default in a migration first.
|
|
2375
|
+
|
|
2376
|
+
### Narrowing types
|
|
2377
|
+
|
|
2378
|
+
To give an attribute a narrower type than its column’s, declare it in the class:
|
|
2379
|
+
|
|
2380
|
+
```ts
|
|
2381
|
+
import { ApplicationRecord } from "./application-record";
|
|
2382
|
+
|
|
2383
|
+
export class Post extends ApplicationRecord {
|
|
2384
|
+
declare status: "draft" | "published";
|
|
2385
|
+
}
|
|
2386
|
+
```
|
|
2387
|
+
|
|
2388
|
+
`post.status` is now typed `"draft" | "published"`, when you read it and when you assign it. `where` and `build` still take any string, and nothing checks the value read from D1. To check what’s saved, add a [validation](/validations): `this.validates("status", { inclusion: ["draft", "published"] })`.
|
|
2389
|
+
|
|
2390
|
+
## Declaring attributes yourself
|
|
2391
|
+
|
|
2392
|
+
For a view, or a table your migrations don’t make, declare the attributes with `define`. TypeScript infers the record’s properties from the object:
|
|
2393
|
+
|
|
2394
|
+
```ts
|
|
2395
|
+
import { column, Model, sql } from "@forestfuture/active-record";
|
|
2396
|
+
|
|
2397
|
+
export class User extends Model.define({
|
|
2398
|
+
id: { type: "string", null: false, generateId: true },
|
|
2399
|
+
email: { type: "string", null: false },
|
|
2400
|
+
role: "string",
|
|
2401
|
+
isActive: "boolean", // column: is_active
|
|
2402
|
+
htmlURL: "string", // column: html_url (a run of capitals is one word)
|
|
2403
|
+
legacyId: { type: "integer", column: "person_identifier" },
|
|
2404
|
+
settings: { type: "json", default: () => ({ theme: "light" }) },
|
|
2405
|
+
createdAt: "datetime",
|
|
2406
|
+
updatedAt: "datetime",
|
|
2407
|
+
}) {
|
|
2408
|
+
static primaryKey = "id"; // the default
|
|
2409
|
+
|
|
2410
|
+
static active = this.scope((q) => q.where({ isActive: true }));
|
|
2411
|
+
static createdAfter = this.scope((q, since: Date) =>
|
|
2412
|
+
q.where(sql`${column("createdAt")} > ${since}`),
|
|
2413
|
+
);
|
|
2414
|
+
}
|
|
2415
|
+
```
|
|
2416
|
+
|
|
2417
|
+
An attribute is a type name, or `{ type, column?, null?, default? }`. To share your base class’s behavior and binding, call `define` on it: `ApplicationRecord.define({...})`.
|
|
2418
|
+
|
|
2419
|
+
## Naming tables
|
|
2420
|
+
|
|
2421
|
+
A Model takes its table name from its class: snake_case, pluralized.
|
|
2422
|
+
|
|
2423
|
+
| Class | Table |
|
|
2424
|
+
| ---------- | ------------ |
|
|
2425
|
+
| `User` | `users` |
|
|
2426
|
+
| `BlogPost` | `blog_posts` |
|
|
2427
|
+
| `Category` | `categories` |
|
|
2428
|
+
| `Person` | `people` |
|
|
2429
|
+
| `Sheep` | `sheep` |
|
|
2430
|
+
|
|
2431
|
+
To use another name, set `static table`:
|
|
2432
|
+
|
|
2433
|
+
```ts
|
|
2434
|
+
import { ApplicationRecord } from "./application-record";
|
|
2435
|
+
|
|
2436
|
+
export class Account extends ApplicationRecord {
|
|
2437
|
+
static override table = "billing_accounts";
|
|
2438
|
+
}
|
|
2439
|
+
```
|
|
2440
|
+
|
|
2441
|
+
A subclass shares its parent’s table. A class with no name to take one from must set `static table`.
|
|
2442
|
+
|
|
2443
|
+
:::note
|
|
2444
|
+
Pluralization follows English rules, quirks included: `Human` becomes `humen` and `Leaf` becomes `leafs`. There’s no way to add your own rules, so set `table` instead.
|
|
2445
|
+
:::
|
|
2446
|
+
|
|
2447
|
+
**Bundlers and class names**
|
|
2448
|
+
|
|
2449
|
+
Wrangler keeps class names by default, even when minifying. If a bundler renames `User` to `e`, the first query throws `InvalidModel`, because no Model named `e` is in the generated schema. Keep class names in your bundler’s settings.
|
|
2450
|
+
|
|
2451
|
+
## Mapping columns
|
|
2452
|
+
|
|
2453
|
+
Attributes are camelCase, and map to snake_case columns:
|
|
2454
|
+
|
|
2455
|
+
| Attribute | Column |
|
|
2456
|
+
| ------------------- | --------------------- |
|
|
2457
|
+
| `createdAt` | `created_at` |
|
|
2458
|
+
| `externalAccountId` | `external_account_id` |
|
|
2459
|
+
| `htmlURL` | `html_url` |
|
|
2460
|
+
| `userID` | `user_id` |
|
|
2461
|
+
| `sha256Hash` | `sha256_hash` |
|
|
2462
|
+
|
|
2463
|
+
To map an attribute to a column with another name, give it `{ column: "..." }`. Conditions, ordering, and association keys always name attributes; only SQL fragments name columns.
|
|
2464
|
+
|
|
2465
|
+
## Attribute types
|
|
2466
|
+
|
|
2467
|
+
| Type | JavaScript | Stored in D1 as |
|
|
2468
|
+
| ---------- | -------------- | ------------------------------------------- |
|
|
2469
|
+
| `string` | `string` | `TEXT` |
|
|
2470
|
+
| `integer` | `number` | `INTEGER` |
|
|
2471
|
+
| `real` | `number` | `REAL` |
|
|
2472
|
+
| `boolean` | `boolean` | `INTEGER`, `0` or `1` |
|
|
2473
|
+
| `datetime` | `Date` | `TEXT`, ISO-8601, or an `INTEGER` Unix time |
|
|
2474
|
+
| `json` | any JSON value | `TEXT`, as JSON |
|
|
2475
|
+
|
|
2476
|
+
An attribute can be `null` unless it’s declared `null: false`, and its TypeScript type includes `| null` to match.
|
|
2477
|
+
|
|
2478
|
+
A `datetime` read from text with no time zone, such as SQLite’s `DEFAULT CURRENT_TIMESTAMP` writes, is UTC in any time zone.
|
|
2479
|
+
|
|
2480
|
+
:::note
|
|
2481
|
+
A column that holds both ISO text and SQLite’s date text compares as text. See [Comparing dates in two forms](/adopt-a-database#comparing-dates-in-two-forms).
|
|
2482
|
+
:::
|
|
2483
|
+
|
|
2484
|
+
:::note
|
|
2485
|
+
Store `json` attributes in a `TEXT` column, as [D1 recommends](https://developers.cloudflare.com/d1/sql-api/query-json/#types), and add `CHECK (json_valid(settings))` to have D1 reject invalid JSON. A column declared `JSON` works too.
|
|
2486
|
+
:::
|
|
2487
|
+
|
|
2488
|
+
:::note
|
|
2489
|
+
A `datetime` can be kept as a Unix time in an `INTEGER` column, as Drizzle writes it. Declare it with `storage: "unixSeconds"` or `"unixMilliseconds"`; [Reading Unix timestamps](/adopt-a-database#reading-unix-timestamps) shows how.
|
|
2490
|
+
:::
|
|
2491
|
+
|
|
2492
|
+
## Casting assigned values
|
|
2493
|
+
|
|
2494
|
+
Every value is cast to its attribute’s type when it’s assigned, so text from JSON, a form, or a query string becomes the right type:
|
|
2495
|
+
|
|
2496
|
+
```ts
|
|
2497
|
+
// Values from JSON, a form or a query string often arrive as text:
|
|
2498
|
+
user.assign(JSON.parse('{ "isActive": "false", "legacyId": " 42 " }'));
|
|
2499
|
+
console.log(user.isActive); // false, not the truthy string "false"
|
|
2500
|
+
console.log(user.legacyId); // 42
|
|
2501
|
+
|
|
2502
|
+
user.assign(JSON.parse('{ "isActive": "no" }'));
|
|
2503
|
+
// TypeError: User: "no" isn't a boolean for "isActive"
|
|
2504
|
+
```
|
|
2505
|
+
|
|
2506
|
+
Values are cast wherever they’re assigned: `build`, `create`, `assign`, `update`, a property setter, a default, [`permit`](#permitting-fields), and the values given to `insert`, `insertAll`, `upsert`, `upsertAll`, and `updateAll`. `null` is always NULL. Only unambiguous values are accepted:
|
|
2507
|
+
|
|
2508
|
+
| Type | Accepts |
|
|
2509
|
+
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------- |
|
|
2510
|
+
| `boolean` | `true`, `false`, `1`, `0`, `"1"`, `"0"`, and `"true"`, `"false"`, `"on"`, `"off"` in any case |
|
|
2511
|
+
| `integer` | a safe integer, or a string that’s wholly one, with an optional sign and spaces around it: `"42"`, `" -7 "`, `"+3"` |
|
|
2512
|
+
| `real` | a finite number, or a string that’s wholly one, with an optional sign, point, and exponent: `"1.5"`, `".5"`, `"5."`, `"-2e3"` |
|
|
2513
|
+
| `string` | a string |
|
|
2514
|
+
| `datetime` | a valid `Date`; a date, `"2026-01-02"` (midnight UTC); or a date and time with `Z` or a `±HH:MM` offset: `"2026-01-02T09:30:00+02:00"` |
|
|
2515
|
+
| `json` | any value JSON can write |
|
|
2516
|
+
|
|
2517
|
+
Anything else throws `TypeError` naming the Model and the attribute, and the attribute keeps its value. The error shows at most 60 characters of the value, and none of a [filtered attribute](#filtering-attributes)’s. Among the values refused:
|
|
2518
|
+
|
|
2519
|
+
- `""` for every type but `string`.
|
|
2520
|
+
- `1.7`, `"12abc"`, `"1e3"`, and integers past `Number.MAX_SAFE_INTEGER`, for an `integer`.
|
|
2521
|
+
- `NaN` and `Infinity`.
|
|
2522
|
+
- A number, boolean, or `Date` for a `string`.
|
|
2523
|
+
- For a `datetime`: a time without an offset, a lowercase `t` or `z`, a day that doesn’t exist (`"2026-02-30"`), other formats, and numbers.
|
|
2524
|
+
- For a `json`: a value JSON can’t write, such as a `BigInt`, an object that refers to itself, a function, or a symbol.
|
|
2525
|
+
|
|
2526
|
+
:::note
|
|
2527
|
+
A `json` attribute stores what `JSON.stringify` writes: a `Map` becomes `{}` and `NaN` becomes `null`. Convert them before assigning. After a save, the record holds what was stored.
|
|
2528
|
+
:::
|
|
2529
|
+
|
|
2530
|
+
A stored cell is checked the same way, when the record loads or `pluck` reads it. One that isn’t the attribute’s type fails with the same error, shows the same value, and fails a list that holds it whole. These cells fail:
|
|
2531
|
+
|
|
2532
|
+
- For a `boolean`: anything but `0` and `1`.
|
|
2533
|
+
- For an `integer`: text, a fraction, or a number outside the safe integer range.
|
|
2534
|
+
- For a `real`: anything but a finite number.
|
|
2535
|
+
- For a `string`: anything but text.
|
|
2536
|
+
- For a `datetime`: text that isn’t a date or a date and time (`"garbage"`, `"12"`), or a number. A number is a [Unix time](/adopt-a-database#reading-unix-timestamps), which needs a `storage`.
|
|
2537
|
+
- For a `datetime` with a `storage`: anything but a number, or one past what a `Date` can hold.
|
|
2538
|
+
- For a `json`: text that isn’t JSON.
|
|
2539
|
+
|
|
2540
|
+
See [Fixing cells of the wrong type](/adopt-a-database#fixing-cells-of-the-wrong-type).
|
|
2541
|
+
|
|
2542
|
+
### Casting conditions and keys
|
|
2543
|
+
|
|
2544
|
+
Conditions are cast the same way, so `where({ quantity: "42" })` finds 42. A condition value that can’t be cast matches nothing, so `find("abc")` on an integer key throws `RecordNotFound`.
|
|
2545
|
+
|
|
2546
|
+
- A condition reads a number as its digits for a `string` attribute, and a record built from that Relation starts with what it matched: `where({ label: 7 }).build()` has the label `"7"`.
|
|
2547
|
+
- A key copied from another record through an association is cast too, so an integer key written into a text foreign key becomes its digits.
|
|
2548
|
+
- A `json` value JSON can’t write matches nothing, never the rows whose cell is `NULL`. In a list, it’s left out and the rest still match.
|
|
2549
|
+
|
|
2550
|
+
> **Beyond Rails**
|
|
2551
|
+
>
|
|
2552
|
+
> Rails casts leniently: `"12abc"` becomes `12`, `1.7` becomes `1`, any other text is `true`, and `""` is `nil`. d1-record refuses each, so `isAdmin=no` from a form can’t save `true`, and an empty field can’t silently become `null`.
|
|
2553
|
+
|
|
2554
|
+
## Building records
|
|
2555
|
+
|
|
2556
|
+
Build a record without touching the database with `build`:
|
|
2557
|
+
|
|
2558
|
+
```ts
|
|
2559
|
+
const user = User.build({ email: "ada@example.com" });
|
|
2560
|
+
console.log(user.id); // already generated, before saving: "3b241101-e2bb-…"
|
|
2561
|
+
console.log(user.role); // null: not assigned yet
|
|
2562
|
+
console.log(user.settings); // { theme: "light" }
|
|
2563
|
+
|
|
2564
|
+
user.assign({ role: "admin", isActive: true });
|
|
2565
|
+
user.isChanged(); // true
|
|
2566
|
+
user.changes(); // { email: [null, "ada@example.com"], role: [null, "admin"], … }
|
|
2567
|
+
await user.save();
|
|
2568
|
+
```
|
|
2569
|
+
|
|
2570
|
+
- **Defaults** and [generated ids](#generating-ids) run at `build()`, so a key generated in code exists before the record is saved. That lets records that point at each other be saved together, in one atomic batch.
|
|
2571
|
+
- **Unassigned attributes** read as `null`, and aren’t written on insert, so the column’s database default applies. After the insert, the record loads what D1 stored.
|
|
2572
|
+
- **Unknown attributes** throw `UnknownAttribute`, and `undefined` throws `TypeError`. Use `null` to store NULL.
|
|
2573
|
+
|
|
2574
|
+
`assign(attrs)` sets several attributes without saving. `update(attrs)` assigns, then saves.
|
|
2575
|
+
|
|
2576
|
+
:::note
|
|
2577
|
+
A record keeps the database it was built or loaded through, for its later saves and association loads. A record made with `new User()` has none, so build records with `User.build(…)`.
|
|
2578
|
+
:::
|
|
2579
|
+
|
|
2580
|
+
### Permitting fields
|
|
2581
|
+
|
|
2582
|
+
Keep only the attributes you name from untrusted input with `permit`. It casts each value as assigning would, and its result goes straight into `build`, `create`, or `update`:
|
|
2583
|
+
|
|
2584
|
+
```ts
|
|
2585
|
+
const permitted = Account.permit(await request.json(), "email", "handle");
|
|
2586
|
+
const account = await Account.create(permitted);
|
|
2587
|
+
```
|
|
2588
|
+
|
|
2589
|
+
It reads three kinds of input:
|
|
2590
|
+
|
|
2591
|
+
| Input | Read |
|
|
2592
|
+
| ----------------- | ---------------------------------------------------------------- |
|
|
2593
|
+
| a plain object | its own keys only, so `__proto__` and inherited keys never count |
|
|
2594
|
+
| `FormData` | each field; a repeated key takes its last value |
|
|
2595
|
+
| `URLSearchParams` | each parameter; a repeated key takes its last value |
|
|
2596
|
+
|
|
2597
|
+
- **Keys you don’t name** are dropped. A named attribute the input doesn’t have is left out, and a `null` is kept.
|
|
2598
|
+
- **A name that isn’t an attribute** is a compile error, and throws `UnknownAttribute`.
|
|
2599
|
+
- **`TypeError`** is thrown for a value that can’t be cast, a file from a form, and any other input: an array, a `Map`, `Headers`, a class instance, `null`, or a string.
|
|
2600
|
+
|
|
2601
|
+
[Untrusted input](/untrusted-input) shows `permit` in a Worker.
|
|
2602
|
+
|
|
2603
|
+
## Generating ids
|
|
2604
|
+
|
|
2605
|
+
A `TEXT` primary key gets its value from the Model’s `generateId` when you don’t give one. By default, that’s a UUID:
|
|
2606
|
+
|
|
2607
|
+
```ts
|
|
2608
|
+
const post = Post.build({ title: "Hello" });
|
|
2609
|
+
post.id; // "3b241101-e2bb-4255-8caf-4136c566a962"
|
|
2610
|
+
```
|
|
2611
|
+
|
|
2612
|
+
To use another kind of id across your app, override `generateId` on your app’s base class:
|
|
2613
|
+
|
|
2614
|
+
```ts
|
|
2615
|
+
import { Model } from "@forestfuture/active-record";
|
|
2616
|
+
import { uuidv7 } from "uuidv7";
|
|
2617
|
+
import { schema } from "../db/schema";
|
|
2618
|
+
|
|
2619
|
+
export abstract class ApplicationRecord extends Model {
|
|
2620
|
+
static override schema = schema;
|
|
2621
|
+
static override generateId = () => uuidv7();
|
|
2622
|
+
}
|
|
2623
|
+
```
|
|
2624
|
+
|
|
2625
|
+
`generateId` gets the attribute’s name, so it can prefix ids: `` `${attribute}_${uuidv7()}` ``.
|
|
2626
|
+
|
|
2627
|
+
To generate another string attribute the same way, turn it on with an override:
|
|
2628
|
+
|
|
2629
|
+
```ts
|
|
2630
|
+
import { ApplicationRecord } from "./application-record";
|
|
2631
|
+
|
|
2632
|
+
export class Post extends ApplicationRecord {
|
|
2633
|
+
static override attributes = { publicId: { generateId: true } } as const;
|
|
2634
|
+
}
|
|
2635
|
+
```
|
|
2636
|
+
|
|
2637
|
+
In a Model declared with `define`, write it on the attribute: `id: { type: "string", null: false, generateId: true }`.
|
|
2638
|
+
|
|
2639
|
+
:::note
|
|
2640
|
+
For one attribute with its own format, use a `default`: ``shareToken: { default: () => `share_${uuidv7()}` }``. A value made from other attributes, such as a slug, belongs in a [callback](/callbacks), since `generateId` never sees the record.
|
|
2641
|
+
:::
|
|
2642
|
+
|
|
2643
|
+
> **Beyond Rails**
|
|
2644
|
+
>
|
|
2645
|
+
> Rails has no `generateId`. Its UUID keys come from the database (`gen_random_uuid()` in PostgreSQL), which D1 can’t do for a key a batch needs before the row is written. See [Primary keys](/coming-from-rails#primary-keys).
|
|
2646
|
+
|
|
2647
|
+
## Using timestamps
|
|
2648
|
+
|
|
2649
|
+
Declare `createdAt` and `updatedAt` as `datetime` attributes, and they’re managed for you. Both are set when a record is created, and `updatedAt` whenever a save changes something. A save with nothing to change leaves `updatedAt` alone, and a timestamp you assign yourself is kept.
|
|
2650
|
+
|
|
2651
|
+
## Tracking changes
|
|
2652
|
+
|
|
2653
|
+
Records know what’s changed since they were loaded or last saved:
|
|
2654
|
+
|
|
2655
|
+
```ts
|
|
2656
|
+
user.email = "ada@lovelace.dev";
|
|
2657
|
+
user.changed(); // ["email"]
|
|
2658
|
+
user.attributeWas("email"); // "ada@example.com"
|
|
2659
|
+
user.isAttributeChanged("email", { from: "ada@example.com" }); // true
|
|
2660
|
+
await user.save();
|
|
2661
|
+
user.savedChangeTo("email"); // ["ada@example.com", "ada@lovelace.dev"]
|
|
2662
|
+
user.hasSavedChangeTo("email"); // true
|
|
2663
|
+
```
|
|
2664
|
+
|
|
2665
|
+
- `isChanged()`, `changed()`, `changedAttributes()`, and `changes()` describe the unsaved changes.
|
|
2666
|
+
- `attributeWas`, `isAttributeChanged`, and `willSaveChangeTo` look at one attribute’s unsaved change. Use them in before-callbacks.
|
|
2667
|
+
- `savedChanges()`, `savedChangeTo`, `hasSavedChangeTo`, and `attributeBeforeLastSave` look at the last save. Use them in after-callbacks, where the record is already clean.
|
|
2668
|
+
- `restoreAttributes()` undoes unsaved changes, to every attribute or the ones you name.
|
|
2669
|
+
|
|
2670
|
+
An update writes only the attributes that changed, and a save with nothing changed sends nothing.
|
|
2671
|
+
|
|
2672
|
+
:::note
|
|
2673
|
+
Changes are found by comparing stored values, so editing a `json` value or a `Date` in place counts as a change.
|
|
2674
|
+
:::
|
|
2675
|
+
|
|
2676
|
+
## Writing SQL fragments
|
|
2677
|
+
|
|
2678
|
+
For anything the query methods can’t express, write an `sql` tagged template. Values are always bound, and `column()` looks up an attribute’s column:
|
|
2679
|
+
|
|
2680
|
+
```ts
|
|
2681
|
+
import { column, sql } from "@forestfuture/active-record";
|
|
2682
|
+
|
|
2683
|
+
const recent = await User.where(sql`${column("createdAt")} > ${since}`).toArray();
|
|
2684
|
+
```
|
|
2685
|
+
|
|
2686
|
+
A plain string is rejected. To write a `Date`, boolean, or JSON value the way an attribute stores it, see [Writing SQL fragments](/querying#writing-sql-fragments).
|
|
2687
|
+
|
|
2688
|
+
## Serializing records
|
|
2689
|
+
|
|
2690
|
+
`toJSON()` gives a record’s attributes with dates as ISO strings, so `Response.json(user)` just works. `attributes()` gives the same object with JavaScript values:
|
|
2691
|
+
|
|
2692
|
+
```ts
|
|
2693
|
+
const body = JSON.stringify(user); // dates as ISO strings, associations left out
|
|
2694
|
+
const attributes = user.attributes(); // a plain object, dates as Date
|
|
2695
|
+
```
|
|
2696
|
+
|
|
2697
|
+
Associations are never included, so a response never loads more than you asked for.
|
|
2698
|
+
|
|
2699
|
+
## Hiding attributes
|
|
2700
|
+
|
|
2701
|
+
Keep an attribute out of `toJSON()` by naming it in `static hiddenAttributes` on your app’s base class:
|
|
2702
|
+
|
|
2703
|
+
```ts
|
|
2704
|
+
import { Model } from "@forestfuture/active-record";
|
|
2705
|
+
|
|
2706
|
+
// src/models/application-record.ts
|
|
2707
|
+
export class Base extends Model {
|
|
2708
|
+
static override hiddenAttributes = ["passwordDigest"];
|
|
2709
|
+
}
|
|
2710
|
+
```
|
|
2711
|
+
|
|
2712
|
+
Every Model built on the base class then leaves it out of `Response.json(user)`. By default, nothing is hidden, and each name must match an attribute exactly.
|
|
2713
|
+
|
|
2714
|
+
A Model’s own list replaces the base class’s:
|
|
2715
|
+
|
|
2716
|
+
```ts
|
|
2717
|
+
import { Model } from "@forestfuture/active-record";
|
|
2718
|
+
|
|
2719
|
+
export class Account extends Model.define({
|
|
2720
|
+
id: "integer",
|
|
2721
|
+
passwordDigest: "string",
|
|
2722
|
+
apiKey: "string",
|
|
2723
|
+
}) {
|
|
2724
|
+
// A Model's list replaces the base class's, so repeat what you still want hidden:
|
|
2725
|
+
static override hiddenAttributes = [...Base.hiddenAttributes, "apiKey"];
|
|
2726
|
+
}
|
|
2727
|
+
```
|
|
2728
|
+
|
|
2729
|
+
`attributes()` still returns every attribute, so you can send a hidden one on purpose.
|
|
2730
|
+
|
|
2731
|
+
:::note
|
|
2732
|
+
A name a Model doesn’t have throws `InvalidModel` when the Model is first used, so a typo can’t leave an attribute in your responses. The base class’s names are the exception: a Model without that attribute ignores them.
|
|
2733
|
+
:::
|
|
2734
|
+
|
|
2735
|
+
> **Beyond Rails**
|
|
2736
|
+
>
|
|
2737
|
+
> Rails’ `serializable_hash(except:)` is per call, and `filter_attributes` only covers logs and inspection. d1-record keeps a class-level list, so `Response.json(user)` is safe without each call site remembering to strip the attribute.
|
|
2738
|
+
|
|
2739
|
+
## Filtering attributes
|
|
2740
|
+
|
|
2741
|
+
`onQuery` listeners and error messages show a filtered attribute’s values as `"[FILTERED]"`. D1 still gets the real values. [Logging](/logging#keeping-secrets-out-of-the-logs) shows how to change the list.
|
|
2742
|
+
|
|
2743
|
+
- **Which attributes:** `static filterAttributes`, a list of strings and RegExps, inherited from your app’s base class. By default, it’s `passw`, `email`, `secret`, `token`, `_key`, `crypt`, `salt`, `certificate`, `otp`, `ssn`, `cvv`, `cvc`. Setting it replaces the list; `[]` filters nothing.
|
|
2744
|
+
- **Matching:** a string matches when the attribute’s snake_case name contains it, in any case: `passwordDigest` (`password_digest`) contains `passw`, and `apiKey` (`api_key`) contains `_key`. A RegExp matches the attribute or its snake_case name.
|
|
2745
|
+
- **Hidden in `QueryEvent.params`:** the values bound for the attribute in inserts (in a multi-row insert’s JSON, its column in every row), updates, `updateAll`, conditions, lists and comparisons, and a filtered primary key in a record’s `UPDATE` and `DELETE`.
|
|
2746
|
+
- **Hidden in errors:** a cast error’s value, and a filtered primary key in `RecordNotFound`.
|
|
2747
|
+
- **Not hidden:** a bare value inside an `sql` fragment, which has no attribute (write it as `column("token").value(token)` to filter it); and `toJSON()` and `attributes()`, which are your data, not logs ([Hiding attributes](#hiding-attributes) keeps names out of `toJSON()`).
|
|
2748
|
+
|
|
2749
|
+
> **Compared with Rails**
|
|
2750
|
+
>
|
|
2751
|
+
> The default list is Rails’ own `filter_parameters` list, and the filtered values read as they do in Rails’ logs.
|
|
2752
|
+
|
|
2753
|
+
## Printing records
|
|
2754
|
+
|
|
2755
|
+
`console.log(user)`, a failed test, and the console show a record’s class and attributes:
|
|
2756
|
+
|
|
2757
|
+
```text
|
|
2758
|
+
User { id: 1, name: 'Johnny' (was 'Alice'), email: [FILTERED], role: 'admin' }
|
|
2759
|
+
```
|
|
2760
|
+
|
|
2761
|
+
- **Filtered attributes** print as `[FILTERED]`, without quotes so it can’t be mistaken for a string, and in a distinct color when the terminal shows colors. An attribute with no value still prints `null`.
|
|
2762
|
+
- **Unsaved changes** print the new value and the old one: `'Johnny' (was 'Alice')`. Once the record is saved, the flag goes. A changed filtered attribute prints `[FILTERED] (changed)`, and so does a column a partial record never loaded: `'Johnny' (changed)`. A new record flags nothing, since all of it is unsaved.
|
|
2763
|
+
- **A partial record** prints only the columns it loaded.
|
|
2764
|
+
|
|
2765
|
+
A Relation prints the SELECT it would send, without sending it:
|
|
2766
|
+
|
|
2767
|
+
```text
|
|
2768
|
+
Relation<User> {
|
|
2769
|
+
sql: 'SELECT * FROM "users" WHERE (("role" = ?))',
|
|
2770
|
+
params: [ 'admin' ]
|
|
2771
|
+
}
|
|
2772
|
+
```
|
|
2773
|
+
|
|
2774
|
+
A record’s `errors` print each failure, so a failed `save()` shows why in the console:
|
|
2775
|
+
|
|
2776
|
+
```text
|
|
2777
|
+
Errors [
|
|
2778
|
+
{ attribute: 'name', type: 'blank', message: "can't be blank" },
|
|
2779
|
+
{ attribute: 'email', type: 'too_short', message: 'is too short' }
|
|
2780
|
+
]
|
|
2781
|
+
```
|
|
2782
|
+
|
|
2783
|
+
Printing can’t wait for D1, so to see the records, `await` it or call `toArray()`. A filtered attribute’s value in `params` prints as `[FILTERED]`.
|
|
2784
|
+
|
|
2785
|
+
:::note
|
|
2786
|
+
Printing shows attributes only, so it never loads an association. [Hidden attributes](#hiding-attributes) still print: they keep values out of `toJSON()`, not out of your console.
|
|
2787
|
+
:::
|
|
2788
|
+
|
|
2789
|
+
> **Compared with Rails**
|
|
2790
|
+
>
|
|
2791
|
+
> A record prints as Rails’ `inspect` does, with `[FILTERED]` for filtered attributes. A Rails Relation runs its query to print its records, which a synchronous `console.log` can’t do here.
|
|
2792
|
+
|
|
2793
|
+
> **Beyond Rails**
|
|
2794
|
+
>
|
|
2795
|
+
> Rails doesn’t mark unsaved changes when it prints a record. d1-record does, so a pending edit is visible in the console before you save it.
|
|
2796
|
+
|
|
2797
|
+
## Sharing behavior
|
|
2798
|
+
|
|
2799
|
+
A subclass, such as `class Admin extends User`, inherits a copy of its parent’s attributes, validations, callbacks, scopes, and associations. Declaring more on the child never changes the parent. Single-table inheritance isn’t supported.
|
|
2800
|
+
|
|
2801
|
+
To share methods, callbacks, and scopes across every Model, write them on your app’s base class. See [Shared behavior](/shared-behavior).
|
|
2802
|
+
|
|
2803
|
+
## Checking declarations
|
|
2804
|
+
|
|
2805
|
+
The first time a Model is used, by its first query or `db.model(X)`, its declaration is checked. It throws `InvalidModel` for:
|
|
2806
|
+
|
|
2807
|
+
- A Model `active-record schema` hasn’t seen, or whose table has changed since. Run it again.
|
|
2808
|
+
- No table name: an empty `table`, or a class with no name to infer one from.
|
|
2809
|
+
- An override of an attribute the table doesn’t have.
|
|
2810
|
+
- A `primaryKey` that isn’t an attribute.
|
|
2811
|
+
- An attribute named like a record method, such as `save` or `attributes`.
|
|
2812
|
+
- A class field that hides an attribute, such as `email!: string` in the class body.
|
|
2813
|
+
|
|
2814
|
+
After that, a Model’s declarations are fixed, so request code can’t change them.
|
|
2815
|
+
|
|
2816
|
+
---
|
|
2817
|
+
|
|
2818
|
+
# Persistence
|
|
2819
|
+
Source: https://d1-record.forestfuture.dev/persistence
|
|
2820
|
+
|
|
2821
|
+
Records are saved, updated, and destroyed with `save`, `create`, `update`, and `destroy`.
|
|
2822
|
+
|
|
2823
|
+
## Saving records
|
|
2824
|
+
|
|
2825
|
+
Save a record with `save`. It validates the record, runs its callbacks, and resolves to `true` or `false`:
|
|
2826
|
+
|
|
2827
|
+
```ts
|
|
2828
|
+
import { User } from "./models";
|
|
2829
|
+
|
|
2830
|
+
const user = User.build({ email: "ada@example.com" });
|
|
2831
|
+
if (await user.save()) {
|
|
2832
|
+
// saved: user.isPersisted() is true
|
|
2833
|
+
} else {
|
|
2834
|
+
console.log(user.errors.fullMessages()); // ["Email has already been taken"]
|
|
2835
|
+
}
|
|
2836
|
+
|
|
2837
|
+
const created = await User.create({ email: "grace@example.com" }); // saved, or not
|
|
2838
|
+
await created.update({ isActive: false }); // true or false
|
|
2839
|
+
```
|
|
2840
|
+
|
|
2841
|
+
A new record is inserted, and a persisted one updates only the attributes that changed. `save` resolves to `false` for one of two reasons:
|
|
2842
|
+
|
|
2843
|
+
- **Validation failed.** The reasons are in `record.errors`.
|
|
2844
|
+
- **A callback aborted** with [`abort()`](/callbacks#stopping-a-save). The reason is in `record.abortReason`.
|
|
2845
|
+
|
|
2846
|
+
`create(attrs)` builds and saves a record, and resolves to it whether it saved or not. Check `isPersisted()` or `errors`. `update(attrs)` assigns, then saves.
|
|
2847
|
+
|
|
2848
|
+
## Throwing on failure
|
|
2849
|
+
|
|
2850
|
+
When a failure is exceptional, use the `OrThrow` version of each method:
|
|
2851
|
+
|
|
2852
|
+
```ts
|
|
2853
|
+
import { RecordInvalid } from "@forestfuture/active-record";
|
|
2854
|
+
import { User } from "./models";
|
|
2855
|
+
|
|
2856
|
+
try {
|
|
2857
|
+
const grace = await User.createOrThrow({ email: "grace@example.com" });
|
|
2858
|
+
await grace.updateOrThrow({ isActive: true });
|
|
2859
|
+
} catch (error) {
|
|
2860
|
+
if (error instanceof RecordInvalid) {
|
|
2861
|
+
return Response.json({ errors: error.record.errors.fullMessages() }, { status: 422 });
|
|
2862
|
+
}
|
|
2863
|
+
throw error; // anything else is a real failure
|
|
2864
|
+
}
|
|
2865
|
+
```
|
|
2866
|
+
|
|
2867
|
+
Instead of returning `false`, they throw:
|
|
2868
|
+
|
|
2869
|
+
- `RecordInvalid` when validation failed, with the record on `error.record`.
|
|
2870
|
+
- `RecordNotSaved` when a callback aborted a save, with the abort’s reason as its message.
|
|
2871
|
+
- `RecordNotDestroyed` from `destroyOrThrow()`, when a callback aborted the destroy or a `restrictWithError` association refused it.
|
|
2872
|
+
|
|
2873
|
+
> **Compared with Rails**
|
|
2874
|
+
>
|
|
2875
|
+
> The `OrThrow` methods are Rails’ `save!`, `create!`, `update!`, and `destroy!`.
|
|
2876
|
+
|
|
2877
|
+
### What each method returns
|
|
2878
|
+
|
|
2879
|
+
| Method | Resolves to | Throws |
|
|
2880
|
+
| ---------------------------------------- | ------------------------------------- | ----------------------------------------------------- |
|
|
2881
|
+
| `save()` / `update(attrs)` | `true` / `false` | constraint errors, `RecordDestroyed` |
|
|
2882
|
+
| `saveOrThrow()` / `updateOrThrow(attrs)` | `true` | same as above, plus `RecordInvalid`, `RecordNotSaved` |
|
|
2883
|
+
| `create(attrs)` | record, persisted or not | constraint errors |
|
|
2884
|
+
| `createOrThrow(attrs)` | persisted record | same as above, plus `RecordInvalid`, `RecordNotSaved` |
|
|
2885
|
+
| `destroy()` | destroyed record, or `false` on abort | constraint errors, `RecordDestroyed` |
|
|
2886
|
+
| `destroyOrThrow()` | destroyed record | same as above, plus `RecordNotDestroyed` |
|
|
2887
|
+
| `find(id)` | record | `RecordNotFound` |
|
|
2888
|
+
| `findBy(conds)` | record or `null` | none |
|
|
2889
|
+
| `findByOrThrow(conds)` | record | `RecordNotFound` |
|
|
2890
|
+
|
|
2891
|
+
`false` only ever means validation failed or a callback aborted. Every method throws for anything else:
|
|
2892
|
+
|
|
2893
|
+
- **Constraint errors**, such as `RecordNotUnique`, since the database refused the write. See [Errors](/errors#constraint-errors).
|
|
2894
|
+
- **An error thrown by a callback**, other than `abort()`, even from an after-callback once the record is saved.
|
|
2895
|
+
- **D1’s own errors.**
|
|
2896
|
+
|
|
2897
|
+
## Destroying records
|
|
2898
|
+
|
|
2899
|
+
Destroy a record with `destroy`:
|
|
2900
|
+
|
|
2901
|
+
```ts
|
|
2902
|
+
const destroyed = await created.destroy(); // the record, or false if a callback aborted
|
|
2903
|
+
if (destroyed) {
|
|
2904
|
+
destroyed.isDestroyed(); // true: readable, but can't be changed or saved
|
|
2905
|
+
}
|
|
2906
|
+
```
|
|
2907
|
+
|
|
2908
|
+
It runs the destroy callbacks and the associations’ [`dependent` options](/associations#destroying-dependent-records), then deletes the row. A destroyed record’s attributes stay readable, but setting one, or calling `save`, `update`, `destroy`, or `reload`, throws `RecordDestroyed`.
|
|
2909
|
+
|
|
2910
|
+
:::note
|
|
2911
|
+
If another request already deleted the row, `save` and `destroy` still succeed.
|
|
2912
|
+
:::
|
|
2913
|
+
|
|
2914
|
+
## Checking a record’s state
|
|
2915
|
+
|
|
2916
|
+
| State | `isNewRecord()` | `isPersisted()` | `isDestroyed()` |
|
|
2917
|
+
| ------------------------------------------------ | --------------- | --------------- | --------------- |
|
|
2918
|
+
| New (from `build()`, or after a failed `create`) | `true` | `false` | `false` |
|
|
2919
|
+
| Persisted (loaded, or after a successful save) | `false` | `true` | `false` |
|
|
2920
|
+
| Destroyed (after a successful `destroy()`) | `false` | `false` | `true` |
|
|
2921
|
+
|
|
2922
|
+
## Reloading records
|
|
2923
|
+
|
|
2924
|
+
Load a record’s row again with `reload`, discarding unsaved changes and loaded associations:
|
|
2925
|
+
|
|
2926
|
+
```ts
|
|
2927
|
+
import { User } from "./models";
|
|
2928
|
+
|
|
2929
|
+
const fresh = await User.find(user.id);
|
|
2930
|
+
fresh.email = "changed@example.com";
|
|
2931
|
+
await fresh.reload(); // back to what D1 holds
|
|
2932
|
+
```
|
|
2933
|
+
|
|
2934
|
+
It throws `RecordNotFound` if the row is gone, or the record was never saved.
|
|
2935
|
+
|
|
2936
|
+
## Writing many rows
|
|
2937
|
+
|
|
2938
|
+
To insert, update, or delete many rows at once, without validations and callbacks, use `insertAll`, `upsertAll`, `updateAll`, and `deleteAll`. See [Bulk writes and batches](/batches).
|
|
2939
|
+
|
|
2940
|
+
---
|
|
2941
|
+
|
|
2942
|
+
# Database resolution
|
|
2943
|
+
Source: https://d1-record.forestfuture.dev/query-databases
|
|
2944
|
+
|
|
2945
|
+
`Product.find(id)` works with no setup, because a Model knows its D1 binding. But a Worker isn’t a long-running server, and that shapes how a query finds its database.
|
|
2946
|
+
|
|
2947
|
+
## One isolate, many requests
|
|
2948
|
+
|
|
2949
|
+
A Worker runs in an **isolate** that serves many requests at the same time, and a Model class is shared by all of them. So anything stored on a class is shared by every request in flight. That rules out storing a connection on a class: some of what a connection carries belongs to one request only.
|
|
2950
|
+
|
|
2951
|
+
- **A D1 Session** keeps one user’s reads at least as new as their own writes. Shared, one user’s Session would serve another’s queries.
|
|
2952
|
+
- **An `onQuery` listener** might tag each query with its request’s ID. Shared, it would mix requests.
|
|
2953
|
+
|
|
2954
|
+
Rails doesn’t keep its connection on the class either: each thread checks one out from a pool, and gives it back afterwards. The JavaScript equivalent of “per request, without passing it around” is `AsyncLocalStorage`, which follows a request through every `await`.
|
|
2955
|
+
|
|
2956
|
+
## Three ways to find a database
|
|
2957
|
+
|
|
2958
|
+
A query finds its database in one of three ways, in this order:
|
|
2959
|
+
|
|
2960
|
+
1. **The request’s database.** Inside `withDatabase(connect(env.DB, { session, onQuery }), fn)`, everything `fn` awaits uses that database, kept in the request’s `AsyncLocalStorage`, never on a class. It’s matched to Models by binding, so a request can open several.
|
|
2961
|
+
2. **The Model’s binding.** Outside `withDatabase`, a Model uses the D1 binding named in the generated schema its base class holds, read from `cloudflare:workers`. The binding is the same object for every request, and the database made for it holds nothing per request (no Session, no listener), so sharing it is safe. This is what makes `Product.find(id)` work with no setup.
|
|
2962
|
+
3. **An explicit database.** `connect(env.DB).model(Product)` always uses that database, whatever `withDatabase` says. It suits code that passes its database around, or uses two at once.
|
|
2963
|
+
|
|
2964
|
+
Most apps only ever use the second. The first exists for what belongs to a request: Sessions, per-request logging, and tests, which run outside a Worker and have no binding to find.
|
|
2965
|
+
|
|
2966
|
+
## Which do I need?
|
|
2967
|
+
|
|
2968
|
+
| Your situation | What to do |
|
|
2969
|
+
| ------------------------------------------------------------ | -------------------------------------------------------------------- |
|
|
2970
|
+
| A Worker with one D1 database | Nothing: `User.find(id)` uses its binding |
|
|
2971
|
+
| D1 read replication, reading your own writes | [A Session per request](/read-your-own-writes) |
|
|
2972
|
+
| Logging queries, or `Server-Timing` | [`onQuery`](/logging), app-wide or per request |
|
|
2973
|
+
| Vitest tests, seed or migration scripts | [`withDatabase(connect(binding), …)`](/testing), or `db.model(...)` |
|
|
2974
|
+
| Several D1 databases | [One base class per binding](/several-databases) |
|
|
2975
|
+
| A compatibility date before 2026-08-04, using `withDatabase` | Add `nodejs_compat` to your Wrangler config’s `compatibility_flags` |
|
|
2976
|
+
|
|
2977
|
+
## What follows from it
|
|
2978
|
+
|
|
2979
|
+
- **Records remember.** A record keeps the database it was loaded through, or first saved through, and so do the records saved with it (autosaved records, a `belongsTo` target), so `post.save()` and `post.user()` use it later, even after `withDatabase` has returned.
|
|
2980
|
+
- **One query or write, one database.** `merge`, `or`, scopes, batches, and saves each run on one database. What counts is the database each side resolves to when it runs, so inside `withDatabase` a loaded record’s `user.posts()` merges with `Post.published()`. Two databases are refused with `IncompatibleRelation`, before anything is written.
|
|
2981
|
+
- **Errors say where the database should come from.** A query outside a Worker with no `withDatabase`, a Model with no binding, or a query at a module’s top level (where Workers allow no I/O) each throws `NoDatabase`, saying what to do.
|
|
2982
|
+
|
|
2983
|
+
For the options themselves, see [Connections](/connecting).
|
|
2984
|
+
|
|
2985
|
+
---
|
|
2986
|
+
|
|
2987
|
+
# Querying
|
|
2988
|
+
Source: https://d1-record.forestfuture.dev/querying
|
|
2989
|
+
|
|
2990
|
+
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
|
+
|
|
2992
|
+
```ts
|
|
2993
|
+
import { User } from "./models";
|
|
2994
|
+
|
|
2995
|
+
const admins = User.where({ role: "admin" }).order({ createdAt: "desc" });
|
|
2996
|
+
const firstTen = admins.limit(10); // a new Relation; admins is unchanged
|
|
2997
|
+
const users = await firstTen.toArray(); // the query runs here
|
|
2998
|
+
```
|
|
2999
|
+
|
|
3000
|
+
:::note
|
|
3001
|
+
Relations have no `then`, so an `async` function that returns one never runs it by accident. Ask for results with a method such as `toArray()`, `first()`, or `count()`.
|
|
3002
|
+
:::
|
|
3003
|
+
|
|
3004
|
+
## Starting a query
|
|
3005
|
+
|
|
3006
|
+
Every Relation method is also a static of every Model: `User.where(…)`, `User.find(id)`, `User.count()`, `User.create(…)`. `User.all()` is the Relation itself, and scopes are statics too: `User.active()`.
|
|
3007
|
+
|
|
3008
|
+
A query runs on the current database: the request’s, if it was opened with `withDatabase`, or the Model’s binding. To use another, start from `db.model(User)`. See [Connections](/connecting).
|
|
3009
|
+
|
|
3010
|
+
## Adding conditions
|
|
3011
|
+
|
|
3012
|
+
Pass `where` an object of attributes that must all match:
|
|
3013
|
+
|
|
3014
|
+
```ts
|
|
3015
|
+
import { User } from "./models";
|
|
3016
|
+
|
|
3017
|
+
User.where({ role: "admin", isActive: true }); // role = ? AND is_active = ?
|
|
3018
|
+
User.where({ role: null }); // role IS NULL
|
|
3019
|
+
User.where({ role: ["admin", "editor"] }); // role IN (…), any number of values
|
|
3020
|
+
User.whereNot({ role: "admin" }); // NOT (role = ?)
|
|
3021
|
+
User.where({ role: "admin" }).or(User.where({ isActive: false }));
|
|
3022
|
+
```
|
|
3023
|
+
|
|
3024
|
+
- `null` matches NULL, and an array matches any of its values. The list is bound as one value, so it can be any length.
|
|
3025
|
+
- `whereNot` negates the whole condition. As in SQL, `whereNot({ role: "admin" })` also leaves out users whose role is NULL.
|
|
3026
|
+
- `or` combines two Relations of the same Model that differ only in their conditions.
|
|
3027
|
+
- `undefined` throws `TypeError`. Leave the key out, or use `null`.
|
|
3028
|
+
|
|
3029
|
+
Values are [cast to the attribute’s type](/models#casting-assigned-values), so `where({ quantity: "42" })` finds 42. A value that can’t be cast matches nothing: `findBy` resolves to `null`, and `find` throws `RecordNotFound`.
|
|
3030
|
+
|
|
3031
|
+
:::note
|
|
3032
|
+
In a list, values that can’t be cast are left out. So `whereNot({ id: "abc" })` on an integer key excludes nothing.
|
|
3033
|
+
:::
|
|
3034
|
+
|
|
3035
|
+
### Comparing values
|
|
3036
|
+
|
|
3037
|
+
Pass a comparison helper as a value:
|
|
3038
|
+
|
|
3039
|
+
```ts
|
|
3040
|
+
import { between, gte, lt } from "@forestfuture/active-record";
|
|
3041
|
+
import { Post, User } from "./models";
|
|
3042
|
+
|
|
3043
|
+
Post.where({ publishedAt: gte(since) }); // published_at >= since
|
|
3044
|
+
User.where({ createdAt: lt(since) }); // created_at < since
|
|
3045
|
+
User.where({ createdAt: between(since, until) }); // both ends included
|
|
3046
|
+
User.where({ createdAt: between(since, until, { excludeEnd: true }) });
|
|
3047
|
+
```
|
|
3048
|
+
|
|
3049
|
+
`gt`, `gte`, `lt`, `lte`, and `between` work on number, string, and datetime attributes, and dates compare by time. `between` includes both ends. Pass `{ excludeEnd: true }` to leave out the end.
|
|
3050
|
+
|
|
3051
|
+
### Writing SQL fragments
|
|
3052
|
+
|
|
3053
|
+
For anything else, write an `sql` tagged template. Values are always bound, and `column()` looks up an attribute’s column:
|
|
3054
|
+
|
|
3055
|
+
```ts
|
|
3056
|
+
import { column, sql } from "@forestfuture/active-record";
|
|
3057
|
+
import { User } from "./models";
|
|
3058
|
+
|
|
3059
|
+
const email = "Ada@Example.com";
|
|
3060
|
+
User.where(sql`lower(${column("email")}) = lower(${email})`);
|
|
3061
|
+
```
|
|
3062
|
+
|
|
3063
|
+
:::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, d1-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
|
+
:::
|
|
3066
|
+
|
|
3067
|
+
```ts
|
|
3068
|
+
import { column, sql } from "@forestfuture/active-record";
|
|
3069
|
+
|
|
3070
|
+
export function publishedBefore(before: Date) {
|
|
3071
|
+
const publishedAt = column("publishedAt");
|
|
3072
|
+
return Article.where(sql`${publishedAt} < ${publishedAt.value(before)}`);
|
|
3073
|
+
}
|
|
3074
|
+
```
|
|
3075
|
+
|
|
3076
|
+
`value` works for any attribute, and writes a boolean as 0 or 1 and a JSON value as text. The value is cast as an assigned one, so a value the attribute can’t hold throws `TypeError` naming the attribute, when `where` is given the fragment. A filtered attribute’s value is hidden from `onQuery`, as it is anywhere else.
|
|
3077
|
+
|
|
3078
|
+
## Using raw statements
|
|
3079
|
+
|
|
3080
|
+
Bind what `serialize` gives when you send SQL to D1 yourself. `typeForAttribute` returns an attribute’s conversions:
|
|
3081
|
+
|
|
3082
|
+
```ts
|
|
3083
|
+
export async function paidSince(db: D1Database, since: Date) {
|
|
3084
|
+
const { serialize } = Invoice.typeForAttribute("paidAt");
|
|
3085
|
+
const { results } = await db
|
|
3086
|
+
.prepare("SELECT id, total FROM invoices WHERE paid_at >= ?")
|
|
3087
|
+
.bind(serialize(since))
|
|
3088
|
+
.all<{ id: number; total: number }>();
|
|
3089
|
+
return results;
|
|
3090
|
+
}
|
|
3091
|
+
```
|
|
3092
|
+
|
|
3093
|
+
`serialize` writes the `Date` as `paidAt` stores it: an integer here, ISO text for a plain `datetime`.
|
|
3094
|
+
|
|
3095
|
+
Turn a cell from a raw query into the attribute’s value with `deserialize`:
|
|
3096
|
+
|
|
3097
|
+
```ts
|
|
3098
|
+
export async function paidAt(db: D1Database, id: number): Promise<Date | null> {
|
|
3099
|
+
const { deserialize } = Invoice.typeForAttribute("paidAt");
|
|
3100
|
+
const row = await db
|
|
3101
|
+
.prepare("SELECT paid_at FROM invoices WHERE id = ?")
|
|
3102
|
+
.bind(id)
|
|
3103
|
+
.first<{ paid_at: number | null }>();
|
|
3104
|
+
return deserialize(row?.paid_at);
|
|
3105
|
+
}
|
|
3106
|
+
```
|
|
3107
|
+
|
|
3108
|
+
For a cache key, or the value a test expects of a raw row, `serialize` gives the stored form too.
|
|
3109
|
+
|
|
3110
|
+
`cast` gives the JavaScript value for an input, without converting it to the stored form: `cast("2026-01-02")` is a `Date`. It keeps a `Date`’s milliseconds, where `serialize` floors them for `unixSeconds`.
|
|
3111
|
+
|
|
3112
|
+
- **`serialize` and `cast`** take what assigning would: a `Date` or an ISO string for a `datetime`, `"42"` for an `integer`. Anything else throws `TypeError` naming the Model and attribute, and so does `undefined`. Use `null` for NULL.
|
|
3113
|
+
- **`deserialize`** reads a cell as loading a record does, and NULL and `undefined` are `null`. It throws the same `TypeError` for a cell that isn’t the attribute’s type. See [Fixing cells of the wrong type](/adopt-a-database#fixing-cells-of-the-wrong-type).
|
|
3114
|
+
- **A filtered attribute’s value** is hidden in those errors, as it is anywhere else.
|
|
3115
|
+
|
|
3116
|
+
:::note
|
|
3117
|
+
`typeForAttribute` needs no connection to D1, and the attribute’s name is checked when you compile.
|
|
3118
|
+
:::
|
|
3119
|
+
|
|
3120
|
+
> **Compared with Rails**
|
|
3121
|
+
>
|
|
3122
|
+
> `typeForAttribute` is `type_for_attribute`, with the same `cast`, `serialize`, and `deserialize`. d1-record’s are strict: a value the attribute can’t hold throws, where Rails casts it leniently.
|
|
3123
|
+
|
|
3124
|
+
## Ordering and paging
|
|
3125
|
+
|
|
3126
|
+
Sort by each key in turn with `order`, and page with `limit` and `offset`:
|
|
3127
|
+
|
|
3128
|
+
```ts
|
|
3129
|
+
import { column, sql } from "@forestfuture/active-record";
|
|
3130
|
+
import { User } from "./models";
|
|
3131
|
+
|
|
3132
|
+
User.order({ role: "asc", createdAt: "desc" });
|
|
3133
|
+
User.order({ role: { direction: "asc", nulls: "last" } });
|
|
3134
|
+
User.order(sql`lower(${column("email")})`);
|
|
3135
|
+
User.order({ role: "asc" }).reorder({ email: "asc" }); // replaces the order
|
|
3136
|
+
User.order({ createdAt: "desc" }).limit(20).offset(40); // page 3
|
|
3137
|
+
```
|
|
3138
|
+
|
|
3139
|
+
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
|
+
|
|
3141
|
+
:::note
|
|
3142
|
+
NULLs sort first in ascending order, as in SQLite. Place them with `nulls: "first"` or `nulls: "last"`.
|
|
3143
|
+
:::
|
|
3144
|
+
|
|
3145
|
+
## Paginating
|
|
3146
|
+
|
|
3147
|
+
`paginate` resolves to one page of records and the total they’re a page of, in a single round trip to D1:
|
|
3148
|
+
|
|
3149
|
+
```ts
|
|
3150
|
+
import { Post } from "./models";
|
|
3151
|
+
|
|
3152
|
+
export async function listPosts(request: Request): Promise<Response> {
|
|
3153
|
+
const page = new URL(request.url).searchParams.get("page");
|
|
3154
|
+
const posts = await Post.order({ publishedAt: "desc" }).paginate({ page, perPage: 20 });
|
|
3155
|
+
return Response.json(posts); // { records, page, perPage, total, totalPages, hasNext, hasPrevious }
|
|
3156
|
+
}
|
|
3157
|
+
```
|
|
3158
|
+
|
|
3159
|
+
- `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
|
+
- Pages sort by the Relation’s order, then by the primary key, so records that tie keep their pages between requests.
|
|
3161
|
+
- A page past the last has no records, but still has the real `total`.
|
|
3162
|
+
- `includes()` preloads the page’s associations in the same round trip, with one more query per association.
|
|
3163
|
+
- A Relation with its own `limit` or `offset` throws `IncompatibleRelation`.
|
|
3164
|
+
|
|
3165
|
+
### Skipping the count
|
|
3166
|
+
|
|
3167
|
+
Counting reads every matching row, and D1 bills each row it reads. If you only need to know whether there’s a next page, pass `count: false`:
|
|
3168
|
+
|
|
3169
|
+
```ts
|
|
3170
|
+
import { Post } from "./models";
|
|
3171
|
+
|
|
3172
|
+
const posts = Post.order({ publishedAt: "desc" });
|
|
3173
|
+
const { records, hasNext } = await posts.paginate({ page: 2, count: false });
|
|
3174
|
+
```
|
|
3175
|
+
|
|
3176
|
+
The page then has no `total` or `totalPages`.
|
|
3177
|
+
|
|
3178
|
+
### Setting the page size
|
|
3179
|
+
|
|
3180
|
+
By default, a page holds 25 records, and none holds more than 100. To change both, set `perPage` and `maxPerPage` on your app’s base class:
|
|
3181
|
+
|
|
3182
|
+
```ts
|
|
3183
|
+
import { Model } from "@forestfuture/active-record";
|
|
3184
|
+
|
|
3185
|
+
export class Base extends Model {
|
|
3186
|
+
static override perPage = 20; // when paginate() isn't given a perPage
|
|
3187
|
+
static override maxPerPage = 50; // a larger perPage is capped at this
|
|
3188
|
+
}
|
|
3189
|
+
```
|
|
3190
|
+
|
|
3191
|
+
:::note
|
|
3192
|
+
D1 limits neither the rows a query returns nor the size of its response. `maxPerPage` keeps one request from reading, and paying for, too many rows, within a Worker’s 128 MB of memory and a query’s 30 seconds.
|
|
3193
|
+
:::
|
|
3194
|
+
|
|
3195
|
+
> **Beyond Rails**
|
|
3196
|
+
>
|
|
3197
|
+
> Rails leaves pagination to gems such as Kaminari and Pagy. d1-record builds it in, and sends the count and the page to D1 together.
|
|
3198
|
+
|
|
3199
|
+
## Getting results
|
|
3200
|
+
|
|
3201
|
+
Run a query with one of these methods:
|
|
3202
|
+
|
|
3203
|
+
```ts
|
|
3204
|
+
import { User } from "./models";
|
|
3205
|
+
|
|
3206
|
+
const all = await User.toArray();
|
|
3207
|
+
const user = await User.find("3b241101-e2bb-4255-8caf-4136c566a962"); // or RecordNotFound
|
|
3208
|
+
const two = await User.find(["id-1", "id-2"]); // in the ids' order
|
|
3209
|
+
const byEmail = await User.findBy({ email: "ada@example.com" }); // or null
|
|
3210
|
+
const oldest = await User.first(); // by primary key, unless ordered
|
|
3211
|
+
const newest = await User.order({ createdAt: "asc" }).last(); // order reversed
|
|
3212
|
+
const any = await User.take(); // no ordering at all
|
|
3213
|
+
const emails = await User.pluck("email"); // string[]
|
|
3214
|
+
const pairs = await User.pluck("id", "email"); // [string, string][]
|
|
3215
|
+
const admins2 = await User.where({ role: "admin" }).count();
|
|
3216
|
+
const hasAdmins = await User.exists({ role: "admin" });
|
|
3217
|
+
```
|
|
3218
|
+
|
|
3219
|
+
- `find` throws `RecordNotFound` if the id is missing. Given several ids, it returns them in order, from one query, and throws if any are missing.
|
|
3220
|
+
- `findBy` resolves to `null` when nothing matches, and `findByOrThrow` throws `RecordNotFound`.
|
|
3221
|
+
- `first` and `last` sort by the primary key unless the Relation has an order, and `last` reverses that order. An `sql` fragment can’t be reversed, so `last` throws `IrreversibleOrder` there.
|
|
3222
|
+
- `count()` always agrees with what `toArray()` returns, even with `limit`, `offset`, or `distinct`.
|
|
3223
|
+
- `size()`, `isEmpty()`, and `hasAny()` count records, or check for any. On a loaded association, they answer without a query.
|
|
3224
|
+
|
|
3225
|
+
:::tip
|
|
3226
|
+
`exists()`, `isEmpty()`, and `hasAny()` ignore the Relation’s order, so D1 stops at the first matching row. `count()` ignores it too, unless a `limit` or `offset` needs it. D1 bills each row it reads, so checks and counts stay cheap on an ordered Relation, such as an ordered association.
|
|
3227
|
+
:::
|
|
3228
|
+
|
|
3229
|
+
> **Compared with Rails**
|
|
3230
|
+
>
|
|
3231
|
+
> `size()`, `isEmpty()`, and `hasAny()` are Rails’ `size`, `empty?`, and `any?`.
|
|
3232
|
+
|
|
3233
|
+
## Selecting attributes
|
|
3234
|
+
|
|
3235
|
+
Load only some attributes with `select`. The primary key is always loaded too, so the records can still be saved:
|
|
3236
|
+
|
|
3237
|
+
```ts
|
|
3238
|
+
import { User } from "./models";
|
|
3239
|
+
|
|
3240
|
+
const partial = await User.select("email").toArray();
|
|
3241
|
+
console.log(partial[0]?.email); // loaded
|
|
3242
|
+
console.log(partial[0]?.id); // the primary key is always loaded too
|
|
3243
|
+
// partial[0]?.role would throw MissingAttribute: it wasn't selected
|
|
3244
|
+
const roles = await User.select("role").distinct().pluck("role");
|
|
3245
|
+
```
|
|
3246
|
+
|
|
3247
|
+
- Reading an attribute that wasn’t loaded throws `MissingAttribute`, including from a validator or callback.
|
|
3248
|
+
- Saving a partial record writes only what changed. `reload()` loads the whole row.
|
|
3249
|
+
- After `distinct()`, the primary key isn’t added, since it would make every row distinct, so those records can’t be saved.
|
|
3250
|
+
|
|
3251
|
+
## Matching nothing
|
|
3252
|
+
|
|
3253
|
+
`none()` matches nothing without asking D1, so it needs no database to answer. Chaining more onto it keeps it empty:
|
|
3254
|
+
|
|
3255
|
+
```ts
|
|
3256
|
+
import { User } from "./models";
|
|
3257
|
+
|
|
3258
|
+
const nothing = await User.none().where({ role: "admin" }).toArray(); // [], no query
|
|
3259
|
+
```
|
|
3260
|
+
|
|
3261
|
+
## Seeing a query’s SQL
|
|
3262
|
+
|
|
3263
|
+
See the SQL a Relation’s `toArray()` would send, without sending it, with `toSql()`:
|
|
3264
|
+
|
|
3265
|
+
```ts
|
|
3266
|
+
import { sql } from "@forestfuture/active-record";
|
|
3267
|
+
import { User } from "./models";
|
|
3268
|
+
|
|
3269
|
+
const { sql: text, params } = User.where({ role: "admin" }).limit(10).toSql();
|
|
3270
|
+
console.log(text); // SELECT * FROM "users" WHERE ("role" = ?) LIMIT ?
|
|
3271
|
+
console.log(params); // ["admin", 10]
|
|
3272
|
+
```
|
|
3273
|
+
|
|
3274
|
+
The values come back in `params`, apart from the SQL.
|
|
3275
|
+
|
|
3276
|
+
A Statement from `toInsert`, `toUpdateAll`, `toDeleteAll`, and the other `to…` methods has `toSql()` too. A `none()` Relation shows `1 = 0`, the condition that matches nothing.
|
|
3277
|
+
|
|
3278
|
+
:::note
|
|
3279
|
+
`toSql()` returns the real values, filtered attributes included. To see what a query sent, with those filtered, use [`onQuery`](/logging).
|
|
3280
|
+
:::
|
|
3281
|
+
|
|
3282
|
+
A record’s `toSave()` and `toDestroy()` have no `toSql()`. Their SQL depends on validations and callbacks that only run inside `db.batch`.
|
|
3283
|
+
|
|
3284
|
+
> **Compared with Rails**
|
|
3285
|
+
>
|
|
3286
|
+
> `toSql()` is Rails’ `to_sql`, except that Rails writes the values into the SQL and `toSql()` keeps them in `params`.
|
|
3287
|
+
|
|
3288
|
+
## Defining scopes
|
|
3289
|
+
|
|
3290
|
+
A scope is a named, reusable part of a query. Declare one as a static that receives the Relation, plus any arguments, and returns a narrower one:
|
|
3291
|
+
|
|
3292
|
+
```ts
|
|
3293
|
+
import { column, Model, sql } from "@forestfuture/active-record";
|
|
3294
|
+
|
|
3295
|
+
export class User extends Model.define({
|
|
3296
|
+
id: { type: "string", null: false, generateId: true },
|
|
3297
|
+
email: { type: "string", null: false },
|
|
3298
|
+
role: "string",
|
|
3299
|
+
isActive: "boolean", // column: is_active
|
|
3300
|
+
htmlURL: "string", // column: html_url (a run of capitals is one word)
|
|
3301
|
+
legacyId: { type: "integer", column: "person_identifier" },
|
|
3302
|
+
settings: { type: "json", default: () => ({ theme: "light" }) },
|
|
3303
|
+
createdAt: "datetime",
|
|
3304
|
+
updatedAt: "datetime",
|
|
3305
|
+
}) {
|
|
3306
|
+
static primaryKey = "id"; // the default
|
|
3307
|
+
|
|
3308
|
+
static active = this.scope((q) => q.where({ isActive: true }));
|
|
3309
|
+
static createdAfter = this.scope((q, since: Date) =>
|
|
3310
|
+
q.where(sql`${column("createdAt")} > ${since}`),
|
|
3311
|
+
);
|
|
3312
|
+
}
|
|
3313
|
+
```
|
|
3314
|
+
|
|
3315
|
+
Call it as a static, or on any Relation of the Model:
|
|
3316
|
+
|
|
3317
|
+
```ts
|
|
3318
|
+
const admins = await User.active().where({ role: "admin" }).toArray();
|
|
3319
|
+
const recent = await User.createdAfter(new Date(Date.now() - 86_400_000)).count();
|
|
3320
|
+
```
|
|
3321
|
+
|
|
3322
|
+
- A scope’s arguments, and anything it computes such as `new Date()`, are evaluated when you call it.
|
|
3323
|
+
- Scopes are inherited, including those on your app’s base class ([Shared behavior](/shared-behavior)). A subclass can replace one with `static override active = this.scope(…)`.
|
|
3324
|
+
- A scope can’t reuse a Relation method’s name (`where`, `count`) or a Model static’s (`validates`, `scope`, `all`).
|
|
3325
|
+
- Inside a scope, `q` has every Relation method but not the Model’s other scopes. Share logic between scopes with a plain function.
|
|
3326
|
+
|
|
3327
|
+
:::note
|
|
3328
|
+
A scope whose body names its own class needs its type written out: `static roots: ScopeStatic<[]> = this.scope(…)`.
|
|
3329
|
+
:::
|
|
3330
|
+
|
|
3331
|
+
## Merging Relations
|
|
3332
|
+
|
|
3333
|
+
Combine two Relations of the same Model with `merge`. Their conditions are joined with AND, and anything the argument sets, such as an order, limit, or select, replaces the receiver’s:
|
|
3334
|
+
|
|
3335
|
+
```ts
|
|
3336
|
+
const recent = User.order({ createdAt: "desc" }).limit(10);
|
|
3337
|
+
const admins = await User.where({ role: "admin" }).merge(recent).toArray();
|
|
3338
|
+
```
|
|
3339
|
+
|
|
3340
|
+
> **Compared with Rails**
|
|
3341
|
+
>
|
|
3342
|
+
> Rails adds the argument’s order to the receiver’s. d1-record replaces it.
|
|
3343
|
+
|
|
3344
|
+
## Preloading associations
|
|
3345
|
+
|
|
3346
|
+
`includes` loads associations for every record, with one query per association, all in one round trip with the records’ own query. See [Associations](/associations#preloading-associations).
|
|
3347
|
+
|
|
3348
|
+
---
|
|
3349
|
+
|
|
3350
|
+
# Read replicas
|
|
3351
|
+
Source: https://d1-record.forestfuture.dev/read-your-own-writes
|
|
3352
|
+
|
|
3353
|
+
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
|
+
|
|
3355
|
+
## Opening a Session for each request
|
|
3356
|
+
|
|
3357
|
+
Wrap each request in `withSession`, passing it the request and your D1 binding:
|
|
3358
|
+
|
|
3359
|
+
```ts
|
|
3360
|
+
import { withSession } from "@forestfuture/d1-record";
|
|
3361
|
+
|
|
3362
|
+
// src/worker.ts: each request reads at least as new as this browser's last write, from any replica.
|
|
3363
|
+
export default {
|
|
3364
|
+
fetch: (request, env) => withSession(request, env.DB, () => handle(request)),
|
|
3365
|
+
} satisfies ExportedHandler<Env>;
|
|
3366
|
+
```
|
|
3367
|
+
|
|
3368
|
+
Every query inside it goes through the request’s Session. That includes uniqueness checks, association loads, preloads, and batches. Records loaded there keep using it.
|
|
3369
|
+
|
|
3370
|
+
`withSession` keeps the Session’s bookmark in a `d1-bookmark` cookie. The user’s next request sends it back, and its Session starts from there. If your handler throws, the error reaches you unchanged and no cookie is set.
|
|
3371
|
+
|
|
3372
|
+
:::note
|
|
3373
|
+
The cookie is `HttpOnly`, `Secure`, and `SameSite=Lax`, with `Path=/`. To name it something else, pass `{ cookie: "name" }` before your handler.
|
|
3374
|
+
:::
|
|
3375
|
+
|
|
3376
|
+
:::note
|
|
3377
|
+
For a second D1 database, call `withSession` again inside the first one. Give each its own cookie name.
|
|
3378
|
+
:::
|
|
3379
|
+
|
|
3380
|
+
:::note
|
|
3381
|
+
`withSession` needs Node.js compatibility, which is on by default for compatibility dates from 2026-08-04. For an earlier date, add `"compatibility_flags": ["nodejs_compat"]`.
|
|
3382
|
+
:::
|
|
3383
|
+
|
|
3384
|
+
## Carrying the bookmark in a header
|
|
3385
|
+
|
|
3386
|
+
If your clients aren’t browsers, carry the bookmark in a header instead:
|
|
3387
|
+
|
|
3388
|
+
```ts
|
|
3389
|
+
import { withSession } from "@forestfuture/d1-record";
|
|
3390
|
+
|
|
3391
|
+
// An API's clients send back the x-d1-bookmark header of the response before.
|
|
3392
|
+
export const api = {
|
|
3393
|
+
fetch: (request, env) =>
|
|
3394
|
+
withSession(request, env.DB, { header: "x-d1-bookmark" }, () => handle(request)),
|
|
3395
|
+
} satisfies ExportedHandler<Env>;
|
|
3396
|
+
```
|
|
3397
|
+
|
|
3398
|
+
Each response has the bookmark in its `x-d1-bookmark` header. Clients send that header with their next request.
|
|
3399
|
+
|
|
3400
|
+
:::note
|
|
3401
|
+
A browser app on another origin can only read the header if your CORS response lists it in `Access-Control-Expose-Headers`.
|
|
3402
|
+
:::
|
|
3403
|
+
|
|
3404
|
+
## Choosing where a Session starts
|
|
3405
|
+
|
|
3406
|
+
A request without a bookmark starts at the nearest instance. To start it at the primary instead, pass `{ start: "first-primary" }`. A request with a bookmark always starts from its bookmark. If D1 can’t use the bookmark, the Session starts from `start` instead. This happens when someone changes the cookie.
|
|
3407
|
+
|
|
3408
|
+
`connect(env.DB, { session })` takes D1’s own values:
|
|
3409
|
+
|
|
3410
|
+
| `session` | The first query goes to |
|
|
3411
|
+
| ----------------------- | -------------------------------------------------------------------------------------- |
|
|
3412
|
+
| `"first-unconstrained"` | The nearest instance, primary or replica. The fastest, but may read slightly old data. |
|
|
3413
|
+
| `"first-primary"` | The primary, so it sees every write made so far. |
|
|
3414
|
+
| A bookmark | An instance at least as new as the moment the bookmark was taken. |
|
|
3415
|
+
|
|
3416
|
+
After the first query, each query reads data at least as new as the one before, including the request’s own writes.
|
|
3417
|
+
|
|
3418
|
+
- **Your handler gets the request’s database** as its argument. Use it for `db.batch(…)` and `db.model(…)`.
|
|
3419
|
+
- **To log the request’s queries**, pass `onQuery` to `withSession`, as you would to `connect`.
|
|
3420
|
+
- **To carry the bookmark yourself**, use `db.bookmark()`. It’s the Session’s latest bookmark. It’s `null` before the first query, and throws `NoSession` on a database opened without a Session.
|
|
3421
|
+
- **To mix the primary and replicas**, open two databases, and use `db.model(…)` with each.
|
|
3422
|
+
|
|
3423
|
+
---
|
|
3424
|
+
|
|
3425
|
+
# Schema and ApplicationRecord
|
|
3426
|
+
Source: https://d1-record.forestfuture.dev/schema
|
|
3427
|
+
|
|
3428
|
+
In Rails, a migration describes a table, and the model never repeats it: Active Record reads the columns from the database when the app runs. d1-record keeps that idea, with one change TypeScript requires: it reads the columns when you **generate** the schema, not when your Worker runs.
|
|
3429
|
+
|
|
3430
|
+
## Migrations are the source of truth
|
|
3431
|
+
|
|
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. d1-record’s generators write migrations for you, but any migration Wrangler can apply works, however it was written.
|
|
3433
|
+
|
|
3434
|
+
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
|
+
|
|
3436
|
+
## The generated schema
|
|
3437
|
+
|
|
3438
|
+
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
|
+
|
|
3440
|
+
That file is to d1-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
|
+
|
|
3442
|
+
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
|
+
|
|
3444
|
+
Columns become attributes by convention, as Rails’ do: the column’s declared type first (`INTEGER` is an `integer`, `DATETIME` a `datetime`), then, for plain `TEXT` and `INTEGER` columns, its name (`created_at` is a `datetime`). The [Command line](/command-line#mapping-columns-to-attributes) reference lists every rule. When a column’s type isn’t what your app means (JSON in a plain `TEXT` column, say), an override in the Model says so, without touching the table.
|
|
3445
|
+
|
|
3446
|
+
## How a Model gets its attributes
|
|
3447
|
+
|
|
3448
|
+
A Model extends your app’s base class, with nothing else on the `extends` line:
|
|
3449
|
+
|
|
3450
|
+
```ts
|
|
3451
|
+
import { ApplicationRecord } from "./application-record";
|
|
3452
|
+
|
|
3453
|
+
export class Product extends ApplicationRecord {}
|
|
3454
|
+
```
|
|
3455
|
+
|
|
3456
|
+
TypeScript can’t give a class types from its name. So `active-record schema` loads your Model files, finds `Product`, and writes a declaration giving the `Product` class the `products` table’s attributes. That’s why the schema is generated from your Models as well as your migrations, and why it changes when you add or rename a Model.
|
|
3457
|
+
|
|
3458
|
+
When your Worker runs, `Product` finds its attributes the first time it’s used. Its table comes from its class name, and the table’s attributes from the schema that `ApplicationRecord` holds. A Model missing from the schema’s list throws `InvalidModel`, telling you to run `active-record schema`. Without that check, a development server, which doesn’t type-check, would run a Model whose types were never generated.
|
|
3459
|
+
|
|
3460
|
+
`ApplicationRecord` itself is a file in your app, `src/models/application-record.ts`, which `active-record schema` writes once. It’s an abstract class that holds the generated schema, and it’s where behavior shared by every Model goes. See [Shared behavior](/shared-behavior).
|
|
3461
|
+
|
|
3462
|
+
A Model can still declare its attributes itself, with `define`, for a view or a table your migrations don’t make. See [Models](/models#declaring-attributes-yourself).
|
|
3463
|
+
|
|
3464
|
+
---
|
|
3465
|
+
|
|
3466
|
+
# Security
|
|
3467
|
+
Source: https://d1-record.forestfuture.dev/security
|
|
3468
|
+
|
|
3469
|
+
Whatever a request sends can reach a query or a record through d1-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
|
+
|
|
3471
|
+
These are the project’s own reviews, not an independent audit. Each says what it covered and what it didn’t.
|
|
3472
|
+
|
|
3473
|
+
## What d1-record protects against
|
|
3474
|
+
|
|
3475
|
+
- **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
|
+
- **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).
|
|
3477
|
+
- **Prototype pollution and inherited names.** Attributes and associations are looked up only by the Model’s own names, so `__proto__`, `constructor`, and other names every object has are unknown names, and `Object.prototype` is never written to.
|
|
3478
|
+
- **Secrets in logs and errors.** Values of attributes named like passwords, tokens, keys, and emails are hidden from `onQuery` listeners and from error messages. See [Logging](/logging#keeping-secrets-out-of-the-logs).
|
|
3479
|
+
- **One request’s data reaching another.** Nothing about a request (a D1 Session, a listener) is ever stored on a Model class. See [Database resolution](/query-databases).
|
|
3480
|
+
- **Denial of service through parsing.** The patterns that read numbers and dates are linear, so a long value can’t use up a Worker’s CPU time.
|
|
3481
|
+
|
|
3482
|
+
## What’s left to your app
|
|
3483
|
+
|
|
3484
|
+
- **Choosing which fields a request may set,** with `permit`, destructuring, or a schema. See [Untrusted input](/untrusted-input).
|
|
3485
|
+
- **An untrusted `null` in a condition.** `findBy({ token: null })` matches rows whose token is NULL. Check a value’s type before querying with it.
|
|
3486
|
+
- **Authorization.** Whether this user may read or change this record is your app’s decision.
|
|
3487
|
+
- **Formats and ranges.** Casting checks types, not meaning: use [validations](/validations).
|
|
3488
|
+
- **Bare values inside `sql` fragments.** A value with no attribute isn’t hidden from listeners. Write it as `column("token").value(token)`, and it’s filtered like the attribute’s other values.
|
|
3489
|
+
- **Which associations a request may include.** A name from `?include=` only matches a Model’s own associations, but each level of a chain adds a subquery. Allow only the include paths you mean.
|
|
3490
|
+
|
|
3491
|
+
## Guarantees, and the tests that check them
|
|
3492
|
+
|
|
3493
|
+
The library’s guarantees are tested against a real D1 database (through Miniflare), and CI’s by a test that reads its workflows. CI runs every test on every change.
|
|
3494
|
+
|
|
3495
|
+
| Guarantee | Tests |
|
|
3496
|
+
| ----------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
|
|
3497
|
+
| Values are bound, identifiers are quoted, and plain strings are refused as SQL | [`sql-safety`](https://github.com/forestfuture/active-record/blob/main/tests/conformance/sql-safety.test.ts) |
|
|
3498
|
+
| Assigned and condition values are cast, or refused, in linear time | [`attribute-casting`](https://github.com/forestfuture/active-record/blob/main/tests/conformance/attribute-casting.test.ts) |
|
|
3499
|
+
| Naming an attribute, table or key takes linear time in the name’s length | [`naming`](https://github.com/forestfuture/active-record/blob/main/tests/unit/naming.test.ts) |
|
|
3500
|
+
| Only a Model’s own names are attributes or associations | [`name-lookups`](https://github.com/forestfuture/active-record/blob/main/tests/conformance/name-lookups.test.ts) |
|
|
3501
|
+
| `permit` keeps only the named attributes, reading own keys only | [`permit`](https://github.com/forestfuture/active-record/blob/main/tests/conformance/permit.test.ts) |
|
|
3502
|
+
| Filtered attributes’ values never reach listeners or errors | [`filter-attributes`](https://github.com/forestfuture/active-record/blob/main/tests/conformance/filter-attributes.test.ts) |
|
|
3503
|
+
| A request’s database stays with that request | [`current-database`](https://github.com/forestfuture/active-record/blob/main/tests/integration/current-database.test.ts) |
|
|
3504
|
+
| Names, assigned values, conditions, bound text, permitted keys, and JSON hold for any input, not only chosen ones | [`properties`](https://github.com/forestfuture/active-record/tree/main/tests) (`*-properties.test.ts`, generated with fast-check) |
|
|
3505
|
+
| The tests cover at least 90% of the library’s and command line’s branches, and CI fails below that | [`coverage`](https://github.com/forestfuture/active-record/blob/main/vite.config.ts) |
|
|
3506
|
+
| CI’s actions are pinned, and release jobs run no install scripts | [`ci-workflows`](https://github.com/forestfuture/active-record/blob/main/tests/unit/ci-workflows.test.ts) |
|
|
3507
|
+
|
|
3508
|
+
## Supply chain
|
|
3509
|
+
|
|
3510
|
+
- **No runtime dependencies in your Worker.** The library imports no package but its own two, `@forestfuture/active-record` and the `@forestfuture/d1-record` adapter, so no other package’s compromise can reach your Worker through it. The command line, a development tool, depends on `jiti` to load your Models; installing `@forestfuture/d1-record` installs it, and your Worker doesn’t bundle it.
|
|
3511
|
+
- **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
|
+
- **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
|
+
- **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.
|
|
3514
|
+
- **Release jobs run no install scripts.** The jobs that decide, build, version, and publish a release install dependencies without running their install scripts and without a shared cache, so a compromised development dependency can’t change what’s built or published.
|
|
3515
|
+
- **Dependencies are watched.** Dependabot proposes updates weekly, waiting a week after each release, since a compromised release is usually caught within days. `pnpm audit` is part of each security review.
|
|
3516
|
+
|
|
3517
|
+
## Review log
|
|
3518
|
+
|
|
3519
|
+
Each security review adds an entry here: what it covered, how, what it found, and what it didn’t cover.
|
|
3520
|
+
|
|
3521
|
+
### 2026-10-04: the library, its command line, and CI
|
|
3522
|
+
|
|
3523
|
+
**Scope:** the library (`src/`), the command line (`cli/`), the CI and release workflows, and the development dependencies.
|
|
3524
|
+
|
|
3525
|
+
**Method:**
|
|
3526
|
+
|
|
3527
|
+
- a security review of the whole codebase with Sentry’s `security-review` skill (OWASP-based), briefed on a library’s risks: what happens when an app passes untrusted input into it;
|
|
3528
|
+
- untrusted inputs probed against a real D1 database: prototype keys, wrong types, `null`, long values;
|
|
3529
|
+
- a dependency audit with Trail of Bits’ `supply-chain-risk-auditor` and `pnpm audit`;
|
|
3530
|
+
- each fix then reviewed with Trail of Bits’ `differential-review`.
|
|
3531
|
+
|
|
3532
|
+
**Findings, all fixed:**
|
|
3533
|
+
|
|
3534
|
+
| Severity | Finding | Issue |
|
|
3535
|
+
| -------- | ----------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
|
|
3536
|
+
| High | Assigned values weren’t checked at runtime: `"false"` saved as `true` for a boolean | [#81](https://github.com/forestfuture/active-record/issues/81) |
|
|
3537
|
+
| High | The publish job used actions pinned by movable tags, and ran install scripts | [#80](https://github.com/forestfuture/active-record/issues/80) |
|
|
3538
|
+
| High | Found while fixing #81: a pattern that backtracked on long numbers (ReDoS) | [#81](https://github.com/forestfuture/active-record/issues/81) |
|
|
3539
|
+
| Medium | No protection against mass assignment, and no guidance on an untrusted `null` | [#82](https://github.com/forestfuture/active-record/issues/82) |
|
|
3540
|
+
| Medium | Bound values, secrets included, reached `onQuery` listeners and errors | [#83](https://github.com/forestfuture/active-record/issues/83) |
|
|
3541
|
+
| Low | Inherited names (`constructor`, `__proto__`) caused errors instead of being unknown names | [#84](https://github.com/forestfuture/active-record/issues/84) |
|
|
3542
|
+
| Low | Development dependency advisories, and unescaped config values in generated code | [#85](https://github.com/forestfuture/active-record/issues/85) |
|
|
3543
|
+
|
|
3544
|
+
**Not covered:** the source of the third-party Actions at their pinned commits; D1 and workerd themselves; isolation between concurrent requests beyond the existing tests; apps’ own code.
|
|
3545
|
+
|
|
3546
|
+
### 2026-10-10: CodeQL’s alerts on the public repository
|
|
3547
|
+
|
|
3548
|
+
**Scope:** the library (`src/`), the command line (`cli/`) and the tests, as CodeQL’s default setup (JavaScript/TypeScript and Actions) scans them on every push and weekly.
|
|
3549
|
+
|
|
3550
|
+
**Method:** each alert from the first scans of `main`, read against the code, then either fixed with a test or dismissed with a written reason on the alert. Property-based tests (#122) then generated inputs for the places untrusted input reaches the library.
|
|
3551
|
+
|
|
3552
|
+
**Findings:**
|
|
3553
|
+
|
|
3554
|
+
| Severity | Finding | Outcome | Link |
|
|
3555
|
+
| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
3556
|
+
| High | Naming an attribute, table or key took quadratic time in the name’s length (ReDoS) | Fixed test-first, and checked against the old rule on every short string | [#116](https://github.com/forestfuture/active-record/issues/116), [alert 1](https://github.com/forestfuture/active-record/security/code-scanning/1) |
|
|
3557
|
+
| High | A test helper strips HTML tags from the guide’s own pages with a regular expression | Dismissed: test-only code, and its output is never rendered | [alert 2](https://github.com/forestfuture/active-record/security/code-scanning/2) |
|
|
3558
|
+
| Medium | The command line writes a column’s default into generated source (two alerts) | Dismissed as false positives: every value goes through `JSON.stringify` or an identifier check, then is only data | [alert 3](https://github.com/forestfuture/active-record/security/code-scanning/3), [alert 4](https://github.com/forestfuture/active-record/security/code-scanning/4) |
|
|
3559
|
+
| Low | Found while triaging alert 4: a `__proto__` key in a JSON column default is lost from the generated schema | Fixed, with a generated property as its test | [#119](https://github.com/forestfuture/active-record/issues/119) |
|
|
3560
|
+
| Low | Found by the generated tests: refusing a value with no JSON form and no string form threw `Cannot convert object to primitive value` first (only code can assign one) | Fixed, with the property that found it | [#122](https://github.com/forestfuture/active-record/issues/122) |
|
|
3561
|
+
|
|
3562
|
+
**Not covered:** the Scorecard findings, which are about the project’s practices, not its code, and the dependencies’ own code.
|
|
3563
|
+
|
|
3564
|
+
### 2026-10-25: before 0.5.0
|
|
3565
|
+
|
|
3566
|
+
**Scope:** the changes to the library (`src/`), the command line (`cli/`), and CI since the 2026-10-04 review: Models extending `ApplicationRecord` (#232), `withSession` (#220), preloading in one batch (#217), stored dates (#73, #159, #216), error messages (#88), `column().value()` (#142), and the console (#104).
|
|
3567
|
+
|
|
3568
|
+
**Method:**
|
|
3569
|
+
|
|
3570
|
+
- a security review of those changes with Sentry’s `security-review` skill (OWASP-based), tracing each untrusted input (a request’s cookie or header, `?include=` names, assigned values, stored cells) to where the library uses it;
|
|
3571
|
+
- Trail of Bits’ `differential-review` of #232’s change before it merged.
|
|
3572
|
+
|
|
3573
|
+
**Findings:**
|
|
3574
|
+
|
|
3575
|
+
| Severity | Finding | Outcome | Link |
|
|
3576
|
+
| -------- | ---------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ---------------------------------------------------------------- |
|
|
3577
|
+
| Low | `active-record schema` wrote a class’s name into generated source unchecked | Fixed before merging: a name that isn’t an identifier is refused | [#234](https://github.com/forestfuture/active-record/pull/234) |
|
|
3578
|
+
| Low | `active-record schema --check` wrote a placeholder schema when there was none | Fixed before merging: `--check` writes nothing | [#234](https://github.com/forestfuture/active-record/pull/234) |
|
|
3579
|
+
| Low | A chain of includes named in a request nests a subquery per level | Documented: allow only the include paths you mean | [#235](https://github.com/forestfuture/active-record/issues/235) |
|
|
3580
|
+
| Low | A bookmark D1 can’t use, in a forged or planted cookie, failed every request carrying it | Fixed: the Session starts again from `start`, checked against a real D1 | [#237](https://github.com/forestfuture/active-record/issues/237) |
|
|
3581
|
+
|
|
3582
|
+
**Not covered:** D1 and workerd themselves; the dependencies’ code; apps’ own code.
|
|
3583
|
+
|
|
3584
|
+
## Reporting a vulnerability
|
|
3585
|
+
|
|
3586
|
+
Please report a security problem privately, as the [security policy](https://github.com/forestfuture/.github/blob/main/SECURITY.md) describes, never in a public issue.
|
|
3587
|
+
|
|
3588
|
+
---
|
|
3589
|
+
|
|
3590
|
+
# Multiple databases
|
|
3591
|
+
Source: https://d1-record.forestfuture.dev/several-databases
|
|
3592
|
+
|
|
3593
|
+
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
|
+
|
|
3595
|
+
## Binding the databases
|
|
3596
|
+
|
|
3597
|
+
Add each database to your Wrangler config, with its own `migrations_dir`:
|
|
3598
|
+
|
|
3599
|
+
```jsonc wrangler.jsonc
|
|
3600
|
+
{
|
|
3601
|
+
"d1_databases": [
|
|
3602
|
+
{ "binding": "DB", "database_name": "my-app-db", "database_id": "…" },
|
|
3603
|
+
{
|
|
3604
|
+
"binding": "LOGS",
|
|
3605
|
+
"database_name": "my-app-logs",
|
|
3606
|
+
"database_id": "…",
|
|
3607
|
+
"migrations_dir": "logs-migrations",
|
|
3608
|
+
},
|
|
3609
|
+
],
|
|
3610
|
+
}
|
|
3611
|
+
```
|
|
3612
|
+
|
|
3613
|
+
Wrangler applies a folder’s migrations to one database, so each needs its own folder.
|
|
3614
|
+
|
|
3615
|
+
## Generating a schema for each
|
|
3616
|
+
|
|
3617
|
+
Generate the schemas as usual:
|
|
3618
|
+
|
|
3619
|
+
```sh
|
|
3620
|
+
npx active-record schema
|
|
3621
|
+
```
|
|
3622
|
+
|
|
3623
|
+
With several databases, it writes one of each per binding:
|
|
3624
|
+
|
|
3625
|
+
| Binding | Schema | Base class |
|
|
3626
|
+
| ------- | ---------------- | -------------------------------------------- |
|
|
3627
|
+
| `DB` | `src/db/DB.ts` | `DbRecord`, in `src/models/db-record.ts` |
|
|
3628
|
+
| `LOGS` | `src/db/LOGS.ts` | `LogsRecord`, in `src/models/logs-record.ts` |
|
|
3629
|
+
|
|
3630
|
+
Each base class holds its database’s schema, which names its binding, so its Models query that database:
|
|
3631
|
+
|
|
3632
|
+
```ts
|
|
3633
|
+
import { LogsRecord } from "./logs-record";
|
|
3634
|
+
|
|
3635
|
+
export class Entry extends LogsRecord {}
|
|
3636
|
+
|
|
3637
|
+
await Entry.where({ level: "error" }).count(); // on LOGS
|
|
3638
|
+
```
|
|
3639
|
+
|
|
3640
|
+
## Generating Models for one database
|
|
3641
|
+
|
|
3642
|
+
Name the binding with `--database`:
|
|
3643
|
+
|
|
3644
|
+
```sh
|
|
3645
|
+
npx active-record g model Entry 'level:string!' message --database LOGS
|
|
3646
|
+
npx active-record migrate --database LOGS
|
|
3647
|
+
```
|
|
3648
|
+
|
|
3649
|
+
## Using both in a request
|
|
3650
|
+
|
|
3651
|
+
Query each Model as usual. Each one uses the database its base class names:
|
|
3652
|
+
|
|
3653
|
+
```ts
|
|
3654
|
+
// src/worker.ts: each Model queries its own database.
|
|
3655
|
+
export default {
|
|
3656
|
+
async fetch(request) {
|
|
3657
|
+
const email = new URL(request.url).searchParams.get("email") ?? "";
|
|
3658
|
+
const user = await User.findByOrThrow({ email }); // on DB
|
|
3659
|
+
await Entry.create({ level: "info", message: `${user.email} signed in` }); // on LOGS
|
|
3660
|
+
return Response.json(user);
|
|
3661
|
+
},
|
|
3662
|
+
} satisfies ExportedHandler<Env>;
|
|
3663
|
+
```
|
|
3664
|
+
|
|
3665
|
+
Records remember their database, so `user.save()` writes back to `DB`, and `entry.save()` to `LOGS`.
|
|
3666
|
+
|
|
3667
|
+
## Writing to both
|
|
3668
|
+
|
|
3669
|
+
Each write goes to one database. Write to the database that matters most first:
|
|
3670
|
+
|
|
3671
|
+
```ts
|
|
3672
|
+
export async function signUp(email: string) {
|
|
3673
|
+
const user = await User.createOrThrow({ email }); // on DB first: if it throws, nothing is logged
|
|
3674
|
+
await Entry.create({ level: "info", message: `${user.email} signed up` }); // then on LOGS
|
|
3675
|
+
return user;
|
|
3676
|
+
}
|
|
3677
|
+
```
|
|
3678
|
+
|
|
3679
|
+
If `createOrThrow` throws, nothing reaches `LOGS`.
|
|
3680
|
+
|
|
3681
|
+
:::warning[Two databases aren’t one write]
|
|
3682
|
+
The second write can still fail after the first one succeeds. A batch can’t join them either. It writes to one database, so entries from two throw `IncompatibleRelation`.
|
|
3683
|
+
:::
|
|
3684
|
+
|
|
3685
|
+
## Reading your own writes on each
|
|
3686
|
+
|
|
3687
|
+
With read replication, give each database its own Session. Nest a `withSession` call for each, and give each its own cookie name:
|
|
3688
|
+
|
|
3689
|
+
```ts
|
|
3690
|
+
import { withSession } from "@forestfuture/d1-record";
|
|
3691
|
+
|
|
3692
|
+
// src/worker.ts: each database's bookmark travels in its own cookie.
|
|
3693
|
+
export const replicas = {
|
|
3694
|
+
fetch: (request, env) =>
|
|
3695
|
+
withSession(request, env.DB, () =>
|
|
3696
|
+
withSession(request, env.LOGS, { cookie: "logs-bookmark" }, () => handle(request)),
|
|
3697
|
+
),
|
|
3698
|
+
} satisfies ExportedHandler<Env>;
|
|
3699
|
+
```
|
|
3700
|
+
|
|
3701
|
+
Every query in `handle` goes through the Session of its Model’s database. See [Read replicas](/read-your-own-writes) for where each Session starts.
|
|
3702
|
+
|
|
3703
|
+
:::note
|
|
3704
|
+
To pass per-request options without Sessions, such as `onQuery`, open the databases yourself and pass them all to `withDatabase`:
|
|
3705
|
+
|
|
3706
|
+
```ts
|
|
3707
|
+
import { withDatabase } from "@forestfuture/active-record";
|
|
3708
|
+
import { connect, type Database, type QueryListener } from "@forestfuture/d1-record";
|
|
3709
|
+
|
|
3710
|
+
const onQuery: QueryListener = ({ sql }) => console.log(sql);
|
|
3711
|
+
const databases: Database[] = [connect(env.DB, { onQuery }), connect(env.LOGS, { onQuery })];
|
|
3712
|
+
return withDatabase(databases, handle); // each Model uses the one on its binding
|
|
3713
|
+
```
|
|
3714
|
+
|
|
3715
|
+
:::
|
|
3716
|
+
|
|
3717
|
+
## Testing with several databases
|
|
3718
|
+
|
|
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 d1-record:
|
|
3720
|
+
|
|
3721
|
+
```ts vitest.config.ts
|
|
3722
|
+
import { defineConfig } from "vitest/config";
|
|
3723
|
+
|
|
3724
|
+
export default defineConfig({
|
|
3725
|
+
test: { server: { deps: { inline: ["@forestfuture/d1-record"] } } },
|
|
3726
|
+
});
|
|
3727
|
+
```
|
|
3728
|
+
|
|
3729
|
+
Then mock the module with your test databases as its `env`, using the `testDatabase` helper from [Testing](/testing):
|
|
3730
|
+
|
|
3731
|
+
```ts test/worker.test.ts
|
|
3732
|
+
import { afterAll, beforeAll, expect, test, vi } from "vitest";
|
|
3733
|
+
import worker from "../src/index";
|
|
3734
|
+
import { testDatabase } from "./d1";
|
|
3735
|
+
|
|
3736
|
+
const env = vi.hoisted(() => ({}) as Env);
|
|
3737
|
+
vi.mock("cloudflare:workers", () => ({ env }));
|
|
3738
|
+
|
|
3739
|
+
let databases: Awaited<ReturnType<typeof testDatabase>>[];
|
|
3740
|
+
beforeAll(async () => {
|
|
3741
|
+
databases = await Promise.all([testDatabase(), testDatabase("logs-migrations")]);
|
|
3742
|
+
Object.assign(env, { DB: databases[0].binding, LOGS: databases[1].binding });
|
|
3743
|
+
});
|
|
3744
|
+
afterAll(() => Promise.all(databases.map((database) => database.dispose())));
|
|
3745
|
+
|
|
3746
|
+
test("signing in logs an entry", async () => {
|
|
3747
|
+
const request = new Request("https://example.com/?email=ada@example.com");
|
|
3748
|
+
const response = await worker.fetch(request, env);
|
|
3749
|
+
expect(response.status).toBe(200);
|
|
3750
|
+
});
|
|
3751
|
+
```
|
|
3752
|
+
|
|
3753
|
+
Each Model now finds its own database, as it does in a Worker. Call your Worker’s `fetch` without `withDatabase`.
|
|
3754
|
+
|
|
3755
|
+
:::note
|
|
3756
|
+
Assign the bindings onto the mocked `env` object, as above. d1-record reads `env` the first time a Model needs its binding, so it never sees an object assigned later.
|
|
3757
|
+
:::
|
|
3758
|
+
|
|
3759
|
+
## Opening one in the console
|
|
3760
|
+
|
|
3761
|
+
Name the binding with `--database`:
|
|
3762
|
+
|
|
3763
|
+
```sh
|
|
3764
|
+
npx active-record console --database LOGS
|
|
3765
|
+
```
|
|
3766
|
+
|
|
3767
|
+
---
|
|
3768
|
+
|
|
3769
|
+
# Shared behavior
|
|
3770
|
+
Source: https://d1-record.forestfuture.dev/shared-behavior
|
|
3771
|
+
|
|
3772
|
+
Every Model extends your app’s `ApplicationRecord`, so whatever you write on it, every Model has.
|
|
3773
|
+
|
|
3774
|
+
## Sharing methods, callbacks, and scopes
|
|
3775
|
+
|
|
3776
|
+
Write them on `ApplicationRecord`, in `src/models/application-record.ts`:
|
|
3777
|
+
|
|
3778
|
+
```ts
|
|
3779
|
+
import { Model } from "@forestfuture/active-record";
|
|
3780
|
+
import { schema } from "../db/schema";
|
|
3781
|
+
|
|
3782
|
+
// What's written on ApplicationRecord, every Model has.
|
|
3783
|
+
export abstract class ApplicationRecord extends Model {
|
|
3784
|
+
static override schema = schema;
|
|
3785
|
+
|
|
3786
|
+
label() {
|
|
3787
|
+
return `${this.constructor.name} ${JSON.stringify(this.attributes())}`;
|
|
3788
|
+
}
|
|
3789
|
+
|
|
3790
|
+
static {
|
|
3791
|
+
this.beforeSave((record) => {
|
|
3792
|
+
console.log(`Saving ${record.constructor.name}`); // before each Model's own callbacks
|
|
3793
|
+
});
|
|
3794
|
+
}
|
|
3795
|
+
}
|
|
3796
|
+
|
|
3797
|
+
// Every Model built on it has label(), and ApplicationRecord's beforeSave.
|
|
3798
|
+
export class Account extends ApplicationRecord {
|
|
3799
|
+
static override table = "billing_accounts";
|
|
3800
|
+
}
|
|
3801
|
+
```
|
|
3802
|
+
|
|
3803
|
+
Each is shared like this:
|
|
3804
|
+
|
|
3805
|
+
| On `ApplicationRecord` | Every Model |
|
|
3806
|
+
| ---------------------------------------- | ------------------------------------------------------ |
|
|
3807
|
+
| A method, such as `label()` | has it, on every record |
|
|
3808
|
+
| A static method | has it, on the Model |
|
|
3809
|
+
| A callback, in `static {}` | runs it, before the Model’s own callbacks of that kind |
|
|
3810
|
+
| A scope, `static newest = this.scope(…)` | has it, as `Product.newest()` and on its Relations |
|
|
3811
|
+
| `static override onQuery` | logs its queries (see [Logging](/logging)) |
|
|
3812
|
+
|
|
3813
|
+
A Model can replace a shared method or scope by declaring one of the same name.
|
|
3814
|
+
|
|
3815
|
+
:::note
|
|
3816
|
+
`active-record schema` writes `application-record.ts` with commented-out examples to start from.
|
|
3817
|
+
:::
|
|
3818
|
+
|
|
3819
|
+
## Writing for every table
|
|
3820
|
+
|
|
3821
|
+
Inside `ApplicationRecord`, `this` is a record of any Model. It has every record method, such as `save()` and `attributes()`, but no attributes, since those differ from table to table:
|
|
3822
|
+
|
|
3823
|
+
- Read attributes through `this.attributes()`, as `label()` does above.
|
|
3824
|
+
- Write shared scopes with `sql` fragments, since they run on each Model’s own table: `static newest = this.scope((q) => q.order(sql\`created_at DESC\`))`.
|
|
3825
|
+
- Validations name attributes, so they belong on each Model. Put shared checks in a callback instead.
|
|
3826
|
+
|
|
3827
|
+
`ApplicationRecord` has no table of its own, so `db.model(ApplicationRecord)` throws `InvalidModel`. Once a Model has been used, `ApplicationRecord` is sealed with it, so request code can’t add callbacks to every Model.
|
|
3828
|
+
|
|
3829
|
+
## Sharing behavior between some Models
|
|
3830
|
+
|
|
3831
|
+
To share behavior between only some Models, put it on a class between them and `ApplicationRecord`, marked `abstract`:
|
|
3832
|
+
|
|
3833
|
+
```ts
|
|
3834
|
+
import { ApplicationRecord } from "./application-record";
|
|
3835
|
+
|
|
3836
|
+
export abstract class Auditable extends ApplicationRecord {
|
|
3837
|
+
static override abstract = true;
|
|
3838
|
+
|
|
3839
|
+
static {
|
|
3840
|
+
this.afterSave((record) => {
|
|
3841
|
+
console.log(`Saved ${record.constructor.name}`);
|
|
3842
|
+
});
|
|
3843
|
+
}
|
|
3844
|
+
}
|
|
3845
|
+
|
|
3846
|
+
export class Invoice extends Auditable {}
|
|
3847
|
+
```
|
|
3848
|
+
|
|
3849
|
+
`Auditable` has no table. Each class that extends it has its own, so `Invoice` reads and writes `invoices`.
|
|
3850
|
+
|
|
3851
|
+
## Sharing across databases
|
|
3852
|
+
|
|
3853
|
+
Each database has its own base class, such as `DbRecord` and `LogsRecord`, holding its own schema. To share behavior across all of them, write it on one abstract class extending `Model`, and extend that class in each base class’s file:
|
|
3854
|
+
|
|
3855
|
+
```ts
|
|
3856
|
+
import { Model } from "@forestfuture/active-record";
|
|
3857
|
+
import { schema } from "../db/LOGS";
|
|
3858
|
+
|
|
3859
|
+
export abstract class AppRecord extends Model {
|
|
3860
|
+
label() {
|
|
3861
|
+
return `${this.constructor.name} ${JSON.stringify(this.attributes())}`;
|
|
3862
|
+
}
|
|
3863
|
+
}
|
|
3864
|
+
|
|
3865
|
+
export abstract class LogsRecord extends AppRecord {
|
|
3866
|
+
static override schema = schema;
|
|
3867
|
+
}
|
|
3868
|
+
```
|
|
3869
|
+
|
|
3870
|
+
See [Multiple databases](/several-databases).
|
|
3871
|
+
|
|
3872
|
+
---
|
|
3873
|
+
|
|
3874
|
+
# Testing
|
|
3875
|
+
Source: https://d1-record.forestfuture.dev/testing
|
|
3876
|
+
|
|
3877
|
+
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
|
+
|
|
3879
|
+
```sh
|
|
3880
|
+
npm install --save-dev vitest miniflare@4
|
|
3881
|
+
```
|
|
3882
|
+
|
|
3883
|
+
## Creating a test database
|
|
3884
|
+
|
|
3885
|
+
Start Miniflare with a D1 database, and apply a folder of migrations to it, in order:
|
|
3886
|
+
|
|
3887
|
+
```ts test/d1.ts
|
|
3888
|
+
import { readdirSync, readFileSync } from "node:fs";
|
|
3889
|
+
import { Miniflare } from "miniflare";
|
|
3890
|
+
|
|
3891
|
+
export async function testDatabase(folder = "migrations") {
|
|
3892
|
+
const mf = new Miniflare({ modules: true, script: "export default {}", d1Databases: ["DB"] });
|
|
3893
|
+
const binding = await mf.getD1Database("DB");
|
|
3894
|
+
for (const file of readdirSync(folder).sort()) {
|
|
3895
|
+
// Each migration's statements, without its comments, applied together.
|
|
3896
|
+
const statements = readFileSync(`${folder}/${file}`, "utf8")
|
|
3897
|
+
.replace(/^\s*--.*$/gm, "")
|
|
3898
|
+
.split(/;\s*$/m)
|
|
3899
|
+
.map((statement) => statement.trim())
|
|
3900
|
+
.filter(Boolean);
|
|
3901
|
+
if (statements.length > 0)
|
|
3902
|
+
await binding.batch(statements.map((statement) => binding.prepare(statement)));
|
|
3903
|
+
}
|
|
3904
|
+
return { binding, dispose: () => mf.dispose() };
|
|
3905
|
+
}
|
|
3906
|
+
```
|
|
3907
|
+
|
|
3908
|
+
## Testing Models
|
|
3909
|
+
|
|
3910
|
+
Outside a Worker there’s no binding, so run the test’s code inside `withDatabase`:
|
|
3911
|
+
|
|
3912
|
+
```ts test/users.test.ts
|
|
3913
|
+
import { withDatabase } from "@forestfuture/active-record";
|
|
3914
|
+
import { connect } from "@forestfuture/d1-record";
|
|
3915
|
+
import { afterAll, beforeAll, expect, test } from "vitest";
|
|
3916
|
+
import { User } from "../src/models/user";
|
|
3917
|
+
import { testDatabase } from "./d1";
|
|
3918
|
+
|
|
3919
|
+
let database: Awaited<ReturnType<typeof testDatabase>>;
|
|
3920
|
+
beforeAll(async () => (database = await testDatabase()));
|
|
3921
|
+
afterAll(() => database.dispose());
|
|
3922
|
+
|
|
3923
|
+
test("emails are saved in lowercase", async () => {
|
|
3924
|
+
await withDatabase(connect(database.binding), async () => {
|
|
3925
|
+
const user = await User.create({ email: "Ada@Example.com" });
|
|
3926
|
+
expect((await User.find(user.id)).email).toBe("ada@example.com");
|
|
3927
|
+
});
|
|
3928
|
+
});
|
|
3929
|
+
```
|
|
3930
|
+
|
|
3931
|
+
Outside a Worker, the database given to `withDatabase` serves every Model, whatever binding its base class names. For code that takes a database explicitly, pass it one: `connect(database.binding).model(User)`.
|
|
3932
|
+
|
|
3933
|
+
## Testing your Worker
|
|
3934
|
+
|
|
3935
|
+
Call your Worker’s `fetch` handler inside `withDatabase` too, and its queries use the test’s database:
|
|
3936
|
+
|
|
3937
|
+
```ts test/worker.test.ts
|
|
3938
|
+
import { withDatabase } from "@forestfuture/active-record";
|
|
3939
|
+
import { connect } from "@forestfuture/d1-record";
|
|
3940
|
+
import { afterAll, beforeAll, expect, test } from "vitest";
|
|
3941
|
+
import worker from "../src/index";
|
|
3942
|
+
import { testDatabase } from "./d1";
|
|
3943
|
+
|
|
3944
|
+
let database: Awaited<ReturnType<typeof testDatabase>>;
|
|
3945
|
+
beforeAll(async () => (database = await testDatabase()));
|
|
3946
|
+
afterAll(() => database.dispose());
|
|
3947
|
+
|
|
3948
|
+
test("GET lists users", async () => {
|
|
3949
|
+
const response = await withDatabase(connect(database.binding), () =>
|
|
3950
|
+
worker.fetch(new Request("https://example.com/")),
|
|
3951
|
+
);
|
|
3952
|
+
expect(response.status).toBe(200);
|
|
3953
|
+
});
|
|
3954
|
+
```
|
|
3955
|
+
|
|
3956
|
+
Each test file gets its own database.
|
|
3957
|
+
|
|
3958
|
+
:::note
|
|
3959
|
+
If your Worker uses [`withSession`](/read-your-own-writes), call `fetch` without `withDatabase`. Pass the test’s database as `env.DB` instead, and `withSession` opens it for the request.
|
|
3960
|
+
:::
|
|
3961
|
+
|
|
3962
|
+
:::note
|
|
3963
|
+
To run tests inside the Workers runtime itself, use Cloudflare’s [Vitest integration](https://developers.cloudflare.com/workers/testing/vitest-integration/).
|
|
3964
|
+
:::
|
|
3965
|
+
|
|
3966
|
+
---
|
|
3967
|
+
|
|
3968
|
+
# Untrusted input
|
|
3969
|
+
Source: https://d1-record.forestfuture.dev/untrusted-input
|
|
3970
|
+
|
|
3971
|
+
A request can send any fields it likes. Pick the ones you want before they reach a Model.
|
|
3972
|
+
|
|
3973
|
+
## Permitting fields
|
|
3974
|
+
|
|
3975
|
+
Only permit the fields you want from a request:
|
|
3976
|
+
|
|
3977
|
+
```ts
|
|
3978
|
+
const permitted = Account.permit(await request.json(), "email", "handle");
|
|
3979
|
+
const account = await Account.create(permitted);
|
|
3980
|
+
```
|
|
3981
|
+
|
|
3982
|
+
:::note
|
|
3983
|
+
`permit` can also read `FormData` or `URLSearchParams`.
|
|
3984
|
+
:::
|
|
3985
|
+
|
|
3986
|
+
Permitted values are cast to their attribute’s types, so `"42"` becomes `42` for an integer. [Models](/models#casting-assigned-values) lists what each type accepts. A page number from a query string can go straight to [`paginate`](/querying#paginating), which casts it too.
|
|
3987
|
+
|
|
3988
|
+
> **Beyond Rails**
|
|
3989
|
+
>
|
|
3990
|
+
> Rails’ `params.permit` only filters keys. d1-record’s also casts each value, and checks that each name is an attribute.
|
|
3991
|
+
|
|
3992
|
+
## Using a schema library
|
|
3993
|
+
|
|
3994
|
+
If you validate requests with a schema library such as [Zod](https://zod.dev) or [Valibot](https://valibot.dev), pass the parsed result to the Model:
|
|
3995
|
+
|
|
3996
|
+
```ts
|
|
3997
|
+
import { z } from "zod";
|
|
3998
|
+
|
|
3999
|
+
const SignUp = z.object({ email: z.string(), handle: z.string().min(3) });
|
|
4000
|
+
|
|
4001
|
+
const fields = SignUp.parse(await request.json());
|
|
4002
|
+
const account = await Account.create(fields);
|
|
4003
|
+
```
|
|
4004
|
+
|
|
4005
|
+
## Returning a 400
|
|
4006
|
+
|
|
4007
|
+
A value that can’t be cast throws a `TypeError`, and a body that isn’t JSON throws a `SyntaxError`. Return a 400 for either:
|
|
4008
|
+
|
|
4009
|
+
```ts
|
|
4010
|
+
export async function updateAccount(account: Account, request: Request): Promise<Response> {
|
|
4011
|
+
let permitted;
|
|
4012
|
+
try {
|
|
4013
|
+
permitted = Account.permit(await request.json(), "handle", "seats");
|
|
4014
|
+
} catch (error) {
|
|
4015
|
+
if (error instanceof SyntaxError || error instanceof TypeError) {
|
|
4016
|
+
return new Response("Bad request", { status: 400 });
|
|
4017
|
+
}
|
|
4018
|
+
throw error;
|
|
4019
|
+
}
|
|
4020
|
+
|
|
4021
|
+
await account.update(permitted);
|
|
4022
|
+
return Response.json(account);
|
|
4023
|
+
}
|
|
4024
|
+
```
|
|
4025
|
+
|
|
4026
|
+
## Querying with request values
|
|
4027
|
+
|
|
4028
|
+
Check that a value is a string before you query with it. JSON can send `null`, and `findBy({ token: null })` matches rows whose token is NULL:
|
|
4029
|
+
|
|
4030
|
+
```ts
|
|
4031
|
+
export async function accept(request: Request): Promise<Response> {
|
|
4032
|
+
const { token } = await request.json<{ token: string }>();
|
|
4033
|
+
if (typeof token !== "string" || token === "") {
|
|
4034
|
+
return new Response("Send the invitation's token", { status: 400 });
|
|
4035
|
+
}
|
|
4036
|
+
|
|
4037
|
+
const invitation = await Invitation.findBy({ token });
|
|
4038
|
+
if (invitation === null) return new Response("No such invitation", { status: 404 });
|
|
4039
|
+
|
|
4040
|
+
await invitation.update({ token: null, acceptedAt: new Date() });
|
|
4041
|
+
return new Response(`Welcome, ${invitation.email}`);
|
|
4042
|
+
}
|
|
4043
|
+
```
|
|
4044
|
+
|
|
4045
|
+
:::note
|
|
4046
|
+
A value that can’t be cast matches nothing, so `whereNot({ id: "abc" })` excludes nothing.
|
|
4047
|
+
:::
|
|
4048
|
+
|
|
4049
|
+
---
|
|
4050
|
+
|
|
4051
|
+
# Upgrading to 0.6
|
|
4052
|
+
Source: https://d1-record.forestfuture.dev/upgrading
|
|
4053
|
+
|
|
4054
|
+
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
|
+
|
|
4056
|
+
## Installing both packages
|
|
4057
|
+
|
|
4058
|
+
Install the core beside the adapter:
|
|
4059
|
+
|
|
4060
|
+
```sh
|
|
4061
|
+
npm install @forestfuture/active-record@^0.6.0 @forestfuture/d1-record@^0.6.0
|
|
4062
|
+
```
|
|
4063
|
+
|
|
4064
|
+
Both packages share a version, so keep them on the same one.
|
|
4065
|
+
|
|
4066
|
+
## Changing imports
|
|
4067
|
+
|
|
4068
|
+
Import from the core everything that isn’t about D1. Import from the adapter what opens D1:
|
|
4069
|
+
|
|
4070
|
+
```ts
|
|
4071
|
+
import {
|
|
4072
|
+
batch,
|
|
4073
|
+
belongsTo,
|
|
4074
|
+
hasMany,
|
|
4075
|
+
Model,
|
|
4076
|
+
RecordNotFound,
|
|
4077
|
+
withDatabase,
|
|
4078
|
+
} from "@forestfuture/active-record";
|
|
4079
|
+
import { connect, d1, withSession } from "@forestfuture/d1-record";
|
|
4080
|
+
```
|
|
4081
|
+
|
|
4082
|
+
| Package | What it holds |
|
|
4083
|
+
| ----------------------------- | ------------------------------------------------------------------------------ |
|
|
4084
|
+
| `@forestfuture/active-record` | Models, Relations, `batch`, `withDatabase`, `sql`, and every error but one |
|
|
4085
|
+
| `@forestfuture/d1-record` | `connect`, `Database`, `withSession`, `NoSession`, `d1`, and D1’s `QueryEvent` |
|
|
4086
|
+
|
|
4087
|
+
`d1-record` re-exports nothing of the core, so an import of `Model` from it fails.
|
|
4088
|
+
|
|
4089
|
+
## Regenerating the schema
|
|
4090
|
+
|
|
4091
|
+
Run the schema command under its new name:
|
|
4092
|
+
|
|
4093
|
+
```sh
|
|
4094
|
+
npx active-record schema
|
|
4095
|
+
```
|
|
4096
|
+
|
|
4097
|
+
The generated schema now names its adapter, `adapter: d1({ binding: "DB" })`, where it named only the binding. Your base class needs no change.
|
|
4098
|
+
|
|
4099
|
+
## Running `active-record`
|
|
4100
|
+
|
|
4101
|
+
The command is now `active-record`, or `ffar` for short. Swap it in your scripts and CI:
|
|
4102
|
+
|
|
4103
|
+
| Before | Now |
|
|
4104
|
+
| ------------------------- | ----------------------------- |
|
|
4105
|
+
| `npx d1-record schema` | `npx active-record schema` |
|
|
4106
|
+
| `npx d1-record g model …` | `npx active-record g model …` |
|
|
4107
|
+
| `npx d1-record console` | `npx active-record console` |
|
|
4108
|
+
|
|
4109
|
+
It also applies migrations through your project’s Wrangler, with `npx active-record migrate`. See [Command line](/command-line#active-record-migrate).
|
|
4110
|
+
|
|
4111
|
+
## Updating for the other changes
|
|
4112
|
+
|
|
4113
|
+
- **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
|
+
- **The base error** is `ActiveRecordError`, where it was `D1RecordError`.
|
|
4115
|
+
- **`toSql()` with no database:** on a Model with no generated schema, outside `withDatabase`, it throws `NoDatabase`. Use a `db` (`db.model(Post).toSql()`), or a Model built on your base class.
|
|
4116
|
+
- **D1’s `meta`** is still on every `onQuery` event.
|
|
4117
|
+
- **The agent skill** is now `active-record`. Install it again with `npx skills add forestfuture/active-record`.
|
|
4118
|
+
|
|
4119
|
+
---
|
|
4120
|
+
|
|
4121
|
+
# Validations
|
|
4122
|
+
Source: https://d1-record.forestfuture.dev/validations
|
|
4123
|
+
|
|
4124
|
+
Validations check a record before it’s saved. An invalid record isn’t saved, and its `errors` say why.
|
|
4125
|
+
|
|
4126
|
+
## Declaring validations
|
|
4127
|
+
|
|
4128
|
+
Declare validations in a Model’s `static {}` block with `this.validates`:
|
|
4129
|
+
|
|
4130
|
+
```ts
|
|
4131
|
+
import { Model } from "@forestfuture/active-record";
|
|
4132
|
+
|
|
4133
|
+
export class Account extends Model.define({
|
|
4134
|
+
id: { type: "integer", null: false },
|
|
4135
|
+
email: { type: "string", null: false },
|
|
4136
|
+
handle: { type: "string", null: false },
|
|
4137
|
+
plan: "string",
|
|
4138
|
+
seats: "integer",
|
|
4139
|
+
website: "string",
|
|
4140
|
+
isCompany: "boolean",
|
|
4141
|
+
companyName: "string",
|
|
4142
|
+
}) {
|
|
4143
|
+
static {
|
|
4144
|
+
this.validates("email", { presence: true, uniqueness: { caseSensitive: false } });
|
|
4145
|
+
this.validates("handle", { length: { minimum: 3, maximum: 30 }, format: /^[a-z0-9_]+$/ });
|
|
4146
|
+
this.validates("plan", { inclusion: ["free", "team", "enterprise"] });
|
|
4147
|
+
this.validates("seats", { numericality: { onlyInteger: true, greaterThan: 0 } });
|
|
4148
|
+
this.validates("website", { format: /^https:\/\//, allowNull: true });
|
|
4149
|
+
this.validates("companyName", {
|
|
4150
|
+
presence: true,
|
|
4151
|
+
if: (account) => account.isCompany === true,
|
|
4152
|
+
message: "is required for a company",
|
|
4153
|
+
});
|
|
4154
|
+
}
|
|
4155
|
+
}
|
|
4156
|
+
```
|
|
4157
|
+
|
|
4158
|
+
Attribute names are typed, so a misspelled attribute is a compile error.
|
|
4159
|
+
|
|
4160
|
+
`save()` validates first, and resolves to `false` when a record is invalid. To validate without saving, call `isValid()`:
|
|
4161
|
+
|
|
4162
|
+
```ts
|
|
4163
|
+
const account = Account.build(permitted);
|
|
4164
|
+
const valid = await account.isValid();
|
|
4165
|
+
```
|
|
4166
|
+
|
|
4167
|
+
:::note
|
|
4168
|
+
`isValid()` is async, since `uniqueness` asks D1.
|
|
4169
|
+
:::
|
|
4170
|
+
|
|
4171
|
+
## Available validators
|
|
4172
|
+
|
|
4173
|
+
| Rule | Options | Error type |
|
|
4174
|
+
| -------------- | -------------------------------------------------------------------------------------------- | ---------------------------------------------- |
|
|
4175
|
+
| `presence` | `true` | `blank` |
|
|
4176
|
+
| `length` | `{ minimum, maximum, is }` | `tooShort`, `tooLong`, `wrongLength` |
|
|
4177
|
+
| `format` | `{ with: /re/ }`, or a regex | `invalid` |
|
|
4178
|
+
| `inclusion` | `{ in: [...] }`, or an array | `inclusion` |
|
|
4179
|
+
| `numericality` | `{ onlyInteger, greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo }`, or `true` | `notANumber`, `notAnInteger`, `greaterThan`, … |
|
|
4180
|
+
| `uniqueness` | `{ scope: [...], caseSensitive }`, or `true` | `taken` |
|
|
4181
|
+
|
|
4182
|
+
Every validation runs, in the order declared, so one attribute can collect several errors. Every rule also accepts these options:
|
|
4183
|
+
|
|
4184
|
+
- **`allowNull`** skips the rule when the value is `null`. Otherwise `null` fails `presence`, `format`, `inclusion`, and `numericality`, counts as length 0, and is never taken.
|
|
4185
|
+
- **`message`** replaces the default messages from that call.
|
|
4186
|
+
- **`if: (record) => boolean`** validates only when it returns `true`.
|
|
4187
|
+
|
|
4188
|
+
The default messages are in English: “can’t be blank”, “is too short (minimum is 3 characters)”, “has already been taken”, and so on. [Finding a built-in message](#finding-a-built-in-message) lists them all, and [Changing error messages](#changing-error-messages) shows how to replace them.
|
|
4189
|
+
|
|
4190
|
+
### Validator details
|
|
4191
|
+
|
|
4192
|
+
- **`presence`** fails a string that’s only whitespace. For a boolean, use `inclusion: [true, false]`, since `false` is a value.
|
|
4193
|
+
- **`numericality`** only accepts numbers, so a numeric string such as `"12"` is `notANumber`.
|
|
4194
|
+
- **`uniqueness`** leaves the record itself out when updating, and never treats `null` as taken, as SQLite’s UNIQUE does. `caseSensitive: false` compares with SQLite’s `lower()`, which only lowercases ASCII letters.
|
|
4195
|
+
|
|
4196
|
+
:::warning[Uniqueness isn’t a guarantee]
|
|
4197
|
+
Two requests can both check that an email is free, then both insert it. `uniqueness` gives a friendly error early, but only a UNIQUE index in the table prevents duplicates, so declare both. When the index catches a duplicate, the save throws [`RecordNotUnique`](/errors#constraint-errors).
|
|
4198
|
+
:::
|
|
4199
|
+
|
|
4200
|
+
## Reading errors
|
|
4201
|
+
|
|
4202
|
+
A record’s `errors` hold each failed rule:
|
|
4203
|
+
|
|
4204
|
+
```ts
|
|
4205
|
+
const account = Account.build({ email: "", handle: "a!" });
|
|
4206
|
+
await account.isValid(); // false
|
|
4207
|
+
|
|
4208
|
+
account.errors.get("email"); // ["can't be blank"]
|
|
4209
|
+
account.errors.fullMessages(); // ["Email can't be blank", "Handle is too short (minimum is 3 characters)", …]
|
|
4210
|
+
account.errors.toArray(); // [{ attribute: "email", type: "blank", message: "can't be blank" }, …]
|
|
4211
|
+
console.log(account.errors.size); // 5
|
|
4212
|
+
```
|
|
4213
|
+
|
|
4214
|
+
Printing `errors`, in the console or a log, lists each failure’s attribute, type, and message. `fullMessages()` puts the attribute’s name in front, so `createdAt` reads as “Created at”. Errors on the record as a whole go on `"base"`, and read without a prefix.
|
|
4215
|
+
|
|
4216
|
+
An error with a number in its message, such as `tooShort`, has it in `toArray()` too:
|
|
4217
|
+
|
|
4218
|
+
```ts
|
|
4219
|
+
{ attribute: "handle", type: "tooShort", message: "is too short (minimum is 3 characters)", values: { count: 3 } }
|
|
4220
|
+
```
|
|
4221
|
+
|
|
4222
|
+
## Adding errors
|
|
4223
|
+
|
|
4224
|
+
For a rule the validators don’t cover, add errors in a `beforeValidation` or `afterValidation` callback. A record with any errors is invalid:
|
|
4225
|
+
|
|
4226
|
+
```ts
|
|
4227
|
+
import { Model } from "@forestfuture/active-record";
|
|
4228
|
+
|
|
4229
|
+
export class Booking extends Model.define({
|
|
4230
|
+
id: { type: "integer", null: false },
|
|
4231
|
+
startsAt: { type: "datetime", null: false },
|
|
4232
|
+
endsAt: { type: "datetime", null: false },
|
|
4233
|
+
}) {
|
|
4234
|
+
static {
|
|
4235
|
+
this.errorMessages({ afterStart: "must be after the start" });
|
|
4236
|
+
|
|
4237
|
+
this.afterValidation((booking) => {
|
|
4238
|
+
if (booking.endsAt <= booking.startsAt) {
|
|
4239
|
+
booking.errors.add("endsAt", { type: "afterStart" });
|
|
4240
|
+
}
|
|
4241
|
+
if (booking.startsAt.getUTCDay() === 0) {
|
|
4242
|
+
booking.errors.add("base", "The room is closed on Sundays");
|
|
4243
|
+
}
|
|
4244
|
+
});
|
|
4245
|
+
}
|
|
4246
|
+
}
|
|
4247
|
+
```
|
|
4248
|
+
|
|
4249
|
+
`errors.add` takes the attribute, or `"base"`, then either a `type` or a message. A `type` takes its message from the Model’s `errorMessages`, as `afterStart` does above. See [Changing error messages](#changing-error-messages). A message is used as written, and its type is `"invalid"`:
|
|
4250
|
+
|
|
4251
|
+
```ts
|
|
4252
|
+
const sunday = new Date("2026-05-03T10:00:00Z");
|
|
4253
|
+
const booking = Booking.build({ startsAt: sunday, endsAt: sunday });
|
|
4254
|
+
await booking.isValid(); // false
|
|
4255
|
+
|
|
4256
|
+
booking.errors.toArray();
|
|
4257
|
+
// [{ attribute: "endsAt", type: "afterStart", message: "must be after the start" },
|
|
4258
|
+
// { attribute: "base", type: "invalid", message: "The room is closed on Sundays" }]
|
|
4259
|
+
booking.errors.fullMessages(); // ["Ends at must be after the start", "The room is closed on Sundays"]
|
|
4260
|
+
```
|
|
4261
|
+
|
|
4262
|
+
To fill in a placeholder, pass its value with the type:
|
|
4263
|
+
|
|
4264
|
+
```ts
|
|
4265
|
+
account.errors.add("handle", { type: "tooShort", count: 3 });
|
|
4266
|
+
```
|
|
4267
|
+
|
|
4268
|
+
To give a message and a type, pass the type as an option:
|
|
4269
|
+
|
|
4270
|
+
```ts
|
|
4271
|
+
account.errors.add("handle", "is reserved", { type: "reserved" });
|
|
4272
|
+
```
|
|
4273
|
+
|
|
4274
|
+
Each validation run, from `isValid()`, `save()`, or `saveOrThrow()`, starts by clearing `errors`. So an error added outside a validation callback is gone by the next save.
|
|
4275
|
+
|
|
4276
|
+
> **Compared with Rails**
|
|
4277
|
+
>
|
|
4278
|
+
> Rails’ `errors.add(:ends_at, :after_start)` is `errors.add("endsAt", { type: "afterStart" })` here, since a type and a message are both strings in TypeScript. When Rails is given a message instead, that text is the type too; here the type is `"invalid"`. Rails’ `message:` and `strict:` options and its procs aren’t here.
|
|
4279
|
+
|
|
4280
|
+
## Changing error messages
|
|
4281
|
+
|
|
4282
|
+
To change the message of one validation, pass `message` to `validates`. To change a message for every Model, call `this.errorMessages` in your app’s base class:
|
|
4283
|
+
|
|
4284
|
+
```ts
|
|
4285
|
+
import { Model } from "@forestfuture/active-record";
|
|
4286
|
+
import { schema } from "../db/schema";
|
|
4287
|
+
|
|
4288
|
+
// src/models/application-record.ts
|
|
4289
|
+
export abstract class ApplicationRecord extends Model {
|
|
4290
|
+
static override schema = schema;
|
|
4291
|
+
|
|
4292
|
+
static {
|
|
4293
|
+
this.errorMessages({
|
|
4294
|
+
blank: "is required",
|
|
4295
|
+
tooShort: {
|
|
4296
|
+
one: "needs at least 1 character",
|
|
4297
|
+
other: "needs at least %{count} characters",
|
|
4298
|
+
},
|
|
4299
|
+
});
|
|
4300
|
+
this.humanAttributeNames({ createdAt: "Added on" });
|
|
4301
|
+
}
|
|
4302
|
+
}
|
|
4303
|
+
```
|
|
4304
|
+
|
|
4305
|
+
Each key is a [built-in error type](#finding-a-built-in-message), or a type of your own. A message with a count, such as `tooShort`, can have a form for one and a form for any other count.
|
|
4306
|
+
|
|
4307
|
+
A Model’s own messages win over the base class’s, and a later call’s over an earlier one’s. Messages under `attributes` apply to one attribute:
|
|
4308
|
+
|
|
4309
|
+
```ts
|
|
4310
|
+
export class Product extends ApplicationRecord {
|
|
4311
|
+
static {
|
|
4312
|
+
this.errorMessages({
|
|
4313
|
+
greaterThan: "must be more than %{count}",
|
|
4314
|
+
attributes: {
|
|
4315
|
+
name: { blank: "needs a name customers will see" },
|
|
4316
|
+
},
|
|
4317
|
+
});
|
|
4318
|
+
this.humanAttributeNames({ priceCents: "Price" });
|
|
4319
|
+
|
|
4320
|
+
this.validates("name", { presence: true, length: { minimum: 3 } });
|
|
4321
|
+
this.validates("priceCents", { numericality: { greaterThan: 0 } });
|
|
4322
|
+
}
|
|
4323
|
+
}
|
|
4324
|
+
```
|
|
4325
|
+
|
|
4326
|
+
Each message is looked up when you read it:
|
|
4327
|
+
|
|
4328
|
+
```ts
|
|
4329
|
+
const product = Product.build({ name: "", priceCents: 0 });
|
|
4330
|
+
await product.isValid(); // false
|
|
4331
|
+
|
|
4332
|
+
product.errors.fullMessages();
|
|
4333
|
+
// ["Name needs a name customers will see",
|
|
4334
|
+
// "Name needs at least 3 characters",
|
|
4335
|
+
// "Price must be more than 0"]
|
|
4336
|
+
Product.humanAttributeName("priceCents"); // "Price"
|
|
4337
|
+
```
|
|
4338
|
+
|
|
4339
|
+
### Naming attributes
|
|
4340
|
+
|
|
4341
|
+
`fullMessages()` starts each message with the attribute’s name, made from the attribute itself: `createdAt` reads as “Created at”. To use another name, call `this.humanAttributeNames`, as the examples above do. Call it in the base class for every Model, or in a Model for its own attributes.
|
|
4342
|
+
|
|
4343
|
+
:::note
|
|
4344
|
+
`Product.humanAttributeName("priceCents")` returns the same name, for a form’s label.
|
|
4345
|
+
:::
|
|
4346
|
+
|
|
4347
|
+
In a Model, `attributes` and `humanAttributeNames` can only name the Model’s attributes, its associations, and `"base"`, so a misspelled name is a compile error. Names in the base class can be any attribute: a Model without that attribute ignores them.
|
|
4348
|
+
|
|
4349
|
+
### Filling in placeholders
|
|
4350
|
+
|
|
4351
|
+
A message can show these values:
|
|
4352
|
+
|
|
4353
|
+
- **`%{count}`**: the number in the rule, such as the `minimum` of `tooShort` or the bound of `greaterThan`.
|
|
4354
|
+
- **`%{attribute}`**: the attribute’s name, as `fullMessages()` shows it.
|
|
4355
|
+
- **`%{model}`**: the Model’s class name in words, so `BlogPost` reads as “Blog post”. A bundler that renames classes changes it too.
|
|
4356
|
+
- **`%{value}`**: the attribute’s value. A [filtered attribute](/models#filtering-attributes) shows `[FILTERED]`.
|
|
4357
|
+
|
|
4358
|
+
A value passed to `errors.add` with the type, such as `count`, fills in the placeholder of the same name.
|
|
4359
|
+
|
|
4360
|
+
### Looking messages up
|
|
4361
|
+
|
|
4362
|
+
For each error, the first message found is used:
|
|
4363
|
+
|
|
4364
|
+
1. A message given to `validates` or `errors.add`.
|
|
4365
|
+
2. The Model’s message for the attribute and type, then its message for the type.
|
|
4366
|
+
3. The same for each class the Model extends, your base class included.
|
|
4367
|
+
4. The built-in English message.
|
|
4368
|
+
|
|
4369
|
+
A type with no message anywhere throws a `TypeError` when the error is added.
|
|
4370
|
+
|
|
4371
|
+
### Finding a built-in message
|
|
4372
|
+
|
|
4373
|
+
Each error type has a built-in message. To replace one, use its type as the key in `errorMessages`:
|
|
4374
|
+
|
|
4375
|
+
| Type | Added by | Message |
|
|
4376
|
+
| -------------------------- | ------------------------------------------------ | ----------------------------------------------------------- |
|
|
4377
|
+
| `blank` | `presence` | can’t be blank |
|
|
4378
|
+
| `invalid` | `format` and an invalid autosaved association | is invalid |
|
|
4379
|
+
| `inclusion` | `inclusion` | is not included in the list |
|
|
4380
|
+
| `tooShort` | `length: { minimum }` | is too short (minimum is `%{count}` characters) |
|
|
4381
|
+
| `tooLong` | `length: { maximum }` | is too long (maximum is `%{count}` characters) |
|
|
4382
|
+
| `wrongLength` | `length: { is }` | is the wrong length (should be `%{count}` characters) |
|
|
4383
|
+
| `notANumber` | `numericality` | is not a number |
|
|
4384
|
+
| `notAnInteger` | `numericality: { onlyInteger }` | must be an integer |
|
|
4385
|
+
| `greaterThan` | `numericality: { greaterThan }` | must be greater than `%{count}` |
|
|
4386
|
+
| `greaterThanOrEqualTo` | `numericality: { greaterThanOrEqualTo }` | must be greater than or equal to `%{count}` |
|
|
4387
|
+
| `lessThan` | `numericality: { lessThan }` | must be less than `%{count}` |
|
|
4388
|
+
| `lessThanOrEqualTo` | `numericality: { lessThanOrEqualTo }` | must be less than or equal to `%{count}` |
|
|
4389
|
+
| `taken` | `uniqueness` | has already been taken |
|
|
4390
|
+
| `restrictDependentDestroy` | a has-one with `dependent: "restrictWithError"` | Cannot delete record because a dependent `%{record}` exists |
|
|
4391
|
+
| `restrictDependentDestroy` | a has-many with `dependent: "restrictWithError"` | Cannot delete record because dependent `%{record}` exist |
|
|
4392
|
+
|
|
4393
|
+
With a count of 1, the three `length` messages say “1 character”. `restrictDependentDestroy` goes on `"base"`, and `%{record}` is the association’s name in lowercase. To replace it, give both forms: `restrictDependentDestroy: { hasOne: "…", hasMany: "…" }`.
|
|
4394
|
+
|
|
4395
|
+
> **Compared with Rails**
|
|
4396
|
+
>
|
|
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. d1-record keeps messages on the classes instead, so a Model’s messages sit next to its validations. Their keys are d1-record’s error types, in camelCase. Rails shows “Translation missing” for a type with no message, where d1-record throws when the error is added. Messages in other languages aren’t here yet.
|