---
title: Persistence
description: "Save, update, and destroy records."
seo:
  description: "Save, create, update, and destroy Active Record records, catch RecordInvalid from the OrThrow variants, findOrCreateBy, increment, touch, and reload."
---

## 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<typeof articles, (typeof Article)["attributes"]> {}
}

declare module "../models/label" {
  interface Label extends TableAttributes<typeof labels, (typeof Label)["attributes"]> {}
}

declare module "../models/post" {
  interface Post extends TableAttributes<typeof posts, (typeof Post)["attributes"]> {}
}

declare module "../models/user" {
  interface User extends TableAttributes<typeof users, (typeof User)["attributes"]> {}
}
```

```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<Response> {
  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).
