# Active Record > A Rails-inspired Active Record for Cloudflare Workers, on D1 or Postgres. # Active Record for Cloudflare Workers Source: https://active-record.forestfuture.dev/ ```package-install npm install @forestfuture/active-record ``` **[Get started](/getting-started)** From an empty Worker to two related Models in about ten minutes. Read the tutorial **[Coming from Rails](/coming-from-rails)** What carries over from Rails, and what’s different. See what’s different ## A Model and its queries Use a Model in your Worker with no connection setup. It finds its database from its binding: ```ts Worker import { User } from "./models/user"; export default { async fetch(request: Request): Promise { // GET: the 20 newest active users, each with their posts. if (request.method === "GET") { const users = await User.active() .includes("posts") // loaded in one extra query, not one per user .order({ createdAt: "desc" }) .limit(20) .toArray(); return Response.json(users); } // POST: sign up a user with a first post, saved together. const { email } = await request.json<{ email: string }>(); const user = User.build({ email }); user.posts().build({ title: "Hello, world" }); // save() validates and runs callbacks; false means it wasn't saved, and why is in errors. if (!(await user.save())) { return Response.json({ errors: user.errors.fullMessages() }, { status: 422 }); } return Response.json(user, { status: 201 }); }, } satisfies ExportedHandler; ``` ```ts Model import { hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Post } from "./post"; export class User extends ApplicationRecord { posts = hasMany(Post, { dependent: "destroy" }); // posts.user_id points here static active = this.scope((q) => q.where({ isActive: true })); static { this.validates("email", { presence: true, uniqueness: true }); this.beforeSave((user) => { user.email = user.email.toLowerCase(); }); } } ``` ```ts Querying import { User } from "./models/user"; const admins = await User.where({ role: "admin", isActive: true }).toArray(); User.where({ role: null }); // role IS NULL User.where({ role: ["admin", "editor"] }); // role IN (…), any number of values ``` ```ts Saving import { User } from "./models/user"; const user = User.build({ email: "jane@example.com" }); if (await user.save()) { // saved: user.isPersisted() is true } else { console.log(user.errors.fullMessages()); // ["Email has already been taken"] } const created = await User.create({ email: "sam@example.com" }); // saved, or not await created.update({ isActive: false }); // true or false ``` ```ts Batches import { batch } from "@forestfuture/active-record"; import { Article } from "./models/article"; import { Author } from "./models/author"; const authorId = crypto.randomUUID(); // generated in code, so the rows can point at it await batch((b) => [ b.insert(Author, { id: authorId, name: "Alex", email: "alex@example.com" }), b.insert(Article, { authorId, title: "Hello" }), b.updateAll(Article.where({ title: "Getting started" }), { authorId }), // Alex takes it over ]); ``` ```sql Table CREATE TABLE posts ( id TEXT PRIMARY KEY NOT NULL, user_id TEXT NOT NULL REFERENCES users (id), title TEXT NOT NULL, published_at DATETIME, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL ); CREATE INDEX index_posts_on_user_id ON posts (user_id); ``` ## Choose your database **[Cloudflare D1](/d1)** Bind a D1 database, and read from nearby replicas with Sessions. Use D1 **[Postgres](/postgresql)** Connect through Hyperdrive in a Worker, or directly on Node. Use Postgres ## What’s inside **[Models, declared once](/models)** Typed attributes come from your tables, camelCase in your code and snake_case in SQL, with defaults, timestamps, dates, and JSON converted both ways. **[Lazy, composable queries](/querying)** Conditions, ordering, pagination, scopes, and preloading with one query per association, never N+1. Hand-written SQL goes through a tagged template, so values are always bound. **[A predictable lifecycle](/persistence)** `save`, `create`, `update`, and `destroy` run validations and callbacks in a predictable order, with dirty tracking and dependent strategies. Methods that throw end in `OrThrow`. **[Atomic batches](/batches)** `batch` writes a set of statements and records all at once, or not at all, on D1 and on Postgres. Keys generated in code let a whole graph save in one batch. **[One API, two databases](/move-to-postgres)** Start on D1 and move to Postgres with your Models and code unchanged. Each adapter lists what works differently on its database. --- # Existing databases Source: https://active-record.forestfuture.dev/adopt-a-database ## Using Drizzle’s migrations Drizzle writes its migrations to `drizzle/`, its `out` setting. Tell Wrangler where they are: ```jsonc wrangler.jsonc { "d1_databases": [ // Migrations as drizzle/0000_name.sql: { "binding": "DB", "database_name": "my-app-db", "migrations_dir": "drizzle" }, // Or, as drizzle/_name/migration.sql: // { …, "migrations_pattern": "drizzle/*/migration.sql" }, ], } ``` Drizzle’s own schema often lives at `src/db/schema.ts` or in `src/db/schema/`, where Active Record writes its schema by default. Generate Active Record’s elsewhere: ```sh npx active-record schema --out src/db/d1-record.ts ``` 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. Pass `--out` to every later `schema` and `g` command, or keep it in a `package.json` script. :::note Without `--out`, Active Record refuses to write over a file it didn’t write, or beside a folder of the same name, so Drizzle’s schema is safe. ::: ## Using Prisma’s migrations 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. Prisma names tables after its models, such as `User`, and columns in camelCase, such as `createdAt`. Active Record keeps both names, so the Model sets its table, `static override table = "User"`, and has attributes such as `createdAt`. :::warning[Two date formats in one column] Prisma writes a `DateTime` as `2026-10-12T06:38:30.325+00:00`, and a `DEFAULT CURRENT_TIMESTAMP` fills `2026-10-12 06:38:30`. Active Record reads both as UTC, but SQLite compares dates as text, so a column with both needs the steps in [Comparing dates in two forms](#comparing-dates-in-two-forms). ::: ## Comparing dates in two forms A column can hold SQLite’s own date text (`2026-10-12 06:38:30`, from a `DEFAULT CURRENT_TIMESTAMP`) beside ISO text (`2026-10-12T06:38:30.000Z`). Active Record reads both as UTC, but SQLite compares them as text. On a column with both, `order` and `between` can misplace values within a day, and a condition on one instant misses the row written in the other form. To make the rows match, rewrite them once in a migration, with your own table and column: ```sql UPDATE reminders SET created_at = strftime('%Y-%m-%dT%H:%M:%fZ', created_at) WHERE strftime('%Y-%m-%dT%H:%M:%fZ', created_at) <> created_at; ``` It writes Active Record’s form for every row SQLite can read as a date, and leaves NULLs and anything else as they were. Running it again changes nothing. The rewrite is permanent, so export the table first. Conditions on the column then use its index. If another tool still writes the other form, compare through `strftime` in a fragment instead: ```ts import { column, sql } from "@forestfuture/active-record"; export function createdSince(since: Date) { const createdAt = column("createdAt"); return Reminder.where( sql`strftime('%Y-%m-%dT%H:%M:%fZ', ${createdAt}) >= ${createdAt.value(since)}`, ); } export function oldestFirst() { const createdAt = column("createdAt"); return Reminder.order(sql`strftime('%Y-%m-%dT%H:%M:%fZ', ${createdAt})`); } ``` `strftime` reads every form SQLite knows and writes Active Record’s ISO text, so rows in either form compare and sort as the times they are. :::note A wrapped column can’t use its index for that condition, so SQLite reads the whole table. ::: ## Starting with no migrations 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: ```sh # The tables, without their data, as a first migration: npx wrangler d1 export my-app-db --remote --no-data --output migrations/0001_baseline.sql # Create Wrangler's record of applied migrations, and mark the snapshot as applied, # so Wrangler never runs it against the database it came from: npx wrangler d1 migrations list my-app-db --remote npx wrangler d1 execute my-app-db --remote --command "INSERT INTO d1_migrations (name) VALUES ('0001_baseline.sql')" ``` From then on, change tables with new migrations. See [Schema changes](/change-a-table). ## Checking the generated attributes 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: ``` 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 (…) Note: posts.metadata: read as a string; if it holds JSON, override it as "json" in its Model ``` Fix a column’s type with an override in its Model. It changes how the column is read and written, never the table: ```ts export class Post extends ApplicationRecord { static override attributes = { metadata: "json", // text({ mode: "json" }): JSON in a plain TEXT column archived: "boolean", // integer({ mode: "boolean" }): 0 or 1 legacyNotes: false, // a column this app no longer uses: never read or written } as const; } ``` A Postgres enum type or a `CHECK (column IN (…))` makes its column an enum of the names it lists. Its type and its checks come from the database. Its methods stay off until you turn them on with `enum: true`. See [Reading enums from the database](/enums#reading-enums-from-the-database). ## Reading Unix timestamps 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: ```ts import { gte } from "@forestfuture/active-record"; export class Article extends ApplicationRecord { static override attributes = { publishedAt: { type: "datetime", storage: "unixSeconds" }, // timestamp: seconds updatedAt: { type: "datetime", storage: "unixMilliseconds" }, // timestamp_ms: milliseconds } as const; } export function publishedSince(since: Date) { return Article.where({ publishedAt: gte(since) }); } ``` | Drizzle mode | `storage` | | ---------------- | -------------------- | | `"timestamp"` | `"unixSeconds"` | | `"timestamp_ms"` | `"unixMilliseconds"` | The column stays an `INTEGER`. `createdAt` and `updatedAt` declared this way are written as integers too, and `where` and `between` take `Date`s. Under `unixSeconds`, a `Date` is stored to the second, so a condition such as `lt(date)` compares to the second too. :::warning[A Date in an sql fragment] A `Date` beside that column in a `sql` fragment throws `TypeError`: a fragment has no attribute, so it would bind as ISO text. Use `column("publishedAt").value(date)`, which writes it as the attribute stores it. See [Writing SQL fragments](/conditions#writing-sql-fragments). ::: :::note In a raw `env.DB.prepare(...)` statement, bind `Article.typeForAttribute("publishedAt").serialize(date)`, and read a cell with `deserialize`. See [Raw statements](/raw-statements). ::: :::note Prisma’s dates need no override. On D1, Prisma writes a `DateTime` as ISO text, which Active Record reads as it is. ::: > **Beyond Rails** > > Rails has no option for a date kept as an integer; there it takes a custom attribute type. Here it’s a `storage` on the `datetime`. ## Fixing cells of the wrong type A cell that isn’t the attribute’s type fails when the record loads or `pluck` reads it, naming the Model and attribute: ```text TypeError: Article: 1767323045 isn't a datetime for "publishedAt" ``` Find the cells by their SQLite type: ```sql SELECT typeof(published_at), count(*) FROM articles GROUP BY 1; ``` Then fix the cause: - If the column holds Unix times, declare the [`storage`](#reading-unix-timestamps) so they’re read as one. - If the attribute’s type is wrong, override it with the type the column holds. - If a few rows hold the wrong thing, `UPDATE` them. - If the column isn’t used, ignore it with `false` in the override. :::note 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. ::: --- # AI agents Source: https://active-record.forestfuture.dev/ai-agents :::tip The agent skill gives your agent the guide and its rules, and is what most projects need. The rest are for agents that can’t load a skill, or for a pointer that’s always in context. ::: ## Giving your agent the docs | Resource | What it is | | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | [`llms.txt`](/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. | | [`llms-full.txt`](/llms-full.txt) | The whole guide in one Markdown file. | | Any page + `.md` | Every page as Markdown: [`/associations.md`](/associations.md). | | `/.well-known/agent-skills/active-record/SKILL.md` | The skill below, published where agents look for a site’s skills. | | `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. | ## Installing the agent skill Install the library’s [agent skill](https://github.com/forestfuture/active-record/blob/main/packages/active-record/skills/active-record/SKILL.md): its rules, the shapes of a Model and a Worker, and the mistakes to watch for, with pointers into the guide. Agents that support skills, such as Claude Code, Cursor, Codex, and [others](https://skills.sh), load it when they work on Active Record code: ```sh npx skills add forestfuture/active-record ``` To install the copy shipped with your installed version, sync skills from `node_modules`: ```sh npx skills experimental_sync ``` :::note The skills CLI marks `experimental_sync` as experimental, so its name may change. ::: ## Pointing AGENTS.md at the guide 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: ```md Before writing code with `@forestfuture/active-record`, read the part of `node_modules/@forestfuture/active-record/llms-full.txt` for the task. ``` The line names the guide shipped with your installed version, so it stays correct after an upgrade. ## Using the rules without a skill 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: ```md Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for Cloudflare Workers, with an adapter per database inside it: `@forestfuture/active-record/d1` for D1, and `@forestfuture/active-record/postgresql` for Postgres, which needs the app's own `pg`. Import Models, Relations, and errors from the core, and what opens a database from its adapter's entry: `connect`, `withSession`, `NoSession`, and `d1` from `/d1`; `connect` and `postgresql` from `/postgresql`. Every `active-record` command reads `active-record.jsonc`, which names each database's adapter, so one project can hold a D1 database and a Postgres one: run `npx active-record init` to write it, never `--adapter` on another command (`init --adapter postgresql` adds Hyperdrive bindings to a file that names only D1 databases). Its guide for the installed version is `node_modules/@forestfuture/active-record/llms-full.txt`, one Markdown file with a `#` heading per page: read the part for the task before writing code with it. - 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`. - A Model extends the app's base class: `class Post extends ApplicationRecord {}`. Its table comes from its class name (`Post` → `posts`), or `static override table = "…"`, and its attributes from the schema, so it declares only behavior. With a bundler that renames classes (Wrangler keeps them by default), set `static override modelName = "Post"` on each Model, so its table, foreign keys and schema entry keep the name. Run `npx active-record schema` after adding or renaming a Model, as after a migration: a Model it hasn't seen throws `InvalidModel`. Change how a column is read with an override in the class, `static override attributes = { metadata: "json" } as const`, never by editing the schema. Normalize an attribute's values (trimming, lowercasing an email) with `this.normalizes("email", { with: (email) => email.trim().toLowerCase() })` in `static {}`, not in a setter, a `beforeValidation` callback or each query: it runs on every assigned value and on a query's values too, so `findBy` with the user's input finds the stored row. It doesn't change rows already stored: normalize those with `record.normalizeAttribute("email")` and `save()`. A value a form sends but the table doesn't keep (a terms checkbox, a confirmation) is a virtual attribute in the same object, `termsOfService: { type: "boolean", virtual: true }`, not a plain class field: it's cast, tracked and taken by `permit`, never saved, and a query can't name it. To give an attribute a second name, add `title: { aliasOf: "name" }` there, rather than a getter and setter: queries, writes and validations take either name. Keep a password as `password: { securePassword: true }` there, with a `password_digest` column, never by hashing in a callback or storing it: it's hashed with PBKDF2 when the record is saved, `await user.authenticate(password)` checks it, and sign in with `await User.authenticateBy({ email, password })`, which resolves to null for a wrong email or password alike, rather than `findBy` then `authenticate`. Ask for the current password before a change with `passwordChallenge`. For bcrypt or a stronger hash, give `{ securePassword: { algorithm } }` an object with `hash`, `verify` and `maxBytes`. The default costs 10–40 ms of CPU per hash, past the Workers Free plan's 10 ms. A random token for each new record (an API token, an invite code) is `authToken: { secureToken: true }` on a string column with a UNIQUE index, with `await user.regenerateAuthToken()` to replace it, rather than `crypto.randomUUID()` in a callback; `generateSecureToken()` makes one for anything else. For a password reset link, use `await user.passwordResetToken()` and `await User.findByPasswordResetToken(token)`, never a token column you store and clear: it lasts 15 minutes and stops working once the password changes. For any other link (confirming an email, unsubscribing), declare `this.generatesTokenFor("emailConfirmation", { expiresIn: { days: 1 }, dependsOn: (user) => user.email })` in `static {}`, then `await user.generateTokenFor(purpose)` and `User.findByTokenFor(purpose, token)`; or sign an id with `await user.signedId({ purpose, expiresIn })` and `User.findSigned(signedId, { purpose })`. Don't put a plain id in such a link, or sign one yourself. They're signed with the Worker's `SECRET_KEY_BASE` (`wrangler secret put SECRET_KEY_BASE`, at least 32 bytes; in tests, `process.env`); to rotate it, override `static signingSecret(env)` on the app's base class to return `[env.SECRET_KEY_BASE, env.PREVIOUS_SECRET_KEY_BASE]`. An `INTEGER` holding a Unix time (Drizzle's `timestamp` modes) is `{ type: "datetime", storage: "unixSeconds" }` or `"unixMilliseconds"`. Bytes are a `binary` attribute (a `Uint8Array`, in a `BLOB` or `bytea` column): assign a form's file as `new Uint8Array(await file.arrayBuffer())`. An exact number (a price, a quantity with a fraction) is a `decimal` attribute, held as text (`"12.5"`) in a `NUMERIC` or `DECIMAL` column, never a `real`, with `precision` and `scale` to round it as `NUMERIC(10, 2)` does; a day with no time is a `date` (`"2026-01-02"`) and a time of day a `time` (`"09:30:00"`), assigned as text, not a `Date`. A value no built-in type holds (money, a value object, a list kept as text) is a custom type: `const money = defineType({ storedAs: "integer", cast, serialize, deserialize })`, given as `priceCents: money` in the override or in `define`, rather than converting in getters, setters or callbacks; its `cast` throws for a value it can't hold. A column with a fixed set of values is an enum: `status: { enum: ["draft", "published"] }` (names stored as text) or `{ enum: { low: 0, high: 1 } }` (an integer column), which gives `post.isDraft()`, `await post.saveAsPublished()`, `Post.published()`, `Post.notPublished()` and `Post.enumValues("status")`; use those and `where({ status: "published" })` rather than a hand-written scope or a `declare status: …` narrowing. Run `npx active-record schema` after adding an enum, so its scopes are typed. A column the database restricts to a list (a Postgres enum type, `CHECK (state IN ('open', 'done'))`) already has the names in the schema, typed and checked but without methods: turn them on with `state: { enum: true }`, rather than listing the names again, or drop it with `enum: false`. An unlisted stored value reads as `null`; rename a name with `{ newName: "old_value" }`. A cell that isn't its attribute's type (a number in an ISO `datetime`, text in an `integer`) fails the load with a `TypeError` naming the attribute: correct the override, don't catch it. - 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. - Never pass a request's whole body, form or query string to a Model: name the fields, with destructuring or `User.permit(await request.json(), "email", "name")` (it reads `FormData` and `URLSearchParams` too). Assigned values are checked against the attribute's type, but that doesn't stop a user setting `role` or `isAdmin`. Check a request value's type before querying with it: `findBy({ token: null })` matches rows whose token is NULL, and a list matches any of its values. `findOrCreateBy`, `findOrInitializeBy` and `createOrFindBy` throw `TypeError` for a list, a comparison or a `sql` fragment. - Name attributes in camelCase everywhere: `where`, `order`, `pluck`, `foreignKey`. Column names (snake_case) appear only inside `sql` fragments. - 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. - 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`. - Bulk writes run when called, without callbacks: `await posts.deleteAll()`, `deleteBy({…})` and `updateAll(…)` resolve to how many rows; `insert(…)`, `insertAll`, `upsert` and `upsertAll` to `{ rowsAffected, rows }`, where `rows` holds each written row's primary key, or the attributes `returning: [...]` names (`returning: false` for none). Through a Relation they write its equality values and `createWith` over the attributes given (`Post.where({ userId: 1 }).insert({ userId: 2, … })` writes `userId: 1`), where `build` and `create` keep the given ones. Make several writes atomic by preparing them in one batch's callback: `batch((b) => [b.insert(Post, {…}), b.updateAll(Post.where(…), {…}), b.save(user), b.destroy(post)])`. The callback can't await, so load what the writes need first. D1 has no interactive transactions, so a read-then-write can't be atomic. - Count with the database, not in memory: `post.incrementColumn("viewCount")` or `Post.updateCounters(id, { viewCount: 1 })` add to the row atomically, where `post.viewCount++` then `save()` loses another request's increment. The counter statics (`Post.updateCounters(ids, …)`, `incrementCounter`) skip the default scope, so with a key from a request, and a default scope that separates tenants or hides deleted rows, write `Post.where({ id }).updateCounters({ … })`, which keeps it. The `…Column` methods and `updateColumns` skip validations, callbacks and `updatedAt`, so use `update` for a change those should see; `increment` and `toggle` only change the record in memory. In an after-callback, `record.isPreviouslyNewRecord()` says whether the save created it. - To mark a record changed without saving it (a cache key, a "last seen"), `await record.touch()` sets `updatedAt`, or `touch("lastSeenAt")` that attribute too, with no validation or save callback; `Post.where(…).touchAll()` touches many rows. A touch runs `afterTouch` and the update commit callbacks (`afterUpdateCommit` included), so code there that should run only on a save belongs in `afterUpdate` or `afterSave`. To keep a parent's `updatedAt` current as its children change (a cache key), declare `belongsTo(Article, { touch: true })` on the child rather than touching the parent in a callback: the parent is touched in the child's batch, runs its own touch callbacks, and touches its own parents in turn. A parent that isn't loaded costs one SELECT per level, so preload the chain (`includes({ article: "blog" })`) when saving many. `hasOne(Profile, { touch: true })` touches a user's profile the same way when the user is updated, destroyed or touched. For a bulk import, wrap it in `Article.noTouching(async () => { … })`, so no article is touched per comment, then touch each article once after it. - To show how many records an association has, keep a counter cache rather than counting on each read: `article = belongsTo(Article, { counterCache: true })` with a `commentsCount` attribute, which `article.comments().size()` reads. Saves, destroys and the association's `delete`/`clear`/`deleteAll()` keep it; bulk writes (`insertAll`, `updateAll`, a Relation's `deleteAll`) don't, so follow them with `Article.resetCounters(id, "comments")`. Add one to existing rows with `{ active: false }`, reset each, then drop `active: false`. - To work through more records than a request should hold (a backfill, an export, a cleanup), iterate in batches rather than `toArray()` or `offset` pages: `for await (const user of User.where(…).findEach())`, `findInBatches()` for arrays, and `inBatches()` for a Relation per batch to `updateAll`, `deleteAll` or `destroyAll`. Batches go in primary-key order, so `reorder()` a Relation that has an order (a default scope's too), and bound them with `start` and `finish`, not `offset`. On D1 a Worker invocation sends at most 1,000 queries (50 on Free), and each batch sends one (`inBatches` reads its keys, then sends the write, and a `destroyAll` adds a load and each record's dependent reads; a `db.batch` counts as one): split a larger job across invocations by `start` and `finish`. - To destroy many records with their callbacks and `dependent:` strategies, use `posts.destroyAll()`, `Post.destroyBy({…})` or `Post.destroy(ids)`: they load the records and destroy them in one write, all or none (`RecordNotDestroyed` if one refuses). They hold every record in memory, so destroy a large set a batch at a time: `for await (const batch of posts.inBatches({ batchSize: 100 })) await batch.destroyAll()`. - Keep the generators' `TEXT` keys, generated in code, for records saved together (`--id integer` gives a key D1 generates instead). An owner whose key is known before its INSERT (generated in code, or already saved) is written in one atomic batch with the records built through it on its database. A key D1 generates exists only after its own write, so each level is then written in a separate batch. Records on another database are always a separate write there, and a batch refuses them. - 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. - Declare associations as fields, passing the target class: `posts = hasMany(Post, { dependent: "destroy" })`, `author = belongsTo(User)`. The field's name is the association's name. Add and remove a `hasMany`'s records through it: `user.posts().push(post)`, `delete(post)` (by its `dependent:`, nullifying by default), `destroy(post)` and `clear()`, rather than writing the foreign key yourself, so a loaded collection stays in step. Saving requires a `belongsTo`'s record ("must exist"), so pass `optional: true` when its foreign key may be `null`. Its target may be on another database (a Model on another base class): reading, preloading (one more round trip), and writing through it go to the target's database, and a save or destroy writes each database separately, not atomically. A `hasOne`'s new record, through `set`, `build` or `create`, replaces the old one, which its `dependent:` strategy removes (without one, its foreign key is set to `null`). Await `user.profile.set(profile)`: on a saved owner it saves at once, unlike a `belongsTo`'s `set`. To save changes to associated records with their owner, declare the association `autosave: true` and change the records it loaded (`await user.posts().toArray()`), not ones found with a query of their own. `record.markForDestruction()` then destroys a record when its owner is saved. For a record that can belong to one of several Models, list them: `commentable = belongsTo([Post, Photo])`, with `commentableType` and `commentableId` attributes, and `comments = hasMany(Comment, { as: "commentable" })` on each listed Model. Point it with `comment.commentable.set(post)`, not by writing the type yourself: the type holds each Model's `modelName`, so set `static modelName` on the listed Models if a bundler renames classes. Reach records through a join Model with `through`: `projects = hasMany(Project, { through: "assignments" })` (`source:` names the join Model's association when it isn't `project`). It reads and preloads as any association, each record once. Write through it to make and remove join records: `user.projects().push(project)`, `build`, `create`, `delete(project)` and `clear()` (`destroy(project)` destroys the join records too, not the project). A built project is linked when the owner is saved, not the project. Don't narrow before `deleteAll` (`user.projects().where(…).deleteAll()`), which deletes the projects themselves. Only a join Model is written through (a `hasMany` to a `belongsTo`); `insert` and `upsert` through it throw. An upsert through a `hasMany` only updates the owner's records, and leaves another owner's clashing row as it is. - 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`. Check a value typed twice with `this.validates("email", { confirmation: true })` and a virtual `emailConfirmation: { type: "string", virtual: true }`; `toJSON()` leaves the confirmation out. Compare one attribute with another with `comparison: { greaterThan: (event) => event.startsAt }`, not a callback. Validate an association's loaded records with `this.validatesAssociated("posts")`, not a callback. Run a rule only when creating or updating with `on: "create"` or `on: "update"` (or skip one with `exceptOn`), not `if: (record) => record.isNewRecord()`. For a step of the app's own, list its name in the Model's `static validationContexts = ["signup"] as const` and validate in it with `isValid("signup")` or `save({ context: "signup" })`; that replaces `"create"`, so pass `["create", "signup"]` to run both. For a custom error, `errors.add("startsAt", { type: "onTheHour" })` and give `onTheHour` a message there. - Check what writes return. `save()` and `update()` resolve to `false` when validation fails (reasons in `record.errors`) or a callback aborts (`record.abortReason`). `destroy()` resolves to `false` when a callback aborts, or a `restrictWithError` association refuses (reason in `record.errors`). The `…OrThrow` methods throw instead. Constraint errors, such as `RecordNotUnique`, always throw, and so does a rule declared `strict: true` (`StrictValidationFailed`), meant for values only a bug could set. ``` Copy it again after upgrading Active Record, since the rules can change. --- # Associations Source: https://active-record.forestfuture.dev/associations ## At a glance | To | Write | | -------------------------------------------- | --------------------------------------------------------------------------- | | point at the record a foreign key names | `author = belongsTo(Author)` | | reach the records that point at this one | `articles = hasMany(Article)` | | reach the one record that points at this one | `profile = hasOne(Profile)` | | point at a record of one of several Models | `likeable = belongsTo([Photo, Video])`, `hasMany(Like, { as: "likeable" })` | | narrow or order an association | `hasMany(Article, { scope: (q) => q.where({ … }) })` | | remove records with their owner | `hasMany(Article, { dependent: "destroy" })` | Each part of associations has a page of its own: | To | See | | ------------------------------------------------- | ---------------------------------------------- | | load an association for many records at once | [Preloading](/preloading) | | save records with their owner | [Autosaving](/autosaving) | | reach records through another association | [Through associations](/through-associations) | | keep a count of a record’s associated records | [Counter caches](/counter-caches) | | set `updatedAt` when an associated record changes | [Touching](/touching) | | filter by associated records | [Joins](/joins) | ## The Models The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates: ```ts author.ts import { hasMany, hasOne } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Article } from "./article"; import { Profile } from "./profile"; export class Author extends ApplicationRecord { articles = hasMany(Article, { dependent: "destroy" }); // Article's authorId profile = hasOne(Profile, { dependent: "delete" }); // Profile's authorId // A scope turns finding the inverse off, so name it: publishedArticles = hasMany(Article, { scope: (q) => q.where({ published: true }), inverseOf: "author", }); } ``` ```ts article.ts import { belongsTo, hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Author } from "./author"; import { Comment } from "./comment"; export class Article extends ApplicationRecord { author = belongsTo(Author); // its own authorId comments = hasMany(Comment, { dependent: "deleteAll" }); // Comment's articleId } ``` ```ts profile.ts import { belongsTo } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Author } from "./author"; export class Profile extends ApplicationRecord { author = belongsTo(Author); } ``` ```ts comment.ts import { belongsTo } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Article } from "./article"; export class Comment extends ApplicationRecord { article = belongsTo(Article); } ``` ```ts category.ts import { belongsTo, hasMany, type HasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; export class Category extends ApplicationRecord { static top = this.scope((q) => q.where({ parentId: null })); static alphabetical = this.scope((q) => q.order({ name: "asc" })); parent = belongsTo(Category, { foreignKey: "parentId", optional: true }); // a top category has none // Written out: TypeScript can't infer a field whose scope uses its own Model's scopes. children: HasMany = hasMany(Category, { foreignKey: "parentId", scope: (q) => q.alphabetical(), }); } ``` ```ts like.ts import { belongsTo } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Photo } from "./photo"; import { Video } from "./video"; export class Like extends ApplicationRecord { likeable = belongsTo([Photo, Video]); // its own likeableType and likeableId } ``` ```ts photo.ts import { hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Like } from "./like"; export class Photo extends ApplicationRecord { likes = hasMany(Like, { as: "likeable" }); // Like's likeableType is "Photo" } ``` ```ts video.ts import { hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Like } from "./like"; export class Video extends ApplicationRecord { likes = hasMany(Like, { as: "likeable" }); // Like's likeableType is "Video" } ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: 936ee2fb777c import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** articles — last changed by 0001_create_tables.sql */ export const articles = { id: { type: "string", null: false, generateId: true }, authorId: { type: "string", null: false }, title: { type: "string", null: false }, published: { type: "boolean", null: false, default: () => false }, } as const; /** authors — last changed by 0001_create_tables.sql */ export const authors = { id: { type: "string", null: false, generateId: true }, name: { type: "string", null: false }, } as const; /** categories — last changed by 0001_create_tables.sql */ export const categories = { id: { type: "string", null: false, generateId: true }, name: { type: "string", null: false }, parentId: "string", } as const; /** comments — last changed by 0001_create_tables.sql */ export const comments = { id: { type: "string", null: false, generateId: true }, articleId: { type: "string", null: false }, body: { type: "string", null: false }, } as const; /** likes — last changed by 0001_create_tables.sql */ export const likes = { id: { type: "string", null: false, generateId: true }, likeableType: { type: "string", null: false }, likeableId: { type: "string", null: false }, } as const; /** photos — last changed by 0001_create_tables.sql */ export const photos = { id: { type: "string", null: false, generateId: true }, title: { type: "string", null: false }, } as const; /** profiles — last changed by 0001_create_tables.sql */ export const profiles = { id: { type: "string", null: false, generateId: true }, authorId: { type: "string", null: false }, bio: "string", } as const; /** videos — last changed by 0001_create_tables.sql */ export const videos = { id: { type: "string", null: false, generateId: true }, title: { type: "string", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { articles: { attributes: articles, primaryKey: "id" }, authors: { attributes: authors, primaryKey: "id" }, categories: { attributes: categories, primaryKey: "id" }, comments: { attributes: comments, primaryKey: "id" }, likes: { attributes: likes, primaryKey: "id" }, photos: { attributes: photos, primaryKey: "id" }, profiles: { attributes: profiles, primaryKey: "id" }, videos: { attributes: videos, primaryKey: "id" }, }, models: { Article: "articles", Author: "authors", Category: "categories", Comment: "comments", Like: "likes", Photo: "photos", Profile: "profiles", Video: "videos", }, }); declare module "../models/article" { interface Article extends TableAttributes {} } declare module "../models/author" { interface Author extends TableAttributes {} } declare module "../models/category" { interface Category extends TableAttributes {} } declare module "../models/comment" { interface Comment extends TableAttributes {} } declare module "../models/like" { interface Like extends TableAttributes {} } declare module "../models/photo" { interface Photo extends TableAttributes {} } declare module "../models/profile" { interface Profile extends TableAttributes {} } declare module "../models/video" { interface Video extends TableAttributes {} } ``` ```sql D1 CREATE TABLE authors ( id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL ); CREATE TABLE profiles ( id TEXT PRIMARY KEY NOT NULL, author_id TEXT NOT NULL REFERENCES authors (id), bio TEXT ); CREATE TABLE articles ( id TEXT PRIMARY KEY NOT NULL, author_id TEXT NOT NULL REFERENCES authors (id), title TEXT NOT NULL, published BOOLEAN NOT NULL DEFAULT FALSE ); CREATE TABLE comments ( id TEXT PRIMARY KEY NOT NULL, article_id TEXT NOT NULL REFERENCES articles (id), body TEXT NOT NULL ); CREATE TABLE categories ( id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, parent_id TEXT REFERENCES categories (id) ); CREATE TABLE photos ( id TEXT PRIMARY KEY NOT NULL, title TEXT NOT NULL ); CREATE TABLE videos ( id TEXT PRIMARY KEY NOT NULL, title TEXT NOT NULL ); CREATE TABLE likes ( id TEXT PRIMARY KEY NOT NULL, likeable_type TEXT NOT NULL, likeable_id TEXT NOT NULL ); CREATE INDEX index_profiles_on_author_id ON profiles (author_id); CREATE INDEX index_articles_on_author_id ON articles (author_id); CREATE INDEX index_comments_on_article_id ON comments (article_id); CREATE INDEX index_categories_on_parent_id ON categories (parent_id); CREATE INDEX index_likes_on_likeable ON likes (likeable_type, likeable_id); ``` ```sql Postgres CREATE TABLE authors ( id UUID PRIMARY KEY, name TEXT NOT NULL ); CREATE TABLE profiles ( id UUID PRIMARY KEY, author_id UUID NOT NULL REFERENCES authors (id), bio TEXT ); CREATE TABLE articles ( id UUID PRIMARY KEY, author_id UUID NOT NULL REFERENCES authors (id), title TEXT NOT NULL, published BOOLEAN NOT NULL DEFAULT FALSE ); CREATE TABLE comments ( id UUID PRIMARY KEY, article_id UUID NOT NULL REFERENCES articles (id), body TEXT NOT NULL ); CREATE TABLE categories ( id UUID PRIMARY KEY, name TEXT NOT NULL, parent_id UUID REFERENCES categories (id) ); CREATE TABLE photos ( id UUID PRIMARY KEY, title TEXT NOT NULL ); CREATE TABLE videos ( id UUID PRIMARY KEY, title TEXT NOT NULL ); CREATE TABLE likes ( id UUID PRIMARY KEY, likeable_type TEXT NOT NULL, likeable_id UUID NOT NULL ); CREATE INDEX index_profiles_on_author_id ON profiles (author_id); CREATE INDEX index_articles_on_author_id ON articles (author_id); CREATE INDEX index_comments_on_article_id ON comments (article_id); CREATE INDEX index_categories_on_parent_id ON categories (parent_id); CREATE INDEX index_likes_on_likeable ON likes (likeable_type, likeable_id); ``` ## Defining associations Declare each association as a field, passing the target Model’s class, as the Models above do: - The field’s name is the association’s name. - Models can refer to each other in any order. - A subclass inherits its parent’s associations, and can redeclare one to change it. ## belongsTo Use `belongsTo` on the Model whose table holds the foreign key, as an article belongs to its author: ```ts import { Article } from "./models/article"; import { Author } from "./models/author"; const article = await Article.findByOrThrow({ title: "On Nothing" }); const author = await article.author(); // an Author, or null const other = await Author.findByOrThrow({ name: "Sam" }); article.author.set(other); // written when the article is saved await article.save(); ``` - **`await record.author()`** reads the associated record, or `null`. - **`record.author.set(user)`** points the record at another record, and `set(null)` clears it. It’s written when the record is saved. - **`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. - **`record.author.create(attrs)`** and **`createOrThrow(attrs)`** save a new record at once, and point at it. The record itself isn’t saved. | Option | Does | | ------------ | --------------------------------------------------------------------------------------------------------------------- | | `foreignKey` | The attribute on this record that holds the link. Defaults to the association’s name + `Id` | | `primaryKey` | The attribute on the target it points at. Defaults to the target’s primary key | | `scope` | Narrows the target, `(q) => q.where(…)`. See [Scoping associations](#scoping-associations) | | `optional` | Lets the record point at nothing. See [Requiring the record](#requiring-the-record) | | `autosave` | `true` saves the record’s changes with this record. See [Saving changed records](/autosaving#saving-changed-records) | | `inverseOf` | The target’s `hasOne` that points back, or `false`. See [Inverse associations](#inverse-associations) | ## Requiring the record Saving a record checks that each `belongsTo` points at a record that exists, unless it’s declared `optional: true`, as a category’s `parent` is: - If the foreign key is `null`, or no row has that key, the save fails with “must exist” on the association, such as `author`. The record it finds stays loaded. - A saved record whose foreign key hasn’t changed isn’t checked again. - A record built through a `hasMany` or `hasOne` already points at its owner, so it passes the check before either is saved. See [Autosaving](/autosaving#saving-a-graph). ## hasMany Use `hasMany` on the Model the other table’s foreign key points at, as an author has many articles: ```ts import { Author } from "./models/author"; const author = await Author.findByOrThrow({ name: "Jane" }); const articles = await author.articles().toArray(); // a Relation of the author's articles author.articles().build({ title: "Untitled" }); // saved with the author, with its key await author.save(); await author.articles().where({ title: "Untitled" }).deleteAll(); // scoped to the author's articles ``` - **`record.articles()`** is a Relation of the associated records, with every Relation method and the target’s scopes. - **`record.articles().build(attrs)`** builds a record with the owner’s key, saved with the owner. See [Autosaving](/autosaving#saving-a-graph). - **`record.articles().create(attrs)`** and **`createOrThrow(attrs)`** save a new record at once. The owner must already be saved. - **`record.articles().push(...records)`** adds records. It sets their foreign key and saves them in one write, or resolves to `false` and saves none if one can’t be saved. On an unsaved owner, they’re saved with it. - **`record.articles().delete(...records)`** removes records by the `dependent` strategy. It destroys them for `"destroy"`, deletes them for `"deleteAll"`, and otherwise sets their foreign key to `NULL`. - **`record.articles().destroy(...records)`** destroys records with their callbacks, whatever the strategy. - **`record.articles().clear()`** removes every record, as `deleteAll()` does. - **`record.articles().destroyAll()`** destroys every record with its callbacks, whatever the strategy, and leaves the association empty. | Option | Does | | ------------ | ------------------------------------------------------------------------------------------------------------------- | | `foreignKey` | The attribute on the target’s records that holds the link. Defaults to this Model’s class name + `Id` | | `primaryKey` | The attribute on this record the foreign key points at. Defaults to the primary key | | `scope` | Narrows or orders the records, `(q) => q.order(…)`. See [Scoping associations](#scoping-associations) | | `dependent` | What destroying the owner does to the records. See [Destroying dependent records](#destroying-dependent-records) | | `autosave` | `true` saves the records’ changes with the owner. See [Saving changed records](/autosaving#saving-changed-records) | | `inverseOf` | The target’s `belongsTo` that points back, or `false`. See [Inverse associations](#inverse-associations) | ## hasOne Use `hasOne` like `hasMany`, when there’s at most one record, as an author has one profile: ```ts import { Author } from "./models/author"; const author = await Author.findByOrThrow({ name: "Jane" }); const profile = await author.profile(); // a Profile, or null if (profile === null) await author.profile.create({ bio: "Writer" }); // saved at once ``` - **`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. - **`await record.profile.set(profile)`** gives the owner another record, and `set(null)` removes it. On a saved owner, the record is saved at once, so await it. On an unsaved owner, it’s saved with the owner. - **`record.profile.build(attrs)`** builds a record with the owner’s key, saved with the owner. - **`record.profile.create(attrs)`** and **`createOrThrow(attrs)`** save a new record at once. The owner must already be saved. `hasOne` takes the same options as `hasMany`. ## Replacing the record Giving a saved owner a new record removes its old one, by the association’s `dependent` strategy: ```ts import { Author } from "./models/author"; import { Profile } from "./models/profile"; const author = await Author.findByOrThrow({ name: "Jane" }); await author.profile.set(Profile.build({ bio: "Novelist" })); // and deletes the old one, in one batch ``` | `dependent` | What happens to the old record | | ----------------------------------------- | ------------------------------------------------ | | `"destroy"` | It’s destroyed, with its own callbacks | | `"delete"` | It’s deleted, without callbacks | | `"nullify"`, a restrict strategy, or none | Its foreign key is set to `NULL`, and it’s saved | - The old record is removed in the same atomic batch that writes the new one. That’s at once for `set` and `create`, and when the owner is saved for `build`. - If the old record can’t be saved with a `NULL` foreign key, the write throws `RecordNotSaved`, and nothing is written. - If the new record doesn’t save, the old one stays. `set` throws `RecordNotSaved` and leaves the association as it was. `create` returns the unsaved record, and saving the owner tries again. ## Polymorphic associations A polymorphic `belongsTo` points at a record of any of several Models, listed in an array, as a like belongs to a photo or a video: ```ts import { Like } from "./models/like"; import { Video } from "./models/video"; const like = await Like.firstOrThrow(); const liked = await like.likeable(); // a Photo, a Video, or null const video = await Video.findByOrThrow({ title: "Launch" }); like.likeable.set(video); // likeableType "Video", likeableId video.id await like.save(); const likes = await video.likes().toArray(); // the likes whose type is "Video" ``` - The record holds the link in two attributes: a type, which names the Model, and a foreign key. They’re the association’s name with `Type` and `Id`, so `likeable` uses `likeableType` and `likeableId`. - On each listed Model, a `hasMany` or `hasOne` names the `belongsTo` with `as`, and reads the records whose type is that Model. - **`await like.likeable()`** reads the record of the Model the type names, or `null`, and **`like.likeable.set(video)`** sets both the type and the foreign key. `set(null)` clears both. - **`video.likes()`** works like any `hasMany`. Records built, created, or pushed through it get the video’s type and key. Removing records through it, or by a `"nullify"` strategy, clears both. - To preload one, see [Preloading polymorphic records](/preloading#preloading-polymorphic-records). | Option | Does | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | `foreignType` | The attribute that holds the type. Defaults to the association’s name + `Type`, or on a `hasMany` or `hasOne`, the `as` name + `Type` | | `as` | On a `hasMany` or `hasOne`: the name of the target’s polymorphic `belongsTo`. Its foreign key defaults to that name + `Id` | The polymorphic `belongsTo` also takes `foreignKey`, `primaryKey`, `optional`, and `autosave`, as any `belongsTo` does. It has no `build` or `create`, since it can’t tell which Model to make, and no `scope`. Neither D1 nor Postgres can enforce a foreign key that points at a different table in each row. ## Storing the type The type holds the listed Model’s `modelName`, such as `"Photo"`: - A subclass of a listed Model is stored as the Model whose table it shares. - If a stored type names none of the listed Models, reading the association throws `UnknownModelName`. :::warning[Set modelName if your bundler renames classes] The type is saved in your rows. A Model’s name is its class name unless it sets `static modelName`, so a bundler that renames `Photo` to `e` saves `"e"`, and a later build can’t read those rows. Wrangler keeps class names by default. With any other bundler, set `static modelName` on each listed Model. See [Naming Models](/models#naming-models). ::: ## Naming foreign keys A foreign key names an attribute, such as `authorId`, rather than a column, and by default it’s inferred: - **`belongsTo`** uses the association’s name + `Id`. `author = belongsTo(Author)` uses the record’s own `authorId`. - **`hasMany` and `hasOne`** use the Model’s name + `Id`, on the target. `Author`’s associations use `authorId`, `BlogPost`’s use `blogPostId`, and `APIKey`’s use `apiKeyId`. - If the name doesn’t follow the convention, pass `foreignKey`, as `Category` does with `parentId`. - Keys are checked the first time a Model is used, and a missing attribute throws `InvalidModel`. If a bundler renames `Author` to `e`, the inferred `eId` doesn’t exist; set `static modelName` (see [Naming Models](/models#naming-models)), pass `foreignKey`, or keep class names in your bundler’s settings. ## Caching loaded records A loaded association is cached on the record, so reading it again sends no query: ```ts import { Article } from "./models/article"; const article = await Article.findByOrThrow({ title: "On Nothing" }); const author = await article.author(); // one query const again = await article.author(); // none: it's cached on the article ``` - Changing a foreign key makes the next read query again. - `reload()` clears the cache, and `await record.reloadAssociation("articles")` reloads one association. - A write through a `hasMany` clears its loaded collection: `insert`, `upsert`, `updateAll` and `deleteAll`, alone or in `db.batch`, even after `where` or `order`, or with the association joined by `or()`, `merge()` or a scope. `create`, `push`, `delete`, `destroy`, and `clear` on the association itself update it instead, so the next read still doesn’t query. - 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. - A `belongsTo` whose foreign key is `null`, or an association on an unsaved owner, reads without a query. ## Inverse associations A record loaded through its owner’s `hasMany` or `hasOne` has the owner loaded already, so reading it back sends no query: ```ts import { Author } from "./models/author"; const author = await Author.findByOrThrow({ name: "Jane" }); const [article] = await author.articles().toArray(); const sameAuthor = await article?.author(); // author itself, with no query ``` - Every record the association loads points back: from `toArray()`, `first()`, `find()`, `findBy()`, a Relation narrowed from it, and [`includes`](/preloading). - Records built or created through the association point back too, before either is saved. - A `belongsTo`’s record points back through its `hasOne`. After `await profile.author()`, the author’s `profile()` is that profile. A `hasMany` isn’t filled this way, because one record isn’t the whole collection. - The owner is the same object on both sides, so a change to it shows from either one. If the `belongsTo` is declared `autosave: true`, saving one of those records also saves the owner’s unsaved changes. - The inverse is the target’s first `belongsTo` that points at the owner’s Model through the same foreign key. None is found when either association has a `scope`, or for an association [through another](/through-associations). Name it with `inverseOf` then, as `publishedArticles` does. - `inverseOf` on a `hasMany` or `hasOne` names a `belongsTo`, and on a `belongsTo` it names a `hasOne`. On a polymorphic `belongsTo`, each Model it lists needs that `hasOne`. `inverseOf: false` turns the inverse off. If the association you name doesn’t link back through the same keys, using the Model throws `InvalidModel`. ## Scoping associations Narrow or order an association’s records with `scope`, as `Author`’s `publishedArticles` does: ```ts import { Author } from "./models/author"; const author = await Author.findByOrThrow({ name: "Jane" }); const published = await author.publishedArticles().toArray(); // only the published ones ``` - The scope applies to reads and preloads alike, and records created through the association take its equality values. - `q` is the target’s Relation, with its attributes and scopes. The target’s [default scope](/scopes#narrowing-every-query) applies too. - 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. ## Associating a Model with itself Point a Model’s association at its own class, with its own foreign key, as `Category` does: ```ts import { Category } from "./models/category"; const [top] = await Category.top().toArray(); const children = await top?.children().toArray(); // in name order, by the scope const parent = await children?.[0]?.parent(); // top itself ``` TypeScript can’t infer an association whose scope uses its own Model’s scopes, such as `children` ordered by `alphabetical()`, so write the field’s type out: `HasMany`. ## Destroying dependent records Set what destroying the owner does to its records with `dependent`: ```ts import { Author } from "./models/author"; const author = await Author.findByOrThrow({ name: "Jane" }); await author.destroy(); // its articles, their comments, and its profile go too, in one batch ``` | Strategy | What happens | | -------------------------- | --------------------------------------------------------------------------------------- | | `"destroy"` | Each record is destroyed with its own callbacks and dependents | | `"deleteAll"` / `"delete"` | The records are deleted in one statement, without callbacks (`"delete"` for a `hasOne`) | | `"nullify"` | Their foreign keys are set to `NULL` | | `"restrictWithException"` | The destroy throws `DeleteRestriction` while there are records | | `"restrictWithError"` | The destroy returns `false`, with an error on the owner’s `base` | - Everything a destroy does on the owner’s database, its DELETE included, is written in one atomic batch. Records on [another database](/several-databases#associating-models-on-different-databases) are written there separately. - Strategies run after the owner’s `beforeDestroy` callbacks, so an `abort()` leaves the records alone. - 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`. ## Writing many rows `insert`, `updateAll`, and `deleteAll` work through a `hasMany`, scoped to the owner’s records: ```ts import { Article } from "./models/article"; const article = await Article.findByOrThrow({ title: "On Nothing" }); await article.comments().deleteAll(); // one DELETE for the article's comments ``` - In a batch, pass the association to the write: `b.deleteAll(article.comments())`. - `upsert` and `upsertAll` through a `hasMany` only update the owner’s records. When a row clashes with another owner’s record, that record stays as it is. The row isn’t written, counted, or returned. To find out whether a row was skipped, compare `rowsAffected` with the number of rows you gave. - `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). ## Not built yet These features aren’t in Active Record yet. The code shows the shape they’re likely to take. - **Associations through another across databases** ([#435](https://github.com/forestfuture/active-record/issues/435)): an association whose hops are on different databases, read with a query per database. > **Compared with Rails** > > Rails requires a `belongs_to` record by default too, and `optional: true` works the same. As in Rails 7.1, an unchanged foreign key isn’t checked. There’s no setting to turn the check off for every association, like Rails’ `belongs_to_required_by_default`. > > `await user.profile.set(profile)` is Rails’ `user.profile = profile`. Rails removes the old record as soon as you build a new one, so a build that’s never saved still loses it. Here, `build` waits for the owner’s save. > > Rails declares `belongs_to :likeable, polymorphic: true` without a list, and finds the class from the stored name. Here you list the Models, so `await like.likeable()` is typed `Photo | Video | null`. Records built through `video.likes()` point back at the video without a query, which Rails doesn’t do for a polymorphic association. > **Beyond Rails** > > After `author.articles().where({ title: "Untitled" }).deleteAll()`, `author.articles()` no longer holds the untitled articles. In Rails it still does, until you reload: only a write on the association itself resets what it has loaded. In Active Record any write built from `author.articles()` clears it, at the cost of one query on the next read. > > Rails finds an inverse by its name, and finds none when you pass `foreign_key:` or name the `belongs_to` otherwise. Active Record finds the inverse by its foreign key, so it finds `writer = belongsTo(Author, { foreignKey: "authorId" })` too, and a polymorphic `belongsTo`’s `hasOne` without `inverseOf`. > > In Rails, `upsert_all` through an association writes the owner’s key into a clashing row. So `current_user.posts.upsert_all(rows)`, given an id from a request, moves another user’s post to the current user. Here that row is skipped, as `onDuplicate: "skip"` skips a duplicate. --- # Attribute types Source: https://active-record.forestfuture.dev/attribute-types ## At a glance | Type | JavaScript | D1 column | Postgres column | | ---------- | -------------- | -------------------------------------------- | ------------------- | | `string` | `string` | `TEXT` | `TEXT`, `UUID` | | `integer` | `number` | `INTEGER` | `INTEGER`, `BIGINT` | | `real` | `number` | `REAL` | `DOUBLE PRECISION` | | `decimal` | `string` | `NUMERIC`, `DECIMAL` | `NUMERIC` | | `boolean` | `boolean` | `BOOLEAN`, stored as `0` or `1` | `BOOLEAN` | | `datetime` | `Date` | `DATETIME`, as ISO-8601 text, or a Unix time | `TIMESTAMPTZ` | | `date` | `string` | `DATE`, as text | `DATE` | | `time` | `string` | `TIME`, as text | `TIME` | | `json` | any JSON value | `JSON`, as JSON text | `JSONB` | | `binary` | `Uint8Array` | `BLOB` | `BYTEA` | An attribute can be `null` unless its column is `NOT NULL`, and its TypeScript type includes `| null` to match. ## The Model The examples use this Model, whose attributes come from its table through the schema `active-record schema` generates: ```ts product.ts import { ApplicationRecord } from "./application-record"; export class Product extends ApplicationRecord {} ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: d6a91373e2cc import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** products — last changed by 0001_create_products.sql */ export const products = { id: { type: "string", null: false, generateId: true }, name: { type: "string", null: false }, price: { type: "decimal", null: false, precision: 10, scale: 2 }, weightKg: "real", stock: { type: "integer", null: false }, inStock: { type: "boolean", null: false }, launchesOn: "date", opensAt: "time", details: "json", photo: "binary", createdAt: { type: "datetime", null: false }, updatedAt: { type: "datetime", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { products: { attributes: products, primaryKey: "id" }, }, models: { Product: "products" }, }); declare module "../models/product" { interface Product extends TableAttributes {} } ``` ```sql D1 CREATE TABLE products ( id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, price NUMERIC(10, 2) NOT NULL, weight_kg REAL, stock INTEGER NOT NULL, in_stock BOOLEAN NOT NULL, launches_on DATE, opens_at TIME, details JSON, photo BLOB, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL ); ``` ```sql Postgres CREATE TABLE products ( id UUID PRIMARY KEY, name TEXT NOT NULL, price NUMERIC(10, 2) NOT NULL, weight_kg DOUBLE PRECISION, stock INTEGER NOT NULL, in_stock BOOLEAN NOT NULL, launches_on DATE, opens_at TIME, details JSONB, photo BYTEA, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL ); ``` ## Assigning values Assign each attribute its type’s JavaScript value: ```ts import { Product } from "./models/product"; const lamp = Product.build({ name: "Lamp", price: "12.50", weightKg: 1.2, stock: 3, inStock: true, launchesOn: "2026-01-02", opensAt: "09:30", details: { colors: ["red", "blue"] }, photo: new Uint8Array([1, 2, 3]), }); console.log(lamp.price); // "12.5" console.log(lamp.opensAt); // "09:30:00" console.log(lamp.createdAt); // null until it's saved ``` - A `datetime` read from text with no time zone, such as SQLite’s `DEFAULT CURRENT_TIMESTAMP` writes, is UTC in any time zone. - 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. - For a value none of these hold, such as money, define a [custom type](/custom-types). :::note On D1, a `JSON` column generates a `json` attribute. A `TEXT` column, as [D1 recommends](https://developers.cloudflare.com/d1/sql-api/query-json/#types), needs an [override](/models#overriding-attributes): `details: "json"`. Add `CHECK (json_valid(details))` to have D1 reject invalid JSON. 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). ::: ## Storing bytes Read a file’s bytes before you assign them to a `binary` attribute, since a file from a form is read asynchronously: ```ts import { Product } from "./models/product"; export async function addPhoto(form: FormData) { const file = form.get("photo") as File; const photo = new Uint8Array(await file.arrayBuffer()); // read before assigning return Product.create({ name: file.name, price: "0", stock: 0, inStock: false, photo }); } ``` - It reads back as a `Uint8Array`, and prints as `<3 bytes of binary data>`, so logs never hold the bytes. - A D1 row holds at most 2 MB. Keep larger files in [R2](https://developers.cloudflare.com/r2/), and store their keys. :::tip `insertAll` and `upsertAll` take any number of rows of bytes. On D1, rows that add up to more than its 2 MB limit on one value go as several statements in one batch, which writes all of them or none. D1 counts the batch as one query. ::: ## Storing exact numbers, days, and times A `decimal` holds an exact number, such as a price, as text, and a `date` and a `time` hold a day and a time of day: - A decimal takes text, a number, or a `bigint`, and reads in one form, without trailing zeros or an exponent, so `"12.50"` and `"12.5"` are the same value. A number keeps 16 significant digits, so `0.1 + 0.2` is `"0.3"`. - Conditions, comparisons, and `order` compare decimals as numbers, and so do the `numericality` and `comparison` validations. - A column’s `scale`, from `NUMERIC(10, 2)`, rounds a decimal to that many places, half away from zero, as Postgres rounds, so a record holds what the database stores. Its `precision` limits its digits in all. A value with too many digits before the point throws `TypeError`, and a `precision` without a `scale` rounds to whole numbers. - A `date` holds a day, such as `"2026-01-02"`, and a `time` a time of day, such as `"09:30:00"`. Neither has a time zone. A time always has its seconds, and a fraction only when it has one: `"09:30:15.25"`. The end of the day is `"24:00:00"`. - Days and times compare and sort in order. A `Date` can’t be assigned to either, since its day and time depend on the time zone. For today’s date in UTC, assign `new Date().toISOString().slice(0, 10)`. :::warning[D1 rounds long decimals] D1 keeps about 15 significant digits of a decimal, and rounds the rest. Postgres keeps every digit. ::: :::tip To do arithmetic with decimals, wrap a decimal library in a [custom type](/custom-types) stored as `"decimal"`. ::: ## Casting assigned values 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: ```ts import { Product } from "./models/product"; const lamp = Product.build({ name: "Lamp", price: "1.555", stock: 0, inStock: false }); console.log(lamp.price); // "1.56", rounded to the column's scale of 2 // Values from JSON, a form or a query string often arrive as text: lamp.assign(JSON.parse('{ "stock": " 42 ", "inStock": "true" }')); console.log(lamp.stock); // 42 console.log(lamp.inStock); // true, not the string "true" ``` Values are cast wherever they’re assigned: `build`, `create`, `assign`, `update`, a property setter, a default, [`permit`](/untrusted-input#permitting-fields), and the values given to `insert`, `insertAll`, `upsert`, `upsertAll`, and `updateAll`. `null` is always NULL. Only unambiguous values are accepted: | Type | Accepts | | ---------- | -------------------------------------------------------------------------------------------------------------------------------------- | | `boolean` | `true`, `false`, `1`, `0`, `"1"`, `"0"`, and `"true"`, `"false"`, `"on"`, `"off"` in any case | | `integer` | a safe integer, or a string that’s wholly one, with an optional sign and spaces around it: `"42"`, `" -7 "`, `"+3"` | | `real` | a finite number, or a string that’s wholly one, with an optional sign, point, and exponent: `"1.5"`, `".5"`, `"5."`, `"-2e3"` | | `decimal` | a finite number, a `bigint`, or a string that’s wholly a decimal number, as for a `real`: `"12.50"`, `"-2e3"` | | `string` | a string | | `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"` | | `date` | a day that exists, as `"YYYY-MM-DD"`: `"2026-01-02"` | | `time` | a time of day, with or without seconds and up to six digits of a fraction: `"09:30"`, `"09:30:15.25"` | | `json` | any value JSON can write | | `binary` | a `Uint8Array`, or an `ArrayBuffer` | ## Refusing other values Anything else throws `TypeError` naming the Model and the attribute, and the attribute keeps its value: ```ts import { Product } from "./models/product"; const lamp = Product.build({ name: "Lamp", price: "1", stock: 0, inStock: false }); lamp.assign(JSON.parse('{ "inStock": "no" }')); // TypeError: Product: "no" isn't a boolean for "inStock" ``` The error shows at most 60 characters of the value, and none of a [filtered attribute](/serialization#filtering-attributes)’s. Among the values refused: - `""` for every type but `string`. - `1.7`, `"12abc"`, `"1e3"`, and integers past `Number.MAX_SAFE_INTEGER`, for an `integer`. - `NaN` and `Infinity`. - A number, boolean, or `Date` for a `string`. - 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. - For a `decimal`: text with anything but a number in it, a number too large or too small for a JavaScript `number`, such as `"1e400"` or `"1e-400"`, and one with more digits after its point than Postgres holds. - For a `date` or a `time`: a `Date`, a time zone, a day or time that doesn’t exist (`"2026-02-30"`, `"24:00:01"`), other formats (`"2026-1-2"`, `"9:30"`), and numbers. - For a `json`: a value JSON can’t write, such as a `BigInt`, an object that refers to itself, a function, or a symbol. - For a `binary`: text, an array of numbers, or another typed array. :::note 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. ::: ## Reading stored cells 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: - For a `boolean`: anything but `0` and `1`. - For an `integer`: text, a fraction, or a number outside the safe integer range. - For a `real`: anything but a finite number. - For a `string`: anything but text. - 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`. - For a `datetime` with a `storage`: anything but a number, or one past what a `Date` can hold. - For a `decimal`: anything but a number or a decimal’s text. - For a `date`: anything but a day’s text. A date and time, such as `"2026-01-02T00:00:00.000Z"`, fails too; see [Reading `DATE` columns](/upgrading#reading-date-columns). - For a `time`: anything but a time of day’s text. - For a `json`: text that isn’t JSON. - For a `binary`: anything but bytes. See [Fixing cells of the wrong type](/adopt-a-database#fixing-cells-of-the-wrong-type). ## Casting conditions and keys Conditions are cast the same way, so `where({ stock: "42" })` finds 42. A condition value that can’t be cast matches nothing, so `find("abc")` on an integer key throws `RecordNotFound`. - 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({ name: 7 }).build()` has the name `"7"`. - 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. - 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. > **Compared with Rails** > > Rails holds a `decimal` as a `BigDecimal`, a `date` as a `Date`, and a `time` as a `Time` on 1 January 2000. Here each one is text, which reads the same from every database and goes into JSON as it is. > **Beyond Rails** > > Rails casts leniently: `"12abc"` becomes `12`, `1.7` becomes `1`, any other text is `true`, and `""` is `nil`. Active Record refuses each, so `inStock=no` from a form can’t save `true`, and an empty field can’t silently become `null`. --- # Autosaving Source: https://active-record.forestfuture.dev/autosaving ## At a glance | To | Write | | ------------------------------------------------ | --------------------------------------------------------------- | | create a record with its owner’s key | `article.comments().create({ body: "…" })` | | build records to save with their owner | `author.articles().build({ … })`, `author.profile.build({ … })` | | save the owner and every record built through it | `author.saveOrThrow()` | | save the loaded records that changed too | `hasMany(Article, { autosave: true })` | | destroy a record when its owner saves | `article.markForDestruction()` | ## The Models The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates: ```ts author.ts import { hasMany, hasOne } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Article } from "./article"; import { Profile } from "./profile"; export class Author extends ApplicationRecord { articles = hasMany(Article, { autosave: true }); // saves changed articles with the author profile = hasOne(Profile); } ``` ```ts article.ts import { belongsTo, hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Author } from "./author"; import { Comment } from "./comment"; export class Article extends ApplicationRecord { author = belongsTo(Author); comments = hasMany(Comment, { dependent: "destroy" }); // destroyed with their article } ``` ```ts comment.ts import { belongsTo } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Article } from "./article"; export class Comment extends ApplicationRecord { article = belongsTo(Article); } ``` ```ts profile.ts import { belongsTo } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Author } from "./author"; export class Profile extends ApplicationRecord { author = belongsTo(Author); } ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: d6e921e3fa3b import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** articles — last changed by 0001_create_tables.sql */ export const articles = { id: { type: "string", null: false, generateId: true }, authorId: { type: "string", null: false }, title: { type: "string", null: false }, } as const; /** authors — last changed by 0001_create_tables.sql */ export const authors = { id: { type: "string", null: false, generateId: true }, name: { type: "string", null: false }, } as const; /** comments — last changed by 0001_create_tables.sql */ export const comments = { id: { type: "string", null: false, generateId: true }, articleId: { type: "string", null: false }, body: { type: "string", null: false }, } as const; /** profiles — last changed by 0001_create_tables.sql */ export const profiles = { id: { type: "string", null: false, generateId: true }, authorId: { type: "string", null: false }, bio: "string", } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { articles: { attributes: articles, primaryKey: "id" }, authors: { attributes: authors, primaryKey: "id" }, comments: { attributes: comments, primaryKey: "id" }, profiles: { attributes: profiles, primaryKey: "id" }, }, models: { Article: "articles", Author: "authors", Comment: "comments", Profile: "profiles" }, }); declare module "../models/article" { interface Article extends TableAttributes {} } declare module "../models/author" { interface Author extends TableAttributes {} } declare module "../models/comment" { interface Comment extends TableAttributes {} } declare module "../models/profile" { interface Profile extends TableAttributes {} } ``` ```sql D1 CREATE TABLE authors ( id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL ); CREATE TABLE profiles ( id TEXT PRIMARY KEY NOT NULL, author_id TEXT NOT NULL REFERENCES authors (id), bio TEXT ); CREATE TABLE articles ( id TEXT PRIMARY KEY NOT NULL, author_id TEXT NOT NULL REFERENCES authors (id), title TEXT NOT NULL ); CREATE TABLE comments ( id TEXT PRIMARY KEY NOT NULL, article_id TEXT NOT NULL REFERENCES articles (id), body TEXT NOT NULL ); ``` ```sql Postgres CREATE TABLE authors ( id UUID PRIMARY KEY, name TEXT NOT NULL ); CREATE TABLE profiles ( id UUID PRIMARY KEY, author_id UUID NOT NULL REFERENCES authors (id), bio TEXT ); CREATE TABLE articles ( id UUID PRIMARY KEY, author_id UUID NOT NULL REFERENCES authors (id), title TEXT NOT NULL ); CREATE TABLE comments ( id UUID PRIMARY KEY, article_id UUID NOT NULL REFERENCES articles (id), body TEXT NOT NULL ); ``` ## Creating related records Create a record through a `hasMany`, and it gets the owner’s key: ```ts import { Article } from "./models/article"; const article = await Article.findByOrThrow({ title: "On Nothing" }); const comment = await article.comments().create({ body: "Lovely." }); // articleId filled in ``` ## Saving a graph Build records through an association, then save the owner, and they’re saved with it: ```ts import { Author } from "./models/author"; const author = Author.build({ name: "Sam" }); author.articles().build({ title: "Getting started" }); author.articles().build({ title: "Going further" }); author.profile.build({ bio: "Writer" }); await author.saveOrThrow(); // the author, both articles, and the profile, in one batch ``` - The built records are validated with the owner. An invalid article makes the author invalid (“Articles is invalid”), with its own errors on the article. To validate the records an association loaded too, use [`validatesAssociated`](/validations#validating-associated-records). - Each built article’s `author` is the owner, without a query, even before either is saved. - When the owner’s key is generated in code, as here, everything is written in one atomic batch. Records on [another database](/several-databases#associating-models-on-different-databases) are written there separately. :::warning[Keys D1 generates] 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. ::: ## Saving changed records Declare an association with `autosave: true`, as `Author`’s `articles` does, to save the changes to its loaded records with their owner: ```ts import { Author } from "./models/author"; const author = await Author.findByOrThrow({ name: "Jane" }); const articles = await author.articles().toArray(); for (const article of articles) article.title = article.title.toUpperCase(); await author.saveOrThrow(); // every article that changed, in one batch ``` - By default, only new records are saved with their owner. - Saving the author saves each article that changed, in the same atomic batch. Unchanged articles aren’t validated or written. - Only the records the association holds count: those it loaded, and those built through it. A record you found with a query of its own isn’t saved. - The changed records are validated with the owner. An invalid one’s errors are copied to the owner under the association’s name: an article with a blank title gives the author an `articles.title` error, “Articles title can’t be blank”. - `autosave: true` works on a `hasOne` and a `belongsTo` too. A `belongsTo`’s record is saved before its owner. ## Removing records on save Mark a record with `markForDestruction()` to destroy it when its owner is saved: ```ts import { Author } from "./models/author"; const author = await Author.findByOrThrow({ name: "Jane" }); const articles = await author.articles().toArray(); for (const article of articles) { if (article.title.startsWith("Draft")) article.markForDestruction(); } await author.saveOrThrow(); // destroys the drafts, with their comments ``` - Marking writes nothing, and the marked articles stay in `author.articles()` until the author is saved. Then each is destroyed with its callbacks and `dependent` strategies, in the same batch as the author, and leaves the association. Changed articles are saved after the destroys. - `isMarkedForDestruction()` reads the mark, and `reload()` clears it. A marked record that was never saved is dropped from the association, and nothing is written for it. - Through a `belongsTo`, the owner’s foreign key is set to `null`, and the owner is written before its record is destroyed. - If a marked record refuses to be destroyed, because its `beforeDestroy` aborts or a `restrictWithError` strategy stops it, nothing is written. `save()` returns `false`, and `saveOrThrow()` throws `RecordNotDestroyed`. The marked record holds the reason, in `abortReason` or `errors`. :::note A mark only counts through an association declared `autosave: true`. ::: ## Not built yet These features aren’t in Active Record yet. The code shows the shape they’re likely to take. - **Autosaving through an association through another** ([#450](https://github.com/forestfuture/active-record/issues/450)): `articles = hasMany(Article, { through: "taggings", autosave: true })`, which saves the tag’s changed articles with it. - **Never autosaving** ([#378](https://github.com/forestfuture/active-record/issues/378)): `articles = hasMany(Article, { autosave: false })`, which never saves the association’s records with the owner, not even new ones. - **Numbered autosave errors** ([#379](https://github.com/forestfuture/active-record/issues/379)): `hasMany(Article, { autosave: true, indexErrors: true })`, which names a copied error by the record’s position, `articles[1].title`. > **Compared with Rails** > > `autosave: true`, `markForDestruction`, and the copied errors work as in Rails. Rails destroys a marked `belongs_to` record before it saves the owner. Here the owner is written first, so a foreign key constraint doesn’t refuse the delete. When a marked record refuses to be destroyed, Rails raises from `save` for a `has_many`, and saves the owner anyway for a `has_one` or `belongs_to`. Here the save is refused the same way for every association. --- # Batch iteration Source: https://active-record.forestfuture.dev/batch-iteration :::note Nothing is atomic across batches: each batch is its own query, and its own write. To write several statements all at once or not at all, use a [batch](/batches). ::: ## At a glance | To | Write | | ------------------------------ | ------------------------------------------------------------------------ | | visit each record | `for await (const post of Post.findEach())` | | visit each batch as an array | `for await (const posts of Post.findInBatches())` | | write a batch at a time | `for await (const batch of drafts.inBatches()) await batch.updateAll(…)` | | bound the keys | `findEach({ start: 1, finish: 100 })` | | walk from the largest key down | `findInBatches({ order: "desc" })` | | Prop | Type | Default | Description | | - | - | - | - | | `batchSize?` | `number` | `1000` | Records in each batch: a whole number from 1. | | `start?` | `primary key` | - | The first key to visit, included. The largest, with order: desc. | | `finish?` | `primary key` | - | The last key to visit, included. The smallest, with order: desc. | | `order?` | `"asc" \| "desc"` | `"asc"` | Which way to walk the primary key. | ## The Model The examples use this Model, whose attributes come from its table through the schema `active-record schema` generates: ```ts post.ts import { ApplicationRecord } from "./application-record"; export class Post extends ApplicationRecord {} ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: ad18f958558e import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** posts — last changed by 0001_create_posts.sql */ export const posts = { id: { type: "integer", null: false }, title: { type: "string", null: false }, publishedAt: "datetime", } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { posts: { attributes: posts, primaryKey: "id" }, }, models: { Post: "posts" }, }); declare module "../models/post" { interface Post extends TableAttributes {} } ``` ```sql D1 CREATE TABLE posts ( id INTEGER PRIMARY KEY, title TEXT NOT NULL, published_at DATETIME ); ``` ```sql Postgres CREATE TABLE posts ( id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, title TEXT NOT NULL, published_at TIMESTAMPTZ ); ``` ## Visiting each record `findEach` loads a Relation’s records a batch at a time, and yields them one by one: ```ts import { Post } from "./models/post"; for await (const post of Post.where({ publishedAt: null }).findEach()) { console.log(post.title); // one post at a time, loaded 1,000 at a time } ``` Batches go in primary-key order, 1,000 records each by default. Each batch is one query, and starts after the last batch’s key, so a deep batch costs no more than the first. ## Visiting each batch `findInBatches` yields each batch as an array: ```ts import { Post } from "./models/post"; for await (const posts of Post.findInBatches({ batchSize: 2 })) { console.log(posts.length); // up to 2 posts at a time } ``` `includes()` preloads each batch’s associations. Breaking out of the loop sends no more queries. ## Writing a batch at a time `inBatches` yields a Relation of each batch’s records, for `updateAll`, `deleteAll`, and `destroyAll`: ```ts import { Post } from "./models/post"; const drafts = Post.where({ publishedAt: null }); for await (const batch of drafts.inBatches({ batchSize: 500 })) { await batch.updateAll({ publishedAt: new Date() }); // one write per 500 drafts } ``` - One query reads each batch’s keys, and the write you run is another. - A batch’s Relation keeps your conditions, so a row that stopped matching since the keys were read isn’t written. - Each batch is its own write. If one fails, the batches before it stay written. ## Choosing the batches Every method takes the same options: ```ts import { Post } from "./models/post"; const firstTwo = Post.findEach({ start: 1, finish: 2 }); // keys 1 and 2, both included const largestKeysFirst = Post.findInBatches({ order: "desc", batchSize: 100 }); ``` - `batchSize` sets the records in each batch: a whole number from 1, or `TypeError`. - `start` and `finish` bound the primary key, both included. With `order: "desc"`, `start` is the largest key and `finish` the smallest. - A `limit()` caps the records across every batch. - Batches follow the primary key, so a Relation with its own order throws `IncompatibleRelation`, a default scope’s order included. Remove it with `reorder()` first: `Post.reorder().findEach()`. - An `offset()` throws too, so bound the walk with `start` instead. :::note A row added while you iterate is visited only if its key sorts after the batch you’re on. With random keys, such as UUIDs, whether a new row is visited comes down to chance. ::: ## Staying within D1’s query limit On D1, one Worker invocation can send up to 1,000 queries, or 50 on the Free plan: - `findEach` and `findInBatches` send one per batch. - `inBatches` sends one for the keys, and one for an `updateAll` or `deleteAll`. - A `destroyAll` loads the batch’s records and reads each record’s `"destroy"` and restricted associations, each with a query of its own. It then sends its deletes as one D1 batch, which counts as one query. A larger `batchSize` sends fewer queries, up to D1’s 50 MB limit on a query’s result. For a table larger than that, split the work across invocations, each with its own `start` and `finish`, such as one Queue message per range. > **Compared with Rails** > > `findEach`, `findInBatches`, and `inBatches` are `find_each`, `find_in_batches`, and `in_batches`, as async iterators rather than blocks. `inBatches` takes `batchSize`, not `of:`. Rails ignores a Relation’s order with a warning, and applies an offset to every batch. Here both throw `IncompatibleRelation`. --- # Bulk writes and batches Source: https://active-record.forestfuture.dev/batches ## At a glance | To | Write | | ------------------------------------------- | -------------------------------------------------------- | | update or delete every row a Relation finds | `updateAll({ … })`, `deleteAll()`, `deleteBy({ … })` | | insert rows without loading records | `insert({ … })`, `insertAll([…])` | | insert, or update a row that clashes | `upsert({ … }, { uniqueBy: "email" })`, `upsertAll([…])` | | get attributes back from an insert | `{ returning: ["id", "body"] }` | | write several statements atomically | `batch((b) => [b.insert(…), b.updateAll(…)])` | | save or destroy records in that batch | `b.save(record)`, `b.destroy(record)` | ## The Models The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates: ```ts author.ts import { hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Article } from "./article"; export class Author extends ApplicationRecord { articles = hasMany(Article, { dependent: "destroy" }); } ``` ```ts article.ts import { belongsTo, hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Author } from "./author"; import { Comment } from "./comment"; export class Article extends ApplicationRecord { author = belongsTo(Author); comments = hasMany(Comment, { dependent: "deleteAll" }); } ``` ```ts comment.ts import { belongsTo } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Article } from "./article"; export class Comment extends ApplicationRecord { article = belongsTo(Article); } ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: 01a9c70ab9ef import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** articles — last changed by 0001_create_tables.sql */ export const articles = { id: { type: "string", null: false, generateId: true }, authorId: { type: "string", null: false }, title: { type: "string", null: false }, } as const; /** authors — last changed by 0001_create_tables.sql */ export const authors = { id: { type: "string", null: false, generateId: true }, name: { type: "string", null: false }, email: { type: "string", null: false }, } as const; /** comments — last changed by 0001_create_tables.sql */ export const comments = { id: { type: "string", null: false, generateId: true }, articleId: { type: "string", null: false }, body: { type: "string", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { articles: { attributes: articles, primaryKey: "id" }, authors: { attributes: authors, primaryKey: "id" }, comments: { attributes: comments, primaryKey: "id" }, }, models: { Article: "articles", Author: "authors", Comment: "comments" }, }); declare module "../models/article" { interface Article extends TableAttributes {} } declare module "../models/author" { interface Author extends TableAttributes {} } declare module "../models/comment" { interface Comment extends TableAttributes {} } ``` ```sql D1 CREATE TABLE authors ( id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, email TEXT NOT NULL ); CREATE UNIQUE INDEX index_authors_on_email ON authors (email); CREATE TABLE articles ( id TEXT PRIMARY KEY NOT NULL, author_id TEXT NOT NULL REFERENCES authors (id), title TEXT NOT NULL ); CREATE TABLE comments ( id TEXT PRIMARY KEY NOT NULL, article_id TEXT NOT NULL REFERENCES articles (id), body TEXT NOT NULL ); ``` ```sql Postgres CREATE TABLE authors ( id UUID PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL ); CREATE UNIQUE INDEX index_authors_on_email ON authors (email); CREATE TABLE articles ( id UUID PRIMARY KEY, author_id UUID NOT NULL REFERENCES authors (id), title TEXT NOT NULL ); CREATE TABLE comments ( id UUID PRIMARY KEY, article_id UUID NOT NULL REFERENCES articles (id), body TEXT NOT NULL ); ``` ## Writing many rows Call a bulk write on a Relation. It runs straight away, without validations or callbacks: ```ts import { column, sql } from "@forestfuture/active-record"; import { Article } from "./models/article"; import { Comment } from "./models/comment"; const article = await Article.findByOrThrow({ title: "Getting started" }); const deleted = await Comment.where({ articleId: article.id }).deleteAll(); // how many await Article.where({ id: article.id }).updateAll({ title: "Edited" }); await Article.where({ id: article.id }).updateAll( sql`${column("title")} = upper(${column("title")})`, ); const { rowsAffected, rows } = await Comment.insert({ articleId: article.id, body: "First!" }); console.log(deleted, rowsAffected, rows[0]?.id); // 1 1, and the new comment's key ``` - **`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. - **`deleteAll()`** resolves to the number of rows deleted. On `none()`, both send nothing and resolve to `0`. - **`deleteBy(conditions)`** is `where(conditions).deleteAll()`. **`Comment.delete(id)`** deletes by primary key, and takes an array of keys too. Both resolve to the number of rows deleted. - **`insert(attrs)`** writes one row. It resolves to `{ rowsAffected, rows }`, and `rows` holds the new row’s primary key. Declared defaults and timestamps fill what isn’t given. A Relation’s equality conditions are written over what is given. So `Article.where({ authorId: jane.id }).insert({ title: "Hi", authorId: sam.id })` writes Jane’s key. :::note To run each record’s callbacks, destroy the records with [`destroyAll`](/persistence#destroying-many-records) instead. ::: ### Inserting many rows Insert many rows at once with `insertAll`: ```ts import { Article } from "./models/article"; import { Author } from "./models/author"; import { Comment } from "./models/comment"; const article = await Article.findByOrThrow({ title: "Getting started" }); await Comment.insertAll([ { articleId: article.id, body: "One" }, { articleId: article.id, body: "Two" }, ]); await Author.upsert({ name: "Jane Doe", email: "jane@example.com" }, { uniqueBy: "email" }); // renames Jane await Author.insert({ name: "Jane", email: "jane@example.com" }, { onDuplicate: "skip" }); // writes nothing ``` - **`insertAll(rows)`** inserts every row, however many. Every row must have the same attributes. A duplicate throws and writes nothing. - **`{ onDuplicate: "skip" }`** skips rows that clash with a unique index. - **`upsert(attrs)`** and **`upsertAll(rows)`** update a row that clashes with the primary key, or with the unique index named by `uniqueBy`. The attributes you give are updated. So are the values a Relation adds to each row, from its equality conditions, its default scope, and `createWith`. Defaults filled in for you aren’t updated. `updatedAt` is set. - **Through a Relation**, `insertAll`, `upsert`, and `upsertAll` write its equality conditions over each row’s values, as `insert` does. - **Through a `hasMany`**, an upsert only updates the owner’s records. A row that clashes with another owner’s record isn’t written, counted, or returned. See [Writing many rows](/associations#writing-many-rows). ### Returning attributes Inserts and upserts return the primary key of each row they write. Name other attributes with `returning`: ```ts import { Article } from "./models/article"; import { Comment } from "./models/comment"; const article = await Article.findByOrThrow({ title: "Getting started" }); const { rows } = await Comment.insertAll( [ { articleId: article.id, body: "One" }, { articleId: article.id, body: "Two" }, ], { returning: ["id", "body"] }, ); for (const { id, body } of rows) console.log(id, body); await Comment.insert({ articleId: article.id, body: "Three" }, { returning: false }); ``` - **`rows`** has one entry for each row written, typed from the attributes you name. A row skipped as a duplicate isn’t in it. - **`returning: false`** returns no rows. - **Order:** the rows come back in no set order. > **Compared with Rails** > > These are Rails’ `insert_all`, `upsert_all`, `update_all`, and `delete_all`, with two differences. Declared defaults fill what an insert isn’t given, since on D1 defaults are where keys are generated. And skipping duplicates is something you opt in to, so an insert’s duplicate is never silently lost. The `returning` option works as Rails’ does. ## Batching writes Prepare several writes in `batch`’s callback to write them atomically: ```ts import { batch } from "@forestfuture/active-record"; import { Article } from "./models/article"; import { Author } from "./models/author"; const authorId = crypto.randomUUID(); // generated in code, so the rows can point at it await batch((b) => [ b.insert(Author, { id: authorId, name: "Alex", email: "alex@example.com" }), b.insert(Article, { authorId, title: "Hello" }), b.updateAll(Article.where({ title: "Getting started" }), { authorId }), // Alex takes it over ]); ``` The callback gets `b`, with a method for each bulk write: `insert`, `insertAll`, `upsert`, `upsertAll`, `updateAll`, `updateCounters`, and `deleteAll`. Each takes what it writes to, then the same arguments as the write itself. Pass a Model to write to its table, or a Relation to write to its rows, such as `Article.where(…)` or `author.articles()`. `batch` resolves to each write’s result, in order. A bulk write gives the same `{ rowsAffected, rows }` it resolves to when it runs alone, and `rows` is empty for `updateAll` and `deleteAll`. - **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). - **Errors:** a write that can’t be prepared, such as one with an unknown attribute, rejects the batch before anything is sent. - **Databases:** `batch` writes a Model’s rows on the current database, and `db.batch` on `db`. A Relation or a record writes on the database it came from. Writes on two databases throw `IncompatibleRelation`. - **Relations in `db.batch`:** `Article.where(…)` uses the current database. Build it with `db.model(Article).where(…)` to write on `db`. :::note The callback returns its writes without awaiting anything, since the batch is sent as one: an atomic batch on D1, and one transaction on Postgres. Load what the writes need before you call `batch`. D1 can’t keep a transaction open across `await`s, so a batch is how you make writes atomic. ::: > **Compared with Rails** > > A batch reads like a `transaction do … end` block, but its callback only prepares writes. They’re sent together when it returns, so it can’t read in between. ## Batching records Add a record’s save or destroy to a batch with `b.save(record)` and `b.destroy(record)`. Its validations and callbacks still run: ```ts import { batch } from "@forestfuture/active-record"; import { Article } from "./models/article"; import { Author } from "./models/author"; import { Comment } from "./models/comment"; const article = await Article.findByOrThrow({ title: "Getting started" }); article.title = "Getting started, again"; const author = Author.build({ name: "Kim", email: "kim@example.com" }); const leaving = await Author.findByOrThrow({ email: "sam@example.com" }); const [savedArticle, savedAuthor] = await batch((b) => [ b.save(article), b.save(author), b.destroy(leaving), // with Sam's articles and their comments b.deleteAll(Comment.where({ articleId: article.id })), ]); ``` When the batch runs: 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. 2. Every write is sent as one atomic batch. If the database refuses it with a constraint error, nothing is written, every record keeps its unsaved state, and each record’s `afterRollback` runs. 3. Each record takes its saved state, then its after-callbacks run. 4. Every record’s [commit callbacks](/callbacks#running-code-after-the-commit) run, in the same order. 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. To validate a record in a [context of your own](/validations#naming-your-own-contexts), pass the context to `b.save`, such as `b.save(member, { context: "signup" })`. > **Compared with Rails** > > 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. --- # Calculations Source: https://active-record.forestfuture.dev/calculations ## At a glance | To | Write | Returns | | ------------------------------ | --------------------------------------------------------- | ------------------------------- | | add up an attribute | `sum("priceCents")` | a number, 0 with no rows | | average it | `average("priceCents")` | a number, or `null` | | find the smallest or largest | `minimum("priceCents")`, `maximum("createdAt")` | the attribute’s type, or `null` | | calculate an expression | ``average(sql`…`)`` | what the database returns | | calculate per group | `group("isAvailable").count()` | a `Map` from group to result | | keep some groups | `group("isAvailable").having(…)`, with an `sql` condition | a grouped Relation | | choose the calculation by name | `calculate("sum", "priceCents")` | as the calculation named | ## The Model The examples use this Model, whose attributes come from its table through the schema `active-record schema` generates: ```ts product.ts import { ApplicationRecord } from "./application-record"; export class Product extends ApplicationRecord {} ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: 69a8287500f9 import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** products — last changed by 0001_create_products.sql */ export const products = { id: { type: "string", null: false, generateId: true }, name: { type: "string", null: false }, priceCents: { type: "integer", null: false }, isAvailable: { type: "boolean", null: false }, createdAt: { type: "datetime", null: false }, updatedAt: { type: "datetime", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { products: { attributes: products, primaryKey: "id" }, }, models: { Product: "products" }, }); declare module "../models/product" { interface Product extends TableAttributes {} } ``` ```sql D1 CREATE TABLE products ( id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, price_cents INTEGER NOT NULL, is_available BOOLEAN NOT NULL, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL ); ``` ```sql Postgres CREATE TABLE products ( id UUID PRIMARY KEY, name TEXT NOT NULL, price_cents INTEGER NOT NULL, is_available BOOLEAN NOT NULL, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL ); ``` ## Calculating values Add up, average, or find the extremes of an attribute: ```ts import { Product } from "./models/product"; const total = await Product.where({ isAvailable: true }).sum("priceCents"); // 0 with no products const averagePrice = await Product.average("priceCents"); // a number, or null const cheapest = await Product.minimum("priceCents"); // or null const newest = await Product.maximum("createdAt"); // a Date, or null ``` - `sum` and `average` take number attributes: integers, reals, and decimals. A decimal’s sum is text, such as `"12.8"`. - `minimum` and `maximum` take any attribute you can compare. The result has the attribute’s own type, so a datetime’s is a `Date`. - NULLs are left out. With no rows, `sum` is 0 and the others are `null`. On `none()`, they answer without a query. :::warning[Exact sums on D1] D1 adds up a decimal column as floating-point numbers. A sum keeps about 15 digits, and small errors can build up over many rows. For an exact sum on D1, store the amount as whole cents in an integer column, as `priceCents` does, with a [custom type](/custom-types#defining-a-type) such as money if you like. D1 adds whole numbers exactly, and `sum` returns the custom type’s value. ::: ## Calculating over some rows A calculation covers the rows `toArray()` would return, so a `limit`, an `offset`, or `distinct()` decides which values count: ```ts import { Product } from "./models/product"; const mostExpensive = Product.order({ priceCents: "desc" }).limit(3); const topThree = await mostExpensive.sum("priceCents"); // only those three ``` ## Calculating an expression Pass an `sql` fragment to calculate an expression: ```ts import { column, sql } from "@forestfuture/active-record"; import { Product } from "./models/product"; const inDollars = sql`${column("priceCents")} / 100.0`; const averageDollars = await Product.average(inDollars); // a number, or null ``` A fragment’s `sum` and `average` are numbers. Its `minimum` and `maximum` are the values the database returns. :::note `calculate("sum", "priceCents")` runs the calculation its first argument names. Use it when the name comes from elsewhere, such as a report’s settings. ::: ## Calculating per group Group the rows by an attribute to calculate each group’s total: ```ts import { Product } from "./models/product"; const byAvailability = await Product.group("isAvailable").count(); // Map { true => 3, false => 1 } const inStock = byAvailability.get(true); // 3 const valueByAvailability = await Product.group("isAvailable").sum("priceCents"); ``` - Each calculation returns a `Map` from the group’s value to its result. `count`, `sum`, `average`, `minimum`, and `maximum` all work this way. - The keys have the attribute’s own type, so a boolean’s key is `true` or `false`, a datetime’s is a `Date`, and an enum’s is its name. Rows with a NULL value form a group with a `null` key. - The groups come in the order the database returns them, unless you order them. ## Grouping by several values Pass each attribute or expression to `group`: ```ts import { column, sql } from "@forestfuture/active-record"; import { Product } from "./models/product"; const band = sql`CASE WHEN ${column("priceCents")} >= ${10_000} THEN 'pricey' ELSE 'cheap' END`; const byBand = await Product.group("isAvailable", band).count(); // Map { [true, "cheap"] => 2, … } ``` Each key is then an array of the values, in the order you passed them. An expression’s value is whatever the database returns. :::note A `Map` finds an array or `Date` key only if it’s the same object, so `get([true, "cheap"])` finds nothing. Loop over the `Map` to read those groups. ::: ## Keeping some groups Pass a condition on the groups’ totals to `having`: ```ts import { sql } from "@forestfuture/active-record"; import { Product } from "./models/product"; const crowded = Product.group("isAvailable").having(sql`COUNT(*) > ${1}`); const crowdedCounts = await crowded.count(); // Map { true => 3 } ``` ## Ordering groups Order the groups by a grouped attribute or by a total, and a `limit` then picks groups: ```ts import { sql } from "@forestfuture/active-record"; import { Product } from "./models/product"; const largestFirst = Product.group("isAvailable").order(sql`COUNT(*) DESC`); const largest = await largestFirst.limit(1).count(); // Map { true => 3 } ``` - `where`, `limit`, `offset`, and `distinct()` work before or after `group`. After `distinct()`, `count`, `sum`, and `average` take each group’s distinct values. - You can only order by attributes you group by, or by an `sql` fragment. `group` drops an earlier order by any other attribute, such as one from a default scope. It keeps an earlier fragment, so call `reorder()` before `group` when a default scope orders by one. With a `limit` or `offset`, `group` throws instead of dropping an order, so call `reorder()` first there too. - On `none()`, each calculation returns an empty `Map` without a query. > **Compared with Rails** > > `average` always returns a number, where Rails returns a BigDecimal for integers and decimals. Rails puts a `limit` on the one row of its result, so `limit(3).sum(:price_cents)` adds up every row. Here, the limit picks the rows. Text attributes can’t be summed. > > Grouped results are a `Map`, not a Hash, so a key that’s an array or a time matches only by identity. A grouped Relation has no records, so there’s no `to_a` on it. Ordering groups by an attribute that isn’t grouped throws an error instead of reaching the database, and `group` drops such an order written before it, where Rails sends it and Postgres refuses it. --- # Callbacks Source: https://active-record.forestfuture.dev/callbacks ## At a glance | To | Write | | ------------------------------------------ | ---------------------------------------------------------- | | run code before a record is validated | `this.beforeValidation((order) => { … })` | | run code only when a record is created | `beforeCreate`, or `beforeValidation(…, { on: "create" })` | | run code on both sides of a write | `this.aroundSave(async (order, next) => { await next() })` | | send an email once a record is created | `this.afterCreateCommit(async (user) => { … })` | | run code after `touch()` | `this.afterTouch(…)` | | run code when the database refuses a write | `this.afterRollback(…)` | | fill in a new record’s defaults | `this.afterInitialize(…)` | | stop a save or destroy | `throw abort("reason")` in a before-callback | ## The Models The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates. Each registers its callbacks in its `static {}` block, and `mail.ts` and `cache.ts` stand in for the app’s own services: ```ts order.ts import { abort } from "@forestfuture/active-record"; import { sendShippedEmail } from "../mail"; import { ApplicationRecord } from "./application-record"; export class Order extends ApplicationRecord { static { this.beforeValidation((order) => { order.email = order.email.trim().toLowerCase(); }); this.beforeValidation( (order) => { order.placedAt = new Date(); }, { on: "create" }, ); this.beforeSave((order) => { if (order.isSuspended) throw abort("Orders can't change while suspended"); }); this.aroundSave(async (order, next) => { const started = Date.now(); await next(); console.log(`Saved order ${order.number} in ${Date.now() - started} ms`); }); this.afterSave(async (order) => { if (order.hasSavedChangeTo("status", { to: "shipped" })) { await sendShippedEmail(order.email); } }); this.afterRollback((order) => { console.log(`Order ${order.number} wasn't saved`); }); } } ``` ```ts user.ts import { sendWelcomeEmail } from "../mail"; import { ApplicationRecord } from "./application-record"; export class User extends ApplicationRecord { static { this.afterCreateCommit(async (user) => { await sendWelcomeEmail(user.email); }); } } ``` ```ts article.ts import { purgeCachedPage } from "../cache"; import { ApplicationRecord } from "./application-record"; export class Article extends ApplicationRecord { static { this.afterTouch(async (article) => { await purgeCachedPage(`/articles/${article.id}`); }); } } ``` ```ts invoice.ts import { ApplicationRecord } from "./application-record"; export class Invoice extends ApplicationRecord { static { this.afterInitialize((invoice) => { if (invoice.isNewRecord()) invoice.currency ??= invoice.country === "GB" ? "GBP" : "USD"; }); this.afterFind((invoice) => { // A record loaded with select() may leave totalCents out. if (invoice.hasAttribute("totalCents") && invoice.totalCents > 1_000_000) { console.log(`Large invoice ${invoice.id} loaded`); } }); } } ``` ```ts mail.ts // The app's emails. Here they're logged, as a test's mailer would. export async function sendWelcomeEmail(email: string): Promise { console.log(`Welcome email to ${email}`); } export async function sendShippedEmail(email: string): Promise { console.log(`Shipped email to ${email}`); } ``` ```ts cache.ts // The app's page cache. Here a purge is logged. export async function purgeCachedPage(path: string): Promise { console.log(`Purged ${path}`); } ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: 141262a87f5f import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** articles — last changed by 0001_create_tables.sql */ export const articles = { id: { type: "string", null: false, generateId: true }, title: { type: "string", null: false }, updatedAt: "datetime", } as const; /** invoices — last changed by 0001_create_tables.sql */ export const invoices = { id: { type: "string", null: false, generateId: true }, country: { type: "string", null: false }, currency: "string", totalCents: { type: "integer", null: false, default: () => 0 }, } as const; /** orders — last changed by 0001_create_tables.sql */ export const orders = { id: { type: "string", null: false, generateId: true }, number: { type: "string", null: false }, status: { type: "string", null: false, default: () => "pending" }, email: { type: "string", null: false }, totalCents: { type: "integer", null: false }, isSuspended: { type: "boolean", null: false, default: () => false }, placedAt: "datetime", } as const; /** users — last changed by 0001_create_tables.sql */ export const users = { id: { type: "string", null: false, generateId: true }, email: { type: "string", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { articles: { attributes: articles, primaryKey: "id" }, invoices: { attributes: invoices, primaryKey: "id" }, orders: { attributes: orders, primaryKey: "id" }, users: { attributes: users, primaryKey: "id" }, }, models: { Article: "articles", Invoice: "invoices", Order: "orders", User: "users" }, }); declare module "../models/article" { interface Article extends TableAttributes {} } declare module "../models/invoice" { interface Invoice extends TableAttributes {} } declare module "../models/order" { interface Order extends TableAttributes {} } declare module "../models/user" { interface User extends TableAttributes {} } ``` ```sql D1 CREATE TABLE orders ( id TEXT PRIMARY KEY NOT NULL, number TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', email TEXT NOT NULL, total_cents INTEGER NOT NULL, is_suspended BOOLEAN NOT NULL DEFAULT FALSE, placed_at DATETIME ); CREATE UNIQUE INDEX index_orders_on_number ON orders (number); CREATE TABLE users ( id TEXT PRIMARY KEY NOT NULL, email TEXT NOT NULL ); CREATE TABLE articles ( id TEXT PRIMARY KEY NOT NULL, title TEXT NOT NULL, updated_at DATETIME ); CREATE TABLE invoices ( id TEXT PRIMARY KEY NOT NULL, country TEXT NOT NULL, currency TEXT, total_cents INTEGER NOT NULL DEFAULT 0 ); ``` ```sql Postgres CREATE TABLE orders ( id UUID PRIMARY KEY, number TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', email TEXT NOT NULL, total_cents INTEGER NOT NULL, is_suspended BOOLEAN NOT NULL DEFAULT FALSE, placed_at TIMESTAMPTZ ); CREATE UNIQUE INDEX index_orders_on_number ON orders (number); CREATE TABLE users ( id UUID PRIMARY KEY, email TEXT NOT NULL ); CREATE TABLE articles ( id UUID PRIMARY KEY, title TEXT NOT NULL, updated_at TIMESTAMPTZ ); CREATE TABLE invoices ( id UUID PRIMARY KEY, country TEXT NOT NULL, currency TEXT, total_cents INTEGER NOT NULL DEFAULT 0 ); ``` ## Registering callbacks Register callbacks in a Model’s `static {}` block, as `Order` does, and they run as the record is saved: ```ts import { Order } from "./models/order"; const order = await Order.create({ number: "1001", email: " Jane@Example.com ", totalCents: 2500, }); console.log(order.email); // "jane@example.com", from the first beforeValidation console.log(order.placedAt); // now, from the beforeValidation that runs on create await order.update({ status: "shipped" }); // afterSave sends the shipped email ``` - Each callback receives the record, and may be async, except the [callbacks for a record built or loaded](#running-code-when-a-record-is-built-or-loaded). - Callbacks of one kind run in the order declared. A subclass runs its parent’s callbacks, then its own. - Pass `on` to `beforeValidation` or `afterValidation` to run it only in some [validation contexts](/validations#validating-only-when-creating-or-updating), as `Order`’s second `beforeValidation` does. :::note Once a Model has been used, registering another callback throws `InvalidModel`, so request code can’t add one that leaks into later requests. ::: ## Callback order | Order | Callback | Runs | `abort()` | | -------------- | -------------------- | -------------------------------------------------------- | --------------------------------- | | **Saving** | | | | | 1 | `beforeValidation` | Before the validators, on every save, and on `isValid()` | Stops the save | | 2 | `afterValidation` | After the validators | Stops the save | | 3 | `beforeSave` | Before every write, new or persisted | Stops the save | | 4 | `aroundSave` | Its first part, before `next()` | Stops the save | | 5 | `beforeCreate` | Before inserting a new record | Stops the save | | 5 | `beforeUpdate` | Before updating a persisted record | Stops the save | | 6 | `aroundCreate` | Its first part, before `next()` | Stops the save | | 6 | `aroundUpdate` | Its first part, before `next()` | Stops the save | | | _The write_ | Skipped when a persisted record has no changes | | | 7 | `aroundCreate` | Its last part, once `next()` resolves | Too late: `AbortAfterPersistence` | | 7 | `aroundUpdate` | Its last part, once `next()` resolves | Too late: `AbortAfterPersistence` | | 8 | `afterCreate` | After inserting a new record | Too late: `AbortAfterPersistence` | | 8 | `afterUpdate` | After updating a persisted record | Too late: `AbortAfterPersistence` | | 9 | `aroundSave` | Its last part, once `next()` resolves | Too late: `AbortAfterPersistence` | | 10 | `afterSave` | After every successful save | Too late: `AbortAfterPersistence` | | 11 | `afterCommit` | Last, after every after-callback | Too late: `AbortAfterPersistence` | | 11 | `afterCreateCommit` | Last, after inserting a new record | Too late: `AbortAfterPersistence` | | 11 | `afterUpdateCommit` | Last, after updating a persisted record | Too late: `AbortAfterPersistence` | | 11 | `afterSaveCommit` | Last, after every successful save | Too late: `AbortAfterPersistence` | | **Destroying** | | | | | 1 | `beforeDestroy` | Before the `dependent` strategies and the DELETE | Stops the destroy | | 2 | `aroundDestroy` | Its first part, before `next()` | Stops the destroy | | | _The delete_ | With the dependents, in one batch | | | 3 | `aroundDestroy` | Its last part, once `next()` resolves | Too late: `AbortAfterPersistence` | | 4 | `afterDestroy` | After the record is destroyed | Too late: `AbortAfterPersistence` | | 5 | `afterCommit` | Last, after every after-callback | Too late: `AbortAfterPersistence` | | 5 | `afterDestroyCommit` | Last, after the record is destroyed | Too late: `AbortAfterPersistence` | | **Touching** | | | | | | _The write_ | `updatedAt`, and any attributes named | | | 1 | `afterTouch` | After `touch()` writes the record’s timestamps | Too late: `AbortAfterPersistence` | | 2 | `afterCommit` | Last, when `touch()` wrote a row | Too late: `AbortAfterPersistence` | | 2 | `afterUpdateCommit` | Last, when `touch()` wrote a row | Too late: `AbortAfterPersistence` | | 2 | `afterSaveCommit` | Last, when `touch()` wrote a row | Too late: `AbortAfterPersistence` | | **Refused** | | | | | 1 | `afterRollback` | When the database refuses the save or destroy | Nothing to stop | | **Loading** | | | | | 1 | `afterFind` | After a record is loaded | Nothing to stop | | 2 | `afterInitialize` | After a record is loaded, or built | Nothing to stop | A save runs either the create pair or the update pair, never both. - **After-callbacks** run after every successful save, even one with no changes to write. - **A before-callback that changes an attribute** makes the record dirty, and the change is written. - **An after-callback that changes an attribute** leaves the record dirty. Nothing is written again. :::warning[Nothing is rolled back] The database has kept a save’s writes before any after-callback runs. An error thrown by an after-callback or a commit callback reaches the caller, but the record stays saved. The callbacks after it don’t run. In a batch, that includes the other records’ callbacks. ::: ## Wrapping a save or destroy An around callback runs code on both sides of a write, as `Order`’s `aroundSave` does. Call `next()` to run the rest of the save, and await it. - **`aroundSave`** runs after `beforeSave`. Its `next()` runs `beforeCreate` or `beforeUpdate`, the write, and `afterCreate` or `afterUpdate`. `afterSave` runs once the callback finishes. - **`aroundCreate`**, **`aroundUpdate`**, and **`aroundDestroy`** wrap only the write, between the matching before- and after-callbacks. - **Several around callbacks of one kind** nest. The first one declared is the outermost. `next()` returns a promise with no value. It resolves once the database has kept the write. A save sends its writes together, so in a [batch](/batches#batching-records), every record’s first part runs before the batch is written. Then each record’s last part runs in turn. ### Stopping a wrapped write - **Not calling `next()`** stops the save, as `abort()` does. `save()` resolves to `false`, and nothing is written. - **An `abort()` before `next()`** stops the save. After `next()`, the write has happened, so `abort()` throws `AbortAfterPersistence`. - **When the database refuses the write**, `afterRollback` runs, then `next()` rejects with the database’s error. The save throws it even if you catch it. - **When the save ends without sending the write**, `next()` rejects with the error the save ends with. That happens when another record in the save or batch is refused before the write is sent. - **When an earlier record’s after-callback throws**, the write is kept. This record’s after-callbacks are skipped, and `next()` rejects with that error. To release something you hold during the write, put `await next()` in a `try` block, and release it in `finally`. ## Running code after the commit Register a commit callback, as `User` does, to run code once everything is written: ```ts import { User } from "./models/user"; await User.create({ email: "sam@example.com" }); // then afterCreateCommit sends the welcome email ``` Commit callbacks run last, after every after-callback of the save. In a [batch](/batches#batching-records), they wait for every record’s after-callbacks. - **`afterCommit`** runs after a create, an update, or a destroy. - **`afterCreateCommit`**, **`afterUpdateCommit`**, and **`afterDestroyCommit`** run after one kind of write. **`afterSaveCommit`** runs after a create or an update. - **Commit callbacks of every kind** run in the order you declared them. :::note Destroying a record that was never saved runs no commit callback, since there was no row to delete. ::: ## Running code after a touch `afterTouch` runs after [`touch()`](/persistence#touching-a-record) writes a record’s timestamps, as `Article`’s does: ```ts import { Article } from "./models/article"; const article = await Article.findByOrThrow({ title: "Hello" }); await article.touch(); // sets updatedAt, then afterTouch purges the cached page ``` - **No validation or save callback runs** for a touch. - **The commit callbacks for an update** run after `afterTouch`: `afterCommit`, `afterUpdateCommit`, and `afterSaveCommit`. When the row is gone, only `afterTouch` runs. - **`savedChanges()`** holds only the touched attributes, so `hasSavedChangeTo("email")` is `false` in a touch’s callbacks. - **A refused touch** runs `afterRollback`, and the record stays as it was. A `belongsTo` declared with [`touch`](/touching#touching-the-record-it-belongs-to) touches its record the same way. Saving a comment can run its article’s `afterTouch` and commit callbacks. `touchAll` and the counters’ `touch` option run no callbacks. :::warning[A touch runs the update commit callbacks] A `touch()` that writes a row runs `afterUpdateCommit`. To send an email only when a record is saved, register it with `afterUpdate` instead. It runs once the database has kept the save. ::: ## Handling a refused write `afterRollback` runs when the database refuses a record’s save or destroy, as `Order`’s does for a number that’s taken: ```ts import { Order } from "./models/order"; const order = Order.build({ number: "1001", email: "sam@example.com", totalCents: 900 }); await order.save(); // throws RecordNotUnique, once afterRollback has logged "Order 1001 wasn't saved" ``` - **A constraint error** refuses the record’s write, and the save then throws the [constraint error](/errors#constraint-errors). - **In a batch**, one refused write refuses them all, so `afterRollback` runs for every record in it. - **A failed validation or an `abort()`** sends nothing, so `afterRollback` doesn’t run. The record keeps its unsaved state, and no after-callback or commit callback runs for it. :::note An error thrown by an `afterRollback` reaches the caller in place of the constraint error, which becomes its `cause`. The `afterRollback` callbacks after it don’t run. ::: ## Running code when a record is built or loaded `afterInitialize` runs for every record you build and every record you load, as `Invoice`’s fills in a new invoice’s currency. `afterFind` runs for every record you load, just before `afterInitialize`: ```ts import { Invoice } from "./models/invoice"; const invoice = Invoice.build({ country: "GB" }); console.log(invoice.currency); // "GBP", from afterInitialize ``` - **`build` and `create`** run `afterInitialize` after their `init` function, so it sees what `init` set. Building through a `hasMany` or `hasOne` runs it once the record points at its owner. Building through a `through` association runs the join record’s `afterInitialize` once it points at the record. - **Every load** runs `afterFind`, then `afterInitialize`: a query, an association read, a preload, and `reload()`. Preloaded associations aren’t attached yet when they run. - **Saving a record** runs neither, and neither does `new Invoice()`. Both callbacks run synchronously, since `build` can’t wait for them. An `async` one is a type error. An error thrown by either reaches the caller, and the query returns no records. ### Handling partial records A record loaded with [`select`](/querying#selecting-attributes) runs both callbacks too, and reading an attribute it left out throws `MissingAttribute`. Check with `hasAttribute` first, as `Invoice`’s `afterFind` does: ```ts import { Invoice } from "./models/invoice"; const invoices = await Invoice.select("id", "country").toArray(); // afterFind skips the total const large = await Invoice.where({ country: "US" }).toArray(); // afterFind logs the large one ``` ## Stopping a save Throw `abort(reason)` from a before-callback to stop a save or destroy, as `Order`’s `beforeSave` does for a suspended order: ```ts import { Order } from "./models/order"; const order = await Order.findByOrThrow({ number: "1002" }); // a suspended order order.totalCents = 0; await order.save(); // false, and nothing is written console.log(order.abortReason); // "Orders can't change while suspended" ``` - **`save()`** resolves to `false` and writes nothing. The record keeps its changes, and `record.abortReason` holds the reason. - **`saveOrThrow()`** throws `RecordNotSaved` with the reason. - **`destroy()`** resolves to `false`, and **`destroyOrThrow()`** throws `RecordNotDestroyed`. Only `abort()` stops a save. Returning `false` does nothing, and any other error reaches the caller as it is. :::note In an after-callback, the write has already happened, so `abort()` throws `AbortAfterPersistence`, naming the callback. ::: > **Compared with Rails** > > `after_commit` and its `on:` forms are `afterCommit`, `afterCreateCommit`, `afterUpdateCommit`, `afterSaveCommit`, and `afterDestroyCommit`, run in the order declared, as Rails 7.1 runs them. In Rails, `after_save` runs before the save’s transaction commits. Here, the database has already kept the write before any after-callback runs, so every after-callback is already “after commit”. An error in `afterSave` rolls a Rails save back; here the record stays saved, and its commit callbacks don’t run. > > `after_touch` is `afterTouch`. As in Rails, `touch` runs the commit callbacks too. > > `after_rollback` is `afterRollback`. Rails also runs it for a save that fails inside a transaction. Here it runs only when the database refuses a write, since validation and the before-callbacks run before anything is sent. > > `around_save`, `around_create`, `around_update`, and `around_destroy` are `aroundSave`, `aroundCreate`, `aroundUpdate`, and `aroundDestroy`, and `yield` is `await next()`. Rails wraps each record’s own SQL in its transaction. Here, `next()` waits for the whole save’s batch. A Rails `around_save` can rescue the database’s error and carry on; here the save still throws it. Rails saves a `has_many`’s autosaved records inside the owner’s `around_save`. Here, the owner’s `aroundSave` finishes before their after-callbacks run. When an inner `around_save` doesn’t `yield`, Rails resumes the outer one after its `yield`. Here, the outer one’s `next()` rejects, and nothing is saved. > > `after_initialize` and `after_find` are `afterInitialize` and `afterFind`, and run in the same order. Here they can’t be async. `new Invoice()` doesn’t run `afterInitialize`, where Rails’ `new` does: build records through the Model instead, with `Invoice.build()`. `reload()` runs both on the record itself, where Rails runs them on a fresh copy and takes its attributes. `has_attribute?` is `hasAttribute`. > > Rails’ `if:` and `unless:` options for callbacks aren’t needed: write the condition inside the callback. --- # Schema changes Source: https://active-record.forestfuture.dev/change-a-table :::note Wrangler applies each migration once, in order. The schema is regenerated after each change, so a Model’s attributes follow its table. ::: ## Adding a column Generate the migration, then apply it: ```sh npx active-record g migration AddBioToUsers bio:string npx active-record migrate ``` ```sql migrations/20261108100000_add_bio_to_users.sql ALTER TABLE users ADD COLUMN bio TEXT; ``` `user.bio` is there straight away, typed as `string | null`. A required column needs a default for the existing rows: `'role:string!=member'`. 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. ## Renaming a column Generate an empty migration, and write the rename: ```sh npx active-record g migration RenameBioToAbout ``` ```sql migrations/20261108100500_rename_bio_to_about.sql ALTER TABLE users RENAME COLUMN bio TO about; ``` 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. :::note Keeping the old attribute name for a renamed column is planned in [#65](https://github.com/forestfuture/active-record/issues/65). ::: ## Removing a column Remove a column in the opposite order to adding one, so the code stops using it before it goes: 1. Ignore the column in the Model, remove the code that uses it, and deploy: ```ts import { ApplicationRecord } from "./application-record"; export class User extends ApplicationRecord { static override attributes = { bio: false } as const; } ``` 2. Generate the migration, and apply it with `--remote`: ```sh npx active-record g migration RemoveBioFromUsers bio ``` 3. Remove `{ bio: false }`, now that the schema no longer has the column. Remove a `references` column the same way, with `RemoveUserFromPosts user:references`. Its index is dropped first, then the column. ## Changing a column’s type 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): ```sql migrations/20261108101000_make_price_cents_an_integer.sql PRAGMA defer_foreign_keys = true; CREATE TABLE products_new ( id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, price_cents INTEGER NOT NULL, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL ); INSERT INTO products_new SELECT id, name, CAST(price_cents AS INTEGER), created_at, updated_at FROM products; DROP TABLE products; ALTER TABLE products_new RENAME TO products; ``` - **`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/). - **Indexes** are dropped with the old table, so recreate them after the swap. - **The schema** needs regenerating with `npx active-record schema`, since you wrote this migration by hand. :::note Wrangler backs up the database before applying migrations to it. ::: --- # Change tracking Source: https://active-record.forestfuture.dev/change-tracking ## At a glance | To | Write | | ------------------------------------------- | ------------------------------------------------------------------------- | | check for unsaved changes | `isChanged()`, `changed()`, `changes()` | | read an attribute’s value before the change | `attributeWas("email")` | | check one attribute’s change | `isAttributeChanged("email", { from: "…" })`, `willSaveChangeTo("email")` | | read what the last save changed | `savedChanges()`, `savedChangeTo("email")`, `hasSavedChangeTo("email")` | | undo unsaved changes | `restoreAttributes()`, or `restoreAttributes(["email"])` | ## The Model The examples use this Model, whose attributes come from its table through the schema `active-record schema` generates. Its `afterSave` callback reads what each save changed: ```ts user.ts import { ApplicationRecord } from "./application-record"; export class User extends ApplicationRecord { static { // After a save, the record is clean: read what the save changed. this.afterSave((user) => { const change = user.savedChangeTo("email"); if (change) console.log(`Email changed from ${change[0]} to ${change[1]}`); }); } } ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: 7ace010c47bc import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** users — last changed by 0001_create_users.sql */ export const users = { id: { type: "string", null: false, generateId: true }, email: { type: "string", null: false }, role: "string", isActive: "boolean", createdAt: { type: "datetime", null: false }, updatedAt: { type: "datetime", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { users: { attributes: users, primaryKey: "id" }, }, models: { User: "users" }, }); declare module "../models/user" { interface User extends TableAttributes {} } ``` ```sql D1 CREATE TABLE users ( id TEXT PRIMARY KEY NOT NULL, email TEXT NOT NULL, role TEXT, is_active BOOLEAN, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL ); ``` ```sql Postgres CREATE TABLE users ( id UUID PRIMARY KEY, email TEXT NOT NULL, role TEXT, is_active BOOLEAN, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL ); ``` ## Reading changes Read a record’s changes before it’s saved, and what the save changed after: ```ts import { User } from "./models/user"; const user = await User.findByOrThrow({ email: "jane@example.com" }); user.email = "jane@work.example"; console.log(user.changed()); // ["email"] console.log(user.attributeWas("email")); // "jane@example.com" console.log(user.isAttributeChanged("email", { from: "jane@example.com" })); // true await user.save(); // logs "Email changed from jane@example.com to jane@work.example" console.log(user.isChanged()); // false ``` - `isChanged()`, `changed()`, `changedAttributes()`, and `changes()` describe the unsaved changes. A new record’s changes run from its defaults, so a default it keeps isn’t a change. - `attributeWas`, `isAttributeChanged`, and `willSaveChangeTo` look at one attribute’s unsaved change. Use them in before-callbacks. - `savedChanges()`, `savedChangeTo`, `hasSavedChangeTo`, and `attributeBeforeLastSave` look at the last save. Use them in after-callbacks, where the record is already clean, as `User` does. - An update writes only the attributes that changed, and a save with nothing changed sends nothing. :::note Changes are found by comparing stored values, so editing a `json` value, a `Date`, or a `binary` attribute’s bytes in place counts as a change. ::: ## Undoing changes Undo unsaved changes with `restoreAttributes`, to every attribute or the ones you name: ```ts import { User } from "./models/user"; const user = await User.findByOrThrow({ email: "jane@example.com" }); user.assign({ email: "typo@example", role: "owner" }); user.restoreAttributes(["email"]); // back to "jane@example.com"; role stays changed ``` --- # Coming from Rails Source: https://active-record.forestfuture.dev/coming-from-rails :::tip Models, validations, callbacks, associations, scopes, and dirty tracking all follow Rails’ Active Record, down to the default error messages. ::: ## Querying from the Model ```ts // Rails: User.where(active: true) const users = await User.where({ isActive: true }).toArray(); ``` A Model queries by itself. The binding in the generated schema its base class holds plays the part of `connects_to`. 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. ## Naming things Most names are Rails’ own, in camelCase: | Rails | Active Record for Workers | | ---------------------------------------- | ------------------------------------------------- | | `created_at` (attribute) | `createdAt`, mapped to `created_at` | | `foreign_key: :user_id` | `foreignKey: "userId"` | | `save!`, `create!`, `find_by!` | `saveOrThrow`, `createOrThrow`, `findByOrThrow` | | `new_record?`, `persisted?` | `isNewRecord()`, `isPersisted()` | | `find_or_create_by(name:) do … end` | `findOrCreateBy({ name }, (tag) => …)` | | `empty?`, `any?` | `isEmpty()`, `hasAny()` | | `many?`, `one?` | `hasMoreThanOne()`, `hasExactlyOne()` | | `unscope(:order, where: :role)` | `unscope("order", { where: "role" })` | | `changed?`, `saved_change_to_email?` | `isChanged()`, `hasSavedChangeTo("email")` | | `rails generate model Post title:string` | `npx active-record g model Post title:string` | | `db/schema.rb`, `rails db:schema:dump` | `src/db/schema.ts`, `npx active-record schema` | | `class Post < ApplicationRecord` | `class Post extends ApplicationRecord` | | `scope :active, -> { … }` | `static active = this.scope((q) => …)` | | `has_many :posts, dependent: :destroy` | `posts = hasMany(Post, { dependent: "destroy" })` | | `post.author = user` | `post.author.set(user)` | | `build_profile` | `user.profile.build()` | | `user.profile = profile` | `await user.profile.set(profile)` | | `reload_author` | `post.reloadAssociation("author")` | | `throw :abort` | `throw abort("reason")` | | `to_json` | `toJSON()` | 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`. ## Declaring Models 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. 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: ```ts import { ApplicationRecord } from "./application-record"; // Rails: // class Product < ApplicationRecord // scope :in_stock, -> { where(available: true) } // validates :name, presence: true // end export class Product extends ApplicationRecord { static override attributes = { available: "boolean" } as const; static inStock = this.scope((q) => q.where({ available: true })); static { this.validates("name", { presence: true }); } } ``` ## Writing atomically There’s no `transaction do … end`, since D1 can’t keep a transaction open across awaits. Use [`batch((b) => [...])`](/batches) instead. In its callback, `b.save(user)`, `b.destroy(post)`, and bulk writes like `b.updateAll(…)` prepare writes. They’re sent atomically once the callback returns. Generating keys in code makes whole graphs of new records atomic too. See [D1’s limits](/d1). ## Primary keys :::warning[Keys are UUIDs, not integers] `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. ::: ## Generating code 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). ## Smaller differences - `insert` and `insertAll` raise on duplicates. Skipping them is opt-in, with `{ onDuplicate: "skip" }`. - `insert` fills in declared defaults, since that’s where keys are generated. - `merge` replaces the order rather than appending to it. - `merge` of another Model needs a join to it, and takes only its conditions and order. Anything else throws `IncompatibleRelation` when you write the query. - `find(1, 2)` on a `hasMany` join returns each record once. - `distinct()` with an order on a joined Model throws `IncompatibleRelation` on every database. Rails leaves it to the database, and only Postgres refuses it. - `last()` can’t reverse an `sql` fragment order, and throws `IrreversibleOrder`, rather than trying to parse SQL. - `find(1, 1)` always returns an array, so its return type follows its arguments. - `dependent:` strategies run after the owner’s `beforeDestroy` callbacks, wherever they’re declared, so an `abort()` always protects the records. - Records in a batch run all their before-callbacks before any write, and their after-callbacks after all of them. - Scopes preloaded with `limit` throw, where Rails silently gives wrong results. ## Not built yet `has_many :through`, `where` keyed by an association, `where.missing`, `eager_load`, single-table inheritance, `destroy_async`, and error messages in other languages. --- # Command line Source: https://active-record.forestfuture.dev/command-line ## Running the command The `active-record` command comes with `@forestfuture/active-record`, and `ffar` is its short name. Run it from your project’s folder: ```sh npx active-record --help ``` Every command reads your databases, and the adapter each one uses, from `active-record.jsonc`. `active-record init` writes it. It needs Node.js 22.5 or later. On D1, it needs 22.13 or later, for Node’s built-in SQLite. [Generators](/generators) shows it step by step. ## `active-record init` Write `active-record.jsonc` for your project: ```sh npx active-record init ``` It reads your Wrangler config. Each database in its `d1_databases` gets a D1 entry. Each Hyperdrive binding gets a PostgreSQL entry, whose `url` is the binding’s `localConnectionString`. Run it again after you add a database to your Wrangler config. It adds each database the file doesn’t name yet, and leaves the rest of the file as you wrote it, comments included: ```text Added LOGS to active-record.jsonc (on d1) ``` It adds only databases on the adapters the file already uses. To add another adapter’s databases, name it with `--adapter`. | Option | | | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- | | `--adapter ` | The adapter, `d1` or `postgresql`, when your Wrangler config has both, or neither. With the file there, it adds that adapter’s databases. | | `--config ` | Write this file, in place of `active-record.jsonc`. | With `--adapter postgresql` and no Hyperdrive binding, it writes a `DATABASE_URL` entry, with a guess at your local database’s `url` for you to correct. ## Declaring your databases `active-record.jsonc` sits beside your `package.json`. It names each of your databases by its binding, and the adapter it uses: ```jsonc { "$schema": "./node_modules/@forestfuture/active-record/config-schema.json", "databases": { "DB": { "adapter": "d1" }, }, } ``` Your generated schema names each database by its binding. The `$schema` line lets your editor complete and check the file. Each database names its own adapter, so one project can use D1 and Postgres together, as [Multiple databases](/several-databases#using-databases-on-different-adapters) shows. On D1, the rest of a database’s settings stay in your Wrangler config’s `d1_databases`, which must have its binding. A D1 database there that the file doesn’t name is left out, and every command notes it. By default, that’s the Wrangler config beside the file. If your Worker’s config is in another folder, name it with `wranglerConfig`. The path is relative to `active-record.jsonc`: ```jsonc { "databases": { "DB": { "adapter": "d1", "wranglerConfig": "../worker/wrangler.jsonc" }, }, } ``` The database’s migrations folder and its local data in `.wrangler/state` are then beside that config, where `wrangler dev` finds them. `migrate` and the console run the `wrangler` installed there, or else your project’s. On Postgres, the file holds a database’s settings: ```jsonc { "databases": { "HYPERDRIVE": { "adapter": "postgresql", "migrationsDir": "migrations", "url": "postgres://localhost/shop_development", "remoteUrl": "${PRODUCTION_DATABASE_URL}", }, }, } ``` | Setting | | | --------------- | ------------------------------------------------------------------------- | | `adapter` | `d1` or `postgresql`. | | `migrationsDir` | Its migrations folder, relative to the file (`migrations` by default). | | `url` | The local database: what `migrate` and the console use. | | `remoteUrl` | The real database, for `--remote`. | | `schemaUrl` | A server the schema may be read on, for an extension PGlite doesn’t have. | `${NAME}` reads a variable from the environment, so a password stays out of the file. The command never prints a connection string, only its database and host. `--config` names another file. On Postgres, the command needs `pg` installed, and PGlite to read your schema. It says what to install when either is missing. ## `active-record schema` Generate the schema file from your migrations: ```sh npx active-record schema ``` It applies your migrations, in order, to an in-memory database, and writes each table’s columns to `src/db/schema.ts`. On D1 that’s SQLite. On Postgres it’s [PGlite](https://pglite.dev), so it needs no server. | Option | | | -------------------- | ---------------------------------------------------------------------------------- | | `--check` | Write nothing: fail (exit 1) if the schema file is out of date. For CI. | | `--watch` | Regenerate whenever a migration or a Model file changes. | | `--out ` | Write the schema here instead. With several databases, a folder for one file each. | | `--migrations ` | Read migrations from here instead of the config’s folder (one database only). | | `--models ` | Where your Models and `application-record.ts` are (`src/models/` by default). | | `--config ` | Use this config file, in place of `active-record.jsonc`. | **What it reads:** each database in `active-record.jsonc`. On Postgres, from its `migrationsDir`. On D1, from its entry in the Wrangler config’s `d1_databases`, with its `binding`, `migrations_dir` (default `migrations/`), `migrations_pattern` (for migrations in folders), and `migrations_table` (left out of the schema). Migrations apply in the order of the numbers their names start with (`9_…` before `10_…`), as Wrangler applies them. It also loads the Model files in `--models`, using your project’s own `@forestfuture/active-record`, to find each Model and its table, so code at a Model file’s top level runs. **What it writes:** - **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. - **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. - **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`). > **Compared with Rails** > > The schema file plays the part of Rails’ `schema.rb`, and each base class is named as Rails names a second database’s. **What it refuses**, writing nothing: - A file it didn’t write (one without its “Generated by” header), such as a Drizzle schema. - 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. - Two bindings whose names would give the same base class (`DB` and `db`). - A migration the database rejects: the error names the file, and the last good schema is kept. - 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. :::warning[Coming from Drizzle or Prisma?] Their schemas often live at `src/db/schema.ts` or `src/db/schema/`. Write Active Record’s somewhere else, with `--out src/db/d1-record.ts`, and, if `application-record.ts` already exists, point its `import { schema }` at it (a new one is written importing the right file). ::: ## `active-record console` 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`: ```sh npx active-record console ``` | Option | | | ------------------- | ------------------------------------------------------------------------------------- | | `--database ` | The database to open, by its binding, when the config has several. | | `--models ` | Where the Models are: a folder (`src/models`) or one file (`src/models.ts`). | | `--config ` | Use this config file, in place of `active-record.jsonc`. | | `--no-history` | Don’t keep what you type (in `.wrangler/` on D1, `node_modules/.cache/` on Postgres). | | `--verbose` | Print each statement a line runs. `.verbose` turns it on and off in the console. | | `-e, --eval ` | Run this code, print its result (alone, on stdout), and exit; a failure exits 1. | | `--remote` | Open your remote database instead, after you type its name. | | `--yes` | With `--remote`, don’t ask first (also how to open it without a terminal). | | `--history` | Keep what you type in a remote session, which isn’t kept unless you ask. | It reads TypeScript Models and uses your project’s own `@forestfuture/active-record` and its adapter. On D1, it opens the database through your project’s `wrangler`. On Postgres, it opens a connection to the database’s `url`, or with `--remote` its `remoteUrl`, and closes it when you leave. It refuses, printing why, when there’s no config, with several databases and no `--database`, with no Models, or with the library not installed. On D1, it also refuses without `wrangler` installed, or with `--remote` when the binding has no `database_id`. On Postgres, it refuses when the database has no `url` (or, with `--remote`, no `remoteUrl`), or names a variable that isn’t set. With `--remote`, it refuses when you don’t confirm it, or aren’t on a terminal and didn’t pass `--yes`. `--yes` only goes with `--remote`, `--history` can’t be combined with `--no-history`, and `-e` takes one piece of code, once. ## `active-record migrate` Apply your pending migrations to the local database: ```sh npx active-record migrate ``` | Option | | | ------------------- | ----------------------------------------------------------------------------- | | `--database ` | The database to migrate, when the config has several. | | `--remote` | Migrate your remote database instead, after you type its name. | | `--yes` | With `--remote`, don’t ask first (also how to migrate it without a terminal). | | `--config ` | Use this config file. | On D1, it runs your project’s `wrangler d1 migrations apply` for the database, `--local` or `--remote`, and prints what Wrangler prints. It exits with Wrangler’s code. On Postgres, it applies them itself, to the database’s `url`, or with `--remote` its `remoteUrl`. It runs the migrations folder’s `.sql` files in the order of their versions and records each one’s version in `schema_migrations`. A version is the number a file’s name starts with: ```text Local database HYPERDRIVE (shop_development on localhost) Applied 20261108090503_create_products.sql Applied 20261108090504_add_sku_to_products.sql ``` - **Each migration runs in a transaction** with its version, so one that fails is rolled back whole, and the ones after it don’t run. A statement Postgres can’t run in a transaction, such as `CREATE INDEX CONCURRENTLY`, fails. - **A second run at the same time is refused**, through an advisory lock, so each migration runs once. Run it again once the first is done. - **A file whose name doesn’t start with a number** is refused before any migration runs, as are two files with the same number. - **A migration with its own `BEGIN`, `COMMIT` or `ROLLBACK`** is refused too, since it would end the transaction the migration runs in. A function’s `BEGIN … END` is fine. :::note[Migrating the real database on Postgres] On D1, `--remote` reaches your database through Cloudflare, signed in with Wrangler. On Postgres, it connects to the database itself, so the machine that runs it needs the `remoteUrl`’s variable, password included, and a network route to the server. That’s usually your CI, with the URL as a secret. If the database is only reachable through a Cloudflare Tunnel, open a local port to it with `cloudflared access tcp --hostname db.example.com --url localhost:5433`, and point `remoteUrl` at `localhost:5433`. ::: ## Mapping columns to attributes On D1, each column becomes an attribute by the first of these that applies: 1. **An override in the Model:** `static override attributes = { available: "boolean" } as const`. 2. **The column’s declared type:** | Declared as | Attribute | | --------------------------------------------------- | ------------------------------------------------ | | `INTEGER`, `INT`, `BIGINT`, … (anything with `INT`) | `integer` | | `TEXT`, `VARCHAR(…)`, `CHAR(…)`, `CLOB` | `string` | | `REAL`, `FLOAT`, `DOUBLE` | `real` | | `NUMERIC`, `DECIMAL` | `decimal`, with a size’s `precision` and `scale` | | `BOOLEAN` | `boolean` | | `DATETIME`, `TIMESTAMP` | `datetime` | | `DATE` | `date` | | `TIME` | `time` | | `TEXT` with `CHECK (json_valid(column))` | `json` | | `JSON` | `json` | | `BLOB` | `binary` | | anything else | `string` | 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). Also: - **Names:** `price_cents` becomes `priceCents`. A column whose name doesn’t come back the same from camelCase gets `column: "…"`. - **`NOT NULL`** becomes `null: false`. A primary key is never null. - **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. - **Defaults:** literal defaults (numbers, strings, `TRUE`/`FALSE`, JSON) are copied, so a new record shows them before it’s saved. A decimal’s, a date’s, or a time’s is copied in its type’s form (`1.50` as `"1.5"`). Expressions such as `CURRENT_TIMESTAMP` are left to D1. - **Foreign keys** take the referenced column’s type. They don’t create associations, which are behavior you declare. - **Enums:** a `TEXT` column with `CHECK (column IN ('open', 'done'))` gets `enum: ["open", "done"]`, with its methods off until the Model turns them on. See [Reading enums from the database](/enums#reading-enums-from-the-database). - **Left out:** SQLite’s own tables, Cloudflare’s (`_cf_…`), the migrations table, and virtual tables. **Notes it prints** when the schema is written: - an `INTEGER` read as a `boolean` from its name; - 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; - a `DATETIME` column whose default is a number or `unixepoch()`, with the [`storage` override](/adopt-a-database#reading-unix-timestamps); - for migrations written by Drizzle or Prisma, a `DATETIME` column whose default is `CURRENT_TIMESTAMP` or `datetime('now')`, since it writes a different date text from Active Record’s and the two [compare as text](/adopt-a-database#comparing-dates-in-two-forms); - migrations in folders with no `migrations_pattern` to find them. ### Mapping Postgres’s columns On Postgres, an override in the Model still comes first. Otherwise each column’s type decides, since Postgres’s types are real: | Type | Attribute | | -------------------------------------------- | ---------------------------------------------- | | `smallint`, `integer`, `bigint` | `integer` | | `real`, `double precision` | `real` | | `numeric` | `decimal`, with its `precision` and `scale` | | `boolean` | `boolean` | | `timestamptz`, `timestamp` | `datetime` | | `date` | `date` | | `time` | `time` | | `json`, `jsonb` | `json` | | `bytea` | `binary` | | `text`, `varchar`, `char`, `citext`, `uuid` | `string` | | an enum type | `string`, with the enum’s labels as its `enum` | | an array | An error: not supported | | anything else (`inet`, `interval`, `timetz`) | `string`, with a note | A domain maps as the type it’s built on. Names, `NOT NULL`, keys, and `CHECK (column IN (…))` work as on D1, and an enum type’s labels keep their order. A string key gets `generateId: true` unless it has a literal default, even when Postgres has a default such as `gen_random_uuid()`. Literal defaults (`'draft'`, `0`, `true`, `'{}'::jsonb`) are copied, and functions such as `now()` are left to Postgres. Views, other schemas, and `schema_migrations` are left out. **Extensions:** a migration can `CREATE EXTENSION` any of the extensions PGlite has its own build of, such as `citext`, `uuid-ossp`, `pg_trgm`, `pgcrypto`, `hstore`, and `ltree`. For any other, such as PostGIS, set `schemaUrl` to a Postgres server that has it, such as a local one. The schema is then read there, in a database of its own: ```jsonc { "databases": { "HYPERDRIVE": { "schemaUrl": "postgres://localhost/postgres" } } } ``` The migrations run in one transaction that’s rolled back, and the database is dropped afterwards, so a `CREATE ROLE` leaves nothing behind. It needs permission to create databases. A note says which server was read. Without `schemaUrl`, the command says to set one, and never uses `url` for it. Stopping the command with Ctrl-C drops the database too. A command killed outright can leave one behind, named `active_record_schema_…`, which you can drop yourself. ## `active-record g model` and `g migration` ```sh npx active-record g model [columns] [options] npx active-record g migration [columns] [options] ``` `generate` is the same as `g`. | Option | | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------- | | `--id integer\|text` | `integer`: a key the database generates. `text` (the default): a key generated in code. | | `--no-timestamps` | Leave out `created_at` and `updated_at`. | | `--models ` | Write Models in this folder (importing `application-record.ts` from it), or append them to one file (`src/models.ts`). | | `--database ` | The database to use, when the config has several. | | `--out ` | The schema file to regenerate, as for `active-record schema` (for a Drizzle project’s `src/db/d1-record.ts`, say). | | `--config ` | Use this config file. | ### Column syntax `name[:type][!][=value][:unique|:index]` | Type | D1 | Postgres | | ---------------------- | --------------------------------- | ------------------ | | `string` (the default) | `TEXT` | `TEXT` | | `integer` | `INTEGER` | `BIGINT` | | `real` | `REAL` | `DOUBLE PRECISION` | | `decimal` | `DECIMAL` | `NUMERIC` | | `boolean` | `BOOLEAN` | `BOOLEAN` | | `datetime` | `DATETIME` | `TIMESTAMPTZ` | | `date` | `DATE` | `DATE` | | `time` | `TIME` | `TIME` | | `json` | `TEXT CHECK (json_valid(column))` | `JSONB` | | `binary` | `BLOB` | `BYTEA` | A `references` column is `_id`, typed like the referenced table’s key, with `REFERENCES (id)` and an index. The key `g model` writes: | Key | D1 | Postgres | | ------------------- | ------------------------------ | -------------------------------------------------------- | | generated in code | `id TEXT PRIMARY KEY NOT NULL` | `id UUID PRIMARY KEY` | | with `--id integer` | `id INTEGER PRIMARY KEY` | `id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY` | Timestamps are `created_at` and `updated_at`, `NOT NULL`, as `DATETIME` on D1 and `TIMESTAMPTZ` on Postgres. - **`!`** 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. - **`=value`** is a literal default, for `string`, `integer`, `real`, `decimal`, `boolean`, `date`, and `time` columns (`=draft`, `=0`, `=1.5`, `=true`, `=2026-01-02`, `=09:00`). - **`{precision,scale}`** after `decimal` gives a decimal’s size: `'price:decimal{10,2}'` writes `DECIMAL(10, 2)` on D1 and `NUMERIC(10, 2)` on Postgres, and `decimal{6}` a precision alone. Quote it, so the shell doesn’t expand the braces. - **`:unique`** adds a unique index, and **`:index`** an index, named like `index_products_on_sku`. - **Names** can be written `priceCents` or `price_cents`; columns are always snake_case. Names the database reserves (`order`, `group`, and on Postgres `user`) are quoted. > **Beyond Rails** > > `=value` is Active Record’s own addition: Rails’ generators can’t give a column a default. ### Migration names | Name | Writes | | ----------------------------- | ------------------------------------------------------------------------- | | `Create` | `CREATE TABLE`, as `g model` does | | `AddTo
` | `ADD COLUMN` for each column, then their indexes | | `RemoveFrom
` | `DROP COLUMN`, after `DROP INDEX IF EXISTS` for its generated index on D1 | | anything else | An empty migration, to write yourself | 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. **File names** start with the UTC time they’re written, to the second (`20261108090503_add_sku_to_products.sql`), so migrations written on two branches don’t clash. Files numbered `0001_…` still run first. ### What’s checked first Nothing is written unless all of these hold: - the new migration applies after the existing ones (in memory, as `active-record schema` applies them); - the Model’s file doesn’t exist yet (or, with one models file, doesn’t have the class yet); - the config’s `migrations_pattern`, if it has one, would match the new file, so Wrangler would apply it; - the schema file can be written (see [What it refuses](#active-record-schema)); - on D1, it isn’t a required column added without a default, which SQLite can’t add. Then the generator writes the files, regenerates the schema, and prints the next step: `npx active-record migrate`. ## Exit codes 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. --- # Conditions Source: https://active-record.forestfuture.dev/conditions ## At a glance | To match | Write | SQL | | ----------------------------- | -------------------------------------- | --------------------------- | | equal values | `where({ role: "admin" })` | `role = ?` | | NULL | `where({ role: null })` | `role IS NULL` | | any value in a list | `where({ role: ["admin", "editor"] })` | `role IN (…)` | | anything but a value | `whereNot({ role: "admin" })` | `NOT (role = ?)` | | either of two queries | `where(a).or(User.where(b))` | `(…) OR (…)` | | a comparison | `where({ createdAt: gte(date) })` | `created_at >= ?` | | a range | `where({ createdAt: between(a, b) })` | both ends included | | anything else | ``where(sql`…`)`` | your SQL, with values bound | | a replacement for a condition | `rewhere({ role: "admin" })` | drops the old `role = ?` | | fewer parts of a query | `unscope("order")`, `only("where")` | drops the parts named | | all but some records | `excluding(record)` | leaves those records out | ## The Model The examples use this Model, whose attributes come from its table through the schema `active-record schema` generates: ```ts user.ts import { ApplicationRecord } from "./application-record"; export class User extends ApplicationRecord {} ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: 7ace010c47bc import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** users — last changed by 0001_create_users.sql */ export const users = { id: { type: "string", null: false, generateId: true }, email: { type: "string", null: false }, role: "string", isActive: "boolean", createdAt: { type: "datetime", null: false }, updatedAt: { type: "datetime", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { users: { attributes: users, primaryKey: "id" }, }, models: { User: "users" }, }); declare module "../models/user" { interface User extends TableAttributes {} } ``` ```sql D1 CREATE TABLE users ( id TEXT PRIMARY KEY NOT NULL, email TEXT NOT NULL, role TEXT, is_active BOOLEAN, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL ); ``` ```sql Postgres CREATE TABLE users ( id UUID PRIMARY KEY, email TEXT NOT NULL, role TEXT, is_active BOOLEAN, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL ); ``` ## Matching values Pass `where` an object of attributes that must all match: ```ts import { User } from "./models/user"; const admins = await User.where({ role: "admin", isActive: true }).toArray(); User.where({ role: null }); // role IS NULL User.where({ role: ["admin", "editor"] }); // role IN (…), any number of values ``` - `null` matches NULL. An array matches any of its values, and is bound as one value, so it can be any length. - Values are [cast to the attribute’s type](/attribute-types#casting-assigned-values), so text from a query string works as it is: `where({ isActive: "false" })` finds inactive users. A value that can’t be cast matches nothing: `findBy` resolves to `null`, and `find` throws `RecordNotFound`. - `undefined` throws `TypeError`. Leave the key out, or use `null`. - A value of an attribute with a [normalization](/models#normalizing-attributes) is normalized first, so `findBy({ email: " Jane@Example.com" })` finds `jane@example.com`. Attribute names are checked when you compile, and a misspelled one that gets past the compiler throws `UnknownAttribute`: ```ts import { User } from "./models/user"; User.where({ rol: "admin" }); ``` ## Negating conditions Negate a condition with `whereNot`, or combine two queries with `or`: ```ts import { User } from "./models/user"; const others = await User.whereNot({ role: "admin" }).toArray(); const either = await User.where({ role: "admin" }) .or(User.where({ isActive: false })) .toArray(); ``` - `whereNot` negates the whole condition. As in SQL, `whereNot({ role: "admin" })` also leaves out users whose role is NULL. - `or` combines two Relations of the same Model that differ only in their conditions. :::note In a list, values that can’t be cast are left out. So `whereNot({ id: "abc" })` on an integer key excludes nothing. ::: ## Comparing values Pass a comparison helper as a value: ```ts import { between, gte, lt } from "@forestfuture/active-record"; import { User } from "./models/user"; const since = new Date("2026-01-01"); const until = new Date("2026-02-01"); User.where({ createdAt: gte(since) }); // created_at >= ? User.where({ createdAt: lt(since) }); // created_at < ? User.where({ createdAt: between(since, until) }); // both ends included User.where({ createdAt: between(since, until, { excludeEnd: true }) }); ``` `gt`, `gte`, `lt`, `lte`, and `between` work on number, string, and datetime attributes, and dates compare by time. `between` includes both ends, unless you pass `{ excludeEnd: true }`. ## Writing SQL fragments Write anything else as an `sql` tagged template, with `column()` for an attribute’s column: ```ts import { column, sql } from "@forestfuture/active-record"; import { User } from "./models/user"; const email = "Jane@Example.com"; const user = await User.findBy(sql`lower(${column("email")}) = lower(${email})`); ``` Values are always bound, as they are, so a `Date` is ISO text. To write a value the way its attribute stores it, use `column(name).value(v)`: ```ts import { column, sql } from "@forestfuture/active-record"; import { User } from "./models/user"; const createdAt = column("createdAt"); const newcomers = await User.where( sql`${createdAt} >= ${createdAt.value(new Date("2026-01-01"))}`, ).toArray(); ``` `value` works for any attribute, and writes a boolean as 0 or 1 and a JSON value as text. It casts as assigning would, so a value the attribute can’t hold throws `TypeError` naming the attribute, when `where` is given the fragment. A filtered attribute’s value is hidden from `onQuery`, as it is anywhere else. :::warning[Datetimes stored as Unix time] For a datetime [stored as a Unix time](/adopt-a-database#reading-unix-timestamps), a bare `Date`, or an ISO datetime string, beside its column throws `TypeError`. Inside an expression, such as `abs(${column("publishedAt")} - ${date})`, or an `IN` list, nothing can tell, and the integer is compared with text: `>` matches nothing and `<` matches every row. Use `value` there. ::: ## Replacing conditions Replace the conditions on some attributes with `rewhere`: ```ts import { User } from "./models/user"; const members = User.where({ role: "member", isActive: true }); const activeAdmins = await members.rewhere({ role: "admin" }).toArray(); // is_active = ? AND role = ? ``` Conditions on other attributes stay, and so do `sql` fragments. A default scope’s condition on the attribute is replaced too. A `whereNot` or `or` is replaced only if it names no other attributes. Drop parts of a query with `unscope`, or keep only some with `only`: ```ts import { User } from "./models/user"; const recent = User.where({ role: "admin" }).order({ createdAt: "desc" }).limit(10); recent.unscope("order", "limit"); // every admin, unordered recent.unscope({ where: "role" }); // the 10 newest users recent.only("where"); // every admin ``` - The parts are `"where"`, `"order"`, `"limit"`, `"offset"`, `"select"`, `"distinct"`, `"includes"`, `"joins"`, `"leftJoins"`, and `"createWith"`. `{ where: "role" }` drops only the conditions on those attributes. - A default scope’s parts are dropped too. To start without the default scope, use [`unscoped()`](/scopes#leaving-the-default-scope-out). - On an association, the link to its owner stays: `user.posts().unscope("where")` is still the user’s posts, and so is `rewhere({ userId })`. Start from `Post` to read past the owner. - Merging a Relation built with `unscope` drops those parts from the Relation it’s merged into. - A join can’t be dropped while a merged condition or order uses it. That throws `IncompatibleRelation`. ## Leaving records out Leave out records you already have with `excluding`: ```ts import { User } from "./models/user"; const me = await User.findByOrThrow({ email: "jane@example.com" }); const everyoneElse = await User.excluding(me).toArray(); ``` It takes records of the Relation’s Model, or arrays of them. A record that isn’t saved yet leaves nothing out. > **Compared with Rails** > > `rewhere`, `unscope`, `only`, and `excluding` work as Rails’ do, with the parts named as strings. `group` and `having` aren’t parts, since a grouped Relation is a type of its own. `invert_where` and `without` aren’t offered, and scopes cover `extending`. > **Beyond Rails** > > On an association, Rails’ `unscope(:where)` drops the link to its owner, so a read can reach records that `create` wouldn’t link to it. Here no rewrite drops the link, so reads and writes agree. --- # Connections Source: https://active-record.forestfuture.dev/connecting ## At a glance Most apps only use the binding. | | How | Use it for | | -------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------- | | **The binding** | `User.find(id)`, with nothing to set up | Everyday queries | | **The request’s database** | `withDatabase(connect(env.DB, …), fn)`, once per request | Read replicas with a Session, per-request `onQuery` logging, tests, and scripts | | **An explicit database** | `connect(env.DB).model(User).find(id)` | Code that passes its database around, or uses two at once | [Database resolution](/query-databases) explains why there are three, and [which one you need](/query-databases#which-do-i-need). ## The Models The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates: ```ts user.ts import { hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Post } from "./post"; export class User extends ApplicationRecord { posts = hasMany(Post); } ``` ```ts post.ts import { belongsTo } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { User } from "./user"; export class Post extends ApplicationRecord { user = belongsTo(User); } ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: f287cc463ec1 import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** posts — last changed by 0001_create_tables.sql */ export const posts = { id: { type: "string", null: false, generateId: true }, userId: { type: "string", null: false }, title: { type: "string", null: false }, } as const; /** users — last changed by 0001_create_tables.sql */ export const users = { id: { type: "string", null: false, generateId: true }, email: { type: "string", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { posts: { attributes: posts, primaryKey: "id" }, users: { attributes: users, primaryKey: "id" }, }, models: { Post: "posts", User: "users" }, }); declare module "../models/post" { interface Post extends TableAttributes {} } declare module "../models/user" { interface User extends TableAttributes {} } ``` ```sql D1 CREATE TABLE users ( id TEXT PRIMARY KEY NOT NULL, email TEXT NOT NULL ); CREATE UNIQUE INDEX index_users_on_email ON users (email); CREATE TABLE posts ( id TEXT PRIMARY KEY NOT NULL, user_id TEXT NOT NULL REFERENCES users (id), title TEXT NOT NULL ); ``` ```sql Postgres CREATE TABLE users ( id UUID PRIMARY KEY, email TEXT NOT NULL ); CREATE UNIQUE INDEX index_users_on_email ON users (email); CREATE TABLE posts ( id UUID PRIMARY KEY, user_id UUID NOT NULL REFERENCES users (id), title TEXT NOT NULL ); ``` :::note The examples use D1’s `connect`, from `@forestfuture/active-record/d1`. On Postgres, `connect` comes from `@forestfuture/active-record/postgresql` and takes your Hyperdrive binding. See [PostgreSQL](/postgresql#connecting). ::: ## Using the binding Each Model names the binding it queries, so a Model queries by itself during any request, as the app’s Worker does: ```ts import { User } from "./models/user"; // The app's Worker. No setup: each Model queries the binding its generated schema names. export const app = { async fetch(request) { const email = new URL(request.url).searchParams.get("email") ?? ""; const user = await User.findByOrThrow({ email }); return Response.json(await user.posts().order({ title: "asc" }).pluck("title")); }, } satisfies ExportedHandler; ``` `active-record schema` writes the binding into the generated schema your app’s base class holds. On D1 it comes from your Wrangler config’s `d1_databases`, and on Postgres from your `active-record.jsonc`. Records remember their database, so `user.save()` and `user.posts()` use the same one later. :::warning[Build records, never `new`] Build records with `User.build(…)`. A record made with `new User()` has no database, so saving it throws `NoDatabase`. ::: :::note 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). ::: ## Using the request’s database 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`: ```ts import { withDatabase } from "@forestfuture/active-record"; import { connect } from "@forestfuture/active-record/d1"; import { app } from "./app"; // src/worker.ts: the app's Worker, with a database for each request. export const worker = { fetch(request, env) { const db = connect(env.DB, { onQuery: ({ sql }) => console.log(sql) }); return withDatabase(db, () => app.fetch(request)); // every query inside uses db }, } satisfies ExportedHandler; ``` Every query started from a Model inside it, and everything it awaits, uses that database instead of the binding. :::warning[Node.js compatibility] `withDatabase` uses Workers’ `AsyncLocalStorage`. It’s on by default for compatibility dates from 2026-08-04. For an earlier date, add `"compatibility_flags": ["nodejs_compat"]` to your Wrangler config, or `withDatabase` throws `NoDatabase`. On D1, only `withDatabase` and [`noTouching`](/touching#turning-touches-off) need it. On Postgres, `pg` needs it too. ::: These pages use a request’s database: - **[Read replicas](/read-your-own-writes):** a D1 Session per request. - **[Logging](/logging):** one request’s queries, tagged with its ID. - **[Testing](/testing):** a database for Models outside a Worker. - **[Multiple databases](/several-databases):** `withDatabase([...])`, matched to each Model’s binding. ## Using an explicit database Start a query from a database you hold with `db.model`. It ignores `withDatabase`: ```ts import { connect } from "@forestfuture/active-record/d1"; import { User } from "./models/user"; export async function findJane(env: Env) { const db = connect(env.DB); return db.model(User).findByOrThrow({ email: "jane@example.com" }); // ignores withDatabase } ``` To name your Models once, use `db.models`: ```ts import { connect } from "@forestfuture/active-record/d1"; import { Post } from "./models/post"; import { User } from "./models/user"; export async function listPosts(env: Env) { const models = connect(env.DB).models({ User, Post }); return models.Post.order({ title: "asc" }).pluck("title"); } ``` `connect(env.DB, { session, onQuery })` takes the same options as a request’s database. ## Batching writes `batch` saves and destroys records and runs bulk writes atomically: ```ts import { batch } from "@forestfuture/active-record"; import { User } from "./models/user"; const user = User.build({ email: "sam@example.com" }); const post = user.posts().build({ title: "Hello" }); // points at the user, saved or not await batch((b) => [b.save(user), b.save(post)]); // atomic: both written, or neither ``` `batch` writes a Model’s rows on the current database. `db.batch` uses an explicit one. See [Bulk writes and batches](/batches). --- # Console Source: https://active-record.forestfuture.dev/console ## Opening the console Run the console from your project’s folder. It opens your local database, or your remote one with [`--remote`](#opening-your-remote-database): ```sh npx active-record console ``` On Postgres, it opens the `url` your [`active-record.jsonc`](/command-line#declaring-your-databases) declares, or with `--remote` its `remoteUrl`. The rest of this page shows D1. It prints which database and Models it opened, then waits for a line: ```text Local database DB (.wrangler/state) Models: Post, User local> const user = await User.find("c5c765b4-b7e1-428e-aa00-88d58f622c71") #=> undefined local> user #=> User { id: 'c5c765b4-b7e1-428e-aa00-88d58f622c71', name: 'Alice', email: [FILTERED] } local> await user.update({ name: "Johnny" }) #=> true local> const admins = await User.where({ role: "admin" }).toArray() #=> undefined ``` 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. ## What you can use - **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. - **`db`,** your connected database, for `db.batch(...)` and `db.model(...)`. - **Top-level `await`,** and `const` and `let`, which last until you leave. 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](/serialization#printing-records) has the details. An error prints and the console carries on. ## Reloading your Models After you edit a Model, or a file it imports, read them again without leaving: ```text > reload! Reloaded: Post, User ``` `.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. 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. :::note Only files in your project’s folder are read again. Your database connection and `@forestfuture/active-record` stay as they are. ::: ## Seeing the SQL Start with `--verbose` to see each statement a line runs, or turn it on and off while you work with `.verbose`: ```text > .verbose SQL logging on > await User.find(1) User 1.2ms SELECT * FROM "users" WHERE (("id" = ?)) LIMIT ? [ 1, 1 ] #=> User { id: 1, name: 'Alice', email: [FILTERED] } ``` 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. :::note The SQL comes from the database’s own `onQuery`, so a listener you set on your base class still runs as well. ::: ## Choosing what to open | Option | | | ------------------- | ------------------------------------------------------------------------------------------------------- | | `--database ` | The database to open, when `active-record.jsonc` names several. | | `--models ` | Where your Models are: a folder (`src/models` by default) or one file (`src/models.ts`). | | `--config ` | Use this config file, in place of `active-record.jsonc`. | | `--no-history` | Don’t keep what you type in the history file. | | `--verbose` | Print each statement a line runs, to begin with. `.verbose` turns it on and off. | | `-e, --eval ` | Run this code, print its result, and exit. See [Running one piece of code](#running-one-piece-of-code). | | `--remote` | Open your remote database instead, after you type its name. See below. | | `--yes` | With `--remote`, don’t ask first. It’s also how to open it without a terminal. | | `--history` | Keep what you type in a remote session, which isn’t kept unless you ask. | ## Where your data lives The console opens the local database in `.wrangler/state`, beside your Wrangler config. It’s the same one `wrangler dev` and `wrangler d1 migrations apply --local` use, so apply your migrations first, and what you change in the console is what your dev server sees. With [`wranglerConfig`](/command-line#declaring-your-databases), it’s beside the config that setting names. It opens your remote database only when you ask with `--remote`, and never for a binding your config marks `remote: true` by itself. 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. On a terminal, what you type is kept in `.wrangler/active-record-history`, which Wrangler projects already ignore. A line can hold a token or an email, so add `--no-history` when you’d rather it wasn’t kept. ## Opening your remote database `--remote` opens the real database your binding points at, to look at production data or fix one record by hand: ```sh npx active-record console --remote ``` 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: ```text Remote database DB (shop, id 1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d) What you change in the console is changed in this database, not a copy. Type its name to continue, anything else cancels: shop ``` 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: ```text Remote database DB (shop, id 1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d) Models: Post, User remote> await User.count() #=> 42 ``` :::warning[Changes can’t be undone] A change is made to the real database, for good. `await user.destroy()` deletes that row from your remote database. ::: 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. 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: ```sh echo 'await User.count()' | npx active-record console --remote --yes ``` What you type isn’t kept unless you add `--history`, and then it goes in `.wrangler/active-record-history-remote`, a file of its own, so the up arrow never offers a local session a line you typed against the real database. :::note 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 (…)`. ::: :::note 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. ::: ## Running one piece of code `-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: ```sh npx active-record console -e 'await User.count()' ``` ```text 42 ``` - **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`. - **Everything else is on stderr:** which database and Models it opened, the SQL with `--verbose`, and a refusal to start. - **A failure exits 1.** Its stack goes to stderr, no result goes to stdout, and no statement after it runs. Success exits 0. - **Join statements with `;`.** The last value is the result: `-e 'await User.create({ name: "Dan" }); await User.count()'`. - **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`. :::note Await every call. `User.find(1)` without `await` prints `Promise { }`, and a promise you don’t await may not finish before the console exits, and its failure isn’t reported. ::: :::note 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()'`. ::: ## Running a few lines at once Lines you paste or pipe run in order, each after the one before, and the console finishes them before it exits: ```sh echo 'await User.count()' | npx active-record console ``` 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`. :::note The console reads your TypeScript Models directly, including extensionless imports and `tsconfig.json` paths, so it works in TypeScript projects. It needs Node.js 22.13 or later, and `wrangler` and `@forestfuture/active-record` installed in your project. It uses your copies, so your Models and the console share one library. ::: :::warning[Only in projects you trust] The console runs your project’s code: your Models, and the `wrangler` and `@forestfuture/active-record` in its `node_modules`. Run it in a project you’d run `wrangler dev` in. ::: > **Compared with Rails** > > 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. > **Beyond Rails** > > `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>`. --- # Counter caches Source: https://active-record.forestfuture.dev/counter-caches ## At a glance | To | Write | | --------------------------------------- | ------------------------------------------------------------------ | | keep an article’s count of comments | `belongsTo(Article, { counterCache: true })`, with `commentsCount` | | keep it in an attribute of another name | `counterCache: "replyCount"`, on the `belongsTo` and the `hasMany` | | read the count, with no query | `article.comments().size()`, `isEmpty()`, `hasAny()` | | set the count from the rows | `Article.resetCounters(id, "comments")` | | fill in a new counter before it’s read | `counterCache: { attribute: "commentsCount", active: false }` | ## The Models The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates: ```ts article.ts import { hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Comment } from "./comment"; export class Article extends ApplicationRecord { comments = hasMany(Comment); // size() reads commentsCount } ``` ```ts comment.ts import { belongsTo } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Article } from "./article"; export class Comment extends ApplicationRecord { article = belongsTo(Article, { counterCache: true }); // keeps Article's commentsCount } ``` ```ts forum.ts import { hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Reply } from "./reply"; export class Forum extends ApplicationRecord { replies = hasMany(Reply, { counterCache: "replyCount" }); // not repliesCount } ``` ```ts reply.ts import { belongsTo } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Forum } from "./forum"; export class Reply extends ApplicationRecord { forum = belongsTo(Forum, { counterCache: "replyCount" }); } ``` ```ts imported-comment.ts import { belongsTo } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Article } from "./article"; export class ImportedComment extends ApplicationRecord { static override table = "comments"; // Writes keep commentsCount, but nothing reads it until active: false goes. article = belongsTo(Article, { counterCache: { attribute: "commentsCount", active: false } }); } ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: 2ed73c98509c import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** articles — last changed by 0001_create_tables.sql */ export const articles = { id: { type: "string", null: false, generateId: true }, title: { type: "string", null: false }, commentsCount: { type: "integer", null: false, default: () => 0 }, updatedAt: "datetime", } as const; /** comments — last changed by 0001_create_tables.sql */ export const comments = { id: { type: "string", null: false, generateId: true }, articleId: { type: "string", null: false }, body: { type: "string", null: false }, } as const; /** forums — last changed by 0001_create_tables.sql */ export const forums = { id: { type: "string", null: false, generateId: true }, replyCount: { type: "integer", null: false, default: () => 0 }, } as const; /** replies — last changed by 0001_create_tables.sql */ export const replies = { id: { type: "string", null: false, generateId: true }, forumId: { type: "string", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { articles: { attributes: articles, primaryKey: "id" }, comments: { attributes: comments, primaryKey: "id" }, forums: { attributes: forums, primaryKey: "id" }, replies: { attributes: replies, primaryKey: "id" }, }, models: { Article: "articles", Comment: "comments", Forum: "forums", ImportedComment: "comments", Reply: "replies", }, }); declare module "../models/article" { interface Article extends TableAttributes {} } declare module "../models/comment" { interface Comment extends TableAttributes {} } declare module "../models/forum" { interface Forum extends TableAttributes {} } declare module "../models/imported-comment" { interface ImportedComment extends TableAttributes {} } declare module "../models/reply" { interface Reply extends TableAttributes {} } ``` ```sql D1 CREATE TABLE articles ( id TEXT PRIMARY KEY NOT NULL, title TEXT NOT NULL, comments_count INTEGER NOT NULL DEFAULT 0, updated_at DATETIME ); CREATE TABLE comments ( id TEXT PRIMARY KEY NOT NULL, article_id TEXT NOT NULL REFERENCES articles (id), body TEXT NOT NULL ); CREATE TABLE forums ( id TEXT PRIMARY KEY NOT NULL, reply_count INTEGER NOT NULL DEFAULT 0 ); CREATE TABLE replies ( id TEXT PRIMARY KEY NOT NULL, forum_id TEXT NOT NULL REFERENCES forums (id) ); ``` ```sql Postgres CREATE TABLE articles ( id UUID PRIMARY KEY, title TEXT NOT NULL, comments_count INTEGER NOT NULL DEFAULT 0, updated_at TIMESTAMPTZ ); CREATE TABLE comments ( id UUID PRIMARY KEY, article_id UUID NOT NULL REFERENCES articles (id), body TEXT NOT NULL ); CREATE TABLE forums ( id UUID PRIMARY KEY, reply_count INTEGER NOT NULL DEFAULT 0 ); CREATE TABLE replies ( id UUID PRIMARY KEY, forum_id UUID NOT NULL REFERENCES forums (id) ); ``` ## Declaring a counter cache Declare `counterCache` on the counted records’ `belongsTo`, as `Comment` does, and give the owner an attribute for the count: - The attribute is named for the counted Model: `commentsCount` for comments. - To keep it in another attribute, name it, as `Reply` does: `counterCache: "replyCount"`. - A polymorphic `belongsTo` counts a record on whichever listed Model its type names, so each of them declares the attribute. - A counter cache on a Model on [another database](/several-databases) throws `InvalidModel`, since its count couldn’t be written in the same batch. So do two `belongsTo`s on one foreign key that keep the same attribute, since each comment would count twice. ## Counting records Creating a comment adds one to its article’s count, and destroying it takes one away: ```ts import { Article } from "./models/article"; const article = await Article.findByOrThrow({ title: "Hello" }); const comment = await article.comments().create({ body: "First!" }); // commentsCount + 1 await comment.destroy(); // commentsCount - 1 ``` - Changing a comment’s `articleId` moves the count to the other article. An article you’ve loaded takes the new count too, without a save. - Removing comments through the article’s association counts them out: `delete`, `clear`, and `deleteAll()` on `article.comments()`. Removing records through an association through another counts out its join records the same way. - Bulk writes leave the count alone: `insert`, `insertAll`, `upsert`, `updateAll`, and `deleteAll()` on any other Relation. :::tip Each change is written in the same atomic batch as the comment, so the count can’t drift from the rows. ::: ## Reading the count `size()`, `isEmpty()`, and `hasAny()` on the association read the count, without a query: ```ts import { Article } from "./models/article"; const article = await Article.findByOrThrow({ title: "Hello" }); const count = await article.comments().size(); // reads commentsCount, with no query ``` - An association reads the counter named for it: `comments` reads `commentsCount`. If its counter has another name, name it on the `hasMany` too, as `Forum` does. - An association with any other name counts its rows, so one narrowed by a scope counts only its own records. - `count()` always counts the rows. ## Resetting a count Set a count from the rows with `resetCounters`, after a bulk write for example: ```ts import { Article } from "./models/article"; const article = await Article.findByOrThrow({ title: "Hello" }); await Article.resetCounters(article.id, "comments", { touch: true }); // counts the rows ``` - It takes one association’s name or a list of them, and sets every counter the association’s records keep on the article. - `touch: true` also sets `updatedAt`. - An association with a scope can’t reset a counter, since its records aren’t all the ones counted. ## Adding a counter to existing records Declare a new counter with `active: false`, as `ImportedComment` does, to fill it in before anything reads it: - A new counter starts at zero, even for an article that already has comments. - With `active: false`, writes keep the count up to date, while `size()` and the others count the rows. - Run `resetCounters` for each article, then remove `active: false`. > **Compared with Rails** > > Rails takes one from the article the comment’s key pointed at when it was loaded. Here the count is taken from the article the comment’s row points at as it’s deleted, so a comment that’s already gone, or that another request moved, doesn’t throw the count off. > > `counterCache` names an attribute, where Rails’ `counter_cache` names a column. Rails also makes the counter read-only. Here it’s an ordinary attribute. > > In Rails, removing records through a scoped association leaves the count too high, and `reset_counters` on one writes the scope’s count into the counter. Here the removal counts its records out, and `resetCounters` refuses the scoped association. > > Rails counts a comment twice when two `belongs_to`s keep the same counter. Here that throws `InvalidModel`. --- # Custom types Source: https://active-record.forestfuture.dev/custom-types ## At a glance | To | Write | | -------------------------------------- | ------------------------------------------------------------------- | | define a type stored as a built-in one | `defineType({ storedAs: "integer", cast, serialize, deserialize })` | | give a generated attribute the type | `static override attributes = { priceCents: money } as const` | | refuse a value | throw from `cast` | | query by the type’s values | `Product.where({ priceCents: new Money(500) })` | ## The Models The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates, with the types in `src/types/`: ```ts product.ts import { money } from "../types/money"; import { ApplicationRecord } from "./application-record"; export class Product extends ApplicationRecord { static override attributes = { priceCents: money, } as const; } ``` ```ts shirt.ts import { sizes } from "../types/sizes"; import { ApplicationRecord } from "./application-record"; export class Shirt extends ApplicationRecord { static override attributes = { sizes: { type: sizes, default: () => [] }, } as const; } ``` ```ts money.ts import { defineType } from "@forestfuture/active-record"; export class Money { readonly cents: number; constructor(cents: number) { this.cents = cents; } toString() { return `$${(this.cents / 100).toFixed(2)}`; } } export const money = defineType({ storedAs: "integer", cast(input) { if (input instanceof Money) return input; if (Number.isSafeInteger(input)) return new Money(input as number); throw new TypeError("money is a Money or a whole number of cents"); }, serialize: (value) => value.cents, deserialize: (cents) => new Money(cents), }); ``` ```ts sizes.ts import { defineType } from "@forestfuture/active-record"; export const sizes = defineType({ storedAs: "string", cast(input) { if (Array.isArray(input) && input.every((size) => typeof size === "string")) { return input as string[]; } throw new TypeError("sizes are a list of strings"); }, serialize: (list) => list.join(","), deserialize: (text) => (text === "" ? [] : text.split(",")), }); ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: b517af0d5b2a import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** products — last changed by 0001_create_tables.sql */ export const products = { id: { type: "string", null: false, generateId: true }, name: { type: "string", null: false }, priceCents: { type: "integer", null: false }, } as const; /** shirts — last changed by 0001_create_tables.sql */ export const shirts = { id: { type: "string", null: false, generateId: true }, name: { type: "string", null: false }, sizes: { type: "string", null: false, default: () => "" }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { products: { attributes: products, primaryKey: "id" }, shirts: { attributes: shirts, primaryKey: "id" }, }, models: { Product: "products", Shirt: "shirts" }, }); declare module "../models/product" { interface Product extends TableAttributes {} } declare module "../models/shirt" { interface Shirt extends TableAttributes {} } ``` ```sql D1 CREATE TABLE products ( id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, price_cents INTEGER NOT NULL ); CREATE TABLE shirts ( id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, sizes TEXT NOT NULL DEFAULT '' ); ``` ```sql Postgres CREATE TABLE products ( id UUID PRIMARY KEY, name TEXT NOT NULL, price_cents INTEGER NOT NULL ); CREATE TABLE shirts ( id UUID PRIMARY KEY, name TEXT NOT NULL, sizes TEXT NOT NULL DEFAULT '' ); ``` ## Defining a type Define a type with `defineType`, naming the built-in type it’s stored as. This one keeps money as whole cents in an integer column: ```ts import { defineType } from "@forestfuture/active-record"; export class Money { readonly cents: number; constructor(cents: number) { this.cents = cents; } toString() { return `$${(this.cents / 100).toFixed(2)}`; } } export const money = defineType({ storedAs: "integer", cast(input) { if (input instanceof Money) return input; if (Number.isSafeInteger(input)) return new Money(input as number); throw new TypeError("money is a Money or a whole number of cents"); }, serialize: (value) => value.cents, deserialize: (cents) => new Money(cents), }); ``` A type has three functions: | Function | Takes | Returns | | ------------- | ---------------------------------- | ---------------------------------- | | `cast` | a value given to the attribute | the type’s value, or throws | | `serialize` | the type’s value | a value of the type it’s stored as | | `deserialize` | a value of the type it’s stored as | the type’s value | The attribute’s TypeScript type is what `cast` returns, so `Money` here. :::note None of them is called with `null`, which is always NULL. ::: ## Using a type Give the type to a generated attribute in `static attributes`, as `Product` does: ```ts import { money } from "../types/money"; import { ApplicationRecord } from "./application-record"; export class Product extends ApplicationRecord { static override attributes = { priceCents: money, } as const; } ``` Changing an attribute’s type drops its generated default, as any [override](/models#overriding-attributes) of a type does. Give it a `default` if it needs one. A Model that declares its attributes itself, with `Model.define`, takes the type in place of a type’s name: `total: { type: money, null: false }`. ## Refusing values Throw from `cast` for a value the type can’t hold. Assigning or permitting that value then throws a `TypeError` naming the Model and attribute, with your error as its `cause`: ```ts import { Product } from "./models/product"; Product.permit({ priceCents: "abc" }, "priceCents"); // TypeError: Product: "abc" isn't a valid value for "priceCents" ``` The same happens when `deserialize` throws for a stored value, and when `serialize` returns a value its stored type can’t hold. For a [filtered attribute](/serialization#filtering-attributes), the error has no `cause`, since yours may show the value. ## Querying by a type Conditions take the type’s values, and anything `cast` takes: ```ts import { gte } from "@forestfuture/active-record"; import { Product } from "./models/product"; import { Money } from "./types/money"; const cheap = await Product.where({ priceCents: new Money(500) }).toArray(); const pricey = await Product.where({ priceCents: gte(new Money(10_000)) }) .order({ priceCents: "desc" }) .toArray(); ``` Values compare and sort as their stored values do, so money sorts by cents. A value `cast` throws for matches nothing. ## Changing values in place A type can hold a value you change in place. This one keeps a list of sizes as text, and `Shirt` gives it to `sizes`: ```ts import { defineType } from "@forestfuture/active-record"; export const sizes = defineType({ storedAs: "string", cast(input) { if (Array.isArray(input) && input.every((size) => typeof size === "string")) { return input as string[]; } throw new TypeError("sizes are a list of strings"); }, serialize: (list) => list.join(","), deserialize: (text) => (text === "" ? [] : text.split(",")), }); ``` Changes are found by comparing what `serialize` returns, so a size pushed onto the list is a change, and `save()` writes it: ```ts import { Shirt } from "./models/shirt"; const shirt = await Shirt.findByOrThrow({ name: "Oxford" }); // sizes: ["S", "M"] shirt.sizes.push("XL"); console.log(shirt.isChanged()); // true await shirt.save(); // writes "S,M,XL" ``` An equal value in another object, such as a new `Money` of the same cents, isn’t a change. > **Compared with Rails** > > Rails registers a type by name, with `ActiveRecord::Type.register(:money, MoneyType)`, and a Model writes `attribute :price, :money`. Here you pass the type itself, so TypeScript knows the attribute’s type. Rails’ types read the database’s values directly. Here a type is always stored as a built-in type, which reads and compares its values the same way on every database. --- # D1 Source: https://active-record.forestfuture.dev/d1 ## Installing The D1 adapter comes with `@forestfuture/active-record`, as its `/d1` entry: ```sh npm install @forestfuture/active-record ``` ## Binding a database Bind your D1 database in your Wrangler config: ```jsonc wrangler.jsonc { "d1_databases": [{ "binding": "DB", "database_name": "my-app-db", "database_id": "…" }], } ``` Then run `npx active-record init`, which names it in your [`active-record.jsonc`](/command-line#declaring-your-databases) as a D1 database. `active-record schema` reads its migrations through your Wrangler config, and your generated schema names it with `adapter: d1({ binding: "DB" })`. Your Models then query it with nothing to set up. `connect(env.DB)` opens it yourself, for [a request’s database](/connecting#using-the-requests-database) or [an explicit one](/connecting#using-an-explicit-database). `active-record migrate` applies your migrations through Wrangler. If your Wrangler config is in another folder, name it in the database’s entry with [`wranglerConfig`](/command-line#declaring-your-databases). ## Reading your own writes With read replication, wrap each request in [`withSession`](/read-your-own-writes), from `@forestfuture/active-record/d1`. It opens a D1 Session, so the request reads its own writes, and carries its bookmark to the user’s next request. ## Sending queries in one round trip D1 sends a batch of queries in one round trip. A [preload](/preloading) sends its whole tree on one database that way, with the records’ own query, so `includes({ articles: "comments" })` is three queries in one round trip. A [page](/ordering-and-pagination#paginating) sends its `COUNT` and its records together, with their preloads. A batch runs as one transaction, so every query in it reads the same data. A preload’s nested query that would bind more than 100 values waits for the records above it, and takes one more round trip. D1 also differs in these ways. ## No interactive transactions 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. What you can make atomic is a set of writes prepared in advance: [`batch`](/batches#batching-writes) sends bulk writes and records together, and D1 writes all of them or none. Active Record uses the same batches itself: - A destroy’s [`dependent` strategies](/associations#destroying-dependent-records) on the owner’s database are written in one batch with its DELETE. - A record [autosaved](/autosaving#saving-a-graph) with its owner joins the owner’s batch when it’s on the owner’s database and the owner’s key is known in advance. ## Generating keys in code 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: - A graph of new records built through associations on one database saves in one atomic batch. - A batch can insert rows that point at each other. 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](/autosaving#saving-a-graph). ## Uniqueness is checked twice The `uniqueness` validation asks D1 before saving, which gives a friendly error, but two requests can both pass it at once. Only a UNIQUE index guarantees uniqueness. Declare both, and handle [`RecordNotUnique`](/errors#constraint-errors) where a race matters. To create such a row only once, use [`createOrFindBy`](/persistence#creating-records-from-concurrent-requests) with the index alone. `caseSensitive: false` compares with SQLite’s `lower()`, which only lowercases ASCII letters, so `"Ä"` and `"ä"` are still different. ## Bound parameters D1 allows 100 bound values in one statement. The adapter binds lists as one JSON value (`json_each`), so `where({ id: [...] })`, `find([...])`, preloads, and `insertAll` work with any number of values. D1 takes at most 2 MB in one value. When a bulk write’s rows add up to more, the adapter sends them as several statements in one batch, which writes all of them or none. D1 counts the batch as one query. ## Foreign keys are enforced 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. ## Nothing rolls back after a write Once D1 has accepted a write, it’s done. An error thrown by an after-callback reaches the caller, but the record stays saved. ## Decimals keep about 15 digits SQLite stores a [`decimal`](/attribute-types#storing-exact-numbers-days-and-times) as a number, so D1 keeps about 15 significant digits of it and rounds the rest: `"1.2345678901234567891"` reads back as `"1.234567890123457"`. Postgres keeps every digit. --- # Enums Source: https://active-record.forestfuture.dev/enums ## At a glance | To | Write | | ----------------------------------- | ------------------------------------------------------------- | | store each name as itself | `status: { enum: ["open", "in_progress", "closed"] }` | | store each name as a value | `priority: { enum: { low: 0, normal: 1, high: 2 } }` | | check a record’s name | `ticket.isOpen()` | | set it and save | `ticket.saveAsClosed()`, `ticket.saveAsClosedOrThrow()` | | find records by name | `Ticket.open()`, `Ticket.notClosed()`, `where({ status: … })` | | read names with their stored values | `Ticket.enumValues("priority")` | | keep two enums’ methods apart | `prefix: true`, `suffix: true` | | report an unknown name as invalid | `validate: true` | | use the names a `CHECK` lists | `state: { enum: true }` | ## The Models The examples use these Models. Their attributes come from their tables through the schema `active-record schema` generates, and each declares its enum in an override: ```ts ticket.ts import { ApplicationRecord } from "./application-record"; export class Ticket extends ApplicationRecord { static override attributes = { status: { enum: ["open", "in_progress", "closed"] }, // stored as the names priority: { enum: { low: 0, normal: 1, high: 2 } }, // stored as 0, 1, and 2 } as const; } ``` ```ts conversation.ts import { ApplicationRecord } from "./application-record"; export class Conversation extends ApplicationRecord { static override attributes = { status: { enum: ["active", "archived"], prefix: true }, // isStatusActive() comments: { enum: ["active", "closed"], suffix: true }, // Conversation.activeComments() } as const; } ``` ```ts survey.ts import { ApplicationRecord } from "./application-record"; export class Survey extends ApplicationRecord { static override attributes = { answer: { enum: ["yes", "no"], validate: true }, // an inclusion error, not a TypeError } as const; } ``` ```ts task.ts import { ApplicationRecord } from "./application-record"; export class Task extends ApplicationRecord { static override attributes = { state: { enum: true } } as const; // the CHECK's names, with methods } ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: 4c1c120c39f8 import { defineSchema, type ScopeStatic, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** conversations — last changed by 0001_create_tables.sql */ export const conversations = { id: { type: "string", null: false, generateId: true }, status: "string", comments: "string", } as const; /** surveys — last changed by 0001_create_tables.sql */ export const surveys = { id: { type: "string", null: false, generateId: true }, answer: "string", } as const; /** tasks — last changed by 0001_create_tables.sql */ export const tasks = { id: { type: "string", null: false, generateId: true }, state: { type: "string", null: false, enum: ["open", "done"], scopes: false, instanceMethods: false }, } as const; /** tickets — last changed by 0001_create_tables.sql */ export const tickets = { id: { type: "string", null: false, generateId: true }, title: { type: "string", null: false }, status: "string", priority: "integer", } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { conversations: { attributes: conversations, primaryKey: "id" }, surveys: { attributes: surveys, primaryKey: "id" }, tasks: { attributes: tasks, primaryKey: "id" }, tickets: { attributes: tickets, primaryKey: "id" }, }, models: { Conversation: "conversations", Survey: "surveys", Task: "tasks", Ticket: "tickets" }, enumScopes: { Conversation: ["statusActive", "notStatusActive", "statusArchived", "notStatusArchived", "activeComments", "notActiveComments", "closedComments", "notClosedComments"], Survey: ["yes", "notYes", "no", "notNo"], Task: ["open", "notOpen", "done", "notDone"], Ticket: ["open", "notOpen", "inProgress", "notInProgress", "closed", "notClosed", "low", "notLow", "normal", "notNormal", "high", "notHigh"], }, }); declare module "../models/conversation" { interface Conversation extends TableAttributes {} namespace Conversation { export const statusActive: ScopeStatic<[]>; export const notStatusActive: ScopeStatic<[]>; export const statusArchived: ScopeStatic<[]>; export const notStatusArchived: ScopeStatic<[]>; export const activeComments: ScopeStatic<[]>; export const notActiveComments: ScopeStatic<[]>; export const closedComments: ScopeStatic<[]>; export const notClosedComments: ScopeStatic<[]>; } } declare module "../models/survey" { interface Survey extends TableAttributes {} namespace Survey { export const yes: ScopeStatic<[]>; export const notYes: ScopeStatic<[]>; export const no: ScopeStatic<[]>; export const notNo: ScopeStatic<[]>; } } declare module "../models/task" { interface Task extends TableAttributes {} namespace Task { export const open: ScopeStatic<[]>; export const notOpen: ScopeStatic<[]>; export const done: ScopeStatic<[]>; export const notDone: ScopeStatic<[]>; } } declare module "../models/ticket" { interface Ticket extends TableAttributes {} namespace Ticket { export const open: ScopeStatic<[]>; export const notOpen: ScopeStatic<[]>; export const inProgress: ScopeStatic<[]>; export const notInProgress: ScopeStatic<[]>; export const closed: ScopeStatic<[]>; export const notClosed: ScopeStatic<[]>; export const low: ScopeStatic<[]>; export const notLow: ScopeStatic<[]>; export const normal: ScopeStatic<[]>; export const notNormal: ScopeStatic<[]>; export const high: ScopeStatic<[]>; export const notHigh: ScopeStatic<[]>; } } ``` ```sql D1 CREATE TABLE tickets ( id TEXT PRIMARY KEY NOT NULL, title TEXT NOT NULL, status TEXT, priority INTEGER ); CREATE TABLE conversations ( id TEXT PRIMARY KEY NOT NULL, status TEXT, comments TEXT ); CREATE TABLE surveys ( id TEXT PRIMARY KEY NOT NULL, answer TEXT ); CREATE TABLE tasks ( id TEXT PRIMARY KEY NOT NULL, state TEXT NOT NULL CHECK (state IN ('open', 'done')) ); ``` ```sql Postgres CREATE TABLE tickets ( id UUID PRIMARY KEY, title TEXT NOT NULL, status TEXT, priority INTEGER ); CREATE TABLE conversations ( id UUID PRIMARY KEY, status TEXT, comments TEXT ); CREATE TABLE surveys ( id UUID PRIMARY KEY, answer TEXT ); CREATE TABLE tasks ( id UUID PRIMARY KEY, state TEXT NOT NULL CHECK (state IN ('open', 'done')) ); ``` ## Declaring enums Declare an enum with `enum` in an override, as `Ticket` does: - The attribute’s type is the union of its names: `"open" | "in_progress" | "closed" | null`. - A list of names stores each name as itself, as text. - An object stores each name as the value you give it, an integer for an `INTEGER` column or text for a `TEXT` one. ## Using an enum’s methods Each name gets a predicate and a setter on records, and two scopes on the Model: ```ts import { Ticket } from "./models/ticket"; const ticket = await Ticket.high().notClosed().first(); if (ticket?.isOpen()) await ticket.saveAsClosed(); const unfinished = await Ticket.where({ status: ["open", "in_progress"] }).count(); ``` | Method | Does | | ------------------------------------------------------- | ------------------------------------------------------------------------ | | `ticket.isOpen()` | Whether `status` is `"open"` | | `ticket.saveAsClosed()`, `ticket.saveAsClosedOrThrow()` | Sets `status` to `"closed"` and saves the record, with its other changes | | `Ticket.open()`, `Ticket.notOpen()` | Scopes of the records whose `status` is, or isn’t, `"open"` | - A name in snake_case reads in camelCase: `in_progress` gives `isInProgress()` and `Ticket.inProgress()`. - `saveAsClosed()` returns `false` when the record is invalid, as `save` does, and `saveAsClosedOrThrow()` throws. - `where`, `whereNot`, `pluck`, and every write take and give names, one or a list. :::note Record methods follow your override as soon as you save it. The scopes are typed in the generated schema, so run `active-record schema` (or keep `--watch` running) after you add an enum. ::: ## Reading stored values Read an enum’s names with their stored values with `enumValues`: ```ts import { Ticket } from "./models/ticket"; const priorities = Ticket.enumValues("priority"); // { low: 0, normal: 1, high: 2 } ``` ## Keeping names apart Add a `prefix` or a `suffix` when two enums share a name, `true` for the attribute’s name or a word of your own, as `Conversation` does: ```ts import { Conversation } from "./models/conversation"; const conversation = await Conversation.activeComments().firstOrThrow(); const live = conversation.isStatusActive(); ``` - A method name that’s taken, by another enum, an attribute, a record method, or a static, throws `InvalidModel` when the Model is first used, and `active-record schema` reports it. - So does a name TypeScript can’t declare, such as `in-progress` or `new`. Map a readable name to the stored value instead: `enum: { inProgress: "in-progress" }`. - To leave an enum’s methods out, declare it with `scopes: false` or `instanceMethods: false`. ## Reading and assigning other values Assigning a value that isn’t one of an enum’s names, or one of its stored values, throws `TypeError`, and a condition with one matches nothing: - A stored value that the enum doesn’t list reads as `null`, so rows written by a newer deploy don’t break an older one. This holds even for an attribute declared `null: false`. - To rename a name without touching stored rows, map the new name to the old value: `enum: { drafted: "draft" }`. Otherwise, migrate the rows in the same deploy. ## Validating names Declare an enum with `validate: true`, as `Survey` does, to report an unknown value as a validation error instead of throwing: ```ts import { Survey } from "./models/survey"; const survey = Survey.build(JSON.parse('{ "answer": "maybe" }')); await survey.save(); // false console.log(survey.errors.fullMessages()); // ["Answer is not included in the list"] ``` A survey with no answer is invalid too, unless you declare `validate: { allowNull: true }`. ## Reading enums from the database `active-record schema` writes the names a database restricts a column to into the generated schema, with the enum’s methods off. A Postgres enum type does it, and so does a `CHECK` such as the `tasks` table’s. Turn the methods on with `enum: true`, as `Task` does: ```ts import { Task } from "./models/task"; const task = await Task.open().firstOrThrow(); await task.saveAsDone(); // task.isDone() is now true ``` - The attribute’s type is `"open" | "done"`, assigning any other value throws `TypeError`, and `enumValues` works as for any enum. - `enum: true` keeps the database’s names, so a name a later migration adds gets its methods the next time you run `active-record schema`. - A `scopes: false` or `instanceMethods: false` beside it still leaves those out, and `scopes: true` or `instanceMethods: true` alone turns on one kind. Names that clash only matter once their methods are on, and you fix them as in [Keeping names apart](#keeping-names-apart). - To keep the column a plain string, override it with `enum: false`. A list of your own, such as `enum: ["open", "done", "archived"]`, replaces the database’s, with its methods on. :::note `active-record schema` reads a `CHECK` whose only condition is `column IN (…)` with text values, or `column IS NULL OR column IN (…)`. Any other `CHECK` leaves the column as it was, and a list of numbers stays an `integer`. Postgres stores a one-name `IN ('open')` as `= 'open'`, so it isn’t read there. ::: > **Compared with Rails** > > Rails declares `enum :status, [:open, :closed]` and stores a list by position. Here a list stores the names, so reordering it changes nothing. `published?` is `isPublished()`, `published!` is `saveAsPublished()` or `saveAsPublishedOrThrow()`, `not_published` is `notPublished()`, and `Post.statuses` is `Post.enumValues("status")`. Two names stored as one value are refused. > **Beyond Rails** > > Rails reads no enums from the database: each one is declared in its Model. Here the database gives an enum its names and its type, and the Model still declares its methods, with `enum: true`. --- # Errors Source: https://active-record.forestfuture.dev/errors ## At a glance | To | Check | | ------------------------------------------ | ----------------------------------------------------------- | | tell Active Record’s errors from any other | `error instanceof ActiveRecordError` | | return a 404 for a missing record | `error instanceof RecordNotFound` | | read why an `OrThrow` save failed | `error instanceof RecordInvalid`, then `error.record` | | catch a duplicate the table refused | `error instanceof RecordNotUnique`, then `error.attributes` | ## The Models The examples use this Model, whose attributes come from its table through the schema `active-record schema` generates: ```ts user.ts import { ApplicationRecord } from "./application-record"; // No uniqueness validation: the table's UNIQUE index refuses a taken email. export class User extends ApplicationRecord {} ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: 29e48056c30c import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** users — last changed by 0001_create_tables.sql */ export const users = { id: { type: "string", null: false, generateId: true }, email: { type: "string", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { users: { attributes: users, primaryKey: "id" }, }, models: { User: "users" }, }); declare module "../models/user" { interface User extends TableAttributes {} } ``` ```sql D1 CREATE TABLE users ( id TEXT PRIMARY KEY NOT NULL, email TEXT NOT NULL ); CREATE UNIQUE INDEX index_users_on_email ON users (email); ``` ```sql Postgres CREATE TABLE users ( id UUID PRIMARY KEY, email TEXT NOT NULL ); CREATE UNIQUE INDEX index_users_on_email ON users (email); ``` ## Checking for Active Record’s errors Every error Active Record throws extends `ActiveRecordError`, so one check separates them from anything else: ```ts import { ActiveRecordError, RecordNotFound } from "@forestfuture/active-record"; import { User } from "./models/user"; export async function showUser(id: string): Promise { try { return Response.json(await User.find(id)); } catch (error) { if (error instanceof RecordNotFound) return new Response("No such user", { status: 404 }); if (error instanceof ActiveRecordError) return new Response(error.message, { status: 400 }); throw error; // not one of Active Record's own } } ``` ## Lifecycle errors | Error | When | | ----------------------- | ------------------------------------------------------------------------ | | `RecordNotFound` | `find`, `sole`, an `OrThrow` finder, or `reload` found nothing | | `SoleRecordExceeded` | `sole` or `findSoleBy` found more than one record | | `RecordInvalid` | an `OrThrow` save found the record invalid; the record is on `.record` | | `RecordNotSaved` | a save was aborted by a callback, or needs an owner that isn’t saved | | `RecordNotDestroyed` | a destroy was aborted, or restricted by `restrictWithError` | | `RecordDestroyed` | writing to a record that’s already destroyed | | `CallbackAbort` | what `abort()` makes; caught by the lifecycle | | `AbortAfterPersistence` | `abort()` in an after-callback, too late to stop the write (`.callback`) | ## Usage errors A usage error means the code needs to change: | Error | When | | ---------------------- | ------------------------------------------------------------------------------- | | `InvalidModel` | a Model’s declaration is wrong, detected the first time it’s used | | `UnknownAttribute` | an attribute that isn’t declared, in `build`, `where`, `update`, … | | `MissingAttribute` | reading an attribute that `select` didn’t load | | `UnknownAssociation` | an association that isn’t declared | | `AssociationNotLoaded` | `loaded()` on an association that wasn’t loaded | | `UnknownModelName` | a polymorphic association’s stored type that names none of the Models it lists | | `IncompatibleRelation` | two Relations or writes can’t be used together (below) | | `IrreversibleOrder` | `last()` on a Relation ordered by an `sql` fragment | | `DeleteRestriction` | destroying an owner whose `restrictWithException` association still has records | | `NoDatabase` | using a record made with `new` rather than `build` | | `NoSession` | `db.bookmark()` on a Database opened without a session | :::note 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. ::: ### When Relations are incompatible `IncompatibleRelation` is thrown for combinations that can’t make a correct query or write: - **`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. - **`batch`, `db.batch`, `save()`, or `destroy()`** with writes or records on two databases, such as a `belongsTo` target built on another `connect()`. A write runs on one database. The message names where each database came from. A batch also refuses a record whose autosave or `dependent` strategies reach an association to [another database](/several-databases#associating-models-on-different-databases). - **`includes`** with `select(...).distinct()`. Preloading needs the keys, and adding them would undo the `distinct`. - **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. - **`updateAll` or `deleteAll`** after `distinct()`: they reject with it, and so does a batch preparing them. ## Constraint errors When the database refuses a write because of a constraint, Active Record throws a subclass of `ConstraintViolation`: | Error | Constraint | | ------------------- | ----------------------- | | `RecordNotUnique` | `UNIQUE`, `PRIMARY KEY` | | `InvalidForeignKey` | `FOREIGN KEY` | | `NotNullViolation` | `NOT NULL` | | `CheckViolation` | `CHECK` | Each has the database’s original error as `cause`, the `table`, and, where the database’s message names them, the `columns` and `attributes`. `User` has no uniqueness validation, so its UNIQUE index refuses a taken email: ```ts import { RecordNotUnique } from "@forestfuture/active-record"; import { User } from "./models/user"; export async function signUp(email: string) { const user = User.build({ email }); try { await user.save(); } catch (error) { if (error instanceof RecordNotUnique && error.attributes.includes("email")) { user.errors.add("email", "has already been taken", { type: "taken" }); } else { throw error; } } return user; } ``` Every method throws them, `save()` as well as `saveOrThrow()`. The record keeps its changes, so you can fix them and save again. --- # Generators Source: https://active-record.forestfuture.dev/generators :::note Each migration is written in your database’s own SQL. [Command line](/command-line#column-syntax) lists the types on D1 and on Postgres, and every option. ::: ## Adding a table Name the Model, and list its columns, with `g model`: ```sh npx active-record g model Product 'name:string!' 'priceCents:integer!=0' user:references ``` ``` Wrote migrations/20261108093000_create_products.sql Wrote src/models/product.ts Wrote src/db/schema.ts (3 tables) from migrations/ Next: npx active-record migrate ``` Then apply the migration to your local database: ```sh npx active-record migrate ``` The table is `products`, with an `id` generated in code, `created_at`, and `updated_at`. - **`--id integer`** gives it a key D1 generates instead. - **`--no-timestamps`** leaves out the timestamps. > **Compared with Rails** > > Keys are UUIDs, not auto-incrementing integers. With `--id integer`, a record and the records built through it no longer save atomically. See [Autosaving](/autosaving#saving-a-graph). Use `--remote` instead of `--local` when you deploy. ## Writing columns Each column is `name:type`, with optional marks: | Column | Means | | ---------------------- | -------------------------------------------------------------------------------- | | `title` | A `string`, the default type | | `email:string!:unique` | Required (`NOT NULL`), with a unique index | | `count:integer!=0` | Required, with a default of `0` | | `settings:json` | JSON, checked by D1 (`CHECK (json_valid(settings))`) | | `user:references` | `user_id`, pointing at `users`, indexed; the Model gets `user = belongsTo(User)` | The [column syntax](/command-line#column-syntax) lists every type. :::note Quote columns that contain `!`, so bash and zsh leave it alone. ::: > **Beyond Rails** > > Rails’ generators have no syntax for a column’s default. Active Record adds `=value` (`=0`, `=true`, `=draft`), because SQLite can’t add a required (`NOT NULL`) column to an existing table without one. ## Changing a table Write a migration with `g migration`. It reads what to do from the migration’s name: ```sh npx active-record g migration AddSlugToPosts slug:string:unique # ADD COLUMN, with a unique index npx active-record g migration RemoveSlugFromPosts slug # DROP COLUMN npx active-record g migration BackfillSlugs # an empty migration to write yourself ``` The name can be written `AddSlugToPosts` or `add_slug_to_posts`. Apply each migration afterwards, as above. 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 `!`. :::warning[A default and a unique index don’t mix on a table with rows] `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. ::: ## Referencing the same table `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: 1. In the migration, point the column at `categories`, and make it optional, since top-level categories have no parent: ```sql parent_id TEXT REFERENCES categories (id), ``` 2. In the Model, use `Category` itself, make it optional too, and add the other direction if you want it. ```ts import { belongsTo, hasMany } from "@forestfuture/active-record"; export class Category extends ApplicationRecord { // foreign key: parentId, from the association's name; optional, since a top-level category has none parent = belongsTo(Category, { optional: true }); children = hasMany(Category, { foreignKey: "parentId" }); // not the default, categoryId } ``` > **Compared with Rails** > > Rails writes `belongs_to :parent, class_name: "Category", optional: true`. Here the association takes the class itself, so there’s no `class_name`. `optional: true` is the same. ## Keeping Models in another folder By default, Models and `application-record.ts` go in `src/models/`. To keep them elsewhere, pass `--models` to every command: ```sh npx active-record schema --models src/app/models npx active-record g model Product 'name:string!' --models src/app/models ``` :::note `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"`. ::: ## Keeping the schema current The generators regenerate `src/db/schema.ts` themselves. After writing or editing a migration by hand, or adding or renaming a Model, regenerate it: ```sh npx active-record schema ``` - **`--watch`** regenerates it whenever a migration or a Model file changes. - **`--check`** fails when the committed schema is out of date. Run it in CI. --- # Getting started Source: https://active-record.forestfuture.dev/getting-started :::warning[Version 0.x] Active Record is before 1.0. Its behavior is tested against real D1, but the API may still change. A breaking change ships in a new minor version, so `^0.7.0` never takes one. ::: ## Prerequisites You’ll need: - **A Worker project** with [Wrangler](https://developers.cloudflare.com/workers/wrangler/). `npm create cloudflare@latest` makes one. - **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: ```jsonc wrangler.jsonc { "d1_databases": [ { "binding": "DB", "database_name": "my-app-db", "database_id": "" }, ], } ``` - **Node.js 22.13 or later**, for the command line. ## Installing Active Record Install Active Record. Its D1 adapter comes with it: ```sh npm install @forestfuture/active-record ``` ## Naming your database Tell Active Record about your database: ```sh npx active-record init ``` It writes `active-record.jsonc`, which names `DB` as a D1 database. Every `active-record` command reads it: ```jsonc active-record.jsonc { "$schema": "./node_modules/@forestfuture/active-record/config-schema.json", "databases": { "DB": { "adapter": "d1", }, }, } ``` ## Generating the Models 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: ```sh npx active-record g model User 'email:string!:unique' 'isActive:boolean!=true' npx active-record g model Post user:references 'title:string!' publishedAt:datetime ``` 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 `!`. The generator writes these files: | File | What it is | | ------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | `migrations/20261108090503_create_users.sql`, `20261108090504_create_posts.sql` | The SQL that creates each table | | `src/db/schema.ts` | Every table’s columns, generated from the migrations. Don’t edit it. | | `src/models/application-record.ts` | Your app’s base class. It’s yours to edit. | | `src/models/user.ts`, `post.ts` | One Model per table | Here’s the migration for posts: ```sql migrations/20261108090504_create_posts.sql CREATE TABLE posts ( id TEXT PRIMARY KEY NOT NULL, user_id TEXT NOT NULL REFERENCES users (id), title TEXT NOT NULL, published_at DATETIME, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL ); CREATE INDEX index_posts_on_user_id ON posts (user_id); ``` > **Compared with Rails** > > 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. ## Creating the tables Apply the migrations to your local database: ```sh npx active-record migrate ``` Use `npx active-record migrate --remote` when you deploy. ## Adding behavior A Model’s attributes come from the generated schema, so a Model only declares behavior. The generated `Post` already belongs to a user: ```ts src/models/post.ts import { belongsTo } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { User } from "./user"; export class Post extends ApplicationRecord { user = belongsTo(User); } ``` The generated `User` is one line. Its table, `users`, comes from its class name: ```ts src/models/user.ts import { ApplicationRecord } from "./application-record"; export class User extends ApplicationRecord {} ``` Give it posts, a scope for active users, and rules for saving: ```ts src/models/user.ts import { hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Post } from "./post"; export class User extends ApplicationRecord { posts = hasMany(Post, { dependent: "destroy" }); // posts.user_id points here static active = this.scope((q) => q.where({ isActive: true })); static { this.validates("email", { presence: true, uniqueness: true }); this.beforeSave((user) => { user.email = user.email.toLowerCase(); }); } } ``` - `user.posts()` finds the user’s posts, and `dependent: "destroy"` destroys them with the user. - `User.active()` finds active users. - `validates` and `beforeSave` run on every save. An invalid user isn’t saved, and `user.errors` says why. ## Using the Models Queries start from the Model. Each Model uses the `DB` binding, so there’s nothing to connect: ```ts src/index.ts import { User } from "./models/user"; export default { async fetch(request: Request): Promise { // GET: the 20 newest active users, each with their posts. if (request.method === "GET") { const users = await User.active() .includes("posts") // loaded in one extra query, not one per user .order({ createdAt: "desc" }) .limit(20) .toArray(); return Response.json(users); } // POST: sign up a user with a first post, saved together. const { email } = await request.json<{ email: string }>(); const user = User.build({ email }); user.posts().build({ title: "Hello, world" }); // save() validates and runs callbacks; false means it wasn't saved, and why is in errors. if (!(await user.save())) { return Response.json({ errors: user.errors.fullMessages() }, { status: 422 }); } return Response.json(user, { status: 201 }); }, } satisfies ExportedHandler; ``` - `includes("posts")` loads every user’s posts in one more query. - A post built with `user.posts().build(…)` is saved with its user, in one atomic batch. - `save()` resolves to `false` when validation fails. ## Trying it Start the Worker: ```sh npx wrangler dev ``` In another terminal, sign up a user, then list the users: ```sh curl -X POST http://localhost:8787 -d '{"email":"Ada@Example.com"}' curl http://localhost:8787 ``` 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"]`. ## Next steps - **[Models](/models):** attributes, types, and overrides. - **[Querying](/querying):** conditions, ordering, scopes, and preloading. - **[Persistence](/persistence):** saving and destroying records. - **[Associations](/associations):** `hasMany`, `belongsTo`, and `hasOne`. - **[Generators](/generators):** every way to write columns. - **[Bulk writes and batches](/batches):** writing several changes at once. - **[D1](/d1):** what’s different on D1, and Sessions for read replicas. - **[Moving to Postgres](/move-to-postgres):** this app on Postgres, with its data. - **[AI agents](/ai-agents):** the guide and its rules, for your coding agent. --- # Joins Source: https://active-record.forestfuture.dev/joins ## At a glance | To | Write | | -------------------------------------- | ---------------------------------------------------- | | find records that have a linked record | `Author.joins("articles")` | | join through several associations | `Author.joins({ articles: "comments" })` | | get each record once | `.distinct()` | | keep records with no linked record | `Author.leftJoins("profile")` | | filter or sort by the joined Model | `Article.joins("author").merge(Author.where({ … }))` | ## The Models The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates: ```ts author.ts import { hasMany, hasOne } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Article } from "./article"; import { Profile } from "./profile"; export class Author extends ApplicationRecord { articles = hasMany(Article); profile = hasOne(Profile); } ``` ```ts profile.ts import { belongsTo } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Author } from "./author"; export class Profile extends ApplicationRecord { author = belongsTo(Author); } ``` ```ts article.ts import { belongsTo, hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Author } from "./author"; import { Comment } from "./comment"; export class Article extends ApplicationRecord { author = belongsTo(Author); comments = hasMany(Comment); } ``` ```ts comment.ts import { belongsTo } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Article } from "./article"; export class Comment extends ApplicationRecord { article = belongsTo(Article); } ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: d6e921e3fa3b import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** articles — last changed by 0001_create_tables.sql */ export const articles = { id: { type: "string", null: false, generateId: true }, authorId: { type: "string", null: false }, title: { type: "string", null: false }, } as const; /** authors — last changed by 0001_create_tables.sql */ export const authors = { id: { type: "string", null: false, generateId: true }, name: { type: "string", null: false }, } as const; /** comments — last changed by 0001_create_tables.sql */ export const comments = { id: { type: "string", null: false, generateId: true }, articleId: { type: "string", null: false }, body: { type: "string", null: false }, } as const; /** profiles — last changed by 0001_create_tables.sql */ export const profiles = { id: { type: "string", null: false, generateId: true }, authorId: { type: "string", null: false }, bio: "string", } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { articles: { attributes: articles, primaryKey: "id" }, authors: { attributes: authors, primaryKey: "id" }, comments: { attributes: comments, primaryKey: "id" }, profiles: { attributes: profiles, primaryKey: "id" }, }, models: { Article: "articles", Author: "authors", Comment: "comments", Profile: "profiles" }, }); declare module "../models/article" { interface Article extends TableAttributes {} } declare module "../models/author" { interface Author extends TableAttributes {} } declare module "../models/comment" { interface Comment extends TableAttributes {} } declare module "../models/profile" { interface Profile extends TableAttributes {} } ``` ```sql D1 CREATE TABLE authors ( id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL ); CREATE TABLE profiles ( id TEXT PRIMARY KEY NOT NULL, author_id TEXT NOT NULL REFERENCES authors (id), bio TEXT ); CREATE TABLE articles ( id TEXT PRIMARY KEY NOT NULL, author_id TEXT NOT NULL REFERENCES authors (id), title TEXT NOT NULL ); CREATE TABLE comments ( id TEXT PRIMARY KEY NOT NULL, article_id TEXT NOT NULL REFERENCES articles (id), body TEXT NOT NULL ); ``` ```sql Postgres CREATE TABLE authors ( id UUID PRIMARY KEY, name TEXT NOT NULL ); CREATE TABLE profiles ( id UUID PRIMARY KEY, author_id UUID NOT NULL REFERENCES authors (id), bio TEXT ); CREATE TABLE articles ( id UUID PRIMARY KEY, author_id UUID NOT NULL REFERENCES authors (id), title TEXT NOT NULL ); CREATE TABLE comments ( id UUID PRIMARY KEY, article_id UUID NOT NULL REFERENCES articles (id), body TEXT NOT NULL ); ``` ## Joining associations `joins` finds the records that have a linked record, through an association or nested ones: ```ts import { Author } from "./models/author"; const commented = await Author.joins({ articles: "comments" }).distinct().toArray(); ``` - A record comes back once for each linked record, so an author with three commented articles appears three times. `distinct()` gets each record once. - A joined query loads only its own Model’s columns, and every Relation method works on it. `count()` counts the rows `toArray()` returns, and `updateAll` and `deleteAll` write the records the join finds. - The association’s `scope` and the joined Model’s default scope are part of the join. So joining an association scoped to published articles finds only authors with a published article. ## Keeping records without a link `leftJoins` joins the same way, but keeps the records that have no linked record: ```ts import { Author } from "./models/author"; const everyAuthor = await Author.leftJoins("profile").toArray(); // with a profile or not ``` ## Filtering by a joined Model Merge a Relation of the joined Model to filter or sort by its attributes: ```ts import { Article } from "./models/article"; import { Author } from "./models/author"; const byJane = await Article.joins("author") .merge(Author.where({ name: "Jane" })) .toArray(); const byAuthorName = await Article.joins("author") .merge(Author.order({ name: "asc" })) .toArray(); ``` Its conditions, its scopes, and its order apply to the joined table. As with any `merge`, the joined Model’s order replaces the receiver’s. :::note The merged Relation can only add conditions and an order. A `limit`, `offset`, `select`, `distinct()`, `includes`, or `joins` of its own throws `IncompatibleRelation`. Merging a Model the query doesn’t join, or joins more than once, throws it too. So does `distinct()` on a query ordered by a joined Model. ::: ## Joining what can’t be joined Some associations can’t be joined, and joining one throws `IncompatibleRelation` when you write the query: - **A Model on another database.** A join reads one database. - **A polymorphic `belongsTo`**, since its records may be in several tables. Join the `as:` association of each Model instead, such as `Photo.joins("likes")`. - **An association through another.** Merge a Relation of the joined Model instead, and preload with `includes`. > **Compared with Rails** > > - Rails builds the SQL for a merged Model the query doesn’t join, and the database rejects it when the query runs. Active Record throws `IncompatibleRelation` when you write it. > - Rails applies a merged Relation’s `limit` to the whole query. Active Record refuses it. > - Rails leaves `distinct` with an order on a joined table to the database, which Postgres refuses and SQLite runs. Active Record throws `IncompatibleRelation` on both. > - With a `hasMany` join, Rails’ `find(1, 2)` counts the duplicate rows and raises `RecordNotFound`. Active Record returns each record once. > - With a `hasMany` join, Rails’ `destroy_all` destroys a record once for each of its rows, running its callbacks each time. Active Record destroys each record once. > - Rails’ `where(author: { name: "Jane" })`, `where.missing`, `eager_load`, and joins through another association aren’t here yet. --- # Logging Source: https://active-record.forestfuture.dev/logging ## At a glance | To | Write | | -------------------------------------- | ------------------------------------------------------------------------ | | log every query, app-wide | `static override onQuery` on `ApplicationRecord` | | log one request’s queries, with its ID | `withDatabase(connect(env.DB, { onQuery }), …)` | | send the database time to the browser | add up `durationMs` into a `Server-Timing` header | | keep more attributes out of the logs | `static override filterAttributes = [...Model.filterAttributes, "iban"]` | ## The Models The examples use this Model, whose attributes come from its table through the schema `active-record schema` generates, and the app’s Worker: ```ts user.ts import { ApplicationRecord } from "./application-record"; export class User extends ApplicationRecord {} ``` ```ts application-record.ts import { Model, type QueryListener } from "@forestfuture/active-record"; import { schema } from "../db/schema"; export abstract class ApplicationRecord extends Model { static override schema = schema; // Every query, from every Model, whichever database runs it. static override onQuery: QueryListener = ({ model, sql, durationMs, error }) => { console.log(`${model} ${durationMs.toFixed(1)}ms ${sql}`, error ?? ""); }; // The defaults, plus an IBAN and a date of birth. static override filterAttributes = [...Model.filterAttributes, "iban", /^dateOfBirth$/]; } ``` ```ts app.ts import { User } from "./models/user"; // The app's Worker: here, one route that finds a user by email. export const app = { async fetch(request) { const email = new URL(request.url).searchParams.get("email") ?? ""; const user = await User.findByOrThrow({ email }); return Response.json({ id: user.id }); }, } satisfies ExportedHandler; ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: cf0bc7e86bda import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** users — last changed by 0001_create_tables.sql */ export const users = { id: { type: "string", null: false, generateId: true }, email: { type: "string", null: false }, iban: "string", dateOfBirth: "string", } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { users: { attributes: users, primaryKey: "id" }, }, models: { User: "users" }, }); declare module "../models/user" { interface User extends TableAttributes {} } ``` ```sql D1 CREATE TABLE users ( id TEXT PRIMARY KEY NOT NULL, email TEXT NOT NULL, iban TEXT, date_of_birth TEXT ); ``` ```sql Postgres CREATE TABLE users ( id UUID PRIMARY KEY, email TEXT NOT NULL, iban TEXT, date_of_birth TEXT ); ``` ## Receiving each query An `onQuery` listener is called once for every statement, writes and batches included, with: | Field | | | --------------- | ------------------------------------------------------------------- | | `model` | The Model’s class name, such as `"Product"` | | `sql`, `params` | The statement and its bound values | | `durationMs` | How long it took; in a D1 batch, D1’s own timing for each statement | | `meta` | The database’s result metadata, such as D1’s rows read and written | | `error` | The database’s error, when it failed | 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. Set a listener in one of two places: | | Where | Knows the request? | | ------------------------- | ----------------------------------------------------- | ------------------ | | **Every query, app-wide** | `static override onQuery` on your app’s base class | No | | **One request’s queries** | `connect(env.DB, { onQuery })`, run in `withDatabase` | Yes | If both are set, the request’s listener runs first, then the base class’s. ## Logging every query Set `onQuery` on your app’s base class, in `application-record.ts`, to see every statement of every Model: ```ts import { Model, type QueryListener } from "@forestfuture/active-record"; import { schema } from "../db/schema"; export abstract class ApplicationRecord extends Model { static override schema = schema; // Every query, from every Model, whichever database runs it. static override onQuery: QueryListener = ({ model, sql, durationMs, error }) => { console.log(`${model} ${durationMs.toFixed(1)}ms ${sql}`, error ?? ""); }; // The defaults, plus an IBAN and a date of birth. static override filterAttributes = [...Model.filterAttributes, "iban", /^dateOfBirth$/]; } ``` It can’t tell requests apart. A Model can set its own `static override onQuery`, which replaces the base class’s for that Model. ## Logging one request’s queries To group a request’s queries, open its database with a listener that knows the request, and run the request inside `withDatabase`: ```ts import { withDatabase } from "@forestfuture/active-record"; import { connect } from "@forestfuture/active-record/d1"; import { app } from "./app"; // src/worker.ts: one request's queries, tagged with its ID, as JSON lines for Workers Logs. export const worker = { fetch(request, env) { const requestId = request.headers.get("cf-ray") ?? crypto.randomUUID(); const db = connect(env.DB, { onQuery: ({ model, sql, params, durationMs, error }) => console.log( JSON.stringify({ requestId, model, ms: Math.round(durationMs), sql, params, // a filtered attribute's value is "[FILTERED]" error: error instanceof Error ? error.message : undefined, }), ), }); // Every query from a Model inside (User.findBy, user.save(), …) goes through db. return withDatabase(db, () => app.fetch(request)); }, } satisfies ExportedHandler; ``` 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. :::note `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"]`. ::: ## Logging only in development Check a variable that only `.dev.vars` sets, such as `LOG_SQL=1`. For one request’s listener: ```ts import { type QueryListener, withDatabase } from "@forestfuture/active-record"; import { connect } from "@forestfuture/active-record/d1"; import { app } from "./app"; // src/worker.ts, with LOG_SQL=1 in .dev.vars: logging in development only, nothing in production. export const development = { fetch(request, env) { const onQuery: QueryListener | undefined = env.LOG_SQL ? ({ model, sql, durationMs }) => console.log(`${model} ${durationMs.toFixed(1)}ms ${sql}`) : undefined; return withDatabase(connect(env.DB, { onQuery }), () => app.fetch(request)); }, } satisfies ExportedHandler; ``` The app-wide listener reads the variable from `cloudflare:workers` when a query runs: ```ts import { Model, type QueryListener } from "@forestfuture/active-record"; import { env } from "cloudflare:workers"; import { schema } from "./db/schema"; // src/models/application-record.ts: logs only when LOG_SQL is set (in .dev.vars), read when a query runs. export abstract class ApplicationRecord extends Model { static override schema = schema; static override onQuery: QueryListener = ({ model, sql, durationMs }) => { if ((env as { LOG_SQL?: string }).LOG_SQL) { console.log(`${model} ${durationMs.toFixed(1)}ms ${sql}`); } }; } ``` ## Timing queries in the browser To see a request’s database time in the browser’s developer tools, add it up, and send it as a `Server-Timing` header: ```ts import { withDatabase } from "@forestfuture/active-record"; import { connect } from "@forestfuture/active-record/d1"; import { app } from "./app"; // src/worker.ts: the request's database time, under its Timing in the browser's developer tools. export const timed = { async fetch(request, env) { let queries = 0; let total = 0; const db = connect(env.DB, { onQuery({ durationMs }) { queries += 1; total += durationMs; }, }); const response = await withDatabase(db, () => app.fetch(request)); response.headers.append( "server-timing", `db;dur=${total.toFixed(1)};desc="${queries} queries"`, ); return response; }, } satisfies ExportedHandler; ``` ## Keeping secrets out of the logs Listeners see the values of passwords, tokens, keys, and emails as `"[FILTERED]"`, while the database still gets the real values. [Serialization](/serialization#filtering-attributes) lists the attributes filtered by default, and everywhere their values are hidden. ### Filtering more attributes Name them on your app’s base class, spreading in the defaults, as `ApplicationRecord` does with `iban` and `dateOfBirth`. A string matches any attribute whose snake_case name contains it, so `"iban"` also covers `ibanNumber`. A string can be in camelCase or snake_case: `"ibanNumber"` and `"iban_number"` both match `ibanNumber`. Use a RegExp to match one name exactly. ### Seeing a filtered attribute To see one while debugging, leave it out of the list in development: ```ts import { Model } from "@forestfuture/active-record"; import { schema } from "../db/schema"; export abstract class ApplicationRecord extends Model { static override schema = schema; static override filterAttributes = Model.filterAttributes.filter((entry) => entry !== "email"); } ``` ### Filtering `sql` fragments 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. > **Compared with Rails** > > Rails filters by its app-wide `filter_parameters`, against parameter and column names. Active Record keeps the list on the Model (`static filterAttributes`, inherited from your base class), and matches each entry against the attribute’s snake_case name, so `"_key"` filters `apiKey`. A RegExp may match either form. It also hides filtered values in cast errors and in `RecordNotFound`, which Rails’ filter doesn’t cover. --- # Models Source: https://active-record.forestfuture.dev/models ## At a glance | To | Write | | ------------------------------------ | --------------------------------------------------------------- | | define a Model | `class Product extends ApplicationRecord {}` | | read a column as another type | `static override attributes = { archived: "boolean" } as const` | | ignore a column | `static override attributes = { legacyNotes: false } as const` | | add an attribute that isn’t a column | `termsOfService: { type: "boolean", virtual: true }` | | normalize a value as it’s assigned | `this.normalizes("email", { with: (email) => email.trim() })` | | give an attribute another name | `title: { aliasOf: "name" }` | | type an attribute more narrowly | `declare status: "draft" \| "published"` | | use another table name | `static override table = "billing_accounts"` | | declare attributes for a view | `class ProductCount extends ApplicationRecord.define({ … }) {}` | | build a record without saving it | `Product.build({ name: "Lamp" })`, never `new Product()` | | take only some fields from a request | `Product.permit(await request.json(), "name", "metadata")` | | Prop | Type | Default | Description | | - | - | - | - | | `with` | `(value) => value` | - | The function `normalizes` runs. It takes a value already cast to the attribute’s type, and returns the one to keep. | | `applyToNull?` | `boolean` | `false` | Hands `null` to `normalizes`’s `with` too. By default, `null` is kept as it is. | Each part of a Model has a page of its own: | To | See | | ------------------------------------------ | ------------------------------------ | | learn each type, and how values are cast | [Attribute types](/attribute-types) | | give an attribute a fixed set of names | [Enums](/enums) | | see what changed before and after a save | [Change tracking](/change-tracking) | | send records as JSON, and keep secrets out | [Serialization](/serialization) | | check records before they’re saved | [Validations](/validations) | | run code as records are saved | [Callbacks](/callbacks) | | share behavior across every Model | [Shared behavior](/shared-behavior) | ## The Models The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates: ```ts product.ts import { ApplicationRecord } from "./application-record"; export class Product extends ApplicationRecord { static override attributes = { archived: { type: "boolean", default: () => false }, // 0 or 1 in a plain INTEGER column metadata: "json", // JSON in a plain TEXT column legacyNotes: false, // a column this app no longer uses: never read or written publicId: { generateId: true }, // generated in code, as a TEXT key is title: { aliasOf: "name" }, // another name for name, in queries too } as const; declare status: "draft" | "published"; // narrower than the column's string } ``` ```ts featured-product.ts import { Product } from "./product"; export class FeaturedProduct extends Product {} // shares products, and Product's declarations ``` ```ts account.ts import { ApplicationRecord } from "./application-record"; export class Account extends ApplicationRecord { static override table = "billing_accounts"; // in place of accounts static override attributes = { termsOfService: { type: "boolean", virtual: true }, // a form's checkbox, never a column } as const; static { this.normalizes("email", { with: (email) => email.trim().toLowerCase() }); } } ``` ```ts product-count.ts import { ApplicationRecord } from "./application-record"; // A view, which migrations don't describe, so the Model declares its attributes itself: export class ProductCount extends ApplicationRecord.define({ status: { type: "string", null: false }, total: { type: "integer", null: false }, }) { static override table = "product_counts"; static override primaryKey = "status"; } ``` ```ts application-record.ts import { Model } from "@forestfuture/active-record"; import { schema } from "../db/schema"; export abstract class ApplicationRecord extends Model { static override schema = schema; } ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: e02b5fa3d693 import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** billing_accounts — last changed by 0001_create_tables.sql */ export const billingAccounts = { id: { type: "string", null: false, generateId: true }, email: { type: "string", null: false }, } as const; /** products — last changed by 0001_create_tables.sql */ export const products = { id: { type: "string", null: false, generateId: true }, publicId: "string", name: { type: "string", null: false }, status: { type: "string", null: false, default: () => "draft" }, archived: { type: "integer", null: false, default: () => 0 }, metadata: "string", legacyNotes: "string", createdAt: { type: "datetime", null: false }, updatedAt: { type: "datetime", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { billing_accounts: { attributes: billingAccounts, primaryKey: "id" }, products: { attributes: products, primaryKey: "id" }, }, models: { Account: "billing_accounts", Product: "products" }, }); declare module "../models/account" { interface Account extends TableAttributes {} } declare module "../models/product" { interface Product extends TableAttributes {} } ``` ```sql D1 CREATE TABLE products ( id TEXT PRIMARY KEY NOT NULL, public_id TEXT, name TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'draft', archived INTEGER NOT NULL DEFAULT 0, metadata TEXT, legacy_notes TEXT, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL ); CREATE TABLE billing_accounts ( id TEXT PRIMARY KEY NOT NULL, email TEXT NOT NULL ); CREATE VIEW product_counts AS SELECT status, COUNT(*) AS total FROM products GROUP BY status; ``` ```sql Postgres CREATE TABLE products ( id UUID PRIMARY KEY, public_id TEXT, name TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'draft', archived INTEGER NOT NULL DEFAULT 0, metadata TEXT, legacy_notes TEXT, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL ); CREATE TABLE billing_accounts ( id UUID PRIMARY KEY, email TEXT NOT NULL ); CREATE VIEW product_counts AS SELECT status, COUNT(*)::integer AS total FROM products GROUP BY status; ``` ## Defining Models Define each Model by extending `ApplicationRecord`, as `Account` does: - **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`. - **[`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. - **The first time it runs, it writes `src/models/application-record.ts`.** It’s an ordinary class, and yours to edit. The schema it holds gives each Model its attributes and the binding its queries use. Methods, callbacks, and scopes you write on it are every Model’s; see [Shared behavior](/shared-behavior). It has no table of its own, so you can’t query it. - **A subclass shares its parent’s table,** as `FeaturedProduct` does, and 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. - **You can still set `static primaryKey`,** as long as it names an attribute. ## Overriding attributes Override an attribute in `static attributes` when a column holds something its type doesn’t say, as `Product` does with a boolean in a plain `INTEGER`. Write the object `as const`, so TypeScript keeps each type name. An override is one of these: | Override | Does | | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------- | | `"boolean"` (a type name) | Reads and writes the attribute as that type | | `money` (a [custom type](/custom-types)) | Reads and writes the attribute as that type | | `{ type?, null?, default?, generateId? }` | Replaces those parts of the generated attribute; `null: false` makes it non-null in TypeScript | | `{ enum, prefix?, suffix?, … }` | Makes the attribute an [enum](/enums), of its column’s type | | `{ enum: true }`, `{ enum: false }` | Turns on the methods of an [enum read from the database](/enums#reading-enums-from-the-database), or drops it | | `false` | Ignores the column: it’s never typed, read, or written, and queries name their columns instead of `*` | - **Changing a `type`** drops the generated default or `generateId`, so the column’s own default applies unless you give one. `archived` gives one, so a new product reads `false` before it’s saved. - **A `default` and `generateId`** replace each other, so an attribute has one or the other. `generateId` is only for strings. - **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. - **Ignoring a `NOT NULL` column** without a default makes inserts fail, so give it a default in a migration first. - **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. ## Adding virtual attributes Add `virtual: true` for a value a form sends but the table doesn’t keep, as `Account` does with `termsOfService`: ```ts import { Account } from "./models/account"; const form = { email: "jane@example.com", termsOfService: "1" }; const permitted = Account.permit(form, "email", "termsOfService"); const account = Account.build(permitted); console.log(account.termsOfService); // true, cast from the form's "1" await account.save(); // inserts the email alone ``` - **It’s typed and cast** like a column’s attribute. `permit` takes it, and its changes are tracked. - **It’s never saved.** An insert or an update leaves it out. A save that changes only virtual attributes sets `updatedAt` alone, or writes nothing on a table without timestamps. - **A loaded record starts it at its default,** or `null`, and so does `reload`. - **A query can’t name it,** since there’s no column to match. `where`, `order`, `select`, `pluck`, `insert`, and `updateAll` throw `UnknownAttribute`. - **It’s in `toJSON()`,** unless a [`confirmation`](/validations#confirming-a-value) rule reads it. A record keeps it after a create, so list a secret one in [`hiddenAttributes`](/serialization), or `Response.json(user)` sends it back. For a password, declare a [secure password](/passwords-and-tokens) instead, which `toJSON()` leaves out. :::note A virtual attribute named for one of the table’s columns throws `InvalidModel`, and so does `virtual` with `column` or `enum`. With `null: false`, give it a `default`. A Model declared with `define` takes `virtual: true` in the same way. ::: ## Normalizing attributes Declare a normalization in `static {}` to change each value assigned to an attribute into one form, as `Account` does with `email`: ```ts import { Account } from "./models/account"; const account = await Account.create({ email: " Jane@Example.COM " }); console.log(account.email); // "jane@example.com" const found = await Account.findBy({ email: "JANE@example.com" }); // the same account console.log(Account.normalizeValueFor("email", " Sam@Example.com")); // "sam@example.com" ``` - **It runs whenever a value is assigned.** That covers the setter, `build`, `create`, `update`, a default, and bulk writes such as `insert`, `upsert`, and `updateAll`. Several normalizations of one attribute run in order, a parent class’s first. - **Queries normalize their values too.** `where`, `findBy`, `find`, lists, comparisons, and `column()` values in an `sql` fragment match what was stored. Plain values in an `sql` fragment are left as they are, and `where({ email: null })` still matches `NULL`. - **`Account.normalizeValueFor("email", value)`** returns a value as assigning it would keep it. :::warning[Rows saved before stay as they were] A record loaded from the database keeps its stored value, and a query for that value no longer finds it, since the query is normalized. The same goes for a default scope’s conditions. Normalize each old row, and save it: ```ts import { Account } from "./models/account"; for await (const account of Account.findEach()) { account.normalizeAttribute("email"); await account.save(); // writes only the accounts whose email changed } ``` An `UPDATE` in a migration does the same for a large table. ::: ## Aliasing attributes Add `aliasOf` to give an attribute a second name, as `Product` does with `title` for `name`: ```ts import { Product } from "./models/product"; const lamp = await Product.create({ title: "Lamp" }); // writes name console.log(lamp.name); // "Lamp" const titles = await Product.where({ title: "Lamp" }).pluck("title"); console.log(titles); // ["Lamp"] lamp.title = "Desk lamp"; console.log(lamp.changes()); // { name: ["Lamp", "Desk lamp"] } ``` - **It reads and writes the attribute it names,** typed as that attribute. - **Queries and writes take either name:** `where`, `order`, `pluck`, `select`, `group`, the calculations, `build`, `create`, `permit`, `insert`, `upsert`, and `updateAll`. - **The record holds the value once,** under the attribute’s name. `attributes()`, `toJSON()`, and `changes()` list `name`, and so does a record `select("title")` loads. `attributeWas("title")` and the other methods that take a name read it through the alias. - **A row that gives both `title` and `name`** throws `TypeError`, since they’re one column. - **`validates("title", …)` reads through the alias,** and its errors go under `title`. :::note An alias of a name that isn’t an attribute throws `InvalidModel`, and so does one named for an attribute, an alias of another alias, or `aliasOf` with any other key. Settings that name an attribute, such as an association’s `foreignKey` or `hiddenAttributes`, take its own name. `filterAttributes` matches an alias too, so naming either one filters the attribute’s values. A Model declared with `define` takes `aliasOf` in the same way. ::: > **Compared with Rails** > > Rails declares an alias with `alias_attribute :title, :name`. Here it goes with the attributes, so it’s typed from the same place. Rails’ `select(:title)` loads the column as `title`; here it loads it as `name`, which `title` reads. Rails follows an alias of an alias; here, name the attribute. ## Narrowing types Declare an attribute in the class to give it a narrower type than its column’s, as `Product` does with `status`: - `product.status` is 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 the database. To have the values checked, and get a method for each, declare an [enum](/enums) instead. ## Declaring attributes yourself Declare the attributes with `define` for a view, or a table your migrations don’t make, as `ProductCount` does: ```ts import { ProductCount } from "./models/product-count"; const counts = await ProductCount.order({ status: "asc" }).toArray(); // [ProductCount { status: "draft", total: 1 }, ProductCount { status: "published", total: 2 }] ``` - TypeScript infers the record’s properties from the object. - An attribute is a type name, or `{ type, column?, null?, default? }`. - Calling `define` on `ApplicationRecord` shares your base class’s behavior and binding. ## Naming Models A Model’s name is its class name, read with `modelName`: ```ts import { Account } from "./models/account"; import { FeaturedProduct } from "./models/featured-product"; console.log(FeaturedProduct.modelName); // "FeaturedProduct" const published = await FeaturedProduct.where({ status: "published" }).toArray(); // from products const account = await Account.create({ email: "jane@example.com" }); // into billing_accounts ``` - The [generated schema](/schema) lists the Model by its name, and its table name, its foreign keys, and its error messages are made from it. - If your bundler renames classes, set `static override modelName = "BlogPost"`, so the Model keeps its name once bundled. Without it, a bundler that renames `User` to `e` makes the first query throw `InvalidModel`, because no Model named `e` is in the generated schema. Wrangler keeps class names by default, even when minifying. - A subclass inherits a `modelName` its parent sets. Otherwise, each class has its own: `FeaturedProduct.modelName` is `"FeaturedProduct"`, though it shares `Product`’s table. ## Naming tables A Model takes its table name from its name, snake_case and pluralized, unless it sets `static table`, as `Account` does: | Class | Table | | ---------- | ------------ | | `User` | `users` | | `BlogPost` | `blog_posts` | | `Category` | `categories` | | `Person` | `people` | | `Sheep` | `sheep` | A class with no name to take one from must set `static table`. :::note 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. ::: ## Mapping columns Attributes are camelCase, and map to snake_case columns: | Attribute | Column | | ------------------- | --------------------- | | `createdAt` | `created_at` | | `externalAccountId` | `external_account_id` | | `htmlURL` | `html_url` | | `userID` | `user_id` | | `sha256Hash` | `sha256_hash` | To map an attribute to a column with another name, give it `{ column: "..." }`. Conditions, ordering, and association keys always name attributes; only [SQL fragments](/conditions#writing-sql-fragments) name columns. ## Building records Build a record without touching the database with `build`: ```ts import { Product } from "./models/product"; const lamp = Product.build({ name: "Lamp" }); console.log(lamp.id); // generated already, before saving: "3b241101-…" console.log(lamp.status); // "draft", the column's default console.log(lamp.archived); // false, read as a boolean console.log(lamp.createdAt); // null until it's saved lamp.assign({ status: "published", metadata: { color: "red" } }); await lamp.save(); // sets createdAt and updatedAt ``` - **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. - **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 the database stored. - **Unknown attributes** throw `UnknownAttribute`, and `undefined` throws `TypeError`. Use `null` to store NULL. - `assign(attrs)` sets several attributes without saving. `update(attrs)` assigns, then saves. :::note A record keeps the database it was built or loaded through, for its later saves and association loads. A record made with `new Product()` has none, so build records with `Product.build(…)`. ::: ## Permitting fields Keep only the attributes you name from untrusted input with `permit`, whose result goes straight into `build`, `create`, or `update`: ```ts import { Product } from "./models/product"; export async function createProduct(request: Request) { const permitted = Product.permit(await request.json(), "name", "metadata"); return Product.create(permitted); // any other key in the body is dropped } ``` It casts each value as assigning would, and reads three kinds of input: | Input | Read | | ----------------- | ---------------------------------------------------------------- | | a plain object | its own keys only, so `__proto__` and inherited keys never count | | `FormData` | each field; a repeated key takes its last value | | `URLSearchParams` | each parameter; a repeated key takes its last value | - **Keys you don’t name** are dropped. A named attribute the input doesn’t have is left out, and a `null` is kept. - **A name that isn’t an attribute** is a compile error, and throws `UnknownAttribute`. - **`TypeError`** is thrown for a value that can’t be cast, a file from a form (read a file’s bytes for a [`binary` attribute](/attribute-types#storing-bytes)), and any other input: an array, a `Map`, `Headers`, a class instance, `null`, or a string. [Untrusted input](/untrusted-input) shows `permit` in a Worker. ## Generating ids A `TEXT` or `UUID` primary key gets its value from the Model’s `generateId` when you don’t give one. By default, that’s a UUID: - To use another kind of id across your app, override it on your app’s base class: `static override generateId = () => uuidv7()`. It gets the attribute’s name, so it can prefix ids: `` `${attribute}_${uuidv7()}` ``. - To generate another string attribute the same way, turn it on with an override, as `Product` does with `publicId: { generateId: true }`. - 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. ## Using timestamps 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. ## Checking declarations A Model’s declaration is checked the first time it’s used, by its first query or `db.model(X)`, and it throws `InvalidModel` for: - A Model `active-record schema` hasn’t seen, or whose table has changed since. Run it again. - No table name: an empty `table`, or a class with no name to infer one from. - A `modelName` that isn’t a string. - An override of an attribute the table doesn’t have. - A `primaryKey` that isn’t an attribute. - An attribute named like a record method, such as `save` or `attributes`. - A class field that hides an attribute, such as `email!: string` in the class body. - A normalization of a name that isn’t one of the Model’s attributes. After that, a Model’s declarations are fixed, so request code can’t change them. > **Compared with Rails** > > `modelName` is a string, where Rails’ `model_name` is an object. > > `normalizes` takes one attribute, where Rails’ takes several. Its result is cast to the attribute’s type again, which Rails doesn’t do. Rails also normalizes an association’s link to its owner. Here the link is the owner’s key as it is, so normalizing a foreign key can’t bring another owner’s records into `author.posts()`. > **Beyond Rails** > > 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). --- # Moving to Postgres Source: https://active-record.forestfuture.dev/move-to-postgres ## Planning the move The examples move the app from [Getting started](/getting-started). | What changes | How | | --------------------- | -------------------------------------------------------- | | Packages | Add `pg`, and PGlite for reading your schema. | | `active-record.jsonc` | It names your Postgres database in place of the D1 one. | | `migrations/` | Rewritten in Postgres’s types, with the same file names. | | `src/db/schema.ts` | Regenerated, so it names the PostgreSQL adapter. | | Your Wrangler config | A Hyperdrive binding in place of the D1 one. | | Your data | Copied from D1 to Postgres. | You’ll need `sqlite3` and `psql` on your machine to copy the data. ## Installing pg The PostgreSQL adapter comes with `@forestfuture/active-record`. Install `pg`, which it connects with, and PGlite, which `active-record schema` reads your schema with: ```sh npm install pg npm install --save-dev @electric-sql/pglite ``` ## Declaring the database Replace the D1 database in your `active-record.jsonc` with your Postgres one: ```jsonc active-record.jsonc { "$schema": "./node_modules/@forestfuture/active-record/config-schema.json", "databases": { "HYPERDRIVE": { "adapter": "postgresql", "url": "postgres://user:password@localhost:5432/my_app", "remoteUrl": "${PRODUCTION_DATABASE_URL}", }, }, } ``` `HYPERDRIVE` is the binding your Worker will reach Postgres through. `url` is your local database, and `remoteUrl` your real one, read here from the environment. Every `active-record` command now works on Postgres. See [Declaring your databases](/command-line#declaring-your-databases). :::note Hyperdrive needs a password in a local connection string, even for a server that asks for none. ::: ## Rewriting the migrations Rewrite each migration in Postgres’s types, and keep its file name. Here are the app’s users: ```sql migrations/20261108090503_create_users.sql CREATE TABLE users ( id UUID PRIMARY KEY, email TEXT NOT NULL, is_active BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL ); CREATE UNIQUE INDEX index_users_on_email ON users (email); ``` And its posts: ```sql migrations/20261108090504_create_posts.sql CREATE TABLE posts ( id UUID PRIMARY KEY, user_id UUID NOT NULL REFERENCES users (id), title TEXT NOT NULL, published_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL ); CREATE INDEX index_posts_on_user_id ON posts (user_id); ``` These are the files `g model` writes on Postgres for the same commands. Change each type this way: | On D1 | On Postgres | | ----------------------------------- | -------------------------------------------------------- | | `id TEXT PRIMARY KEY`, made in code | `id UUID PRIMARY KEY` | | `id INTEGER PRIMARY KEY` | `id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY` | | `INTEGER` | `BIGINT` | | `REAL` | `DOUBLE PRECISION` | | `DATETIME` | `TIMESTAMPTZ` | | `BOOLEAN`, `TEXT` | The same | | `TEXT` holding JSON | `JSONB` | If your `generateId` makes keys that aren’t UUIDs, keep those keys `TEXT`, and their foreign keys too. A datetime kept as a Unix time has a `storage` override. It can stay `BIGINT`, and keep the override. To store it as `TIMESTAMPTZ` instead, add a migration that converts it after you copy the data. Then remove the override from your Model: ```sql ALTER TABLE payments ALTER COLUMN paid_at TYPE TIMESTAMPTZ USING to_timestamp(paid_at); ``` For milliseconds, convert `to_timestamp(paid_at / 1000.0)`. Then create the tables in your local database: ```sh npx active-record migrate ``` ## Regenerating the schema Regenerate your schema from the new migrations: ```sh npx active-record schema ``` Its attributes come out the same as on D1. Only its adapter changes: ```ts src/db/schema.ts import { defineSchema } from "@forestfuture/active-record"; import { postgresql } from "@forestfuture/active-record/postgresql"; export const schema = defineSchema({ adapter: postgresql({ binding: "HYPERDRIVE" }), // … }); ``` ## Copying the data Copy your rows with this script. It exports your D1 database through Wrangler, writes each table as CSV with `sqlite3`, and loads them into Postgres with `psql`, all in one transaction: ```sh copy-data.sh #!/bin/sh # Copies rows from the D1 database bound as DB to the Postgres database DATABASE_URL names. # # DATABASE_URL=postgres://… sh copy-data.sh --remote users posts # # Name each table after the tables its foreign keys point at. Use --local for your local D1. set -eu fail() { echo "copy-data.sh: $1" >&2 exit 1 } d1=$1 # --remote or --local shift # Names go into SQL, so each must be letters, digits and underscores. for table in "$@"; do case $table in "" | [0-9]* | *[!A-Za-z0-9_]*) fail "can't copy a table named '$table'" ;; esac done work=$(mktemp -d) trap 'rm -rf "$work"' EXIT # dash runs no EXIT trap on Ctrl-C, so exit first, and the copies of your data go too. trap 'exit 1' INT TERM HUP # D1's tables and rows, as SQL, loaded into a SQLite file of your own. npx wrangler d1 export DB "$d1" --output "$work/d1.sql" sqlite3 "$work/d1.db" < "$work/d1.sql" # Each table as CSV. sqlite3 quotes empty text and leaves NULL unquoted, as Postgres reads them. for table in "$@"; do info="FROM pragma_table_info('$table')" odd=$(sqlite3 "$work/d1.db" "SELECT count(*) $info WHERE name GLOB '[0-9]*' OR name GLOB '*[^A-Za-z0-9_]*'") [ "$odd" = 0 ] || fail "$table has a column whose name isn't letters, digits and underscores" columns=$(sqlite3 "$work/d1.db" "SELECT group_concat('\"' || name || '\"', ', ') $info") [ -n "$columns" ] || fail "D1 has no table named $table" sqlite3 -csv -header "$work/d1.db" "SELECT $columns FROM \"$table\"" > "$work/$table.csv" # Postgres folds an unquoted migration's names to lowercase, so they're named that way here. pg_table=$(printf '%s' "$table" | tr '[:upper:]' '[:lower:]') pg_columns=$(printf '%s' "$columns" | tr '[:upper:]' '[:lower:]') printf '%s\n' "\\copy \"$pg_table\" ($pg_columns) FROM '$work/$table.csv' WITH (FORMAT csv, HEADER true)" >> "$work/copy.sql" done # Every table in one transaction, so a failure copies nothing. psql "$DATABASE_URL" --single-transaction -v ON_ERROR_STOP=1 --quiet --file "$work/copy.sql" ``` Copy your local data to your local database: ```sh DATABASE_URL=postgres://user:password@localhost:5432/my_app sh copy-data.sh --local users posts ``` Name each table after the tables it points at, so `users` comes before `posts`. :::note If a table has integer keys, set its identity past the keys you copied, so the next row Postgres makes doesn’t take one of them: ```sql SELECT setval(pg_get_serial_sequence('comments', 'id'), (SELECT max(id) FROM comments)); ``` ::: ## Switching the binding to Hyperdrive Create a Hyperdrive config for your real database: ```sh npx wrangler hyperdrive create my-app --connection-string="$PRODUCTION_DATABASE_URL" ``` Then bind it in your Wrangler config, with the `nodejs_compat` flag `pg` needs. Keep your D1 binding there too: ```jsonc wrangler.jsonc { "name": "my-app", "main": "src/index.ts", "compatibility_date": "2026-09-01", "compatibility_flags": ["nodejs_compat"], "hyperdrive": [ { "binding": "HYPERDRIVE", "id": "", "localConnectionString": "postgres://user:password@localhost:5432/my_app", }, ], // copy-data.sh exports D1 through this binding. Remove it once you've copied your real data. "d1_databases": [{ "binding": "DB", "database_name": "my-app-db", "database_id": "…" }], } ``` `npx wrangler dev` now runs your app on your local Postgres. ## Going live :::warning[Stop writes before you copy] A write that reaches D1 after you copy its data never reaches Postgres. Stop writes first, for example with a deploy that answers them with a 503. ::: :::note While it copies, `psql` shows its connection string to anyone on your machine who lists its processes. Copy from a machine only you use. To check your server’s certificate, add `sslmode=verify-full&sslrootcert=system` to the URL you copy to (libpq 16 or later). ::: Then create your tables on the real database, copy the data, and deploy: ```sh npx active-record migrate --remote DATABASE_URL="$PRODUCTION_DATABASE_URL" sh copy-data.sh --remote users posts npx wrangler deploy ``` ## Removing the D1 database Once your app runs on Postgres, remove the `d1_databases` entry from your Wrangler config. :::tip Your queries, validations, callbacks, and associations work the same on Postgres. A few things work differently, such as how NULLs and text sort, and `sql` fragments that use SQLite’s own functions. [PostgreSQL](/postgresql) lists each one. ::: --- # Ordering and pagination Source: https://active-record.forestfuture.dev/ordering-and-pagination ## At a glance | To | Write | | --------------------------- | -------------------------------------------------------------- | | sort by attributes | `order({ publishedAt: "desc", title: "asc" })` | | place NULLs | `order({ publishedAt: { direction: "desc", nulls: "last" } })` | | replace the order | `reorder({ createdAt: "desc" })`, or `reorder()` to drop it | | sort by a list of values | `inOrderOf("status", ["published", "draft"])` | | skip and take rows | `limit(20).offset(40)` | | get one page with its total | `paginate({ page, perPage: 20 })` | | get a page without counting | `paginate({ page, count: false })` | | Prop | Type | Default | Description | | - | - | - | - | | `page?` | `number \| string \| null` | `1` | The page to read. Text from a query string works as it is. | | `perPage?` | `number \| string \| null` | `25` | Records on each page, up to maxPerPage. | | `count?` | `boolean` | `true` | Whether to count every matching record for total and totalPages. | ## The Model The examples use this Model, whose attributes come from its table through the schema `active-record schema` generates: ```ts post.ts import { ApplicationRecord } from "./application-record"; export class Post extends ApplicationRecord {} ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: 136cbf4aca25 import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** posts — last changed by 0001_create_posts.sql */ export const posts = { id: { type: "string", null: false, generateId: true }, title: { type: "string", null: false }, status: "string", publishedAt: "datetime", createdAt: { type: "datetime", null: false }, updatedAt: { type: "datetime", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { posts: { attributes: posts, primaryKey: "id" }, }, models: { Post: "posts" }, }); declare module "../models/post" { interface Post extends TableAttributes {} } ``` ```sql D1 CREATE TABLE posts ( id TEXT PRIMARY KEY NOT NULL, title TEXT NOT NULL, status TEXT, published_at DATETIME, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL ); ``` ```sql Postgres CREATE TABLE posts ( id UUID PRIMARY KEY, title TEXT NOT NULL, status TEXT, published_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL ); ``` ## Ordering records Sort by each key in turn with `order`, and page with `limit` and `offset`: ```ts import { column, sql } from "@forestfuture/active-record"; import { Post } from "./models/post"; const newest = await Post.order({ publishedAt: "desc", title: "asc" }).toArray(); Post.order({ publishedAt: { direction: "desc", nulls: "last" } }); // unpublished last, on both Post.order(sql`lower(${column("title")})`); Post.order({ title: "asc" }).reorder({ createdAt: "desc" }); // replaces the order Post.order({ createdAt: "desc" }).limit(20).offset(40); // page 3 ``` Calling `order` again adds more keys. `reorder` replaces the order so far, and `reorder()` removes it. :::note On D1, NULLs sort first in ascending order and last in descending order. Postgres does the opposite. Place them with `nulls: "first"` or `nulls: "last"` to sort them the same on both. ::: ## Ordering by a list of values Sort records by where their value comes in a list with `inOrderOf`: ```ts import { Post } from "./models/post"; const byStatus = await Post.inOrderOf("status", ["published", "draft"]).toArray(); // only those const everyPost = await Post.inOrderOf("status", ["published"], { filter: false }).toArray(); ``` - By default, only records whose value is in the list are kept. Pass `filter: false` to keep the rest, after them. - Values are cast as `where`’s are, and `null` places NULL. The list is bound as one value, so it can be any length. - An order written after it sorts the records that tie, and `last()` reverses it. - It can’t be combined with `distinct()`, which throws `IncompatibleRelation`. - The database looks each record’s value up in the list, so a long list costs more on a large table. Keep it to the values you mean to order by. ## Paginating `paginate` resolves to one page of records and the total they’re a page of: ```ts import { Post } from "./models/post"; export async function listPosts(request: Request): Promise { const page = new URL(request.url).searchParams.get("page"); const posts = await Post.order({ publishedAt: "desc" }).paginate({ page, perPage: 20 }); return Response.json(posts); // { records, page, perPage, total, totalPages, hasNext, hasPrevious } } ``` - `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`. - Pages sort by the Relation’s order, then by the primary key, so records that tie keep their pages between requests. - A page past the last has no records, but still has the real `total`. - `includes()` preloads the page’s associations, with one more query per association. - On D1, the count, the records, and their preloads take [one round trip](/d1#sending-queries-in-one-round-trip). On Postgres they run [one after another](/postgresql#reads-run-one-after-another). - A Relation with its own `limit` or `offset` throws `IncompatibleRelation`. ## Skipping the count Pass `count: false` when you only need to know whether there’s a next page: ```ts import { Post } from "./models/post"; const { records, hasNext } = await Post.order({ publishedAt: "desc" }).paginate({ page: 2, perPage: 2, count: false, }); ``` Counting reads every matching row, and D1 bills each row it reads. Without it, the page has no `total` or `totalPages`. ## Setting the page size Set `perPage` and `maxPerPage` on your app’s base class to change the default size and its cap: ```ts title="src/models/application-record.ts" import { Model } from "@forestfuture/active-record"; import { schema } from "../db/schema"; export abstract class ApplicationRecord extends Model { static override schema = schema; static override perPage = 20; // when paginate() isn't given a perPage static override maxPerPage = 50; // a larger perPage is capped at this } ``` By default, a page holds 25 records, and none holds more than 100. :::note 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. ::: > **Compared with Rails** > > `inOrderOf` is Rails’ `in_order_of`, `filter: false` included. Rails writes the list into a `CASE`, one bound value per item. Here the list is one bound value, so it fits D1’s limit of 100. > **Beyond Rails** > > Rails leaves pagination to gems such as Kaminari and Pagy. Active Record builds it in, and on D1 sends the count and the page together. --- # Passwords and tokens Source: https://active-record.forestfuture.dev/passwords-and-tokens :::warning[The default hash is limited by Workers] Passwords are hashed with PBKDF2-SHA256 at 100,000 iterations. That’s the most Cloudflare Workers allow, and about a sixth of the 600,000 that OWASP recommends. Each sign-up, sign-in, or password change also takes about 10–40 ms of CPU time. The Workers Free plan allows 10 ms per request, so an app that signs people in may need Workers Paid. Each digest records its iteration count, so a later default can raise it without breaking the passwords you’ve stored. For a stronger hash, [plug in your own](#choosing-the-hash). ::: ## At a glance | To | Write | | -------------------------------------- | ----------------------------------------------------------------------------- | | keep a password as its digest | `password: { securePassword: true }`, with a `password_digest` column | | check a record’s password | `await user.authenticate(password)`: the record, or `false` | | find a record and check its password | `await User.authenticateBy({ email, password })`: the record, or `null` | | confirm a new password | `User.create({ password, passwordConfirmation })` | | ask for the current password to change | `user.update({ password, passwordChallenge })` | | hash with your own algorithm | `password: { securePassword: { algorithm: bcryptPassword } }` | | give each new record a random token | `authToken: { secureToken: true }` | | save a new token | `await user.regenerateAuthToken()` | | make a token yourself | `generateSecureToken(32)` | | send a password reset link | `await user.passwordResetToken()` | | find the user a reset link is for | `await User.findByPasswordResetToken(token)`: the record, or `null` | | declare a token for a purpose | `this.generatesTokenFor("emailConfirmation", { expiresIn, dependsOn })` | | make and check one | `await user.generateTokenFor(purpose)`, `User.findByTokenFor(purpose, token)` | | sign a record’s id | `await user.signedId({ purpose, expiresIn })` | | find the record a signed id is for | `await User.findSigned(signedId, { purpose })`: the record, or `null` | | set the secret tokens are signed with | `wrangler secret put SECRET_KEY_BASE` | | Prop | Type | Default | Description | | - | - | - | - | | `algorithm?` | `PasswordAlgorithm` | `PBKDF2-SHA256` | `securePassword`’s algorithm: `{ hash, verify, maxBytes? }`, which hashes a password and verifies one against its digest. | | `validations?` | `boolean` | `true` | `securePassword`’s validations. `false` leaves them out. | | `resetToken?` | `boolean \| { expiresIn }` | `true` | `securePassword`’s reset token, which lasts 15 minutes unless `expiresIn` says otherwise. `false` leaves it out. | | `length?` | `number` | `24` | `secureToken`’s characters, after any prefix. At least 24. | | `prefix?` | `true \| string` | - | Text before a `secureToken`’s characters. `true` uses the column’s name and `_`, as in `auth_token_…`. | | `on?` | `"initialize" \| "create"` | `"initialize"` | When a new record without a token gets one: as it’s built, or as it’s created. | | `expiresIn?` | `Duration` | - | How long a token lasts, such as `{ minutes: 15 }`: `seconds`, `minutes`, `hours`, or `days`. Without it, a signed id or a token for a purpose lasts until its secret changes. | | `dependsOn?` | `(record) => unknown` | - | `generatesTokenFor`’s value, such as the user’s email. A token finds its record only while the value is the same as when it was made. | ## The Models The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates: ```ts user.ts import { ApplicationRecord } from "./application-record"; export class User extends ApplicationRecord { static override attributes = { password: { securePassword: true }, // kept in password_digest authToken: { secureToken: true }, // a random token for each new user } as const; static { this.normalizes("email", { with: (email) => email.trim().toLowerCase() }); // A token that confirms the email it was sent to, for a day. this.generatesTokenFor("emailConfirmation", { expiresIn: { days: 1 }, dependsOn: (user) => user.email, }); } } ``` ```ts admin.ts import { bcryptPassword } from "../bcrypt"; import { ApplicationRecord } from "./application-record"; export class Admin extends ApplicationRecord { static override attributes = { password: { securePassword: { algorithm: bcryptPassword } }, } as const; } ``` ```ts application-record.ts import { Model } from "@forestfuture/active-record"; import { schema } from "../db/schema"; export abstract class ApplicationRecord extends Model { static override schema = schema; } ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: d7a909d3f64f import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** admins — last changed by 0001_create_users.sql */ export const admins = { id: { type: "string", null: false, generateId: true }, email: { type: "string", null: false }, passwordDigest: "string", createdAt: { type: "datetime", null: false }, updatedAt: { type: "datetime", null: false }, } as const; /** users — last changed by 0001_create_users.sql */ export const users = { id: { type: "string", null: false, generateId: true }, email: { type: "string", null: false }, passwordDigest: "string", authToken: "string", createdAt: { type: "datetime", null: false }, updatedAt: { type: "datetime", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { admins: { attributes: admins, primaryKey: "id" }, users: { attributes: users, primaryKey: "id" }, }, models: { Admin: "admins", User: "users" }, }); declare module "../models/admin" { interface Admin extends TableAttributes {} } declare module "../models/user" { interface User extends TableAttributes {} } ``` ```sql D1 CREATE TABLE users ( id TEXT PRIMARY KEY NOT NULL, email TEXT NOT NULL UNIQUE, password_digest TEXT, auth_token TEXT UNIQUE, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL ); CREATE TABLE admins ( id TEXT PRIMARY KEY NOT NULL, email TEXT NOT NULL UNIQUE, password_digest TEXT, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL ); ``` ```sql Postgres CREATE TABLE users ( id UUID PRIMARY KEY, email TEXT NOT NULL UNIQUE, password_digest TEXT, auth_token TEXT UNIQUE, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL ); CREATE TABLE admins ( id UUID PRIMARY KEY, email TEXT NOT NULL UNIQUE, password_digest TEXT, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL ); ``` ## Storing passwords Declare `password: { securePassword: true }` in `static attributes`, as `User` does, and give the table a `password_digest` column. A sign-up form can then send the password and its confirmation: ```ts import { User } from "./models/user"; export async function signUp(request: Request): Promise { const form = await request.formData(); const permitted = User.permit(form, "email", "password", "passwordConfirmation"); const user = await User.create(permitted); if (!user.isPersisted()) { return Response.json({ errors: user.errors.fullMessages() }, { status: 422 }); } return Response.json(user, { status: 201 }); // no password, digest, or token in it } ``` - **It adds three virtual attributes:** `password`, `passwordConfirmation`, and `passwordChallenge`. None of them is saved. - **Responses and logs never show them.** `toJSON()` leaves out the password, its confirmation, its challenge, and its digest, without listing them in [`hiddenAttributes`](/serialization#hiding-attributes). `onQuery` listeners, error messages, and printed records show them as `[FILTERED]`, whatever [`filterAttributes`](/serialization#filtering-attributes) says. A secure token is treated the same way, and `attributes()` still has them all. - **Another name works the same way.** `recoveryPassword: { securePassword: true }` keeps its digest in `recovery_password_digest`, and checks it with `authenticateRecoveryPassword`. The password is hashed when the record is saved, so `passwordDigest` keeps its old value until then: ```ts import { User } from "./models/user"; const user = User.build({ email: "jane@example.com", password: "correct horse battery" }); console.log(user.passwordDigest === null); // true, until the user is saved await user.saveOrThrow(); const isHashed = user.passwordDigest?.startsWith("$pbkdf2-sha256$") === true; console.log(isHashed); // true ``` Assigning `null` clears the digest. Assigning `""` is ignored, so a blank field in a form leaves the password as it was. :::note Without a string digest column, the Model throws `InvalidModel`, and `active-record schema` reports it. Declaring `passwordConfirmation` or `passwordChallenge` yourself throws `InvalidModel` too. ::: ## Checking a password Call `authenticate` with a password to check it against the record’s digest: ```ts import { User } from "./models/user"; const user = await User.findByOrThrow({ email: "jane@example.com" }); const isSignedIn = (await user.authenticate("correct horse battery")) !== false; console.log(isSignedIn); // true ``` - It resolves to the record, or `false` when the password isn’t the one, or the record has no digest. - It checks the digest as it’s saved, so a password you’ve assigned since is checked once you save it. - Each secure password gets its own method, named for it: `authenticatePassword`, `authenticateRecoveryPassword`. Only `password` gets `authenticate`. ## Signing in Call `authenticateBy` with an email (or any other attributes) and a password to find a record and check its password in one step: ```ts import { User } from "./models/user"; export async function signIn(request: Request): Promise { const form = await request.formData(); const { email = "", password = "" } = User.permit(form, "email", "password"); const user = await User.authenticateBy({ email, password }); if (user === null) return new Response("Wrong email or password", { status: 401 }); return Response.json({ token: user.authToken }); } ``` - **It resolves to the record, or `null`.** It’s `null` when no record matches, when the password is wrong, or when the password is blank. - **It takes as long when no record matches.** It hashes the password anyway, as it does for a record with no digest. So how long a sign-in takes doesn’t tell anyone which emails have accounts. - **Its other attributes find the record as `findBy` does.** Normalizations and default scopes apply. - **It needs both.** Without a password, or without an attribute to find the record by, it throws `TypeError`. ## Confirming and challenging A secure password adds these validations, unless it’s declared with `validations: false`: | Fails when | Error on | Message | | -------------------------------------------------------------------------------- | ---------------------- | ---------------------- | | there’s no digest, and no new password to hash | `password` | can’t be blank | | `passwordChallenge` isn’t the current password | `passwordChallenge` | is invalid | | the password is longer than the algorithm allows (72 bytes in UTF-8, by default) | `password` | is too long | | `passwordConfirmation` is given and doesn’t match | `passwordConfirmation` | doesn’t match Password | Set `passwordChallenge` to ask for the current password before a change: ```ts import { User } from "./models/user"; const user = await User.findByOrThrow({ email: "jane@example.com" }); const isChanged = await user.update({ password: "staple battery horse", passwordConfirmation: "staple battery horse", passwordChallenge: "correct horse battery", // the current password }); console.log(isChanged); // false if the challenge isn't the current password ``` - The challenge is checked against the digest as it was last saved. A record with no saved digest fails any challenge. - A `null` challenge or confirmation is skipped, so leave them out when you don’t ask for them. ## Choosing the hash Give `securePassword` an `algorithm` to hash passwords your own way. An algorithm has `hash`, `verify`, and an optional `maxBytes`. This one uses bcrypt, from the `bcryptjs` package: ```ts title="src/bcrypt.ts" import type { PasswordAlgorithm } from "@forestfuture/active-record"; import bcrypt from "bcryptjs"; /** bcrypt, at a cost of 10. It verifies digests another app made with bcrypt too. */ export const bcryptPassword: PasswordAlgorithm = { hash: (password) => bcrypt.hash(password, 10), verify: (password, digest) => bcrypt.compare(password, digest), maxBytes: 72, // bcrypt reads only a password's first 72 bytes }; ``` `Admin` declares it as its password’s algorithm, and its digests are bcrypt’s: ```ts import { Admin } from "./models/admin"; const admin = await Admin.create({ email: "sam@example.com", password: "correct horse battery" }); const isBcrypt = admin.passwordDigest?.startsWith("$2b$10$") === true; console.log(isBcrypt); // true ``` - **`hash`** resolves to a salted digest of the password, and **`verify`** to whether a password is the one a digest was made from. - **`maxBytes`** sets the `is too long` validation. Without it, a password can be any length. - **Each digest belongs to its algorithm.** The default throws `TypeError` for a digest it didn’t make, so give an algorithm that reads the digests you already have. bcrypt reads those made by another app’s bcrypt. :::warning[A stronger hash costs more CPU time] bcrypt in JavaScript at a cost of 10 takes about 100 ms of CPU time for each hash, well past the Free plan’s 10 ms. On Workers Paid, a request gets 30 seconds of CPU time by default. `bcryptjs` imports Node’s `crypto`, so turn on the `nodejs_compat` compatibility flag in `wrangler.jsonc`. ::: ## Generating tokens Declare `secureToken: true` on a string column, as `User` does with `authToken`, to give each new record a random token: ```ts import { User } from "./models/user"; const user = User.build({ email: "sam@example.com", password: "correct horse battery" }); console.log(user.authToken?.length); // 24, such as "pX27zsMN2ViQKta1bGfLmVJE" await user.saveOrThrow(); const found = await User.findBy({ authToken: user.authToken }); ``` - **It’s made as the record is built,** unless a value is given that isn’t `null` or `""`. With `on: "create"`, it’s made as the record is created instead. A bulk insert, such as `insertAll`, makes the first kind for a row that doesn’t give one, but not the second. - **It’s 24 characters of base58:** letters and digits, without `0`, `O`, `I`, and `l`, which look alike. `length` makes it longer, and `prefix` puts text before it. - **A record loaded from the database keeps the token it has,** even when it has none. - **Nothing checks that a token is unique.** Two tokens matching is very unlikely, but give the column a UNIQUE index, as `users.auth_token` has. `generateSecureToken(length)` makes a token the same way, for anything that isn’t an attribute. :::note A `length` under 24, a type other than `string`, or a `default` alongside it throws `InvalidModel`. ::: ## Regenerating tokens Call `regenerateAuthToken()` to save a new token, so the old one stops working: ```ts import { User } from "./models/user"; const user = await User.findByOrThrow({ email: "sam@example.com" }); await user.regenerateAuthTokenOrThrow(); // saves a new token, so the old one stops working ``` - It saves the new token as `update` does. Validations and callbacks run, and it resolves to `false` when the record is invalid. - `regenerateAuthTokenOrThrow()` throws `RecordInvalid` instead. - Each token gets its own pair, named for it: `inviteCode` gets `regenerateInviteCode()`. ## Resetting passwords Call `passwordResetToken()` to put a token in a reset link: ```ts import { sendResetEmail } from "./email"; import { User } from "./models/user"; export async function requestReset(request: Request): Promise { const { email = "" } = User.permit(await request.formData(), "email"); const user = await User.findBy({ email }); if (user !== null) { const token = await user.passwordResetToken(); // lasts 15 minutes await sendResetEmail(email, `https://example.com/reset?token=${token}`); } return new Response("Check your email", { status: 202 }); // the same whether the email is known } ``` When the link is followed, find the user it was sent to with `findByPasswordResetToken`, and set their new password: ```ts import { User } from "./models/user"; export async function resetPassword(request: Request): Promise { const form = await request.formData(); const user = await User.findByPasswordResetToken(form.get("token")); if (user === null) return new Response("That link has expired", { status: 400 }); const isReset = await user.update(User.permit(form, "password", "passwordConfirmation")); if (!isReset) return Response.json({ errors: user.errors.fullMessages() }, { status: 422 }); return new Response(null, { status: 204 }); // the link stops working: the password changed } ``` - **A reset token lasts 15 minutes.** `resetToken: { expiresIn: { hours: 1 } }` makes it last longer, and `resetToken: false` leaves it out. - **It works until the password changes.** Once the user resets their password, the link finds nobody, even if they choose the same password again. - **It’s signed, not stored.** Nothing is saved for it, so there’s no column to add and nothing to clear. - **`findByPasswordResetTokenOrThrow`** throws `InvalidToken` for a token that’s changed or expired, and `RecordNotFound` once the password has changed. `recoveryPassword` gets `recoveryPasswordResetToken()`. Find the user it’s for with `User.findByTokenFor("recoveryPasswordReset", token)`. ## Making tokens for a purpose Declare `generatesTokenFor` in `static {}` for a token your app sends for one purpose, as `User` does for confirming an email: ```ts import { User } from "./models/user"; const user = await User.findByOrThrow({ email: "jane@example.com" }); const token = await user.generateTokenFor("emailConfirmation"); const confirmed = await User.findByTokenFor("emailConfirmation", token); console.log(confirmed?.email); // "jane@example.com", until the email changes or a day passes ``` - **`expiresIn`** sets how long a token lasts. Without it, a token lasts until its secret changes. - **`dependsOn`** ties a token to a value of the record’s. A token finds its record only while the value is the same as when it was made, so a confirmation sent to an old email stops working once the email changes. The token holds a fingerprint of the value, never the value itself. - **Changing `expiresIn` stops the tokens already sent,** since a token is signed for how long it lasts. - **A purpose the Model doesn’t declare throws `TypeError`.** Declaring a purpose again replaces it, except a reset token’s, such as `passwordReset`, which throws `InvalidModel`. - **`findByTokenForOrThrow`** throws `InvalidToken` for a token that’s changed or expired, and `RecordNotFound` when the record is gone or the value has changed. ## Signing ids Call `signedId()` to sign a record’s id, and `findSigned` to find the record again: ```ts import { User } from "./models/user"; const user = await User.findByOrThrow({ email: "jane@example.com" }); const signedId = await user.signedId({ purpose: "unsubscribe", expiresIn: { days: 30 } }); const found = await User.findSigned(signedId, { purpose: "unsubscribe" }); console.log(found?.email); // "jane@example.com" console.log(await User.findSigned(signedId)); // null: it was signed for unsubscribing ``` - **A purpose keeps a signed id to one use.** `findSigned` finds its record only given the same purpose. - **`expiresIn` or `expiresAt`** makes it expire. Without either, it lasts until its secret changes. - **Anyone can read the id in it, but nobody can change it.** A signed id that’s changed, made up, or signed with another secret finds nothing. - **`findSignedOrThrow`** throws `InvalidToken` for a signed id that isn’t valid, and `RecordNotFound` when its record is gone. `findSigned` and `findByTokenFor` are Relation methods too. `User.where({ isActive: true }).findSigned(signedId)` finds the user only if they’re active, and a default scope always applies. :::note A new record has no id to sign, so `signedId` and `generateTokenFor` throw `RecordNotSaved` for one. ::: ## Setting the signing secret Reset tokens, tokens for a purpose, and signed ids are signed with the Worker’s `SECRET_KEY_BASE`. Set it as a secret, with at least 32 random bytes: ```sh openssl rand -hex 32 | npx wrangler secret put SECRET_KEY_BASE ``` For local development, put one in `.dev.vars`. Tests and scripts that run outside a Worker read it from `process.env`. Without one, or with one shorter than 32 bytes, making or checking a token throws `InvalidModel`. To change the secret without breaking the links you’ve sent, override `signingSecret` on `ApplicationRecord` and return both secrets, the new one first: ```ts import { Model, type SigningEnv } from "@forestfuture/active-record"; import { schema } from "../db/schema"; export abstract class ApplicationRecord extends Model { static override schema = schema; static override signingSecret(env: SigningEnv) { return [env.SECRET_KEY_BASE, env.PREVIOUS_SECRET_KEY_BASE]; // the first signs, and both verify } } ``` Once the tokens the old secret signed have expired, remove it. :::note A token isn’t tied to a database. If each tenant has a database of its own, put the tenant in a signed id’s purpose, as in ``signedId({ purpose: `${tenant}/unsubscribe` })``, and in what a token for a purpose `dependsOn`. Otherwise a token made in one tenant finds the record with the same id in another. ::: > **Compared with Rails** > > Rails declares these with `has_secure_password` and `has_secure_token`. Here they go with the attributes, so their methods are typed from the same place. Rails hashes a password with bcrypt as it’s assigned; here PBKDF2 hashes it when the record is saved, since Workers have no bcrypt of their own and hashing is asynchronous. `authenticate_by`, `password_challenge`, `regenerate_`, and base58 tokens work as in Rails. Rails’ `regenerate_token` raises on an invalid record; here `regenerateAuthToken()` resolves to `false`, and its `OrThrow` throws. Rails filters a password only when `filter_parameters` names it, and sends `password_digest` and a token in `as_json`; here a secure password, its digest, and a secure token are always filtered, and `toJSON()` leaves them out. `generates_token_for`, `signed_id`, and Rails 8’s reset tokens work as in Rails, with tokens of their own format, and each is asynchronous. Rails’ tokens carry the value a token depends on, readable by anyone who has one, and its reset token depends on part of bcrypt’s salt; here a token carries only a fingerprint, and a reset token depends on the whole digest, so there’s no `password_salt`. Rails reads `secret_key_base` and rotates through `message_verifiers`; here `signingSecret` reads `SECRET_KEY_BASE` from the Worker and returns a list to rotate. --- # Persistence Source: https://active-record.forestfuture.dev/persistence ## At a glance | To | Write | | ------------------------------------------ | --------------------------------------------------------- | | save a record, true or false | `user.save()`, `User.create({ … })`, `user.update({ … })` | | throw when it can’t be saved | `saveOrThrow()`, `createOrThrow()`, `updateOrThrow()` | | return a 422 for an invalid record | catch `RecordInvalid`, then read `error.record.errors` | | change one attribute in memory | `increment("viewCount")`, `toggle("isPinned")` | | write straight to the row | `incrementColumn(…)`, `updateColumns({ … })` | | set `updatedAt` without saving | `touch()` | | add to a number without loading the record | `Article.updateCounters(id, { viewCount: 1 })` | | find a record, or create one | `findOrCreateBy({ … })`, `createOrFindBy({ … })` | | destroy a record, or many | `destroy()`, `destroyAll()`, `destroyBy({ … })` | | load a record’s row again | `reload()` | ## The Models The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates: ```ts user.ts import { hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Post } from "./post"; export class User extends ApplicationRecord { posts = hasMany(Post, { dependent: "destroy" }); static { this.validates("email", { presence: true, uniqueness: true }); } } ``` ```ts post.ts import { belongsTo } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { User } from "./user"; export class Post extends ApplicationRecord { user = belongsTo(User); } ``` ```ts article.ts import { ApplicationRecord } from "./application-record"; export class Article extends ApplicationRecord { static { this.afterSave((article) => { if (article.isPreviouslyNewRecord()) { console.log(`New article: ${article.title}`); // not after later saves } }); } } ``` ```ts label.ts import { ApplicationRecord } from "./application-record"; // The UNIQUE index on name keeps it unique, so createOrFindBy can rely on it. export class Label extends ApplicationRecord {} ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: 33a3c8502c9c import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** articles — last changed by 0001_create_tables.sql */ export const articles = { id: { type: "string", null: false, generateId: true }, title: { type: "string", null: false }, viewCount: { type: "integer", null: false, default: () => 0 }, isPinned: { type: "boolean", null: false, default: () => false }, viewedAt: "datetime", updatedAt: "datetime", } as const; /** labels — last changed by 0001_create_tables.sql */ export const labels = { id: { type: "string", null: false, generateId: true }, name: { type: "string", null: false }, color: "string", } as const; /** posts — last changed by 0001_create_tables.sql */ export const posts = { id: { type: "string", null: false, generateId: true }, userId: { type: "string", null: false }, title: { type: "string", null: false }, publishedAt: "datetime", } as const; /** users — last changed by 0001_create_tables.sql */ export const users = { id: { type: "string", null: false, generateId: true }, email: { type: "string", null: false }, isActive: { type: "boolean", null: false, default: () => true }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { articles: { attributes: articles, primaryKey: "id" }, labels: { attributes: labels, primaryKey: "id" }, posts: { attributes: posts, primaryKey: "id" }, users: { attributes: users, primaryKey: "id" }, }, models: { Article: "articles", Label: "labels", Post: "posts", User: "users" }, }); declare module "../models/article" { interface Article extends TableAttributes {} } declare module "../models/label" { interface Label extends TableAttributes {} } declare module "../models/post" { interface Post extends TableAttributes {} } declare module "../models/user" { interface User extends TableAttributes {} } ``` ```sql D1 CREATE TABLE users ( id TEXT PRIMARY KEY NOT NULL, email TEXT NOT NULL, is_active BOOLEAN NOT NULL DEFAULT TRUE ); CREATE UNIQUE INDEX index_users_on_email ON users (email); CREATE TABLE posts ( id TEXT PRIMARY KEY NOT NULL, user_id TEXT NOT NULL REFERENCES users (id), title TEXT NOT NULL, published_at DATETIME ); CREATE TABLE articles ( id TEXT PRIMARY KEY NOT NULL, title TEXT NOT NULL, view_count INTEGER NOT NULL DEFAULT 0, is_pinned BOOLEAN NOT NULL DEFAULT FALSE, viewed_at DATETIME, updated_at DATETIME ); CREATE TABLE labels ( id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, color TEXT ); CREATE UNIQUE INDEX index_labels_on_name ON labels (name); ``` ```sql Postgres CREATE TABLE users ( id UUID PRIMARY KEY, email TEXT NOT NULL, is_active BOOLEAN NOT NULL DEFAULT TRUE ); CREATE UNIQUE INDEX index_users_on_email ON users (email); CREATE TABLE posts ( id UUID PRIMARY KEY, user_id UUID NOT NULL REFERENCES users (id), title TEXT NOT NULL, published_at TIMESTAMPTZ ); CREATE TABLE articles ( id UUID PRIMARY KEY, title TEXT NOT NULL, view_count INTEGER NOT NULL DEFAULT 0, is_pinned BOOLEAN NOT NULL DEFAULT FALSE, viewed_at TIMESTAMPTZ, updated_at TIMESTAMPTZ ); CREATE TABLE labels ( id UUID PRIMARY KEY, name TEXT NOT NULL, color TEXT ); CREATE UNIQUE INDEX index_labels_on_name ON labels (name); ``` ## Saving records Save a record with `save`. It validates the record, runs its callbacks, and resolves to `true` or `false`: ```ts import { User } from "./models/user"; const user = User.build({ email: "jane@example.com" }); if (await user.save()) { // saved: user.isPersisted() is true } else { console.log(user.errors.fullMessages()); // ["Email has already been taken"] } const created = await User.create({ email: "sam@example.com" }); // saved, or not await created.update({ isActive: false }); // true or false ``` A new record is inserted, and a persisted one updates only the attributes that changed. `save` resolves to `false` for one of two reasons: - **Validation failed.** The reasons are in `record.errors`. - **A callback aborted** with [`abort()`](/callbacks#stopping-a-save). The reason is in `record.abortReason`. `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. ## Throwing on failure When a failure is exceptional, use the `OrThrow` version of each method: ```ts import { RecordInvalid } from "@forestfuture/active-record"; import { User } from "./models/user"; export async function signUp(request: Request): Promise { try { const { email } = await request.json<{ email: string }>(); const user = await User.createOrThrow({ email }); return Response.json(user, { status: 201 }); } catch (error) { if (error instanceof RecordInvalid) { return Response.json({ errors: error.record.errors.fullMessages() }, { status: 422 }); } throw error; // anything else is a real failure } } ``` Instead of returning `false`, they throw: - `RecordInvalid` when validation failed, with the record on `error.record`. - `RecordNotSaved` when a callback aborted a save, with the abort’s reason as its message. - `RecordNotDestroyed` from `destroyOrThrow()`, when a callback aborted the destroy or a `restrictWithError` association refused it. ### What each method returns | Method | Resolves to | Throws | | ---------------------------------------- | ------------------------------------- | ----------------------------------------------------------------- | | `save()` / `update(attrs)` | `true` / `false` | constraint errors, `RecordDestroyed` | | `saveOrThrow()` / `updateOrThrow(attrs)` | `true` | same as above, plus `RecordInvalid`, `RecordNotSaved` | | `create(attrs)` | record, persisted or not | constraint errors | | `createOrThrow(attrs)` | persisted record | same as above, plus `RecordInvalid`, `RecordNotSaved` | | `destroy()` | destroyed record, or `false` on abort | constraint errors, `RecordDestroyed` | | `destroyOrThrow()` | destroyed record | same as above, plus `RecordNotDestroyed` | | `find(id)` | record | `RecordNotFound` | | `findBy(conds)` | record or `null` | none | | `findByOrThrow(conds)` | record | `RecordNotFound` | | `findOrCreateBy(attrs)` | record, persisted or not | constraint errors | | `createOrFindBy(attrs)` | record, persisted or not | constraint errors but its own `RecordNotUnique`, `RecordNotFound` | `false` only ever means validation failed or a callback aborted. Every method throws for anything else: - **Constraint errors**, such as `RecordNotUnique`, since the database refused the write. See [Errors](/errors#constraint-errors). - **An error thrown by a callback**, other than `abort()`, even from an after-callback once the record is saved. - **The database’s own errors.** > **Compared with Rails** > > A TypeScript method name can’t contain `!`, so the `OrThrow` suffix takes its place. `saveOrThrow`, `createOrThrow`, `updateOrThrow`, and `destroyOrThrow` are Rails’ `save!`, `create!`, `update!`, and `destroy!`. ## Changing one attribute To bump a number or flip a flag, use `increment`, `decrement`, or `toggle`. They change the record without saving it, so save it afterwards: ```ts import { Article } from "./models/article"; const article = await Article.findByOrThrow({ title: "Hello" }); article.increment("viewCount"); // viewCount + 1, not saved yet article.toggle("isPinned"); await article.save(); ``` `increment` and `decrement` take an amount as their second argument, and count `null` as zero. `toggle` turns `null` into `true`. ### Writing straight to the row To write a value without validations, callbacks, or a new `updatedAt`, use a method ending in `Column`. Each one writes to the row at once: ```ts import { Article } from "./models/article"; const article = await Article.findByOrThrow({ title: "Hello" }); await article.incrementColumn("viewCount"); // adds 1 in the row, now await article.toggleColumn("isPinned"); await article.updateColumns({ title: "Renamed" }); // no validations, callbacks, or updatedAt ``` - **`incrementColumn` and `decrementColumn`** add to the value in the row, not the one the record loaded. When two requests increment the same row, both count. The record then holds the row’s new value. To set `updatedAt` in the same write, pass `{ touch: true }` after the amount. - **`toggleColumn`** writes the flipped value. - **`updateColumns(attrs)`** writes the attributes you give. `updateColumn(name, value)` writes one. Each resolves to `true`, or `false` when the row is gone. The record’s other unsaved changes stay unsaved. A record that was never saved has no row, so these methods throw `RecordNotSaved`. ### Touching a record To mark a record as changed without saving it, call `touch`. It sets `updatedAt` to the current time in the row: ```ts import { Article } from "./models/article"; const article = await Article.findByOrThrow({ title: "Hello" }); await article.touch(); // sets updatedAt to now await article.touch("viewedAt"); // sets viewedAt and updatedAt await article.touch({ time: new Date("2026-01-01T00:00:00Z") }); await Article.where({ isPinned: true }).touchAll(); // every pinned article, in one statement ``` - **Name datetime attributes** to set them as well as `updatedAt`. - **Pass `{ time }` last** to set a time other than now. - **A Relation’s `touchAll`** sets them in every row it matches, in one statement. Like `updateAll`, it keeps the default scope and runs no callbacks. `touch` skips validations and the save callbacks, and the record’s other unsaved changes stay unsaved. It runs `afterTouch`, then the commit callbacks for an update. See [Running code after a touch](/callbacks#running-code-after-a-touch). `touch` resolves to `true`, or `false` when the row is gone. A record that was never saved throws `RecordNotSaved`. On a Model with no `updatedAt`, name at least one attribute. Inside a [`noTouching` block](/touching#turning-touches-off) for its Model, `touch` writes nothing and resolves to `false`. To touch the record a record belongs to whenever it changes, declare `touch` on its `belongsTo`. See [Touching the record it belongs to](/touching#touching-the-record-it-belongs-to). ### Updating counters To add to a number without loading the record, pass its primary key to `updateCounters`: ```ts import { Article } from "./models/article"; const { id } = await Article.findByOrThrow({ title: "Hello" }); await Article.updateCounters(id, { viewCount: 1 }); await Article.where({ isPinned: true }).updateCounters({ viewCount: 10 }); await Article.incrementCounter("viewCount", [id], { by: 5, touch: true }); // sets updatedAt too ``` - **`Article.updateCounters(ids, counters)`** adds to the rows with those keys, even ones a default scope leaves out. - **A Relation’s `updateCounters(counters)`** adds to every row it matches. - **`incrementCounter` and `decrementCounter`** change one attribute by one, or by the amount in `{ by: 5 }`. Each one sends a single statement and resolves to the number of rows it changed. Like `updateAll`, it skips validations and callbacks. To set `updatedAt` too, pass `{ touch: true }`. To set other datetime attributes as well, name them, as in `{ touch: "viewedAt" }`. To keep a count of an association’s records, see [counter caches](/counter-caches). :::warning[Counting by key skips the default scope] `Article.updateCounters`, `incrementCounter`, and `decrementCounter` find rows by primary key alone. If a default scope keeps tenants apart or hides deleted rows, a key from a request can reach a row it hides. Start from a Relation instead, which keeps the default scope: ```ts import { Article } from "./models/article"; const { id } = await Article.findByOrThrow({ title: "Hello" }); await Article.where({ id }).updateCounters({ viewCount: 1 }); // keeps the default scope ``` ::: :::note `increment` and the counters take `integer` and `real` attributes. A `decimal` is stored as text, so they refuse it. ::: > **Compared with Rails** > > `incrementColumn`, `decrementColumn`, and `toggleColumn` are Rails’ `increment!`, `decrement!`, and `toggle!`. A method name can’t contain `!`, and the `OrThrow` suffix means something else, so the `Column` ending names what they do: write to the row now, as `updateColumns` does. > > Rails’ `toggle!` runs the save callbacks and saves the record’s other changes. `toggleColumn` runs no callbacks and writes only the one attribute. For callbacks, call `toggle`, then `save`. > > Rails’ `increment!` keeps the value it worked out. `incrementColumn` reads the row’s new value back, so it includes other requests’ increments. > > `touch` and `touchAll` are Rails’ `touch` and `touch_all`. Rails writes the time to any column you name, and touching a Model with no `updated_at` does nothing. Here, an attribute that isn’t a datetime, or nothing to touch, throws a `TypeError`. ## Finding or creating a record Find a record by its attributes, or create one with them when there isn’t one, with `findOrCreateBy`: ```ts import { Label } from "./models/label"; const travel = await Label.findOrCreateBy({ name: "travel" }); // found, or created const food = await Label.findOrInitializeBy({ name: "food" }); // found, or built and not saved ``` `findOrCreateBy` creates the record as `create` does, so check `isPersisted()` or `errors` if it might not save. `findOrCreateByOrThrow` throws `RecordInvalid` instead. `findOrInitializeBy` builds the record without saving it. They work on any Relation. A scope’s or an association’s conditions become the new record’s attributes too, so `user.posts().findOrCreateBy({ title })` finds or creates one of the user’s posts. The attributes you pass become the new record’s values, so each must be one value. A list, a comparison such as `gte(18)`, or a `sql` fragment throws a `TypeError` before anything is sent. An array that an attribute holds as its value, such as a `json` attribute’s, is one value. These methods find the record that holds it. ### Giving new records more attributes To give a new record attributes that aren’t part of the search, use `createWith`: ```ts import { Label } from "./models/label"; const music = await Label.createWith({ color: "blue" }).findOrCreateBy({ name: "music" }); // blue ``` The Relation’s `build`, `create`, and `insert` use them too. Attributes you pass to `build` and `create` win over them. `insert`, `insertAll`, `upsert`, and `upsertAll` write them over the attributes you pass. `createWith(null)` removes them. To set attributes in code, pass a function as the last argument. It gets the new record once its attributes are assigned, before it’s saved: ```ts import { Label } from "./models/label"; const art = await Label.findOrCreateBy({ name: "art" }, (label) => { label.color = "green"; // set only when it's created }); ``` The function runs only when a record is made. `build`, `create`, and `createOrThrow` take one too. Each method awaits it, except `build`, which returns the record at once. An async function given to `build` throws a `TypeError`. ### Creating records from concurrent requests Two requests can both find nothing, and both create a record. When a UNIQUE index covers the attributes, use `createOrFindBy` instead. It inserts first, and finds the existing row when the index refuses the duplicate: ```ts import { Label } from "./models/label"; const news = await Label.createOrFindBy({ name: "news" }); // created, or found ``` `createOrFindByOrThrow` throws `RecordInvalid` when the record is invalid. :::warning[Let the index decide] `createOrFindBy` only finds the existing row when the database refuses the insert: - **Leave out a `uniqueness` validation on those attributes.** It refuses the duplicate before the insert, so `createOrFindBy` resolves to the invalid record, not the existing one. The UNIQUE index alone keeps the column unique. - **Save the record alone.** When `init` builds or sets records through its associations, a refusal may be theirs, so `createOrFindBy` throws the `RecordNotUnique` instead of finding. - **It throws `RecordNotFound` when there’s nothing to find:** when the index refused a value in an attribute you didn’t pass, when the existing row isn’t linked to the owner of an [association through another](/through-associations), or when a [D1 Session](/read-your-own-writes) reads from a replica that the other request’s row hasn’t reached yet. ::: > **Compared with Rails** > > `findOrCreateBy`, `findOrInitializeBy`, `createOrFindBy`, and `createWith` are Rails’ `find_or_create_by`, `find_or_initialize_by`, `create_or_find_by`, and `create_with`, and the `OrThrow` versions are the `!` ones. The function passed last takes the place of Rails’ block. > > Rails reads a list in their attributes as `IN`, as `find_by` does. These methods refuse one instead, as [Untrusted input](/untrusted-input#querying-with-request-values) explains. ## Destroying records Destroy a record with `destroy`: ```ts import { User } from "./models/user"; const user = await User.findByOrThrow({ email: "jane@example.com" }); const destroyed = await user.destroy(); // the record, or false if a callback aborted if (destroyed) console.log(destroyed.isDestroyed()); // true: readable, but can't be saved ``` 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`. :::note If another request already deleted the row, `save` and `destroy` still succeed. ::: ### Destroying many records Destroy every record a query matches with `destroyAll`: ```ts import { Post } from "./models/post"; import { User } from "./models/user"; const drafts = await Post.where({ publishedAt: null }).destroyAll(); // the destroyed posts const user = await User.findByOrThrow({ email: "jane@example.com" }); await Post.destroyBy({ userId: user.id }); // where(…).destroyAll() ``` - **`destroyAll()`** loads the records, runs each one’s destroy callbacks and `dependent` options, and deletes them all in one write. It resolves to the destroyed records. - **`destroyBy(conditions)`** is `where(conditions).destroyAll()`. - **`Post.destroy(id)`** finds the record by its primary key and destroys it. Given an array of keys, it destroys those records in one write. It throws `RecordNotFound` if a key has no record, before destroying any. When one record can’t be destroyed, nothing is. A callback that aborts and a `restrictWithError` association both stop the whole write with `RecordNotDestroyed`. To delete rows without loading them or running callbacks, use `deleteAll`, `deleteBy`, or `Post.delete(ids)`. See [Bulk writes and batches](/batches). > **Compared with Rails** > > Rails’ `destroy_all` on a Relation destroys each record in a transaction of its own, skips a record whose callback aborts, and returns every record. Here the records are destroyed in one write, and one refusal stops them all, as Rails’ `destroy_all` on an association does. ### Destroying a large set `destroyAll` holds every record it matches in memory, and writes them together. To destroy a large set in smaller writes, destroy it [a batch at a time](/batch-iteration#writing-a-batch-at-a-time): ```ts import { Post } from "./models/post"; const unpublished = Post.where({ publishedAt: null }); for await (const batch of unpublished.inBatches({ batchSize: 100 })) { await batch.destroyAll(); // one write per batch } ``` Each batch is its own write, so a batch that fails leaves the earlier batches destroyed. :::note A batch bounds memory, not queries. Each record reads its `"destroy"` and restricted associations with a query of its own, so a large set sends as many reads, a batch at a time or not. On D1, that counts toward [the queries one Worker invocation can send](/batch-iteration#staying-within-d1s-query-limit). ::: ## Checking a record’s state | State | `isNewRecord()` | `isPersisted()` | `isDestroyed()` | | ------------------------------------------------ | --------------- | --------------- | --------------- | | New (from `build()`, or after a failed `create`) | `true` | `false` | `false` | | Persisted (loaded, or after a successful save) | `false` | `true` | `false` | | Destroyed (after a successful `destroy()`) | `false` | `false` | `true` | `isPreviouslyNewRecord()` says whether the last save created the record. `Article` uses it in an after-callback that runs only for new records: ```ts import { Article } from "./models/article"; const article = await Article.create({ title: "Fresh" }); // logs "New article: Fresh" await article.update({ title: "Fresher" }); // logs nothing ``` It’s `false` again once the record is saved again or destroyed. ## Reloading records Load a record’s row again with `reload`, which discards unsaved changes and loaded associations: ```ts import { User } from "./models/user"; const user = await User.findByOrThrow({ email: "jane@example.com" }); user.email = "changed@example.com"; await user.reload(); // back to what the database holds ``` It throws `RecordNotFound` if the row is gone, or the record was never saved. ## Writing many rows To insert, update, or delete many rows at once, without validations and callbacks, use `insertAll`, `upsertAll`, `updateAll`, `deleteAll`, and `deleteBy`. See [Bulk writes and batches](/batches). --- # PostgreSQL Source: https://active-record.forestfuture.dev/postgresql ## Installing The PostgreSQL adapter comes with `@forestfuture/active-record`, as its `/postgresql` entry. Install the library with `pg`, and PGlite for reading your schema: ```sh npm install @forestfuture/active-record pg npm install --save-dev @electric-sql/pglite ``` Then name your database in [`active-record.jsonc`](/command-line#declaring-your-databases), with `npx active-record init --adapter postgresql`. A Worker on Postgres needs `"compatibility_flags": ["nodejs_compat"]` in its Wrangler config, for `pg`. To move an app from D1, see [Moving to Postgres](/move-to-postgres). Your Models, queries, and callbacks work the same on Postgres. The sections after [Connecting](#connecting) are the places Postgres works differently from D1. ## Connecting `connect` takes a Hyperdrive binding, a connection string, or a `pg` Pool. Open the request’s database from your Hyperdrive binding: ```ts import { withDatabase } from "@forestfuture/active-record"; import { connect } from "@forestfuture/active-record/postgresql"; export default { fetch(request, env) { const db = connect(env.HYPERDRIVE); return withDatabase(db, () => app.fetch(request, env)); }, }; ``` The first query inside `withDatabase` opens a client, and the rest of the request shares it. It closes when `withDatabase` finishes. Each `withDatabase` call gets its own client, so a Database your Worker opens once can serve every request. Without `withDatabase`, each query opens a client of its own and closes it when it’s done. So does work that outlives the request, such as a save in `ctx.waitUntil`. Your schema names the binding with `adapter: postgresql({ binding: "HYPERDRIVE" })`, so `User.find(id)` works in a Worker with nothing to set up. Declare it in your [`active-record.jsonc`](/command-line#declaring-your-databases), where the command finds your databases. `connect(env.DATABASE_URL)` takes a connection string the same way. :::tip On Workers, use Hyperdrive. It pools connections, so a new client doesn’t mean a new connection to Postgres. ::: On Node, pass your own Pool, which your app ends when it shuts down: ```ts import pg from "pg"; import { connect } from "@forestfuture/active-record/postgresql"; const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); const db = connect(pool); ``` Outside a Worker there’s no binding, so wrap each request in `withDatabase(db, …)` for your Models’ statics. Opening a client from a binding or a connection string waits up to 10 seconds for Postgres to answer. After that, the query fails with `Error: timeout expired`. Each query waiting for that client tries again, and can wait as long. To change the limit, set `connect_timeout` to a number of seconds: ```ts import { connect } from "@forestfuture/active-record/postgresql"; const db = connect("postgres://app@db.example.com/app?connect_timeout=5"); ``` If you want no limit, set `connect_timeout=0`. :::note A Hyperdrive binding’s connection string isn’t yours to change, so it always waits up to 10 seconds. A Pool uses its own `connectionTimeoutMillis`. ::: > **Compared with Rails** > > Rails sets no limit, so opening a connection waits as long as it takes unless you set `connect_timeout`. Here the limit is 10 seconds unless you set one. ## Batches are transactions A [batch](/batches#batching-writes) is written whole or not at all, as on D1. On Postgres its writes run between `BEGIN` and `COMMIT`, on a client of its own. A query your request sends while the batch runs stays outside the transaction, so a failed batch never rolls it back. ## Reads run one after another On D1, a [preload](/preloading) or a [page](/ordering-and-pagination#paginating) sends all its queries [in one round trip](/d1#sending-queries-in-one-round-trip). On Postgres they run one after another, on one client. A page’s `total` comes from its own query, so a write between the two can make it disagree with the page’s records for a moment. Queries you send at once with `Promise.all` inside one `withDatabase` call also run one after another, on that call’s client. ## Large integers A `bigint` column reads as a number. A value past `Number.MAX_SAFE_INTEGER` throws a `TypeError` naming its attribute, rather than reading as a number that’s slightly wrong. For exact numbers of any size, use a `numeric` column and a [`decimal`](/attribute-types#storing-exact-numbers-days-and-times) attribute, which keeps every digit. ## Placeholders `onQuery` and `toSql()` show the SQL Postgres runs, with `$1`, `$2`, and so on where D1 shows `?`. ## Raw SQL stays on its database An [`sql` fragment](/conditions#writing-sql-fragments) is sent as you wrote it. A fragment that uses SQLite’s functions fails on Postgres, and one that uses Postgres’s fails on D1. ## Sorting Postgres sorts NULL after every value: last in ascending order, and first in descending order. D1 sorts it first in ascending order. Place NULLs yourself to sort them the same on both: ```ts User.order({ role: { direction: "asc", nulls: "last" } }); ``` Postgres sorts text by your database’s collation, usually its locale’s, where capitals and lowercase letters interleave. D1 sorts by code point, so every capital comes before every lowercase letter. ## Distinct records ordered by another column Postgres refuses to order `distinct()` records by a column they don’t select, and throws its own error. Select the column, or order by one you select. After `distinct()`, `pluck("title")` selects only `title`. So does `count("title")` with a `limit` or `offset`. Order them by `title`, or leave the order out. ## NUL characters Postgres text, and strings in a `jsonb` value, can’t hold the NUL character (`\u0000`). A value with one fails with Postgres’s own error. ## Keys written by hand A key you set yourself doesn’t move a Postgres identity column. The next key Postgres makes can then be one you’ve already used, which fails as a duplicate. ## Constraint errors name their table Postgres’s constraint errors name their table and columns. So a batch’s foreign-key failure has `.table` and `.columns`, where D1’s has `.table` `null` when the batch writes to several tables. ## Migrations are applied by the command On D1, `active-record migrate` runs Wrangler, which records each migration by its file name. On Postgres, the command applies them itself. It records each one’s version in a `schema_migrations` table. A version is the number a file’s name starts with, so every file’s name needs one. Renaming the rest of the name doesn’t run the migration again. Each migration runs in a transaction. One that fails leaves nothing behind, since Postgres can undo a `CREATE TABLE` or an `ALTER TABLE`. A statement that can’t run in a transaction, such as `CREATE INDEX CONCURRENTLY`, fails. [Migrating the real database](/command-line#active-record-migrate) needs its connection string and a route to its server. ## Reading the schema `active-record schema` reads your schema by applying your migrations to [PGlite](https://pglite.dev), Postgres in memory, so it needs no server. A migration that creates an extension PGlite doesn’t have, such as PostGIS, is read on the server your [`schemaUrl`](/command-line#mapping-postgress-columns) names instead. Postgres’s column types decide the attributes. Unlike on D1, a column’s name never does, so an `is_active BIGINT` is an integer. ## Adding a required column A generated migration can add a `NOT NULL` column without a default, which SQLite refuses. Postgres runs it on an empty table, and refuses it on a table with rows. ## Migrations in folders The command reads a Postgres database’s migrations from its folder, not from folders inside it. Migrations a tool writes in folders, such as `migrations/0000_init/migration.sql`, aren’t read. ## jsonb keeps the value A `jsonb` column keeps a JSON value, not the text you wrote. A raw query reads it back with Postgres’s own spacing and key order. Your Models read the same value either way. --- # Preloading Source: https://active-record.forestfuture.dev/preloading ## At a glance | To | Write | | ------------------------------------------- | ------------------------------------------------------------------------------------ | | preload an association | `Author.includes("profile")` | | preload several | `Author.includes("profile", "articles")` | | preload nested associations | `includes({ articles: "comments" })`, `includes({ articles: ["comments", "tags"] })` | | preload a polymorphic association | `Like.includes("likeable")` | | read a preloaded association, with no query | `author.loaded("profile")` | | check whether it’s loaded | `author.isLoaded("profile")` | ## The Models The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates: ```ts author.ts import { hasMany, hasOne } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Article } from "./article"; import { Profile } from "./profile"; export class Author extends ApplicationRecord { articles = hasMany(Article); profile = hasOne(Profile); } ``` ```ts profile.ts import { belongsTo } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Author } from "./author"; export class Profile extends ApplicationRecord { author = belongsTo(Author); } ``` ```ts article.ts import { belongsTo, hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Author } from "./author"; import { Comment } from "./comment"; export class Article extends ApplicationRecord { author = belongsTo(Author); comments = hasMany(Comment); } ``` ```ts comment.ts import { belongsTo } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Article } from "./article"; export class Comment extends ApplicationRecord { article = belongsTo(Article); } ``` ```ts like.ts import { belongsTo } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Photo } from "./photo"; import { Video } from "./video"; export class Like extends ApplicationRecord { likeable = belongsTo([Photo, Video]); // its own likeableType and likeableId } ``` ```ts photo.ts import { hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Like } from "./like"; export class Photo extends ApplicationRecord { likes = hasMany(Like, { as: "likeable" }); // Like's likeableType is "Photo" } ``` ```ts video.ts import { hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Like } from "./like"; export class Video extends ApplicationRecord { likes = hasMany(Like, { as: "likeable" }); // Like's likeableType is "Video" } ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: 9e181a91394e import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** articles — last changed by 0001_create_tables.sql */ export const articles = { id: { type: "string", null: false, generateId: true }, authorId: { type: "string", null: false }, title: { type: "string", null: false }, } as const; /** authors — last changed by 0001_create_tables.sql */ export const authors = { id: { type: "string", null: false, generateId: true }, name: { type: "string", null: false }, } as const; /** comments — last changed by 0001_create_tables.sql */ export const comments = { id: { type: "string", null: false, generateId: true }, articleId: { type: "string", null: false }, body: { type: "string", null: false }, } as const; /** likes — last changed by 0001_create_tables.sql */ export const likes = { id: { type: "string", null: false, generateId: true }, likeableType: { type: "string", null: false }, likeableId: { type: "string", null: false }, } as const; /** photos — last changed by 0001_create_tables.sql */ export const photos = { id: { type: "string", null: false, generateId: true }, title: { type: "string", null: false }, } as const; /** profiles — last changed by 0001_create_tables.sql */ export const profiles = { id: { type: "string", null: false, generateId: true }, authorId: { type: "string", null: false }, bio: "string", } as const; /** videos — last changed by 0001_create_tables.sql */ export const videos = { id: { type: "string", null: false, generateId: true }, title: { type: "string", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { articles: { attributes: articles, primaryKey: "id" }, authors: { attributes: authors, primaryKey: "id" }, comments: { attributes: comments, primaryKey: "id" }, likes: { attributes: likes, primaryKey: "id" }, photos: { attributes: photos, primaryKey: "id" }, profiles: { attributes: profiles, primaryKey: "id" }, videos: { attributes: videos, primaryKey: "id" }, }, models: { Article: "articles", Author: "authors", Comment: "comments", Like: "likes", Photo: "photos", Profile: "profiles", Video: "videos", }, }); declare module "../models/article" { interface Article extends TableAttributes {} } declare module "../models/author" { interface Author extends TableAttributes {} } declare module "../models/comment" { interface Comment extends TableAttributes {} } declare module "../models/like" { interface Like extends TableAttributes {} } declare module "../models/photo" { interface Photo extends TableAttributes {} } declare module "../models/profile" { interface Profile extends TableAttributes {} } declare module "../models/video" { interface Video extends TableAttributes {} } ``` ```sql D1 CREATE TABLE authors ( id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL ); CREATE TABLE profiles ( id TEXT PRIMARY KEY NOT NULL, author_id TEXT NOT NULL REFERENCES authors (id), bio TEXT ); CREATE TABLE articles ( id TEXT PRIMARY KEY NOT NULL, author_id TEXT NOT NULL REFERENCES authors (id), title TEXT NOT NULL ); CREATE TABLE comments ( id TEXT PRIMARY KEY NOT NULL, article_id TEXT NOT NULL REFERENCES articles (id), body TEXT NOT NULL ); CREATE TABLE photos ( id TEXT PRIMARY KEY NOT NULL, title TEXT NOT NULL ); CREATE TABLE videos ( id TEXT PRIMARY KEY NOT NULL, title TEXT NOT NULL ); CREATE TABLE likes ( id TEXT PRIMARY KEY NOT NULL, likeable_type TEXT NOT NULL, likeable_id TEXT NOT NULL ); CREATE INDEX index_articles_on_author_id ON articles (author_id); CREATE INDEX index_comments_on_article_id ON comments (article_id); ``` ```sql Postgres CREATE TABLE authors ( id UUID PRIMARY KEY, name TEXT NOT NULL ); CREATE TABLE profiles ( id UUID PRIMARY KEY, author_id UUID NOT NULL REFERENCES authors (id), bio TEXT ); CREATE TABLE articles ( id UUID PRIMARY KEY, author_id UUID NOT NULL REFERENCES authors (id), title TEXT NOT NULL ); CREATE TABLE comments ( id UUID PRIMARY KEY, article_id UUID NOT NULL REFERENCES articles (id), body TEXT NOT NULL ); CREATE TABLE photos ( id UUID PRIMARY KEY, title TEXT NOT NULL ); CREATE TABLE videos ( id UUID PRIMARY KEY, title TEXT NOT NULL ); CREATE TABLE likes ( id UUID PRIMARY KEY, likeable_type TEXT NOT NULL, likeable_id UUID NOT NULL ); CREATE INDEX index_articles_on_author_id ON articles (author_id); CREATE INDEX index_comments_on_article_id ON comments (article_id); ``` ## Preloading associations Load an association for every record at once with `includes`, one query per association however many records there are: ```ts import { Author } from "./models/author"; const authors = await Author.includes("profile", { articles: "comments" }).toArray(); for (const author of authors) { const articles = await author.articles().toArray(); // no query: already loaded console.log(author.name, articles.length, author.loaded("profile")?.bio); } ``` - The example sends four queries, however many authors there are. On D1, the whole tree goes [in one round trip](/d1#sending-queries-in-one-round-trip) with the authors’ own query. On Postgres, the queries run one after another. An association to [another database](/several-databases#associating-models-on-different-databases) takes one more. - `author.loaded("profile")` reads a preloaded association synchronously, and throws `AssociationNotLoaded` if it wasn’t loaded, so a template never sends a query. `author.isLoaded("profile")` checks first. - With a `limit` or `offset`, `includes` ends the order with the primary key, so the preloads find the same records the query loads. ## Preloading polymorphic records `includes` preloads a polymorphic association with one query for each listed Model: ```ts import { Like } from "./models/like"; const likes = await Like.includes("likeable").toArray(); // the likes, photos, and videos for (const like of likes) { console.log(like.loaded("likeable")?.title); // no query: already loaded } ``` - Each query runs the likes’ query again to find their keys, even for a Model no like points at. Index what that query filters and sorts by. - A nested include can name an association that only some listed Models have: `includes({ likeable: "album" })` loads the photos’ albums and skips the videos. ## Indexing what preloads read Index each foreign key, as the migrations index `author_id` and `article_id`: - `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()`. Without an index, 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. - `includes` also runs the query’s own conditions again for each association it preloads, and with a `limit` or `offset`, its order. Index the columns the query filters and sorts by, too. > **Beyond Rails** > > Rails sends each association’s preload query on its own, so every association adds a round trip. On D1, the whole tree on one database takes one. Rails preloads a polymorphic association after the likes load, with one query per type it finds. Here every listed Model’s query goes with the likes’ own, in one round trip, at the cost of reading the likes’ query again for each. --- # Database resolution Source: https://active-record.forestfuture.dev/query-databases ## One isolate, many requests 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. - **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. - **An `onQuery` listener** might tag each query with its request’s ID. Shared, it would mix requests. 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`. ## Three ways to find a database A query finds its database in one of three ways, in this order: 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. 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. 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. 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. ## Which do I need? | Your situation | What to do | | ------------------------------------------------------------ | -------------------------------------------------------------------- | | A Worker with one D1 database | Nothing: `User.find(id)` uses its binding | | D1 read replication, reading your own writes | [A Session per request](/read-your-own-writes) | | Logging queries, or `Server-Timing` | [`onQuery`](/logging), app-wide or per request | | Vitest tests, seed or migration scripts | [`withDatabase(connect(binding), …)`](/testing), or `db.model(...)` | | Several D1 databases | [One base class per binding](/several-databases) | | A compatibility date before 2026-08-04, using `withDatabase` | Add `nodejs_compat` to your Wrangler config’s `compatibility_flags` | ## What follows from it - **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. - **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. - **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. For the options themselves, see [Connections](/connecting). --- # Querying Source: https://active-record.forestfuture.dev/querying ## At a glance | To | Write | | ------------------------------- | ------------------------------------------------------ | | build a query | `User.where({ role: "admin" }).order({ … }).limit(10)` | | run it | `.toArray()`, `.first()`, `.count()` | | find one record | `find(id)`, `findBy({ … })`, `findByOrThrow({ … })` | | read attributes without records | `pluck("email")`, `pick("email")`, `ids()` | | check for records | `exists({ … })`, `hasAny()`, `hasMoreThanOne()` | | load only some attributes | `select("email")` | | match nothing, without a query | `none()` | | combine two queries | `where(…).merge(other)` | | see the SQL | `toSql()` | Each part of a query has a page of its own: | To | See | | ------------------------------------------- | ---------------------------------------------------- | | filter with `where`, comparisons, and `sql` | [Conditions](/conditions) | | sort and page | [Ordering and pagination](/ordering-and-pagination) | | count, add up, and group | [Calculations](/calculations) | | name reusable queries | [Scopes](/scopes) | | filter by associated records | [Joins](/joins) | | walk a large table | [Batch iteration](/batch-iteration) | | send your own SQL | [Raw statements](/raw-statements) | | load associations with each record | [Preloading associations](/preloading) | ## The Model The examples use this Model, whose attributes come from its table through the schema `active-record schema` generates: ```ts user.ts import { ApplicationRecord } from "./application-record"; export class User extends ApplicationRecord {} ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: 7ace010c47bc import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** users — last changed by 0001_create_users.sql */ export const users = { id: { type: "string", null: false, generateId: true }, email: { type: "string", null: false }, role: "string", isActive: "boolean", createdAt: { type: "datetime", null: false }, updatedAt: { type: "datetime", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { users: { attributes: users, primaryKey: "id" }, }, models: { User: "users" }, }); declare module "../models/user" { interface User extends TableAttributes {} } ``` ```sql D1 CREATE TABLE users ( id TEXT PRIMARY KEY NOT NULL, email TEXT NOT NULL, role TEXT, is_active BOOLEAN, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL ); ``` ```sql Postgres CREATE TABLE users ( id UUID PRIMARY KEY, email TEXT NOT NULL, role TEXT, is_active BOOLEAN, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL ); ``` ## Building a Relation A query is a **Relation**, and each method that narrows, orders, or pages it returns a new one: ```ts import { User } from "./models/user"; const admins = User.where({ role: "admin" }).order({ createdAt: "desc" }); const firstTen = admins.limit(10); // a new Relation; admins is unchanged const users = await firstTen.toArray(); // the query runs here ``` - Nothing runs until you ask for results, with a method such as `toArray()`, `first()`, or `count()`. - Relations have no `then`, so an `async` function that returns one never runs it by accident. - Every Relation method is also a static of every Model: `User.where(…)`, `User.find(id)`, `User.count()`. `User.all()` is the Relation itself. - 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). ## Finding records Find one record with a finder: ```ts import { User } from "./models/user"; const user = await User.findByOrThrow({ email: "jane@example.com" }); // or RecordNotFound const nobody = await User.findBy({ email: "nobody@example.com" }); // null const again = await User.find(user.id); // by primary key, or RecordNotFound const oldest = await User.first(); // by primary key, unless ordered const newest = await User.order({ createdAt: "asc" }).last(); // the order reversed const owner = await User.findSoleBy({ role: "owner" }); // the only one, or throws ``` - `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. - `findBy` resolves to `null` when nothing matches, and `findByOrThrow` throws `RecordNotFound`. `findOrCreateBy` creates the record. See [Finding or creating a record](/persistence#finding-or-creating-a-record). - `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. `take` reads a record with no order at all. - `firstOrThrow`, `lastOrThrow`, and `takeOrThrow` throw `RecordNotFound` instead of resolving to `null`. - `sole` resolves to the only matching record. It throws `RecordNotFound` when nothing matches, and `SoleRecordExceeded` when more than one does. `findSoleBy(conditions)` is short for `where(conditions).sole()`. ## Reading attributes Read attributes without loading records with `pluck`, `pick`, and `ids`: ```ts import { User } from "./models/user"; const emails = await User.order({ email: "asc" }).pluck("email"); // string[] const pairs = await User.order({ email: "asc" }).pluck("id", "email"); // [string, string][] const latest = await User.order({ createdAt: "desc" }).pick("email"); // string | null const adminIds = await User.where({ role: "admin" }).ids(); // primary keys ``` - `pluck` reads one attribute from every record, or a tuple of several. - `pick` reads from the first record, and resolves to `null` when nothing matches. - `ids` plucks every primary key. On a loaded association, it leaves out records you’ve built that don’t have a key yet. ## Counting and checking Count records, or check whether any match: ```ts import { User } from "./models/user"; const admins = await User.where({ role: "admin" }).count(); const hasAdmins = await User.exists({ role: "admin" }); const severalAdmins = await User.where({ role: "admin" }).hasMoreThanOne(); const oneOwner = await User.where({ role: "owner" }).hasExactlyOne(); ``` - `count()` always agrees with what `toArray()` returns, even with `limit`, `offset`, or `distinct`. - `size()`, `isEmpty()`, and `hasAny()` count records, or check for any. On a loaded association, they answer without a query. - `hasMoreThanOne()` and `hasExactlyOne()` count no further than two records. On a loaded association, they answer without a query too. :::tip `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. ::: ## Selecting attributes Load only some attributes with `select`: ```ts import { User } from "./models/user"; const [first] = await User.order({ email: "asc" }).select("email").toArray(); console.log(first?.email); // loaded console.log(first?.id); // the primary key is always loaded too // first?.role would throw MissingAttribute: it wasn't selected const roles = await User.select("role").distinct().pluck("role"); ``` - The primary key is always loaded too, so the records can still be saved. - Reading an attribute that wasn’t loaded throws `MissingAttribute`, including from a validator or callback. `record.hasAttribute("email")` says whether it was loaded. - Saving a partial record writes only what changed. `reload()` loads the whole row. - After `distinct()`, the primary key isn’t added, since it would make every row distinct, so those records can’t be saved. ## Matching nothing `none()` matches nothing without asking the database, and chaining more onto it keeps it empty: ```ts import { User } from "./models/user"; const nothing = await User.none().where({ role: "admin" }).toArray(); // [], with no query ``` ## Merging Relations Combine two Relations of the same Model with `merge`: ```ts import { User } from "./models/user"; const newest = User.order({ createdAt: "desc" }).limit(1); const newestAdmin = await User.where({ role: "admin" }).merge(newest).toArray(); ``` Their conditions are joined with AND, and anything the argument sets, such as an order, limit, or select, replaces the receiver’s. To merge a Relation of another Model, join that Model first. See [Joins](/joins#filtering-by-a-joined-model). ## Seeing a query’s SQL See the SQL a Relation’s `toArray()` would send, without sending it, with `toSql()`: ```ts import { User } from "./models/user"; const { sql, params } = User.where({ role: "admin" }).limit(10).toSql(); console.log(sql); // SELECT * FROM "users" WHERE ("role" = ?) LIMIT ?, with $1 and $2 on Postgres console.log(params); // ["admin", 10] ``` - The values come back in `params`, apart from the SQL. Postgres numbers its placeholders: `$1`, `$2`. - A `none()` Relation shows `1 = 0`, the condition that matches nothing. - `toSql()` returns the real values, filtered attributes included. To see what a query sent, with those filtered, use [`onQuery`](/logging). - Bulk writes and [batches](/batches#batching-writes) have no `toSql()`. Use [`onQuery`](/logging) to see what they sent. > **Compared with Rails** > > `size()`, `isEmpty()`, and `hasAny()` are Rails’ `size`, `empty?`, and `any?`, and `hasMoreThanOne()` and `hasExactlyOne()` are `many?` and `one?`. `firstOrThrow()` is `first!`, and `findSoleBy` is `find_sole_by`. There’s no `second` or `third`. Use `offset(1).first()` instead. Rails’ `ids` gives `nil` for a built record with no key, where `ids()` leaves it out. > > `merge` replaces the receiver’s order, where Rails adds the argument’s to it. `toSql()` is Rails’ `to_sql`, except that Rails writes the values into the SQL and `toSql()` keeps them in `params`. --- # Raw statements Source: https://active-record.forestfuture.dev/raw-statements :::warning[Postgres reads BIGINT cells as text] `pg` reads a `BIGINT` cell as text, unless you set its type parsers. Active Record’s own clients convert it, but a query you send through your own `pg` client doesn’t. Pass `Number(cell)` to `deserialize`. ::: ## At a glance | To | Write | | --------------------------------------- | ------------------------------------ | | get an attribute’s conversions | `Invoice.typeForAttribute("paidAt")` | | bind a value as the attribute stores it | `serialize(date)` | | read a cell as the attribute’s value | `deserialize(row.paid_at)` | | get the JavaScript value for an input | `cast("2026-01-02")` | ## The Model The example uses this Model, whose attributes come from its table through the schema `active-record schema` generates. Its table stores `paid_at` as Unix seconds, so the Model overrides it as a datetime: ```ts invoice.ts import { ApplicationRecord } from "./application-record"; export class Invoice extends ApplicationRecord { static override attributes = { paidAt: { type: "datetime", storage: "unixSeconds" }, // an integer column of Unix seconds } as const; } ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: c040bb92ffaf import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** invoices — last changed by 0001_create_invoices.sql */ export const invoices = { id: { type: "integer", null: false }, total: { type: "integer", null: false }, paidAt: "integer", } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { invoices: { attributes: invoices, primaryKey: "id" }, }, models: { Invoice: "invoices" }, }); declare module "../models/invoice" { interface Invoice extends TableAttributes {} } ``` ```sql D1 -- An integer Unix time column, as Drizzle's `integer({ mode: "timestamp" })` writes it. CREATE TABLE invoices ( id INTEGER PRIMARY KEY, total INTEGER NOT NULL, paid_at INTEGER ); ``` ```sql Postgres CREATE TABLE invoices ( id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, total INTEGER NOT NULL, paid_at BIGINT ); ``` ## Binding values Bind what `serialize` gives when you send SQL yourself: ```ts import { Invoice } from "./models/invoice"; export async function paidSince(db: D1Database, since: Date) { const { serialize } = Invoice.typeForAttribute("paidAt"); const { results } = await db .prepare("SELECT id, total FROM invoices WHERE paid_at >= ?") .bind(serialize(since)) // an integer, as paid_at holds it .all<{ id: number; total: number }>(); return results; } ``` `serialize` writes the `Date` as `paidAt` stores it: an integer here, ISO text for a plain `datetime`. On Postgres, bind it as `$1` through your `pg` client. For a cache key, or the value a test expects of a raw row, `serialize` gives the stored form too. ## Reading cells Turn a cell from a raw query into the attribute’s value with `deserialize`: ```ts import { Invoice } from "./models/invoice"; export async function paidAt(db: D1Database, id: number) { const { deserialize } = Invoice.typeForAttribute("paidAt"); const row = await db .prepare("SELECT paid_at FROM invoices WHERE id = ?") .bind(id) .first<{ paid_at: number | null }>(); return deserialize(row?.paid_at); // a Date, or null } ``` ## Converting values `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`. - `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. - `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). - A filtered attribute’s value is hidden in those errors, as it is anywhere else. :::note `typeForAttribute` needs no connection to a database, and the attribute’s name is checked when you compile. ::: > **Compared with Rails** > > `typeForAttribute` is `type_for_attribute`, with the same `cast`, `serialize`, and `deserialize`. Active Record’s are strict: a value the attribute can’t hold throws, where Rails casts it leniently. --- # Read replicas Source: https://active-record.forestfuture.dev/read-your-own-writes :::note [D1 read replication](https://developers.cloudflare.com/d1/best-practices/read-replication/) serves reads from a nearby replica, which may be a moment behind. A D1 **Session** keeps each user’s reads at least as new as their own writes. ::: ## Opening a Session for each request Wrap each request in `withSession`, passing it the request and your D1 binding: ```ts import { withSession } from "@forestfuture/active-record/d1"; // src/worker.ts: each request reads at least as new as this browser's last write, from any replica. export default { fetch: (request, env) => withSession(request, env.DB, () => handle(request)), } satisfies ExportedHandler; ``` 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. `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. :::note The cookie is `HttpOnly`, `Secure`, and `SameSite=Lax`, with `Path=/`. To name it something else, pass `{ cookie: "name" }` before your handler. ::: :::note For a second D1 database, call `withSession` again inside the first one. Give each its own cookie name. ::: :::note `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"]`. ::: ## Carrying the bookmark in a header If your clients aren’t browsers, carry the bookmark in a header instead: ```ts import { withSession } from "@forestfuture/active-record/d1"; // An API's clients send back the x-d1-bookmark header of the response before. export const api = { fetch: (request, env) => withSession(request, env.DB, { header: "x-d1-bookmark" }, () => handle(request)), } satisfies ExportedHandler; ``` Each response has the bookmark in its `x-d1-bookmark` header. Clients send that header with their next request. :::note A browser app on another origin can only read the header if your CORS response lists it in `Access-Control-Expose-Headers`. ::: ## Choosing where a Session starts 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. `connect(env.DB, { session })` takes D1’s own values: | `session` | The first query goes to | | ----------------------- | -------------------------------------------------------------------------------------- | | `"first-unconstrained"` | The nearest instance, primary or replica. The fastest, but may read slightly old data. | | `"first-primary"` | The primary, so it sees every write made so far. | | A bookmark | An instance at least as new as the moment the bookmark was taken. | After the first query, each query reads data at least as new as the one before, including the request’s own writes. - **Your handler gets the request’s database** as its argument. Use it for `db.batch(…)` and `db.model(…)`. - **To log the request’s queries**, pass `onQuery` to `withSession`, as you would to `connect`. - **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. - **To mix the primary and replicas**, open two databases, and use `db.model(…)` with each. --- # Schema and ApplicationRecord Source: https://active-record.forestfuture.dev/schema ## Migrations are the source of truth Tables are created and changed by **migrations**: numbered SQL files that Wrangler applies in order, recording each one in the database (in a `d1_migrations` table), so each runs once. Cloudflare’s [D1 migrations](https://developers.cloudflare.com/d1/reference/migrations/) guide covers Wrangler’s side. Active Record’s generators write migrations for you, but any migration Wrangler can apply works, however it was written. 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. ## The generated schema 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`. That file is to Active Record what `db/schema.rb` is to Rails: a document of every table, regenerated after each migration, never edited by hand, and committed, so each schema change shows up as a readable diff next to its migration. Each table names the migration that last changed it. In CI, `active-record schema --check` catches a schema someone forgot to regenerate. 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. 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. ## How a Model gets its attributes A Model extends your app’s base class, with nothing else on the `extends` line: ```ts import { ApplicationRecord } from "./application-record"; export class Product extends ApplicationRecord {} ``` 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. When your Worker runs, `Product` finds its attributes the first time it’s used. Its table comes from its [name](/models#naming-models), and the table’s attributes from the schema that `ApplicationRecord` holds. The schema lists each Model by that name, and a Model missing from the list throws `InvalidModel`, telling you to run `active-record schema`. Without that check, a development server, which doesn’t type-check, would run a Model whose types were never generated. `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). 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). --- # Scopes Source: https://active-record.forestfuture.dev/scopes ## At a glance | To | Write | | -------------------------------- | ------------------------------------------------------------------------ | | declare a scope | `static published = this.scope((q) => q.whereNot({ … }))` | | declare one that takes arguments | `static publishedSince = this.scope((q, since: Date) => q.where({ … }))` | | call it | `Post.published()`, or on any Relation: `Post.where(…).published()` | | narrow every query | `static { this.defaultScope((q) => q.where({ isAvailable: true })) }` | | leave the default scope out | `Product.unscoped()` | ## The Models The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates: ```ts post.ts import { gte } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; export class Post extends ApplicationRecord { static published = this.scope((q) => q.whereNot({ publishedAt: null })); static publishedSince = this.scope((q, since: Date) => q.where({ publishedAt: gte(since) })); } ``` ```ts product.ts import { ApplicationRecord } from "./application-record"; export class Product extends ApplicationRecord { static { this.defaultScope((q) => q.where({ isAvailable: true })); } } ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: e9579b7b05ee import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** posts — last changed by 0001_create_tables.sql */ export const posts = { id: { type: "string", null: false, generateId: true }, title: { type: "string", null: false }, publishedAt: "datetime", } as const; /** products — last changed by 0001_create_tables.sql */ export const products = { id: { type: "string", null: false, generateId: true }, name: { type: "string", null: false }, isAvailable: { type: "boolean", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { posts: { attributes: posts, primaryKey: "id" }, products: { attributes: products, primaryKey: "id" }, }, models: { Post: "posts", Product: "products" }, }); declare module "../models/post" { interface Post extends TableAttributes {} } declare module "../models/product" { interface Product extends TableAttributes {} } ``` ```sql D1 CREATE TABLE posts ( id TEXT PRIMARY KEY NOT NULL, title TEXT NOT NULL, published_at DATETIME ); CREATE TABLE products ( id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, is_available BOOLEAN NOT NULL ); ``` ```sql Postgres CREATE TABLE posts ( id UUID PRIMARY KEY, title TEXT NOT NULL, published_at TIMESTAMPTZ ); CREATE TABLE products ( id UUID PRIMARY KEY, name TEXT NOT NULL, is_available BOOLEAN NOT NULL ); ``` ## Defining scopes Declare a scope as a static that receives the Relation, plus any arguments, and returns a narrower one: ```ts title="src/models/post.ts" import { gte } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; export class Post extends ApplicationRecord { static published = this.scope((q) => q.whereNot({ publishedAt: null })); static publishedSince = this.scope((q, since: Date) => q.where({ publishedAt: gte(since) })); } ``` ## Calling scopes Call a scope as a static, or on any Relation of the Model: ```ts import { Post } from "./models/post"; const published = await Post.published().toArray(); const thisYear = await Post.published().publishedSince(new Date("2026-01-01")).toArray(); const hellos = await Post.where({ title: "Hello" }).published().count(); // on any Relation ``` - Its arguments, and anything it computes such as `new Date()`, are evaluated when you call it. - Scopes are inherited, including those on your app’s base class ([Shared behavior](/shared-behavior)). A subclass can replace one with `static override published = this.scope(…)`. - A scope can’t reuse a Relation method’s name (`where`, `count`) or a Model static’s (`validates`, `scope`, `all`). - Inside a scope, `q` has every Relation method but not the Model’s other scopes. Share logic between scopes with a plain function. :::note A scope whose body names its own class needs its type written out: `static roots: ScopeStatic<[]> = this.scope(…)`. ::: An [enum](/enums#declaring-enums) gives its Model a scope for each name, and a `not…` scope: `Ticket.open()` and `Ticket.notOpen()`. Conditions take its names, one or a list: `Ticket.where({ status: ["open", "in_progress"] })`. ## Narrowing every query Declare a default scope in the class’s `static {}` block, as `Product` does, to narrow every query on the Model: ```ts import { Product } from "./models/product"; const listed = await Product.order({ name: "asc" }).toArray(); // available products only const draft = Product.build({ name: "Pen" }); // isAvailable: true, from the default scope ``` - New records take its conditions’ values. - It applies to everything that queries the Model: `find`, `count`, `updateAll`, `deleteAll`, its scopes, and associations that read it, preloads included. - `reload`, uniqueness validation, and a record’s own `save` and `destroy` ignore it, since they work by primary key. - `insert`, `insertAll`, `upsert`, and `upsertAll` write its conditions’ values over the values you give. `build` and `create` use the values you give. - Several default scopes all apply. A subclass adds its own to its parent’s. - An order in a default scope is the Relation’s order. `reorder` replaces it. - `rewhere` replaces its condition on an attribute, and [`unscope`](/conditions#replacing-conditions) drops its parts. ## Leaving the default scope out Start from `unscoped()` to leave the default scope out: ```ts import { Product } from "./models/product"; const everything = await Product.unscoped().toArray(); // available or not ``` `unscoped()` is a Model static only. With a database you hold, call it inside [`withDatabase`](/connecting#using-the-requests-database). :::warning[Default scopes hide records from associations too] A default scope that hides soft-deleted records also hides them from every association. A comment on a deleted post then fails to save with “Post must exist”. And `dependent: "destroy"` leaves a deleted post’s comments behind. An upsert that updates a deleted post writes `deletedAt: null`, which brings the post back. It does this even when you pass a `deletedAt`. For soft deletes, use a named scope, such as `static kept = this.scope((q) => q.where({ deletedAt: null }))`, and call `Post.kept()` where deleted posts should stay hidden. ::: > **Compared with Rails** > > `this.defaultScope` is Rails’ `default_scope`, applied the same way. `unscoped()` is only a static: Rails also has it on a Relation, where `Post.where(…).unscoped` drops every condition, the Relation’s own included. Rails’ block form, `Post.unscoped { … }`, and `all_queries: true` aren’t here. --- # Security Source: https://active-record.forestfuture.dev/security ## What Active Record protects against - **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. - **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 [Attribute types](/attribute-types#casting-assigned-values). - **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. - **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). - **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). - **Passwords kept in clear.** A [secure password](/passwords-and-tokens) is saved only as a salted digest. `toJSON()` leaves out the password, its digest, and a secure token, and `authenticateBy` takes as long whether or not a record matches, so its timing doesn’t tell anyone which accounts exist. - **Forged or reused links.** A [signed id, a token for a purpose, or a reset token](/passwords-and-tokens#signing-ids) is signed with HMAC-SHA256, so a changed or made-up one finds nothing. It finds its record only for its purpose, until it expires, and through a Relation’s conditions and default scopes. A token holds a fingerprint of the value it depends on, never the value, and a reset token stops working once the password changes. - **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. ## What’s left to your app - **Choosing which fields a request may set,** with `permit`, destructuring, or a schema. See [Untrusted input](/untrusted-input). - **An untrusted `null` in a condition.** `findBy({ token: null })` matches rows whose token is NULL. Check a value’s type before querying with it. - **How strong your password hash is.** The default, PBKDF2-SHA256, runs 100,000 iterations, the most Workers allow and about a sixth of OWASP’s 600,000. Each hash also takes about 10–40 ms of CPU time, more than the Workers Free plan’s 10 ms. For a stronger hash, give `securePassword` an algorithm of your own, as [Choosing the hash](/passwords-and-tokens#choosing-the-hash) shows, on a plan with the CPU time it needs. - **Keeping the signing secret secret.** Anyone with `SECRET_KEY_BASE` can sign tokens for any record. Set it with `wrangler secret put`, never in `wrangler.jsonc` or the repository, and [rotate it](/passwords-and-tokens#setting-the-signing-secret) if it leaks. A signed id or a token can be used again until it expires, so give one that grants access a short `expiresIn`. A token isn’t tied to a database, so with a database per tenant, [put the tenant in its purpose or `dependsOn`](/passwords-and-tokens#setting-the-signing-secret). - **Authorization.** Whether this user may read or change this record is your app’s decision. - **Formats and ranges.** Casting checks types, not meaning: use [validations](/validations). - **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. - **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. ## Guarantees, and the tests that check them 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. | Guarantee | Tests | | --------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | 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) | | 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) | | 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) | | 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) | | `permit` keeps only the named attributes, reading own keys only | [`permit`](https://github.com/forestfuture/active-record/blob/main/tests/conformance/permit.test.ts) | | Passwords are saved only as digests, never sent by `toJSON()`, and checked in the same time whether a record matches or not | [`secure-password`](https://github.com/forestfuture/active-record/blob/main/tests/conformance/secure-password.test.ts) | | Signed ids and tokens find their record only when unchanged, for their purpose, before they expire, and through a Relation’s conditions | [`signed-ids`](https://github.com/forestfuture/active-record/blob/main/tests/conformance/signed-ids.test.ts), [`token-for`](https://github.com/forestfuture/active-record/blob/main/tests/conformance/token-for.test.ts) | | Filtered attributes’ values never reach listeners or errors | [`filter-attributes`](https://github.com/forestfuture/active-record/blob/main/tests/conformance/filter-attributes.test.ts) | | A request’s database stays with that request | [`current-database`](https://github.com/forestfuture/active-record/blob/main/tests/integration/d1/current-database.test.ts) | | 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) | | 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) | | 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) | ## Supply chain - **No runtime dependencies in your Worker.** The library is one package, `@forestfuture/active-record`, with its adapters inside it. On D1 it imports no other package, so no other package’s compromise can reach your Worker through it. On Postgres it imports `pg`, the driver your app installs itself. The command line, a development tool, depends on `jiti` to load your Models; installing the library installs it, and your Worker doesn’t bundle it. - **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. - **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. - **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. - **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. - **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. ## Review log Each security review adds an entry here: what it covered, how, what it found, and what it didn’t cover. These are the project’s own reviews, not an independent audit. ### 2026-10-04: the library, its command line, and CI **Scope:** the library (`src/`), the command line (`cli/`), the CI and release workflows, and the development dependencies. **Method:** - 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; - untrusted inputs probed against a real D1 database: prototype keys, wrong types, `null`, long values; - a dependency audit with Trail of Bits’ `supply-chain-risk-auditor` and `pnpm audit`; - each fix then reviewed with Trail of Bits’ `differential-review`. **Findings, all fixed:** | Severity | Finding | Issue | | -------- | ----------------------------------------------------------------------------------------- | -------------------------------------------------------------- | | High | Assigned values weren’t checked at runtime: `"false"` saved as `true` for a boolean | [#81](https://github.com/forestfuture/active-record/issues/81) | | High | The publish job used actions pinned by movable tags, and ran install scripts | [#80](https://github.com/forestfuture/active-record/issues/80) | | High | Found while fixing #81: a pattern that backtracked on long numbers (ReDoS) | [#81](https://github.com/forestfuture/active-record/issues/81) | | Medium | No protection against mass assignment, and no guidance on an untrusted `null` | [#82](https://github.com/forestfuture/active-record/issues/82) | | Medium | Bound values, secrets included, reached `onQuery` listeners and errors | [#83](https://github.com/forestfuture/active-record/issues/83) | | Low | Inherited names (`constructor`, `__proto__`) caused errors instead of being unknown names | [#84](https://github.com/forestfuture/active-record/issues/84) | | Low | Development dependency advisories, and unescaped config values in generated code | [#85](https://github.com/forestfuture/active-record/issues/85) | **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. ### 2026-10-10: CodeQL’s alerts on the public repository **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. **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. **Findings:** | Severity | Finding | Outcome | Link | | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 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) | | 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) | | 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) | | 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) | | 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) | **Not covered:** the Scorecard findings, which are about the project’s practices, not its code, and the dependencies’ own code. ### 2026-10-25: before 0.5.0 **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). **Method:** - 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; - Trail of Bits’ `differential-review` of #232’s change before it merged. **Findings:** | Severity | Finding | Outcome | Link | | -------- | ---------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ---------------------------------------------------------------- | | 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) | | 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) | | 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) | | 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) | **Not covered:** D1 and workerd themselves; the dependencies’ code; apps’ own code. ## Reporting a vulnerability 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. --- # Serialization Source: https://active-record.forestfuture.dev/serialization ## At a glance | To | Write | | ----------------------------------------- | ------------------------------------------------------------------------ | | send a record as JSON | `Response.json(account)` | | read its attributes as JavaScript values | `account.attributes()` | | keep an attribute out of JSON | `static override hiddenAttributes = ["passwordDigest"]` | | show an attribute as `[FILTERED]` in logs | `static override filterAttributes = [...Model.filterAttributes, "iban"]` | | see a record or a Relation | `console.log(account)` | | Setting | Keeps values out of | Default | | ------------------ | -------------------------------------------------------- | --------------------------------------------- | | `hiddenAttributes` | `toJSON()`, so `Response.json` and `JSON.stringify` | nothing | | `filterAttributes` | `onQuery` listeners, error messages, and printed records | passwords, emails, tokens, keys, and the like | ## The Model The examples use this Model, whose attributes come from its table through the schema `active-record schema` generates. Your app’s base class holds the settings every Model shares: ```ts application-record.ts import { Model } from "@forestfuture/active-record"; import { schema } from "../db/schema"; export abstract class ApplicationRecord extends Model { static override schema = schema; // Left out of toJSON(), so Response.json(record) never sends them: static override hiddenAttributes = ["passwordDigest"]; // Shown as [FILTERED] in logs, errors, and printed records: the defaults, and an IBAN. static override filterAttributes = [...Model.filterAttributes, "iban"]; } ``` ```ts account.ts import { ApplicationRecord } from "./application-record"; export class Account extends ApplicationRecord { // A Model's list replaces the base class's, so repeat what you still want hidden: static override hiddenAttributes = [...ApplicationRecord.hiddenAttributes, "apiKey"]; } ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: 0735d8f7f772 import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** accounts — last changed by 0001_create_accounts.sql */ export const accounts = { id: { type: "string", null: false, generateId: true }, email: { type: "string", null: false }, passwordDigest: "string", apiKey: "string", iban: "string", createdAt: { type: "datetime", null: false }, updatedAt: { type: "datetime", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { accounts: { attributes: accounts, primaryKey: "id" }, }, models: { Account: "accounts" }, }); declare module "../models/account" { interface Account extends TableAttributes {} } ``` ```sql D1 CREATE TABLE accounts ( id TEXT PRIMARY KEY NOT NULL, email TEXT NOT NULL, password_digest TEXT, api_key TEXT, iban TEXT, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL ); ``` ```sql Postgres CREATE TABLE accounts ( id UUID PRIMARY KEY, email TEXT NOT NULL, password_digest TEXT, api_key TEXT, iban TEXT, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL ); ``` ## Serializing records `toJSON()` gives a record’s attributes with dates as ISO strings, and `attributes()` gives them with JavaScript values: ```ts import { Account } from "./models/account"; const account = await Account.findByOrThrow({ email: "jane@example.com" }); const body = JSON.stringify(account); // dates as ISO strings, passwordDigest and apiKey left out const attributes = account.attributes(); // every attribute, dates as Date ``` Associations are never included, so a response never loads more than you asked for. `Response.json(record)` uses `toJSON()`: ```ts import { Account } from "./models/account"; export async function show(request: Request): Promise { const email = new URL(request.url).searchParams.get("email") ?? ""; const account = await Account.findBy({ email }); return account ? Response.json(account) : new Response("Not found", { status: 404 }); } ``` ## Hiding attributes Name an attribute in `static hiddenAttributes` on your app’s base class to keep it out of every Model’s `toJSON()`, as `ApplicationRecord` does with `passwordDigest`: - A Model’s own list replaces the base class’s, so `Account` repeats it beside `apiKey`. - By default, nothing is hidden, and each name must match an attribute exactly. - `attributes()` still returns every attribute, so you can send a hidden one on purpose. - A [secure password](/passwords-and-tokens), with its confirmation, challenge, and digest, and a secure token are left out without being listed. :::note 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. ::: ## Filtering attributes `onQuery` listeners, error messages, and printed records show a filtered attribute’s values as `"[FILTERED]"`, while the database still gets the real values. [Logging](/logging#keeping-secrets-out-of-the-logs) shows a listener: - **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 by name. A [secure password](/passwords-and-tokens), with its confirmation, challenge, and digest, and a secure token are filtered whatever the list says. - **Matching:** a string matches when the attribute’s snake_case name contains it, in any case: `passwordDigest` (`password_digest`) contains `passw`, and `apiKey` (`api_key`) contains `_key`. A string can also be written as the attribute is, so `"secretAt"`, `"secret_at"`, and `"secret"` all match `secretAt`. A RegExp matches the attribute or its snake_case name. - **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`. - **Hidden in errors:** a cast error’s value, and a filtered primary key in `RecordNotFound`. - **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()`). ## Printing records `console.log(account)`, a failed test, and the console show a record’s class and attributes: ```text Account { id: '3b241101-e2bb-4255-8caf-4136c566a962', email: [FILTERED], passwordDigest: [FILTERED], apiKey: [FILTERED], iban: [FILTERED], createdAt: 2026-01-15T00:00:00.000Z, updatedAt: 2026-01-15T00:00:00.000Z } ``` - **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`. - **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. A new record flags nothing, since all of it is unsaved. - **A partial record** prints only the columns it loaded, and bytes print as how many there are: `<3 bytes of binary data>`. - **Hidden attributes** still print: they keep values out of `toJSON()`, not out of your console. Printing never loads an association. A Relation prints the SELECT it would send, without sending it, with a filtered attribute’s value in `params` as `[FILTERED]`: ```text Relation { sql: 'SELECT * FROM "accounts" WHERE (("email" = ?))', params: [ [FILTERED] ] } ``` Printing can’t wait for the database, so to see the records, `await` it or call `toArray()`. A record’s `errors` print each failure, so a failed `save()` shows why in the console: ```text Errors [ { attribute: 'name', type: 'blank', message: "can't be blank" }, { attribute: 'email', type: 'too_short', message: 'is too short' } ] ``` > **Compared with Rails** > > The default filter list is Rails’ own `filter_parameters` list, and the filtered values read as they do in Rails’ logs. A record prints as Rails’ `inspect` does. A Rails Relation runs its query to print its records, which a synchronous `console.log` can’t do here. > **Beyond Rails** > > Rails’ `serializable_hash(except:)` is per call, and `filter_attributes` only covers logs and inspection. Active Record keeps a class-level list, so `Response.json(user)` is safe without each call site remembering to strip the attribute. Rails also doesn’t mark unsaved changes when it prints a record. Active Record does, so a pending edit is visible in the console before you save it. --- # Multiple databases Source: https://active-record.forestfuture.dev/several-databases ## Binding the databases Add each database to your Wrangler config, with its own `migrations_dir`: ```jsonc wrangler.jsonc { "d1_databases": [ { "binding": "DB", "database_name": "my-app-db", "database_id": "…" }, { "binding": "LOGS", "database_name": "my-app-logs", "database_id": "…", "migrations_dir": "logs-migrations", }, ], } ``` Wrangler applies a folder’s migrations to one database, so each needs its own folder. ## Generating a schema for each Generate the schemas as usual: ```sh npx active-record schema ``` With several databases, it writes one of each per binding: | Binding | Schema | Base class | | ------- | ---------------- | -------------------------------------------- | | `DB` | `src/db/DB.ts` | `DbRecord`, in `src/models/db-record.ts` | | `LOGS` | `src/db/LOGS.ts` | `LogsRecord`, in `src/models/logs-record.ts` | Each base class holds its database’s schema, which names its binding, so its Models query that database: ```ts import { LogsRecord } from "./logs-record"; export class Entry extends LogsRecord {} await Entry.where({ level: "error" }).count(); // on LOGS ``` ## Generating Models for one database Name the binding with `--database`: ```sh npx active-record g model Entry 'level:string!' message --database LOGS npx active-record migrate --database LOGS ``` ## Using both in a request Query each Model as usual. Each one uses the database its base class names: ```ts // src/worker.ts: each Model queries its own database. export default { async fetch(request) { const email = new URL(request.url).searchParams.get("email") ?? ""; const user = await User.findByOrThrow({ email }); // on DB await Entry.create({ level: "info", message: `${user.email} signed in` }); // on LOGS return Response.json(user); }, } satisfies ExportedHandler; ``` Records remember their database, so `user.save()` writes back to `DB`, and `entry.save()` to `LOGS`. ## Writing to both Each write goes to one database. Write to the database that matters most first: ```ts export async function signUp(email: string) { const user = await User.createOrThrow({ email }); // on DB first: if it throws, nothing is logged await Entry.create({ level: "info", message: `${user.email} signed up` }); // then on LOGS return user; } ``` If `createOrThrow` throws, nothing reaches `LOGS`. :::warning[Two databases aren’t one write] 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`. ::: ## Associating Models on different databases An association can link Models on different databases. Declare it as usual: ```ts import { belongsTo, hasMany } from "@forestfuture/active-record"; export class User extends DbRecord { entries = hasMany(Entry); // on LOGS } export class Entry extends LogsRecord { user = belongsTo(User, { optional: true }); // on DB; an entry may have no user } ``` Each read goes to the database its Model is on: ```ts export async function errorEntriesOf(userId: number) { const user = await User.find(userId); // on DB return user.entries().where({ level: "error" }).toArray(); // on LOGS } export async function entriesWithUsers() { return Entry.includes("user").toArray(); // the entries on LOGS, then their users on DB } ``` `includes` loads the users from `DB` once the entries are loaded, in one more round trip. Each other database a [preload](/preloading) reaches adds one. Records you create through an association are written to their own database: ```ts export async function logFor(user: User, message: string) { return user.entries().create({ level: "info", message }); // on LOGS, with the user's key } ``` Saving a record also saves the records built through it, each on its own database. Here the user is written to `DB` first, then the entry to `LOGS` with the user’s new key: ```ts export async function signUpWithEntry(email: string) { const user = User.build({ email }); user.entries().build({ level: "info", message: "signed up" }); await user.saveOrThrow(); // the user on DB, then the entry on LOGS return user; } ``` [`dependent` strategies](/associations#destroying-dependent-records) work the same way. With `dependent: "destroy"` on a user’s entries, destroying the user destroys its entries on `LOGS`, then deletes the user from `DB`. :::warning[Each database is written on its own] A save or a destroy that reaches two databases writes to each one separately. If the second write fails, the first stays written. A batch writes to one database, so `batch` throws `IncompatibleRelation` for a record whose writes reach another one. ::: ## Reading your own writes on each With read replication, give each database its own Session. Nest a `withSession` call for each, and give each its own cookie name: ```ts import { withSession } from "@forestfuture/active-record/d1"; // src/worker.ts: each database's bookmark travels in its own cookie. export const replicas = { fetch: (request, env) => withSession(request, env.DB, () => withSession(request, env.LOGS, { cookie: "logs-bookmark" }, () => handle(request)), ), } satisfies ExportedHandler; ``` 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. :::note To pass per-request options without Sessions, such as `onQuery`, open the databases yourself and pass them all to `withDatabase`: ```ts import { withDatabase } from "@forestfuture/active-record"; import { connect, type Database, type QueryListener } from "@forestfuture/active-record/d1"; const onQuery: QueryListener = ({ sql }) => console.log(sql); const databases: Database[] = [connect(env.DB, { onQuery }), connect(env.LOGS, { onQuery })]; return withDatabase(databases, handle); // each Model uses the one on its binding ``` ::: ## Testing with several databases Outside a Worker, a Model can’t look up its binding. Give your tests the bindings by mocking `cloudflare:workers`. First, let Vitest’s mocks reach Active Record: ```ts vitest.config.ts import { defineConfig } from "vitest/config"; export default defineConfig({ test: { server: { deps: { inline: ["@forestfuture/active-record"] } } }, }); ``` Then mock the module with your test databases as its `env`, using the `testDatabase` helper from [Testing](/testing): ```ts test/worker.test.ts import { afterAll, beforeAll, expect, test, vi } from "vitest"; import worker from "../src/index"; import { testDatabase } from "./d1"; const env = vi.hoisted(() => ({}) as Env); vi.mock("cloudflare:workers", () => ({ env })); let databases: Awaited>[]; beforeAll(async () => { databases = await Promise.all([testDatabase(), testDatabase("logs-migrations")]); Object.assign(env, { DB: databases[0].binding, LOGS: databases[1].binding }); }); afterAll(() => Promise.all(databases.map((database) => database.dispose()))); test("signing in logs an entry", async () => { const request = new Request("https://example.com/?email=ada@example.com"); const response = await worker.fetch(request, env); expect(response.status).toBe(200); }); ``` Each Model now finds its own database, as it does in a Worker. Call your Worker’s `fetch` without `withDatabase`. :::note Assign the bindings onto the mocked `env` object, as above. Active Record reads `env` the first time a Model needs its binding, so it never sees an object assigned later. ::: ## Opening one in the console Name the binding with `--database`: ```sh npx active-record console --database LOGS ``` ## Using databases on different adapters One project can keep some of its tables on D1 and others on Postgres. First install `pg` and PGlite, as [PostgreSQL](/postgresql) describes. Name each database’s adapter in `active-record.jsonc`, and give the Postgres one its own migrations folder: ```jsonc active-record.jsonc { "databases": { "DB": { "adapter": "d1" }, "HYPERDRIVE": { "adapter": "postgresql", "migrationsDir": "pg-migrations", "url": "postgres://localhost/shop_development", }, }, } ``` D1 and Postgres write their SQL differently, so each database needs a folder of its own. Both adapters read `migrations/` by default, and the command refuses two databases on different adapters that share one. To add your Hyperdrive bindings to a file that names only D1 databases, run `init` with the adapter: ```sh npx active-record init --adapter postgresql ``` `npx active-record schema` reads each database with its own adapter. `src/db/DB.ts` imports `d1`, and `src/db/HYPERDRIVE.ts` imports `postgresql`. Build each Model on its database’s base class: ```ts import { HyperdriveRecord } from "./hyperdrive-record"; export class Order extends HyperdriveRecord {} ``` Name the database with `--database` for the generators, `migrate`, and the console: ```sh npx active-record g model Order total:integer --database HYPERDRIVE npx active-record migrate --database HYPERDRIVE ``` --- # Shared behavior Source: https://active-record.forestfuture.dev/shared-behavior ## At a glance | To | Write, on `ApplicationRecord` | | --------------------------------------- | -------------------------------------------------------- | | give every record a method | `label() { … }` | | run a callback for every Model | `this.beforeSave(…)`, in `static {}` | | give every Model a scope | ``static newest = this.scope((q) => q.order(sql`…`))`` | | share behavior between only some Models | an `abstract` class between them and `ApplicationRecord` | ## The Models The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates: ```ts application-record.ts import { Model, sql } from "@forestfuture/active-record"; import { schema } from "../db/schema"; // What's written on ApplicationRecord, every Model has. export abstract class ApplicationRecord extends Model { static override schema = schema; static newest = this.scope((q) => q.order(sql`created_at DESC`)); label() { return `${this.constructor.name} ${JSON.stringify(this.attributes())}`; } static { this.beforeSave((record) => { console.log(`Saving ${record.constructor.name}`); // before each Model's own callbacks }); } } ``` ```ts product.ts import { ApplicationRecord } from "./application-record"; export class Product extends ApplicationRecord {} ``` ```ts auditable.ts import { ApplicationRecord } from "./application-record"; // Shared by only the Models that extend it. It has no table of its own. export abstract class Auditable extends ApplicationRecord { static override abstract = true; static { this.afterSave((record) => { console.log(`Saved ${record.constructor.name}`); }); } } ``` ```ts invoice.ts import { Auditable } from "./auditable"; export class Invoice extends Auditable {} ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: 114ec35af314 import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** invoices — last changed by 0001_create_tables.sql */ export const invoices = { id: { type: "string", null: false, generateId: true }, totalCents: { type: "integer", null: false }, createdAt: { type: "datetime", null: false }, } as const; /** products — last changed by 0001_create_tables.sql */ export const products = { id: { type: "string", null: false, generateId: true }, name: { type: "string", null: false }, createdAt: { type: "datetime", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { invoices: { attributes: invoices, primaryKey: "id" }, products: { attributes: products, primaryKey: "id" }, }, models: { Invoice: "invoices", Product: "products" }, }); declare module "../models/invoice" { interface Invoice extends TableAttributes {} } declare module "../models/product" { interface Product extends TableAttributes {} } ``` ```sql D1 CREATE TABLE products ( id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, created_at DATETIME NOT NULL ); CREATE TABLE invoices ( id TEXT PRIMARY KEY NOT NULL, total_cents INTEGER NOT NULL, created_at DATETIME NOT NULL ); ``` ```sql Postgres CREATE TABLE products ( id UUID PRIMARY KEY, name TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL ); CREATE TABLE invoices ( id UUID PRIMARY KEY, total_cents INTEGER NOT NULL, created_at TIMESTAMPTZ NOT NULL ); ``` ## Sharing methods, callbacks, and scopes Write them on `ApplicationRecord`, in `src/models/application-record.ts`, and every Model has them, as `Product` does: ```ts import { Product } from "./models/product"; const lamp = await Product.create({ name: "Lamp" }); // logs "Saving Product" console.log(lamp.label()); // Product {"id":"…","name":"Lamp","createdAt":"…"} const newest = await Product.newest().first(); // the shared scope, on products ``` Each is shared like this: | On `ApplicationRecord` | Every Model | | ---------------------------------------- | ------------------------------------------------------ | | A method, such as `label()` | has it, on every record | | A static method | has it, on the Model | | A callback, in `static {}` | runs it, before the Model’s own callbacks of that kind | | A scope, `static newest = this.scope(…)` | has it, as `Product.newest()` and on its Relations | | `static override onQuery` | logs its queries (see [Logging](/logging)) | A Model can replace a shared method or scope by declaring one of the same name. :::note `active-record schema` writes `application-record.ts` with commented-out examples to start from. ::: ## Writing for every table 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: - Read attributes through `this.attributes()`, as `label()` does. - Write shared scopes with `sql` fragments, as `newest` does, since they run on each Model’s own table. - Validations name attributes, so they belong on each Model. Put shared checks in a callback instead. `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. ## Sharing behavior between some Models To share behavior between only some Models, put it on a class between them and `ApplicationRecord`, marked `abstract`, as `Auditable` is: ```ts import { Invoice } from "./models/invoice"; await Invoice.create({ totalCents: 1200 }); // logs "Saving Invoice", then "Saved Invoice" ``` `Auditable` has no table. Each class that extends it has its own, so `Invoice` reads and writes `invoices`. ## Sharing across databases 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: ```ts import { Model } from "@forestfuture/active-record"; import { schema } from "../db/LOGS"; export abstract class AppRecord extends Model { label() { return `${this.constructor.name} ${JSON.stringify(this.attributes())}`; } } export abstract class LogsRecord extends AppRecord { static override schema = schema; } ``` See [Multiple databases](/several-databases). --- # Testing Source: https://active-record.forestfuture.dev/testing ## At a glance | To | Write | | ------------------------------ | ------------------------------------------------------------ | | get a real D1 database in Node | Miniflare’s `getD1Database`, with your migrations applied | | run a Model’s code in a test | `withDatabase(connect(database.binding), async () => { … })` | | call your Worker in a test | `withDatabase(…, () => worker.fetch(request))` | | query a database you hold | `connect(database.binding).model(User)` | ## The Model The tests below check this Model and Worker, with the users table its migration creates: ```ts user.ts import { ApplicationRecord } from "./application-record"; export class User extends ApplicationRecord { static { this.beforeValidation((user) => { user.email = user.email.toLowerCase(); }); } } ``` ```ts index.ts import { User } from "./models/user"; // The app's Worker: here, one route that lists the users' emails. export default { async fetch() { return Response.json(await User.order({ email: "asc" }).pluck("email")); }, } satisfies ExportedHandler; ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: ae4437c2fc95 import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** users — last changed by 0001_create_users.sql */ export const users = { id: { type: "string", null: false, generateId: true }, email: { type: "string", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { users: { attributes: users, primaryKey: "id" }, }, models: { User: "users" }, }); declare module "../models/user" { interface User extends TableAttributes {} } ``` ```sql D1 CREATE TABLE users ( id TEXT PRIMARY KEY NOT NULL, email TEXT NOT NULL ); ``` ```sql Postgres CREATE TABLE users ( id UUID PRIMARY KEY, email TEXT NOT NULL ); ``` ## Installing [Miniflare](https://developers.cloudflare.com/workers/testing/miniflare/) runs Cloudflare’s runtime, D1 included, inside Node: ```sh npm install --save-dev vitest miniflare@4 ``` ## Creating a test database Start Miniflare with a D1 database, and apply a folder of migrations to it, in order: ```ts test/d1.ts import { readdirSync, readFileSync } from "node:fs"; import { Miniflare } from "miniflare"; export async function testDatabase(folder = "migrations") { const mf = new Miniflare({ modules: true, script: "export default {}", d1Databases: ["DB"] }); const binding = await mf.getD1Database("DB"); for (const file of readdirSync(folder).sort()) { // Each migration's statements, without its comments, applied together. const statements = readFileSync(`${folder}/${file}`, "utf8") .replace(/^\s*--.*$/gm, "") .split(/;\s*$/m) .map((statement) => statement.trim()) .filter(Boolean); if (statements.length > 0) await binding.batch(statements.map((statement) => binding.prepare(statement))); } return { binding, dispose: () => mf.dispose() }; } ``` ## Testing Models Outside a Worker there’s no binding, so run the test’s code inside `withDatabase`. This checks that `User` saves emails in lowercase: ```ts test/users.test.ts import { withDatabase } from "@forestfuture/active-record"; import { connect } from "@forestfuture/active-record/d1"; import { afterAll, beforeAll, expect, test } from "vitest"; import { User } from "../src/models/user"; import { testDatabase } from "./d1"; let database: Awaited>; beforeAll(async () => (database = await testDatabase())); afterAll(() => database.dispose()); test("emails are saved in lowercase", async () => { await withDatabase(connect(database.binding), async () => { const user = await User.create({ email: "Jane@Example.com" }); expect((await User.find(user.id)).email).toBe("jane@example.com"); }); }); ``` Outside a Worker, the database given to `withDatabase` serves every Model on its adapter, whatever binding its base class names. For code that takes a database explicitly, pass it one: `connect(database.binding).model(User)`. ## Testing your Worker Call your Worker’s `fetch` handler inside `withDatabase` too, and its queries use the test’s database. This calls the Worker in `src/index.ts`: ```ts test/worker.test.ts import { withDatabase } from "@forestfuture/active-record"; import { connect } from "@forestfuture/active-record/d1"; import { afterAll, beforeAll, expect, test } from "vitest"; import worker from "../src/index"; import { testDatabase } from "./d1"; let database: Awaited>; beforeAll(async () => (database = await testDatabase())); afterAll(() => database.dispose()); test("GET lists users", async () => { const response = await withDatabase(connect(database.binding), () => worker.fetch(new Request("https://example.com/")), ); expect(response.status).toBe(200); }); ``` Each test file gets its own database. :::note 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. ::: :::note To run tests inside the Workers runtime itself, use Cloudflare’s [Vitest integration](https://developers.cloudflare.com/workers/testing/vitest-integration/). ::: --- # Through associations Source: https://active-record.forestfuture.dev/through-associations ## At a glance | To | Write | | --------------------------------------- | ------------------------------------------------------------ | | declare a many-to-many association | `hasMany(Article, { through: "taggings" })` | | follow an association with another name | `hasMany(Author, { through: "articles", source: "author" })` | | reach one record | `hasOne(Author, { through: "article" })` | | read the records | `tag.articles()`, a Relation | | preload them | `Tag.includes("articles")` | | link a record | `tag.articles().push(article)` | | create a record and link it | `tag.articles().create({ … })` | | unlink a record | `tag.articles().delete(article)` | ### Options | Prop | Type | Default | Description | | - | - | - | - | | `through` | `string` | - | The association to go through. | | `source?` | `string` | - | The join Model’s association to follow. Defaults to this association’s name, singular or plural. | | `scope?` | `(q) => Relation` | - | Narrows or orders the records, as on any association. | | `dependent?` | `"destroy" \| "deleteAll"` | - | What destroying the owner does to the join records. hasMany only. | `scope` works as it does on any association. See [Scoping associations](/associations#scoping-associations). ## The Models The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates: ```ts author.ts import { hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Article } from "./article"; export class Author extends ApplicationRecord { articles = hasMany(Article); } ``` ```ts article.ts import { belongsTo, hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Author } from "./author"; import { Tag } from "./tag"; import { Tagging } from "./tagging"; export class Article extends ApplicationRecord { author = belongsTo(Author); taggings = hasMany(Tagging); tags = hasMany(Tag, { through: "taggings" }); // each tagging's tag } ``` ```ts tag.ts import { hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Article } from "./article"; import { Author } from "./author"; import { Tagging } from "./tagging"; export class Tag extends ApplicationRecord { taggings = hasMany(Tagging); articles = hasMany(Article, { through: "taggings" }); // each tagging's article writers = hasMany(Author, { through: "articles", source: "author" }); // each article's author } ``` ```ts tagging.ts import { belongsTo, hasOne } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Article } from "./article"; import { Author } from "./author"; import { Tag } from "./tag"; export class Tagging extends ApplicationRecord { article = belongsTo(Article); tag = belongsTo(Tag); author = hasOne(Author, { through: "article" }); // the article's author } ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: 37e9b66aad51 import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** articles — last changed by 0001_create_tables.sql */ export const articles = { id: { type: "string", null: false, generateId: true }, authorId: { type: "string", null: false }, title: { type: "string", null: false }, } as const; /** authors — last changed by 0001_create_tables.sql */ export const authors = { id: { type: "string", null: false, generateId: true }, name: { type: "string", null: false }, } as const; /** taggings — last changed by 0001_create_tables.sql */ export const taggings = { id: { type: "integer", null: false }, articleId: { type: "string", null: false }, tagId: { type: "integer", null: false }, } as const; /** tags — last changed by 0001_create_tables.sql */ export const tags = { id: { type: "integer", null: false }, name: { type: "string", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { articles: { attributes: articles, primaryKey: "id" }, authors: { attributes: authors, primaryKey: "id" }, taggings: { attributes: taggings, primaryKey: "id" }, tags: { attributes: tags, primaryKey: "id" }, }, models: { Article: "articles", Author: "authors", Tag: "tags", Tagging: "taggings" }, }); declare module "../models/article" { interface Article extends TableAttributes {} } declare module "../models/author" { interface Author extends TableAttributes {} } declare module "../models/tag" { interface Tag extends TableAttributes {} } declare module "../models/tagging" { interface Tagging extends TableAttributes {} } ``` ```sql D1 CREATE TABLE authors ( id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL ); CREATE TABLE articles ( id TEXT PRIMARY KEY NOT NULL, author_id TEXT NOT NULL REFERENCES authors (id), title TEXT NOT NULL ); CREATE TABLE tags ( id INTEGER PRIMARY KEY, name TEXT NOT NULL ); CREATE TABLE taggings ( id INTEGER PRIMARY KEY, article_id TEXT NOT NULL REFERENCES articles (id), tag_id INTEGER NOT NULL REFERENCES tags (id) ); ``` ```sql Postgres CREATE TABLE authors ( id UUID PRIMARY KEY, name TEXT NOT NULL ); CREATE TABLE articles ( id UUID PRIMARY KEY, author_id UUID NOT NULL REFERENCES authors (id), title TEXT NOT NULL ); CREATE TABLE tags ( id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, name TEXT NOT NULL ); CREATE TABLE taggings ( id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, article_id UUID NOT NULL REFERENCES articles (id), tag_id BIGINT NOT NULL REFERENCES tags (id) ); ``` ## Reading records Read a through association as you would any `hasMany`: ```ts import { Article } from "./models/article"; import { Tag } from "./models/tag"; const tag = await Tag.findByOrThrow({ name: "essays" }); const articles = await tag.articles().order({ title: "asc" }).toArray(); // one query const article = await Article.findByOrThrow({ title: "Engines" }); const tags = await article.tags().toArray(); // the other way, through the same taggings ``` - `through` names one of the Model’s own associations, here `taggings`. The join Model’s association with the same name, singular or plural, leads on to the records: `articles` follows each tagging’s `article`. - `tag.articles()` is a Relation, with every Relation method, read in one query. Its writes go to the taggings, as [below](#writing-through-it). - Each record comes back once, however many join records point at it. - The scopes of both associations it goes through apply, and so does its own `scope`. ## Preloading records Preload the records for every tag with `includes`: ```ts import { Tag } from "./models/tag"; const everyTag = await Tag.includes("articles").toArray(); // tags, taggings, and articles for (const each of everyTag) console.log(each.name, each.loaded("articles").length); ``` The join records and the articles load with the tags’ own query, in one round trip on D1. The join records aren’t kept as `taggings` unless you include them too. ## Naming the source If the join Model’s association has another name, pass it as `source`, as `writers` does to follow each article’s `author`: ```ts import { Tag } from "./models/tag"; const tag = await Tag.findByOrThrow({ name: "essays" }); const writers = await tag.writers().toArray(); // each author once ``` `writers` goes through `articles`, which goes through `taggings`. An association can go through any number of others this way. ## Going through a belongsTo or a hasOne A `hasOne` can go through a `belongsTo`, as a tagging’s `author` does through its `article`: ```ts import { Tagging } from "./models/tagging"; const tagging = await Tagging.firstOrThrow(); const author = await tagging.author(); ``` `through` can name a `belongsTo`, a `hasMany`, or a `hasOne`, and the association it follows can be any of the three. A `hasOne` goes through a `belongsTo` or a `hasOne`. ## Writing through it Add records with `push`, `build`, and `create`, which each make the join record that links the owner to the record: ```ts import { Article } from "./models/article"; import { Tag } from "./models/tag"; const tag = await Tag.findByOrThrow({ name: "essays" }); const article = await Article.findByOrThrow({ title: "Engines" }); await tag.articles().push(article); // saves a tagging that links them const draft = await tag.articles().create({ authorId: article.authorId, title: "Draft" }); await tag.articles().delete(article); // deletes the tagging; the article stays ``` - `push(article)` saves a tagging for each article, in one write. A new article is saved first. - `build(attributes)` builds the article and its tagging. Saving the tag saves both. Saving the article on its own saves no tagging. - `create(attributes)` saves the article, then its tagging. An invalid article comes back unsaved, and nothing is written. On a tag that isn’t saved yet, `push` and `build` wait for the tag’s save. `create` throws `RecordNotSaved` there, as it does through a `hasMany`. Records built or created through it take the equality values of its `scope`, and their join records take those of the association it goes through. ## Removing records Removing records through the association removes their join records. The records themselves stay: | Method | Does | | ------------------ | --------------------------------------------------------------------------------------------------- | | `delete(article)` | Deletes the tag’s taggings to the article, without callbacks | | `destroy(article)` | Destroys those taggings, running their callbacks, in one write | | `clear()` | Deletes every tagging to the tag’s articles, without callbacks. The tag then has no articles loaded | | `deleteAll()` | Deletes the same taggings, and resolves to how many it deleted | | `destroyAll()` | Destroys the same taggings, running their callbacks, and resolves to the articles | An article the tag doesn’t reach removes nothing. To remove an article itself, destroy it: `await article.destroy()`. In a batch, pass the association to the write: `b.deleteAll(tag.articles())` deletes the tag’s taggings. :::warning[A narrowed deleteAll or destroyAll removes the records themselves] `updateAll`, and a narrowed `deleteAll` or `destroyAll`, act on the records, as any Relation’s do. `tag.articles().where({ title: "Draft" }).deleteAll()` deletes those articles for every tag, not the tag’s taggings. ::: ### Removing join records with dependent A `hasMany` through a join Model takes `dependent: "destroy"` or `dependent: "deleteAll"`, which acts on its join records: - With `"destroy"`, destroying the tag destroys its taggings, running their callbacks, and `delete` destroys them too. - With `"deleteAll"`, destroying the tag deletes them without callbacks. - `clear` and `deleteAll` always delete them without callbacks. ## Setting a hasOne through another A `hasOne` that goes through another `hasOne` has `set`, and no `build` or `create`: - `set(record)` points the owner’s join record at the record, or creates the join record if there isn’t one, with the equality values of the join association’s `scope`. - `set(null)` destroys the join record. ## Spotting read-only associations Writes need a join Model: the association has to go through a `hasMany` (a `hasOne`, for a `hasOne`), and follow a `belongsTo` from there, with neither going through another. Any other write throws `ReadonlyAssociation`, naming the association that stops it. `writers` is read-only, since it goes through `articles`, which goes through `taggings`. `insert`, `insertAll`, `upsert`, and `upsertAll` throw `ReadonlyAssociation` on any association through another, since they write no join records. :::note Every association it goes through must be on one database. One that reaches [another database](/several-databases#associating-models-on-different-databases) is an `InvalidModel` for now ([#435](https://github.com/forestfuture/active-record/issues/435)). ::: > **Compared with Rails** > > `through` and `source` work as Rails’ `has_many :through` and `has_one :through` options do. Rails reads through a SQL join, so a record two join records point at comes back twice unless the association is `distinct`. Here it comes back once. > > Writing through it works as in Rails: `destroy` destroys the join records rather than the records, `clear` deletes them whatever `dependent` is, and `insert_all` through it raises. Rails also writes through a `belongsTo` or `hasOne` hop by building or updating that hop’s record, which can change a record that other records share. Here that throws `ReadonlyAssociation`. Rails’ `disable_joins` has no counterpart yet. --- # Touching Source: https://active-record.forestfuture.dev/touching ## At a glance | To | Write | | ------------------------------------------- | ---------------------------------------------- | | touch an article whenever a comment changes | `belongsTo(Article, { touch: true })` | | set another datetime attribute too | `touch: "lastCommentedAt"`, or a list of names | | touch a profile whenever its user changes | `hasOne(Profile, { touch: true })` | | touch a record yourself | `comment.touch()` | | skip touches during an import | `Article.noTouching(async () => { … })` | ## The Models The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates: ```ts comment.ts import { belongsTo } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Article } from "./article"; export class Comment extends ApplicationRecord { article = belongsTo(Article, { touch: true }); // sets the article's updatedAt } ``` ```ts article.ts import { belongsTo, hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Blog } from "./blog"; import { Comment } from "./comment"; export class Article extends ApplicationRecord { blog = belongsTo(Blog, { touch: true }); // touching an article touches its blog comments = hasMany(Comment); } ``` ```ts blog.ts import { ApplicationRecord } from "./application-record"; export class Blog extends ApplicationRecord {} ``` ```ts reply.ts import { belongsTo } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Article } from "./article"; export class Reply extends ApplicationRecord { static override table = "comments"; article = belongsTo(Article, { touch: "lastCommentedAt" }); // and updatedAt } ``` ```ts user.ts import { hasOne } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Profile } from "./profile"; export class User extends ApplicationRecord { profile = hasOne(Profile, { touch: true }); // sets the profile's updatedAt } ``` ```ts profile.ts import { ApplicationRecord } from "./application-record"; export class Profile extends ApplicationRecord {} ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: 1b91f7d16771 import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** articles — last changed by 0001_create_tables.sql */ export const articles = { id: { type: "string", null: false, generateId: true }, blogId: { type: "string", null: false }, title: { type: "string", null: false }, updatedAt: "datetime", lastCommentedAt: "datetime", } as const; /** blogs — last changed by 0001_create_tables.sql */ export const blogs = { id: { type: "string", null: false, generateId: true }, updatedAt: "datetime", } as const; /** comments — last changed by 0001_create_tables.sql */ export const comments = { id: { type: "string", null: false, generateId: true }, articleId: { type: "string", null: false }, body: { type: "string", null: false }, updatedAt: "datetime", } as const; /** profiles — last changed by 0001_create_tables.sql */ export const profiles = { id: { type: "string", null: false, generateId: true }, userId: { type: "string", null: false }, bio: "string", updatedAt: "datetime", } as const; /** users — last changed by 0001_create_tables.sql */ export const users = { id: { type: "string", null: false, generateId: true }, name: { type: "string", null: false }, updatedAt: "datetime", } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { articles: { attributes: articles, primaryKey: "id" }, blogs: { attributes: blogs, primaryKey: "id" }, comments: { attributes: comments, primaryKey: "id" }, profiles: { attributes: profiles, primaryKey: "id" }, users: { attributes: users, primaryKey: "id" }, }, models: { Article: "articles", Blog: "blogs", Comment: "comments", Profile: "profiles", Reply: "comments", User: "users", }, }); declare module "../models/article" { interface Article extends TableAttributes {} } declare module "../models/blog" { interface Blog extends TableAttributes {} } declare module "../models/comment" { interface Comment extends TableAttributes {} } declare module "../models/profile" { interface Profile extends TableAttributes {} } declare module "../models/reply" { interface Reply extends TableAttributes {} } declare module "../models/user" { interface User extends TableAttributes {} } ``` ```sql D1 CREATE TABLE blogs ( id TEXT PRIMARY KEY NOT NULL, updated_at DATETIME ); CREATE TABLE articles ( id TEXT PRIMARY KEY NOT NULL, blog_id TEXT NOT NULL REFERENCES blogs (id), title TEXT NOT NULL, updated_at DATETIME, last_commented_at DATETIME ); CREATE TABLE comments ( id TEXT PRIMARY KEY NOT NULL, article_id TEXT NOT NULL REFERENCES articles (id), body TEXT NOT NULL, updated_at DATETIME ); CREATE TABLE users ( id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, updated_at DATETIME ); CREATE TABLE profiles ( id TEXT PRIMARY KEY NOT NULL, user_id TEXT NOT NULL REFERENCES users (id), bio TEXT, updated_at DATETIME ); ``` ```sql Postgres CREATE TABLE blogs ( id UUID PRIMARY KEY, updated_at TIMESTAMPTZ ); CREATE TABLE articles ( id UUID PRIMARY KEY, blog_id UUID NOT NULL REFERENCES blogs (id), title TEXT NOT NULL, updated_at TIMESTAMPTZ, last_commented_at TIMESTAMPTZ ); CREATE TABLE comments ( id UUID PRIMARY KEY, article_id UUID NOT NULL REFERENCES articles (id), body TEXT NOT NULL, updated_at TIMESTAMPTZ ); CREATE TABLE users ( id UUID PRIMARY KEY, name TEXT NOT NULL, updated_at TIMESTAMPTZ ); CREATE TABLE profiles ( id UUID PRIMARY KEY, user_id UUID NOT NULL REFERENCES users (id), bio TEXT, updated_at TIMESTAMPTZ ); ``` ## Touching the record it belongs to Declare `touch: true` on a comment’s `belongsTo`, as `Comment` does, and creating, updating, destroying, or touching a comment touches its article: ```ts import { Article } from "./models/article"; const article = await Article.findByOrThrow({ title: "Hello" }); const comment = await article.comments().create({ body: "First!" }); // sets article.updatedAt await comment.update({ body: "Edited" }); // sets it again await comment.touch(); // and again ``` - The article’s new time is written in the same atomic batch as the comment. A save with nothing to write doesn’t touch it. - Changing a comment’s `articleId` touches both the old article and the new one. - `updateColumns`, `updateAll`, `insert`, and the other bulk writes don’t touch the article, since they run no callbacks. - A Model without `updatedAt` needs a named attribute. Touching a Model on [another database](/several-databases) throws `InvalidModel`, since the touch couldn’t be written in the same batch. ## Setting another attribute Name a datetime attribute, as `Reply` does, to set it to the same time as `updatedAt`: ```ts import { Article } from "./models/article"; import { Reply } from "./models/reply"; const article = await Article.findByOrThrow({ title: "Hello" }); await Reply.create({ articleId: article.id, body: "Agreed" }); // sets updatedAt and lastCommentedAt ``` To set several, list them: `touch: ["lastCommentedAt", "lastActivityAt"]`. ## Running the article’s callbacks The article is touched as `article.touch()` touches it, so it runs its `afterTouch` callbacks, then its update commit callbacks: - An article that declares `touch` on its own `belongsTo`, as `Article` does, touches that record too: the comment touches the article, and the article its blog. - An article the same save creates, such as one built with `comment.article.build()`, is touched after it’s inserted. It runs `afterTouch` and its create commit callbacks, but not the update ones. - A write touches each record once, however many of its comments touch it. ## Loading the article The article is loaded before the comment is written, so its callbacks can run. Preload the chain to skip those queries: ```ts import { Comment } from "./models/comment"; const comments = await Comment.includes({ article: "blog" }).toArray(); for (const comment of comments) await comment.touch(); // no query to load an article or blog ``` - A loaded article sends no query, such as one reached through `article.comments()`. Each level of the chain that isn’t loaded takes one query, and each one waits for the one before it. - The article is found through the association, so the association’s scope and Article’s default scope apply. An article they hide isn’t touched. - Inside [`noTouching`](#turning-touches-off), the touch doesn’t load the article. ## Touching with a counter cache A comment that also keeps a [counter cache](/counter-caches) on the article touches it the same way, in the same batch as the count. An article the default scope hides is counted, but isn’t touched. ## Turning touches off Run an import in `Article.noTouching` to skip touching the article for each comment: ```ts import { Article } from "./models/article"; import { Comment } from "./models/comment"; const article = await Article.findByOrThrow({ title: "Hello" }); await Article.noTouching(async () => { for (const body of ["One", "Two"]) { await Comment.create({ articleId: article.id, body }); // doesn't touch the article } }); await article.touch(); // touch it once, after the import ``` - Inside the block, no article is touched. A comment’s `belongsTo` leaves its article alone, and `article.touch()` writes nothing and resolves to `false`. Once the block ends, articles are touched again. - `noTouching` covers the Model you call it on and the Models that extend it. To turn off touches for every Model, call `ApplicationRecord.noTouching`. - It covers only the code the block runs and what that code awaits, so other requests still touch. - The comments still set their own `updatedAt` when they’re saved. `Article.touchAll()` and `Article.updateCounters(id, counters, { touch: true })` still set the articles’ `updatedAt`. A comment whose `belongsTo` also keeps a counter cache still counts, but doesn’t touch the article. :::note Like `withDatabase`, `noTouching` needs [Node.js compatibility](/connecting#using-the-requests-database). ::: ## Touching the record it has Declare `touch: true` on a user’s `hasOne`, as `User` does, and updating, destroying, or touching a user touches its profile, in the same atomic batch: ```ts import { User } from "./models/user"; const user = await User.findByOrThrow({ name: "Sam" }); await user.update({ name: "Sam Smith" }); // sets the user's profile's updatedAt await user.touch(); // and again ``` - A save with nothing to write doesn’t touch the profile. A `hasOne` through another touches the record it reaches. - The profile is touched as [a `belongsTo`’s record is](#running-the-articles-callbacks). It takes the names of datetime attributes to set, runs its `afterTouch` and update commit callbacks, and touches its own records in turn. - It’s found through the association, so a profile the association’s scope or Profile’s default scope hides isn’t touched. Inside [`Profile.noTouching`](#turning-touches-off), it isn’t loaded or touched. - It isn’t touched when the user is new, when the user’s own save writes it (built through the user, or changed with `autosave: true`), or when the user’s `dependent` removes it with `"destroy"` or `"delete"`. With `"nullify"`, it’s touched once it no longer points at the user. - A profile saved as its own entry in the user’s batch is still touched, whether it comes before or after the user. > **Compared with Rails** > > Rails’ `touch:` takes `true` or one column. Here it also takes a list of attributes. > > Rails does nothing when the article has no `updated_at`, and writes the time to any column you name. Here both throw `InvalidModel` when the Model is first used. > > With a counter cache, Rails sets the time in the counter’s `UPDATE` and runs none of the article’s callbacks. Here the article is touched as it is without one, so its `afterTouch` and commit callbacks run. > > When a comment moves to another article, Rails finds the old one without the association’s scope. Here the scope applies to both. > > When a comment’s `belongs_to` has both `counter_cache:` and `touch:`, Rails’ `no_touching` still touches the article, since the time is set in the counter’s `UPDATE`. Here the article is only counted. Inside the block, Rails’ `touch` returns `nil`, and here it resolves to `false`. Rails also loads each comment’s article for its touch, then leaves it alone. Here the touch doesn’t load it, though a required `belongsTo` still checks that its article exists. > > Rails touches a changed profile before its autosave saves it, so its `after_touch` runs too. Here only its save writes it. After a user is created, Rails finds and touches a profile that already points at the new user’s key. Here a new user touches nothing, so a create sends no query for it. --- # Untrusted input Source: https://active-record.forestfuture.dev/untrusted-input ## At a glance | To | Write | | -------------------------------------- | --------------------------------------------------------- | | take only the fields you want | `Account.permit(await request.json(), "email", "handle")` | | return a 400 for a value you can’t use | catch `TypeError` and `SyntaxError` | | query with a value from a request | check `typeof token === "string"` first | | widen a query | `rewhere` and `unscope`, with names you chose | ## The Models The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates: ```ts account.ts import { ApplicationRecord } from "./application-record"; export class Account extends ApplicationRecord {} ``` ```ts invitation.ts import { ApplicationRecord } from "./application-record"; // Its token is NULL once the invitation is accepted. export class Invitation extends ApplicationRecord {} ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: a77f61266d3a import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** accounts — last changed by 0001_create_tables.sql */ export const accounts = { id: { type: "string", null: false, generateId: true }, email: { type: "string", null: false }, handle: { type: "string", null: false }, plan: "string", seats: "integer", } as const; /** invitations — last changed by 0001_create_tables.sql */ export const invitations = { id: { type: "string", null: false, generateId: true }, email: { type: "string", null: false }, token: "string", acceptedAt: "datetime", } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { accounts: { attributes: accounts, primaryKey: "id" }, invitations: { attributes: invitations, primaryKey: "id" }, }, models: { Account: "accounts", Invitation: "invitations" }, }); declare module "../models/account" { interface Account extends TableAttributes {} } declare module "../models/invitation" { interface Invitation extends TableAttributes {} } ``` ```sql D1 CREATE TABLE accounts ( id TEXT PRIMARY KEY NOT NULL, email TEXT NOT NULL, handle TEXT NOT NULL, plan TEXT, seats INTEGER ); CREATE TABLE invitations ( id TEXT PRIMARY KEY NOT NULL, email TEXT NOT NULL, token TEXT, accepted_at DATETIME ); ``` ```sql Postgres CREATE TABLE accounts ( id UUID PRIMARY KEY, email TEXT NOT NULL, handle TEXT NOT NULL, plan TEXT, seats INTEGER ); CREATE TABLE invitations ( id UUID PRIMARY KEY, email TEXT NOT NULL, token TEXT, accepted_at TIMESTAMPTZ ); ``` ## Permitting fields Only permit the fields you want from a request: ```ts import { Account } from "./models/account"; export async function signUp(request: Request) { const permitted = Account.permit(await request.json(), "email", "handle"); // drops plan and seats return Account.create(permitted); } ``` :::note `permit` can also read `FormData` or `URLSearchParams`. ::: Permitted values are cast to their attribute’s types, so `"42"` becomes `42` for an integer. [Attribute types](/attribute-types#casting-assigned-values) lists what each type accepts. A page number from a query string can go straight to [`paginate`](/ordering-and-pagination#paginating), which casts it too. > **Beyond Rails** > > Rails’ `params.permit` only filters keys. Active Record’s also casts each value, and checks that each name is an attribute. ## Using a schema library 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: ```ts import { z } from "zod"; const SignUp = z.object({ email: z.string(), handle: z.string().min(3) }); const fields = SignUp.parse(await request.json()); const account = await Account.create(fields); ``` ## Returning a 400 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: ```ts import { Account } from "./models/account"; export async function updateAccount(request: Request): Promise { const account = await Account.find(new URL(request.url).searchParams.get("id") ?? ""); let permitted; try { permitted = Account.permit(await request.json(), "handle", "seats"); } catch (error) { if (error instanceof SyntaxError || error instanceof TypeError) { return new Response("Bad request", { status: 400 }); } throw error; } await account.update(permitted); return Response.json(account); } ``` ## Querying with request values Check that a value is a string before you query with it. An accepted invitation’s token is NULL, so an unchecked `null` would find one: ```ts import { Invitation } from "./models/invitation"; export async function accept(request: Request): Promise { const { token } = await request.json<{ token: string }>(); if (typeof token !== "string" || token === "") { return new Response("Send the invitation's token", { status: 400 }); } const invitation = await Invitation.findBy({ token }); if (invitation === null) return new Response("No such invitation", { status: 404 }); await invitation.update({ token: null, acceptedAt: new Date() }); return new Response(`Welcome, ${invitation.email}`); } ``` JSON can send `null` or a list. `findBy({ token: null })` matches rows whose token is NULL, and `findBy({ token: [first, second] })` matches a row with either token. `findOrCreateBy`, `findOrInitializeBy`, and `createOrFindBy` refuse a list. They throw a `TypeError` before they query, since their attributes become the new record’s values. :::note A value that can’t be cast matches nothing, so `whereNot({ id: "abc" })` excludes nothing. ::: > **Beyond Rails** > > Rails’ `find_or_create_by` reads a list as `IN`, as `find_by` does. Rails doesn’t need to refuse one. A request’s params must be permitted before a model takes them, and `permit(:email)` keeps only single values. > > Here, `await request.json()` is a plain object, and `permit` is up to you. So `findOrCreateBy(await request.json())` could find another user’s row. The find-or-create methods refuse a list instead. `findBy` and `where` still read a list as `IN`. ### Rewriting queries Pass `rewhere` and `unscope` the attribute names and values you chose, never a request’s. They widen a query, where `where` only narrows one, so `Post.where({ published: true }).rewhere(await request.json())` would find any post the body names. An association’s link to its owner always stays. `user.posts().rewhere({ userId: 2 })` finds nothing, since no post belongs to both users. [Security](/security) lists what Active Record protects against, and what it leaves to your app. --- # Upgrading Source: https://active-record.forestfuture.dev/upgrading ## Upgrading from 0.7 to 0.8 In 0.8, a `belongsTo` requires its record, a batch prepares its writes in a callback, a new record’s changes run from its defaults, a `hasOne`’s new record replaces its old one, a `hasMany` gives its records its own key, a bulk write gives its Relation’s values over yours, the generated schema is a `defineSchema` call and reads a `DATE` column as a `date`, and `serialize` can give bytes. Upgrade in nine steps. ### Marking optional associations Saving now fails with “must exist” when a `belongsTo` points at nothing. Add `optional: true` to each one whose foreign key can be `null`: ```ts import { belongsTo } from "@forestfuture/active-record"; export class Category extends ApplicationRecord { parent = belongsTo(Category, { optional: true }); } ``` A record built through its owner’s `hasMany` or `hasOne` passes without it. ### Reading a new record’s changes A new record’s `changes()`, `changed()`, and `isChanged()` no longer list its declared defaults or generated id, and `savedChanges()` after a create leaves out the defaults it kept. Check code that reads them on new records, such as a callback that tests `isChanged()` before an insert. Use `isNewRecord()` to ask whether a record is new. ### Preparing batch writes in a callback Pass `batch` and `db.batch` a callback that returns the writes, instead of an array: ```ts import { batch } from "@forestfuture/active-record"; await batch((b) => [b.save(user), b.deleteAll(Post.where({ userId: user.id }))]); ``` Records’ `toSave()` and `toDestroy()`, and the `to…` methods such as `toInsert` and `toDeleteAll`, are gone. Call `b.save`, `b.destroy`, `b.insert`, and the rest instead. ### Replacing a hasOne’s record Building or creating a record through a saved owner’s `hasOne` now removes the old record, by the association’s `dependent` strategy. Without one, the old record’s foreign key is set to `NULL`, which fails on a `NOT NULL` column. Set `dependent: "destroy"` or `"delete"` where the old record should go instead. Building twice through an unsaved owner now saves only the last record. See [Replacing the record](/associations#replacing-the-record). ### Checking keys given through a hasMany A record built, created, or inserted through a `hasMany` now always gets its owner’s key, as one built through a `hasOne` already did. A foreign key you pass, such as `user.posts().build({ userId: otherId })`, is replaced. To write a record for another owner, build it through that owner, or through the Model: `Post.build({ userId: otherId })`. ### Checking values given to bulk writes `insert`, `insertAll`, `upsert`, and `upsertAll` through a Relation now write its equality conditions, its `createWith` attributes, and its default scope’s values over the attributes you pass. So `Post.where({ userId: 1 }).insert({ title: "Hi", userId: 2 })` now writes `userId: 1`. Check bulk writes that pass a value their Relation also sets. To write the value you pass, leave the condition out. To write over a default scope’s value, start from `Post.unscoped()`. `build` and `create` still use the values you pass. ### Regenerating the schema Run `schema` in your project’s folder: ```sh npx active-record schema ``` The generated `schema.ts` now declares `schema` with `defineSchema({ … })`, which an [enum](/enums#declaring-enums)’s scopes need. Until you regenerate it, `active-record schema --check` reports it as out of date. ### Reading `DATE` columns The generated schema now reads a `DATE` column as a [`date`](/attribute-types#storing-exact-numbers-days-and-times), a day’s text such as `"2026-01-02"`, where it was a `datetime`. Update code that reads one as a `Date`, or keep the attribute a `datetime` with an override: ```ts import { ApplicationRecord } from "./application-record"; export class Event extends ApplicationRecord { static override attributes = { startsOn: "datetime" } as const; } ``` On D1, a `DATE` column that a `datetime` wrote holds a date and time, such as `"2026-01-02T00:00:00.000Z"`, and a `date` can’t read it. Count the rows whose time isn’t midnight: ```sql SELECT count(*) FROM events WHERE length(starts_on) > 10 AND substr(starts_on, 11) <> 'T00:00:00.000Z'; ``` If there are none, keep only each day: ```sql UPDATE events SET starts_on = substr(starts_on, 1, 10) WHERE length(starts_on) > 10; ``` Postgres stores a `date` without a time, so its rows need no change. A `TIME` column is now a [`time`](/attribute-types#storing-exact-numbers-days-and-times), where it was a `string`, and reads as `"09:30:00"`. A `NUMERIC` or `DECIMAL` column is now a `decimal`, where it was an error. ### Typing serialized values `typeForAttribute(name).serialize` now returns `string | number | Uint8Array | null`, since a [`binary` attribute](/attribute-types#storing-bytes) is stored as bytes. Code that gives its result a narrower type, such as `string | number | null`, needs the wider one. ## Upgrading from 0.6 to 0.7 In 0.7, the adapters ship inside `@forestfuture/active-record`, so an app on D1 installs one package. Upgrade in four steps. ### Replacing the D1 package Remove the D1 package, then update the core: ```sh npm uninstall @forestfuture/d1-record npm install @forestfuture/active-record@^0.7.0 ``` ### Changing imports Import what opens D1 from the core’s `/d1` entry: ```ts import { connect, d1, withSession } from "@forestfuture/active-record/d1"; ``` Everything else still comes from `@forestfuture/active-record`. If your Vitest config inlines the D1 adapter (`server.deps.inline`), inline `@forestfuture/active-record` instead. ### Writing `active-record.jsonc` Run `init` in your project’s folder: ```sh npx active-record init ``` It writes `active-record.jsonc`, naming each database in your Wrangler config’s `d1_databases` and its adapter: ```jsonc { "$schema": "./node_modules/@forestfuture/active-record/config-schema.json", "databases": { "DB": { "adapter": "d1" }, }, } ``` Every `active-record` command reads it. Each database’s migrations folder stays in your Wrangler config. `--adapter` is gone, and `--config` now names this file. If you used `--config` to name a Wrangler config in another folder, name it in the database’s entry with [`wranglerConfig`](/command-line#declaring-your-databases) instead. ### Regenerating the schema Regenerate your schema: ```sh npx active-record schema ``` Its import changes to `@forestfuture/active-record/d1`. Until you regenerate it, `active-record schema --check` reports it as out of date. ## Upgrading from d1-record 0.5 to 0.6 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. ### Installing both packages Install the core beside the adapter: ```sh npm install @forestfuture/active-record@^0.6.0 @forestfuture/d1-record@^0.6.0 ``` Both packages share a version, so keep them on the same one. ### Changing imports Import from the core everything that isn’t about D1. Import from the adapter what opens D1: ```ts import { batch, belongsTo, hasMany, Model, RecordNotFound, withDatabase, } from "@forestfuture/active-record"; import { connect, d1, withSession } from "@forestfuture/d1-record"; ``` | Package | What it holds | | ----------------------------- | ------------------------------------------------------------------------------ | | `@forestfuture/active-record` | Models, Relations, `batch`, `withDatabase`, `sql`, and every error but one | | `@forestfuture/d1-record` | `connect`, `Database`, `withSession`, `NoSession`, `d1`, and D1’s `QueryEvent` | `d1-record` re-exports nothing of the core, so an import of `Model` from it fails. ### Regenerating the schema Run the schema command under its new name: ```sh npx active-record schema ``` The generated schema now names its adapter, `adapter: d1({ binding: "DB" })`, where it named only the binding. Your base class needs no change. ### Running `active-record` The command is now `active-record`, or `ffar` for short. Swap it in your scripts and CI: | Before | Now | | ------------------------- | ----------------------------- | | `npx d1-record schema` | `npx active-record schema` | | `npx d1-record g model …` | `npx active-record g model …` | | `npx d1-record console` | `npx active-record console` | It also applies migrations through your project’s Wrangler, with `npx active-record migrate`. See [Command line](/command-line#active-record-migrate). ### Updating for the other changes - **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. - **The base error** is `ActiveRecordError`, where it was `D1RecordError`. - **`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. - **D1’s `meta`** is still on every `onQuery` event. - **The agent skill** is now `active-record`. Install it again with `npx skills add forestfuture/active-record`. --- # Validations Source: https://active-record.forestfuture.dev/validations ## At a glance | To | Write | | ------------------------------------- | ----------------------------------------------------------------- | | declare a rule | `this.validates("email", { presence: true })` | | validate without saving | `await record.isValid()` | | read why a record is invalid | `record.errors.fullMessages()`, `errors.get("email")` | | run a rule only when creating | `on: "create"` | | run rules for a step of your own | `static validationContexts = ["signup"] as const`, `on: "signup"` | | validate an association’s records too | `this.validatesAssociated("tracks")` | | add an error yourself | `record.errors.add("base", "…")`, in a validation callback | | change a message | `message: "…"`, or `this.errorMessages({ blank: "…" })` | ## The Models The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates. Each declares its validations in its `static {}` block: ```ts account.ts import { ApplicationRecord } from "./application-record"; export class Account extends ApplicationRecord { static { this.validates("email", { presence: true, uniqueness: { caseSensitive: false } }); this.validates("handle", { length: { minimum: 3, maximum: 30 }, format: /^[a-z0-9_]+$/ }); this.validates("plan", { inclusion: ["free", "team", "enterprise"] }); this.validates("seats", { numericality: { onlyInteger: true, greaterThan: 0 } }); this.validates("website", { format: /^https:\/\//, allowNull: true }); this.validates("companyName", { presence: true, if: (account) => account.isCompany === true, message: "is required for a company", }); } } ``` ```ts event.ts import { ApplicationRecord } from "./application-record"; export class Event extends ApplicationRecord { static { this.validates("endsAt", { comparison: { greaterThan: (event) => event.startsAt } }); } } ``` ```ts invoice.ts import { ApplicationRecord } from "./application-record"; export class Invoice extends ApplicationRecord { static { this.validates("currency", { inclusion: ["USD", "EUR"], strict: true }); // throws, not collects } } ``` ```ts member.ts import { ApplicationRecord } from "./application-record"; export class Member extends ApplicationRecord { static override attributes = { emailConfirmation: { type: "string", virtual: true }, // typed a second time, never saved } as const; static validationContexts = ["signup"] as const; static { this.validates("email", { format: /@/, confirmation: true }); this.validates("password", { presence: true, on: "create" }); this.validates("inviteCode", { presence: true, on: "signup" }); } } ``` ```ts playlist.ts import { hasMany } from "@forestfuture/active-record"; import { ApplicationRecord } from "./application-record"; import { Track } from "./track"; export class Playlist extends ApplicationRecord { tracks = hasMany(Track); static { this.validatesAssociated("tracks"); } } ``` ```ts track.ts import { ApplicationRecord } from "./application-record"; export class Track extends ApplicationRecord { static { this.validates("title", { presence: true }); } } ``` ```ts booking.ts import { ApplicationRecord } from "./application-record"; export class Booking extends ApplicationRecord { static { this.errorMessages({ onTheHour: "must be on the hour" }); this.afterValidation((booking) => { if (booking.startsAt.getUTCMinutes() !== 0) { booking.errors.add("startsAt", { type: "onTheHour" }); } if (booking.startsAt.getUTCDay() === 0) { booking.errors.add("base", "The room is closed on Sundays"); } }); } } ``` ```ts product.ts import { ApplicationRecord } from "./application-record"; export class Product extends ApplicationRecord { static { this.errorMessages({ greaterThan: "must be more than %{count}", attributes: { name: { blank: "needs a name customers will see" }, }, }); this.humanAttributeNames({ priceCents: "Price" }); this.validates("name", { presence: true, length: { minimum: 3 } }); this.validates("priceCents", { numericality: { greaterThan: 0 } }); } } ``` ```ts application-record.ts import { Model } from "@forestfuture/active-record"; import { schema } from "../db/schema"; export abstract class ApplicationRecord extends Model { static override schema = schema; static { // Messages and names for every Model, in place of the built-in English: this.errorMessages({ tooShort: { one: "needs at least 1 character", other: "needs at least %{count} characters", }, }); this.humanAttributeNames({ createdAt: "Added on" }); } } ``` ```ts schema.ts // Generated by `active-record schema` from migrations/ — don't edit. // schema: 0f1c01679a71 import { defineSchema, type TableAttributes } from "@forestfuture/active-record"; import { d1 } from "@forestfuture/active-record/d1"; /** accounts — last changed by 0001_create_tables.sql */ export const accounts = { id: { type: "string", null: false, generateId: true }, email: { type: "string", null: false }, handle: { type: "string", null: false }, plan: "string", seats: "integer", website: "string", isCompany: "boolean", companyName: "string", } as const; /** bookings — last changed by 0001_create_tables.sql */ export const bookings = { id: { type: "string", null: false, generateId: true }, startsAt: { type: "datetime", null: false }, endsAt: { type: "datetime", null: false }, } as const; /** events — last changed by 0001_create_tables.sql */ export const events = { id: { type: "string", null: false, generateId: true }, startsAt: { type: "datetime", null: false }, endsAt: { type: "datetime", null: false }, } as const; /** invoices — last changed by 0001_create_tables.sql */ export const invoices = { id: { type: "string", null: false, generateId: true }, total: { type: "integer", null: false }, currency: { type: "string", null: false }, } as const; /** members — last changed by 0001_create_tables.sql */ export const members = { id: { type: "string", null: false, generateId: true }, email: { type: "string", null: false }, password: "string", inviteCode: "string", } as const; /** playlists — last changed by 0001_create_tables.sql */ export const playlists = { id: { type: "string", null: false, generateId: true }, name: { type: "string", null: false }, } as const; /** products — last changed by 0001_create_tables.sql */ export const products = { id: { type: "string", null: false, generateId: true }, name: { type: "string", null: false }, priceCents: { type: "integer", null: false }, createdAt: "datetime", } as const; /** tracks — last changed by 0001_create_tables.sql */ export const tracks = { id: { type: "string", null: false, generateId: true }, playlistId: { type: "string", null: false }, title: { type: "string", null: false }, } as const; /** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */ export const schema = defineSchema({ adapter: d1({ binding: "DB" }), tables: { accounts: { attributes: accounts, primaryKey: "id" }, bookings: { attributes: bookings, primaryKey: "id" }, events: { attributes: events, primaryKey: "id" }, invoices: { attributes: invoices, primaryKey: "id" }, members: { attributes: members, primaryKey: "id" }, playlists: { attributes: playlists, primaryKey: "id" }, products: { attributes: products, primaryKey: "id" }, tracks: { attributes: tracks, primaryKey: "id" }, }, models: { Account: "accounts", Booking: "bookings", Event: "events", Invoice: "invoices", Member: "members", Playlist: "playlists", Product: "products", Track: "tracks", }, }); declare module "../models/account" { interface Account extends TableAttributes {} } declare module "../models/booking" { interface Booking extends TableAttributes {} } declare module "../models/event" { interface Event extends TableAttributes {} } declare module "../models/invoice" { interface Invoice extends TableAttributes {} } declare module "../models/member" { interface Member extends TableAttributes {} } declare module "../models/playlist" { interface Playlist extends TableAttributes {} } declare module "../models/product" { interface Product extends TableAttributes {} } declare module "../models/track" { interface Track extends TableAttributes {} } ``` ```sql D1 CREATE TABLE accounts ( id TEXT PRIMARY KEY NOT NULL, email TEXT NOT NULL, handle TEXT NOT NULL, plan TEXT, seats INTEGER, website TEXT, is_company BOOLEAN, company_name TEXT ); CREATE UNIQUE INDEX index_accounts_on_email ON accounts (email); CREATE TABLE events ( id TEXT PRIMARY KEY NOT NULL, starts_at DATETIME NOT NULL, ends_at DATETIME NOT NULL ); CREATE TABLE invoices ( id TEXT PRIMARY KEY NOT NULL, total INTEGER NOT NULL, currency TEXT NOT NULL ); CREATE TABLE members ( id TEXT PRIMARY KEY NOT NULL, email TEXT NOT NULL, password TEXT, invite_code TEXT ); CREATE TABLE playlists ( id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL ); CREATE TABLE tracks ( id TEXT PRIMARY KEY NOT NULL, playlist_id TEXT NOT NULL REFERENCES playlists (id), title TEXT NOT NULL ); CREATE TABLE bookings ( id TEXT PRIMARY KEY NOT NULL, starts_at DATETIME NOT NULL, ends_at DATETIME NOT NULL ); CREATE TABLE products ( id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, price_cents INTEGER NOT NULL, created_at DATETIME ); ``` ```sql Postgres CREATE TABLE accounts ( id UUID PRIMARY KEY, email TEXT NOT NULL, handle TEXT NOT NULL, plan TEXT, seats INTEGER, website TEXT, is_company BOOLEAN, company_name TEXT ); CREATE UNIQUE INDEX index_accounts_on_email ON accounts (email); CREATE TABLE events ( id UUID PRIMARY KEY, starts_at TIMESTAMPTZ NOT NULL, ends_at TIMESTAMPTZ NOT NULL ); CREATE TABLE invoices ( id UUID PRIMARY KEY, total INTEGER NOT NULL, currency TEXT NOT NULL ); CREATE TABLE members ( id UUID PRIMARY KEY, email TEXT NOT NULL, password TEXT, invite_code TEXT ); CREATE TABLE playlists ( id UUID PRIMARY KEY, name TEXT NOT NULL ); CREATE TABLE tracks ( id UUID PRIMARY KEY, playlist_id UUID NOT NULL REFERENCES playlists (id), title TEXT NOT NULL ); CREATE TABLE bookings ( id UUID PRIMARY KEY, starts_at TIMESTAMPTZ NOT NULL, ends_at TIMESTAMPTZ NOT NULL ); CREATE TABLE products ( id UUID PRIMARY KEY, name TEXT NOT NULL, price_cents INTEGER NOT NULL, created_at TIMESTAMPTZ ); ``` ## Declaring validations Declare validations in a Model’s `static {}` block with `this.validates`, as `Account` does, then check a record with `isValid()`: ```ts import { Account } from "./models/account"; const account = Account.build({ email: "jane@example.com", handle: "jane", plan: "free", seats: 1, }); const valid = await account.isValid(); // true; async, since uniqueness asks the database ``` - Attribute names are typed, so a misspelled attribute is a compile error. - `save()` validates first, and resolves to `false` when a record is invalid. - `isValid()` is async, since `uniqueness` asks the database. ## Available validators | Rule | Options | Error type | | -------------- | -------------------------------------------------------------------------------------------- | ---------------------------------------------- | | `presence` | `true` | `blank` | | `absence` | `true` | `present` | | `length` | `{ minimum, maximum, is }` | `tooShort`, `tooLong`, `wrongLength` | | `format` | `{ with: /re/ }`, or a regex | `invalid` | | `inclusion` | `{ in: [...] }`, or an array | `inclusion` | | `exclusion` | `{ in: [...] }`, or an array | `exclusion` | | `numericality` | `{ onlyInteger, greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo }`, or `true` | `notANumber`, `notAnInteger`, `greaterThan`, … | | `comparison` | `{ greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo, equalTo, otherThan }` | `blank`, `greaterThan`, … | | `acceptance` | `true`, or `{ accept: [...] }` | `accepted` | | `confirmation` | `true`, or `{ caseSensitive }` | `confirmation` | | `uniqueness` | `{ scope: [...], caseSensitive }`, or `true` | `taken` | Every validation runs, in the order declared, so one attribute can collect several errors. Within one `validates` call, the rules run in the table’s order. Every rule also accepts these options: - **`allowNull`** skips the rule when the value is `null`. Otherwise `null` fails `presence`, `format`, `inclusion`, `numericality`, `comparison`, and `acceptance`, counts as length 0, and is never taken. - **`allowBlank`** skips the rule when the value is blank: `null`, or a string that’s only whitespace. - **`message`** replaces the default messages from that call. - **`if: (record) => boolean`** validates only when it returns `true`. - **`unless: (record) => boolean`** skips the rule when it returns `true`. With `if` as well, both must allow it. - **`strict`** throws instead of adding an error. See [Raising instead of collecting errors](#raising-instead-of-collecting-errors). - **`on`** and **`exceptOn`** run the rule only when creating, only when updating, or in a context of your own. See [Validating only when creating or updating](#validating-only-when-creating-or-updating). 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. ### Validator details - **`presence`** fails a string that’s only whitespace. For a boolean, use `inclusion: [true, false]`, since `false` is a value. - **`absence`** passes what `presence` fails: `null` and a string that’s only whitespace. So `false` fails it. - **`inclusion`** is added for you by an [enum](/enums#reading-and-assigning-other-values) declared `validate: true`. - **`exclusion`** passes `null` unless the list holds it. - **`numericality`** only accepts numbers, so a numeric string such as `"12"` is `notANumber`. A [`decimal`](/attribute-types#storing-exact-numbers-days-and-times) attribute’s text is the exception: it’s compared with each bound as a number, exactly. - **`comparison`** compares a number with a number, a string with a string, or a Date with a Date by its time. A `decimal` attribute compares as a number, with a number or a decimal’s text. A bound is a value, or a function of the record (see [Comparing with another attribute](#comparing-with-another-attribute)). A blank value fails once, as `blank`. Blank means `null` or a string that’s only whitespace. Comparing a number with a Date, or any two different kinds, throws `TypeError`. Against a bound of `NaN` or an invalid Date, only `otherThan` passes. - **`acceptance`** is for a box that must be ticked. It passes `true` and `"1"`, or the values you give in `{ accept: [...] }`. A checkbox left unticked sends nothing, so `null` fails too. To let `null` pass, add `allowNull: true`. The box is usually a [virtual attribute](/models#adding-virtual-attributes), since the table needn’t keep it. - **`confirmation`** compares the attribute with a [virtual attribute](/models#adding-virtual-attributes) named for it, such as `emailConfirmation`. See [Confirming a value](#confirming-a-value). - **`uniqueness`** leaves the record itself out when updating, and never treats `null` as taken, since a UNIQUE index lets several rows hold NULL. `caseSensitive: false` compares with the database’s `lower()`: on D1, SQLite’s lowercases only ASCII letters. > **Compared with Rails** > > Rails treats `false` as blank, so it passes `absence`. Here `false` passes `presence`, so it fails `absence`. > > Rails’ `acceptance` lets `nil` pass, since its form helpers send `"0"` for an unticked checkbox. A plain HTML checkbox sends nothing, so here `null` fails. > > Rails’ `allow_blank` also skips `false`, `[]`, and `{}`. Here `allowBlank` skips what `presence` fails: `null` and a string that’s only whitespace. :::warning[Uniqueness isn’t a guarantee] Two requests can both check that an email is free, then both insert it. `uniqueness` gives a friendly error early, but only a UNIQUE index in the table prevents duplicates, so declare both. When the index catches a duplicate, the save throws [`RecordNotUnique`](/errors#constraint-errors). For attributes you create with [`createOrFindBy`](/persistence#creating-records-from-concurrent-requests), declare only the index. ::: ### Confirming a value Add `confirmation: true` for a value typed twice, with its second copy in a virtual attribute, as `Member` does with `email` and `emailConfirmation`: ```ts import { Member } from "./models/member"; const form = { email: "jane@example.com", emailConfirmation: "jane@exmaple.com" }; const permitted = Member.permit(form, "email", "emailConfirmation"); const member = Member.build({ ...permitted, password: "secret" }); await member.isValid(); // false: "Email confirmation doesn't match Email" console.log(member.toJSON().emailConfirmation); // undefined: never sent back ``` - **A mismatch is an error on the confirmation,** “Email confirmation doesn’t match Email”, so a form shows it beside the second field. - **A `null` confirmation passes,** so code that sets the email alone needs no confirmation. Add `presence` to the confirmation to require it. - **`caseSensitive: false`** ignores case. - **Without the virtual attribute,** the rule throws `InvalidModel`, naming the attribute to declare. - **`toJSON()` leaves the confirmation out,** so `Response.json(member)` never sends it back. > **Compared with Rails** > > Rails’ `confirmation` defines `email_confirmation` for you, as a plain accessor. Here you declare it as a virtual attribute, so it’s typed, cast, and taken by `permit`. Like Rails, `toJSON()` never sends it. ### Comparing with another attribute Give `comparison` a function of the record to compare with another attribute, as `Event` does: ```ts import { Event } from "./models/event"; const at = new Date("2026-05-01T10:00:00Z"); const event = Event.build({ startsAt: at, endsAt: at }); await event.isValid(); // false: "Ends at must be greater than 2026-05-01T10:00:00.000Z" ``` When the function returns `null`, that bound is skipped. Validate the other attribute’s presence to report it. > **Compared with Rails** > > Rails names the other attribute with a symbol, `comparison: { greater_than: :starts_at }`. Here a function does it, so the attribute’s name is typed. ### Raising instead of collecting errors Pass `strict: true`, as `Invoice` does, for a value only a bug in your own code could set. A failing rule then throws `StrictValidationFailed` with its full message, instead of adding an error: ```ts import { Invoice } from "./models/invoice"; const invoice = Invoice.build({ total: 1200, currency: "GBP" }); await invoice.isValid(); // throws StrictValidationFailed: "Currency is not included in the list" ``` `isValid()`, `save()`, and `saveOrThrow()` all throw it, and the validations after it don’t run. To throw an error class of your own, pass the class as `strict`, such as `strict: UnknownCurrency`. It’s made with the same message. ## Validating only when creating or updating Pass `on: "create"` to run a rule only when a record is created, as `Member` does with `password`. By default, a rule runs on every save. A new record is validated in the `"create"` context, and a saved one in `"update"`. A rule with `on` runs only in the contexts it names, so `password` is checked when a member is created, and not when one is updated. To name several contexts, pass a list, such as `on: ["create", "signup"]`. `exceptOn` works the other way. The rule runs in every context except the ones it names. ### Naming your own contexts List a step of your own, such as a signup form, in the Model’s `static validationContexts`, with `as const`, as `Member` does. Then pass it to `isValid` or `save`: ```ts import { Member } from "./models/member"; const member = Member.build({ email: "jane@example.com", password: "secret" }); await member.isValid("signup"); // false: invite code can't be blank member.inviteCode = "WELCOME"; await member.save({ context: ["create", "signup"] }); // the create rules and the signup ones ``` Rules without `on` run in every context. A context you pass takes the place of `"create"` or `"update"`, so the `on: "create"` rules don’t run. To run both, pass both, as the example does. `"create"` and `"update"` are always there, so list only your own. A context the Model doesn’t list is a compile error in `on` and `exceptOn`. Passed to `isValid` or `save`, it throws `TypeError`. :::note List contexts on each Model. A Model’s subclass shares its list, and an abstract base class can’t have one. ::: ### Validating associated records in a context When you pass a context of your own, the records validated with the owner are validated in it too. These are the records checked by `validatesAssociated`, and the records [saved with their owner](/autosaving#saving-a-graph). With `"create"` or `"update"`, each record uses its own: a new record is validated in `"create"` even when its owner is updated. A list that holds a context of your own reaches them whole, so `["create", "signup"]` runs the `on: "create"` rules of related records that are already saved, too. > **Beyond Rails** > > Rails accepts any context name, so a misspelled one quietly runs none of its rules. Here a Model lists its contexts, and a name it doesn’t list is a compile error or a `TypeError`. > **Compared with Rails** > > `valid?(:signup)` is `isValid("signup")`, `save(context: :signup)` is `save({ context: "signup" })`, and `except_on:` is `exceptOn`. ## Validating associated records Call `this.validatesAssociated`, as `Playlist` does, to validate an association’s records with their owner: ```ts import { Playlist } from "./models/playlist"; const playlist = Playlist.build({ name: "Road trip" }); const track = playlist.tracks().build({ title: "" }); await playlist.isValid(); // false: "Tracks is invalid" track.errors.fullMessages(); // ["Title can't be blank"] ``` An invalid track makes its playlist invalid, with a “Tracks is invalid” error, and keeps its own errors. If the association isn’t loaded, validating the playlist loads it, with one query. A record marked for destruction isn’t validated. Records built through an association are [validated with their owner](/autosaving#saving-a-graph) even without `validatesAssociated`. `validatesAssociated` takes `if`, `unless`, `on`, `exceptOn`, `message`, and `strict`, as `validates` does. The association’s name is typed, so a misspelled one is a compile error. You can declare `validatesAssociated` on both sides of an association. A record that’s already being validated counts as valid, so validating either side finishes. :::note Each track is validated with its own rules and callbacks, so a `uniqueness` rule on a track sends a query for every track. Use `validatesAssociated` on associations that stay small. ::: > **Compared with Rails** > > When `validates_associated` and autosave both check a record, Rails validates it twice and adds “is invalid” twice. Here it’s validated once, with one error. > > Rails’ `validates_associated` on both sides of an association recurses until the stack overflows. Here the record already being validated counts as valid. ## Reading errors A record’s `errors` hold each failed rule: ```ts import { Account } from "./models/account"; const account = Account.build({ email: "", handle: "a!" }); await account.isValid(); // false account.errors.get("email"); // ["can't be blank"] // "needs at least 3 characters" is ApplicationRecord's tooShort message, not the built-in one. account.errors.fullMessages(); // ["Email can't be blank", "Handle needs at least 3 characters", …] account.errors.toArray(); // [{ attribute: "email", type: "blank", message: "can't be blank" }, …] console.log(account.errors.size); // 5 ``` 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. An error with a number in its message, such as `tooShort`, has it in `toArray()` too: ```ts { attribute: "handle", type: "tooShort", message: "needs at least 3 characters", values: { count: 3 } } ``` ## Adding errors Add errors in a `beforeValidation` or `afterValidation` callback for a rule the validators don’t cover, as `Booking` does. A record with any errors is invalid: ```ts import { Booking } from "./models/booking"; const startsAt = new Date("2026-05-03T10:30:00Z"); // a Sunday const booking = Booking.build({ startsAt, endsAt: new Date("2026-05-03T11:30:00Z") }); await booking.isValid(); // false booking.errors.toArray(); // [{ attribute: "startsAt", type: "onTheHour", message: "must be on the hour" }, // { attribute: "base", type: "invalid", message: "The room is closed on Sundays" }] booking.errors.fullMessages(); // ["Starts at must be on the hour", "The room is closed on Sundays"] ``` `errors.add` takes the attribute, or `"base"`, then either a `type` or a message. A `type` takes its message from the Model’s `errorMessages`, as `onTheHour` does. See [Changing error messages](#changing-error-messages). A message is used as written, and its type is `"invalid"`. To fill in a placeholder, pass its value with the type: ```ts account.errors.add("handle", { type: "tooShort", count: 3 }); ``` To give a message and a type, pass the type as an option: ```ts account.errors.add("handle", "is reserved", { type: "reserved" }); ``` 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. > **Compared with Rails** > > Rails’ `errors.add(:starts_at, :on_the_hour)` is `errors.add("startsAt", { type: "onTheHour" })` here, since a type and a message are both strings in TypeScript. When Rails is given a message instead, that text is the type too; here the type is `"invalid"`. Rails’ `message:` and `strict:` options and its procs aren’t here. ## Changing error messages Pass `message` to `validates` to change one validation’s message, or call `this.errorMessages` in your app’s base class to change a message for every Model, as `ApplicationRecord` does with `tooShort`: 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. 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, as `Product`’s do. Each message is looked up when you read it: ```ts import { Product } from "./models/product"; const product = Product.build({ name: "", priceCents: 0 }); await product.isValid(); // false product.errors.fullMessages(); // ["Name needs a name customers will see", // "Name needs at least 3 characters", // "Price must be more than 0"] Product.humanAttributeName("priceCents"); // "Price" ``` ### Naming attributes `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. :::note `Product.humanAttributeName("priceCents")` returns the same name, for a form’s label. ::: 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. ### Filling in placeholders A message can show these values: - **`%{count}`**: the rule’s number or bound, such as the `minimum` of `tooShort` or the bound of `greaterThan`. A Date bound shows as an ISO string. A bound’s function that returns a [filtered attribute](/serialization#filtering-attributes)’s value shows `[FILTERED]`. - **`%{attribute}`**: the attribute’s name, as `fullMessages()` shows it. - **`%{model}`**: the Model’s name in words, so `BlogPost` reads as “Blog post”. It’s the class name, unless the Model sets [`static modelName`](/models#naming-models). - **`%{value}`**: the attribute’s value. A [filtered attribute](/serialization#filtering-attributes) shows `[FILTERED]`. A value passed to `errors.add` with the type, such as `count`, fills in the placeholder of the same name. ### Looking messages up For each error, the first message found is used: 1. A message given to `validates` or `errors.add`. 2. The Model’s message for the attribute and type, then its message for the type. 3. The same for each class the Model extends, your base class included. 4. The built-in English message. A type with no message anywhere throws a `TypeError` when the error is added. ### Finding a built-in message Each error type has a built-in message. To replace one, use its type as the key in `errorMessages`: | Type | Added by | Message | | -------------------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------- | | `blank` | `presence`, and `comparison` for a blank value | can’t be blank | | `present` | `absence` | must be blank | | `invalid` | `format` and an invalid autosaved association | is invalid | | `inclusion` | `inclusion` | is not included in the list | | `exclusion` | `exclusion` | is reserved | | `tooShort` | `length: { minimum }` | is too short (minimum is `%{count}` characters) | | `tooLong` | `length: { maximum }` | is too long (maximum is `%{count}` characters) | | `wrongLength` | `length: { is }` | is the wrong length (should be `%{count}` characters) | | `notANumber` | `numericality` | is not a number | | `notAnInteger` | `numericality: { onlyInteger }` | must be an integer | | `greaterThan` | `numericality` or `comparison`: `{ greaterThan }` | must be greater than `%{count}` | | `greaterThanOrEqualTo` | `numericality` or `comparison`: `{ greaterThanOrEqualTo }` | must be greater than or equal to `%{count}` | | `lessThan` | `numericality` or `comparison`: `{ lessThan }` | must be less than `%{count}` | | `lessThanOrEqualTo` | `numericality` or `comparison`: `{ lessThanOrEqualTo }` | must be less than or equal to `%{count}` | | `equalTo` | `comparison: { equalTo }` | must be equal to `%{count}` | | `otherThan` | `comparison: { otherThan }` | must be other than `%{count}` | | `passwordTooLong` | a [secure password](/passwords-and-tokens) longer than its algorithm allows | is too long | | `accepted` | `acceptance` | must be accepted | | `confirmation` | `confirmation`, on the confirming attribute | doesn’t match `%{attribute}` | | `taken` | `uniqueness` | has already been taken | | `required` | a `belongsTo` whose record doesn’t exist | must exist | | `restrictDependentDestroy` | a has-one with `dependent: "restrictWithError"` | Cannot delete record because a dependent `%{record}` exists | | `restrictDependentDestroy` | a has-many with `dependent: "restrictWithError"` | Cannot delete record because dependent `%{record}` exist | 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: "…" }`. > **Compared with Rails** > > Rails looks messages up in its locale files, in nearly the same order: the Model’s, then its ancestors’, then the shared ones. Among the shared ones, Rails tries a message for the type before one for the attribute. Your base class tries the attribute’s first, as every class does. Active Record keeps messages on the classes instead, so a Model’s messages sit next to its validations. Their keys are Active Record’s error types, in camelCase. Rails shows “Translation missing” for a type with no message, where Active Record throws when the error is added. Messages in other languages aren’t here yet.