Skip to content
Active Record
Esc
↑↓navigate↵open⌘Jpreview
On this page

Persistence

Save, update, and destroy records.

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:

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 });
  }
}
import { belongsTo } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { User } from "./user";

export class Post extends ApplicationRecord {
  user = belongsTo(User);
}
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
      }
    });
  }
}
import { ApplicationRecord } from "./application-record";

// The UNIQUE index on name keeps it unique, so createOrFindBy can rely on it.
export class Label extends ApplicationRecord {}
// 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"]> {}
}
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);
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:

import { class UserUser } from "./models/user";

const const user: Useruser = class UserUser.
build<typeof User>(this: typeof User, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly isActive: {
        readonly type: "boolean";
        readonly null: false;
        readonly default: () => boolean;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: ((record: User) => void) | undefined): User
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it joins the association, and saving the owner saves it too (autosave).
build
({ email?: string | undefinedemail: "jane@example.com" });
if (await const user: Useruser.Model.save(options?: SaveOptions): Promise<boolean>
Inserts a new record or updates a persisted one; `false` if it's invalid, a callback aborted, or a record it destroys refused (#37). `context` validates it in that context (`"signup"`), as `isValid(context)` does.
save
()) {
// saved: user.isPersisted() is true } else { var console: Consoleconsole.Console.log(...data: any[]): void (+1 overload)
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(const user: Useruser.Model.errors: Errors
The errors from the last validation run.
errors
.Errors.fullMessages(): string[]
Every message with its attribute's human name first: "Email can't be blank".
fullMessages
()); // ["Email has already been taken"]
} const const created: Usercreated = await class UserUser.
create<typeof User>(this: typeof User, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly isActive: {
        readonly type: "boolean";
        readonly null: false;
        readonly default: () => boolean;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: Init<User> | undefined): Promise<...>
Builds a record, awaits `init` with it if it's given, and saves it; resolves to it whether or not it was saved (check `isPersisted()`).
create
({ email?: string | undefinedemail: "sam@example.com" }); // saved, or not
await const created: Usercreated.
Model.update(attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly isActive: {
        readonly type: "boolean";
        readonly null: false;
        readonly default: () => boolean;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>): Promise<boolean>
`assign` then `save`.
update
({ isActive?: boolean | undefinedisActive: 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(). 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:

import { class RecordInvalid
A `…OrThrow` save was refused because the record is invalid; `record.errors` says why.
RecordInvalid
} from "@forestfuture/active-record";
import { class UserUser } from "./models/user"; export async function function signUp(request: Request): Promise<Response>signUp(request: Request<unknown, CfProperties<unknown>>request: interface Request<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>>
The **`Request`** interface of the Fetch API represents a resource request. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request)
Request
): interface Promise<T>
Represents the completion of an asynchronous operation
Promise
<Response> {
try { const { const email: stringemail } = await request: Request<unknown, CfProperties<unknown>>request.
Body.json<{
    email: string;
}>(): Promise<{
    email: string;
}> (+1 overload)
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json)
json
<{ email: stringemail: string }>();
const const user: Useruser = await class UserUser.
createOrThrow<typeof User>(this: typeof User, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly isActive: {
        readonly type: "boolean";
        readonly null: false;
        readonly default: () => boolean;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: Init<User> | undefined): Promise<...>
Like `create`, but throws if the record can't be saved.
createOrThrow
({ email?: string | undefinedemail });
return
var Response: {
    new (body?: BodyInit | null, init?: ResponseInit): Response;
    prototype: Response;
    error(): Response;
    json(data: any, init?: ResponseInit): Response;
    redirect(url: string | URL, status?: number): Response;
}
The **`Response`** interface of the Fetch API represents the response to a request. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)
Response
.function json(data: any, init?: ResponseInit): Response
The **`json()`** static method of the Response interface returns a Response that contains the provided JSON data as body, and a Content-Type header which is set to application/json. The response status, status message, and additional headers can also be set. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static)
json
(const user: Useruser, { ResponseInit.status?: number | undefinedstatus: 201 });
} catch (function (local var) error: unknownerror) { if (function (local var) error: unknownerror instanceof class RecordInvalid
A `…OrThrow` save was refused because the record is invalid; `record.errors` says why.
RecordInvalid
) {
return
var Response: {
    new (body?: BodyInit | null, init?: ResponseInit): Response;
    prototype: Response;
    error(): Response;
    json(data: any, init?: ResponseInit): Response;
    redirect(url: string | URL, status?: number): Response;
}
The **`Response`** interface of the Fetch API represents the response to a request. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)
Response
.function json(data: any, init?: ResponseInit): Response
The **`json()`** static method of the Response interface returns a Response that contains the provided JSON data as body, and a Content-Type header which is set to application/json. The response status, status message, and additional headers can also be set. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static)
json
({ errors: string[]errors: function (local var) error: RecordInvaliderror.RecordInvalid.record: Modelrecord.Model.errors: Errors
The errors from the last validation run.
errors
.Errors.fullMessages(): string[]
Every message with its attribute's human name first: "Email can't be blank".
fullMessages
() }, { ResponseInit.status?: number | undefinedstatus: 422 });
} throw function (local var) error: unknownerror; // 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.
  • An error thrown by a callback, other than abort(), even from an after-callback once the record is saved.
  • The database’s own errors.

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:

import { class ArticleArticle } from "./models/article";

const const article: Articlearticle = await class ArticleArticle.findByOrThrow<typeof Article>(this: typeof Article, conditions: SafeSql | Conditions<Article>): Promise<Article>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ title?: string | readonly string[] | Comparison<string> | undefinedtitle: "Hello" });
const article: Articlearticle.AttributeWrites.increment<Article>(this: Article, name: "viewCount", by?: number): Article
Adds `by` (one by default) to a number attribute, null counting as zero; doesn't save.
increment
("viewCount"); // viewCount + 1, not saved yet
const article: Articlearticle.AttributeWrites.toggle<Article>(this: Article, name: "isPinned"): Article
Flips a boolean attribute, null becoming `true`; doesn't save.
toggle
("isPinned");
await const article: Articlearticle.Model.save(options?: SaveOptions): Promise<boolean>
Inserts a new record or updates a persisted one; `false` if it's invalid, a callback aborted, or a record it destroys refused (#37). `context` validates it in that context (`"signup"`), as `isValid(context)` does.
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:

import { class ArticleArticle } from "./models/article";

const const article: Articlearticle = await class ArticleArticle.findByOrThrow<typeof Article>(this: typeof Article, conditions: SafeSql | Conditions<Article>): Promise<Article>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ title?: string | readonly string[] | Comparison<string> | undefinedtitle: "Hello" });
await const article: Articlearticle.AttributeWrites.incrementColumn<Article>(this: Article, name: "viewCount", by?: number, { touch }?: CounterOptions<Article>): Promise<boolean>
Adds `by` to a number attribute in the row, as `SET x = COALESCE(x, 0) + by`, so concurrent writes all count, with no validation, callback or `updatedAt`; the record then holds the row's new value. An unsaved change to it is added too. With `{ touch }`, the same UPDATE sets `updatedAt` (and any datetime attributes named) to now, and the record holds them (#50). Resolves to whether there was a row to write.
incrementColumn
("viewCount"); // adds 1 in the row, now
await const article: Articlearticle.AttributeWrites.toggleColumn<Article>(this: Article, name: "isPinned"): Promise<boolean>
Writes a boolean attribute's flipped value straight to the row, as `updateColumn` does: no validation or callback. Flip the attribute and `save()` to run the save callbacks.
toggleColumn
("isPinned");
await const article: Articlearticle.
AttributeWrites.updateColumns<Article>(this: Article, attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly title: {
        readonly type: "string";
        readonly null: false;
    };
    readonly viewCount: {
        readonly type: "integer";
        readonly null: false;
        readonly default: () => number;
    };
    readonly isPinned: {
        readonly type: "boolean";
        readonly null: false;
        readonly default: () => boolean;
    };
    readonly viewedAt: "datetime";
    readonly updatedAt: "datetime";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>): Promise<boolean>
Writes these attributes straight to the row, with no validation, callback or `updatedAt`, and leaves the record clean for them. Resolves to whether there was a row to write. A new record is `RecordNotSaved`.
updateColumns
({ title?: string | undefinedtitle: "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:

import { class ArticleArticle } from "./models/article";

const const article: Articlearticle = await class ArticleArticle.findByOrThrow<typeof Article>(this: typeof Article, conditions: SafeSql | Conditions<Article>): Promise<Article>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ title?: string | readonly string[] | Comparison<string> | undefinedtitle: "Hello" });
await const article: Articlearticle.AttributeWrites.touch<Article>(this: Article, ...args: TouchArguments<Article>): Promise<boolean>
Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`), straight to the row, with no validation or save callback. Resolves to whether there was a row to write. Inside its Model's `noTouching` block, it writes nothing (#496).
touch
(); // sets updatedAt to now
await const article: Articlearticle.AttributeWrites.touch<Article>(this: Article, ...args: TouchArguments<Article>): Promise<boolean>
Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`), straight to the row, with no validation or save callback. Resolves to whether there was a row to write. Inside its Model's `noTouching` block, it writes nothing (#496).
touch
("viewedAt"); // sets viewedAt and updatedAt
await const article: Articlearticle.AttributeWrites.touch<Article>(this: Article, ...args: TouchArguments<Article>): Promise<boolean>
Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`), straight to the row, with no validation or save callback. Resolves to whether there was a row to write. Inside its Model's `noTouching` block, it writes nothing (#496).
touch
({ TouchOptions.time?: Date | undefined
The time to set, now by default.
time
: new
var Date: DateConstructor
new (value: number | string | Date) => Date (+4 overloads)
Date
("2026-01-01T00:00:00Z") });
await class ArticleArticle.where<typeof Article>(this: typeof Article, conditions: SafeSql | Conditions<Article>): Relation<Article, ScopesOf<typeof Article>>where({ isPinned?: boolean | readonly boolean[] | undefinedisPinned: true }).Relation<Article, ScopesOf<typeof Article>>.touchAll(...args: TouchArguments<Article>): Promise<number>
Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`) in every row this Relation matches, in one statement (#50). Resolves to the number of rows; skips what `updateAll` skips.
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.

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 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.

Updating counters

To add to a number without loading the record, pass its primary key to updateCounters:

import { class ArticleArticle } from "./models/article";

const { const id: stringid } = await class ArticleArticle.findByOrThrow<typeof Article>(this: typeof Article, conditions: SafeSql | Conditions<Article>): Promise<Article>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ title?: string | readonly string[] | Comparison<string> | undefinedtitle: "Hello" });
await class ArticleArticle.KeyedWriteStatics.updateCounters: <typeof Article>(this: typeof Article, ids: Keys, counters: Counters<Article>, options?: CounterOptions<Article> | undefined) => Promise<number>
Adds to number attributes in the rows with these primary keys, as a Relation's `updateCounters` does, whatever the default scope: `Post.updateCounters(id, { viewCount: 1 })`. Resolves to the number of rows.
updateCounters
(const id: stringid, { viewCount?: number | undefinedviewCount: 1 });
await class ArticleArticle.where<typeof Article>(this: typeof Article, conditions: SafeSql | Conditions<Article>): Relation<Article, ScopesOf<typeof Article>>where({ isPinned?: boolean | readonly boolean[] | undefinedisPinned: true }).Relation<Article, ScopesOf<typeof Article>>.updateCounters(counters: Counters<Article>, { touch }?: CounterOptions<Article>): Promise<number>
Adds to number attributes in every row this Relation matches, now, in one statement: `updateCounters({ viewCount: 1 })` sets `view_count = COALESCE(view_count, 0) + 1`, so concurrent writes all count. Resolves to the number of rows; skips what `updateAll` skips.
updateCounters
({ viewCount?: number | undefinedviewCount: 10 });
await class ArticleArticle.
KeyedWriteStatics.incrementCounter: <typeof Article>(this: typeof Article, name: "viewCount", ids: Keys, options?: ({
    by?: number;
} & CounterOptions<Article>) | undefined) => Promise<number>
`updateCounters` for one attribute, adding `by` (one by default): `{ by: 5, touch }`.
incrementCounter
("viewCount", [const id: stringid], { by?: number | undefinedby: 5, CounterOptions<Article>.touch?: Touch<Article> | undefinedtouch: 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.

Finding or creating a record

Find a record by its attributes, or create one with them when there isn’t one, with findOrCreateBy:

import { class LabelLabel } from "./models/label";

const const travel: Labeltravel = await class LabelLabel.
findOrCreateBy<typeof Label>(this: typeof Label, attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly color: "string";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>, init?: Init<Label> | undefined): Promise<Label>
The first record with these attributes or, when none has them, one created with them (and handed to `init` before it's saved), as `create` does: check `isPersisted()`. Two requests at once can both create one; `createOrFindBy` is safe from that.
findOrCreateBy
({ name?: string | undefinedname: "travel" }); // found, or created
const const food: Labelfood = await class LabelLabel.
findOrInitializeBy<typeof Label>(this: typeof Label, attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly color: "string";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>, init?: Init<Label> | undefined): Promise<Label>
The first record with these attributes or, when none has them, a new one built with them and handed to `init`, which is awaited. Saves nothing.
findOrInitializeBy
({ name?: string | undefinedname: "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:

import { class LabelLabel } from "./models/label";

const const music: Labelmusic = await class LabelLabel.
createWith<typeof Label>(this: typeof Label, attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly color: "string";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | null): Relation<Label, ScopesOf<typeof Label>>
Attributes for the records this Relation builds, creates or inserts, but not conditions its finders use: `createWith({ role: "member" }).findOrCreateBy({ email })`. Added to any it has; `null` removes them. They win over its conditions' values. Attributes given to `build` or `create` win over them, and a bulk write such as `insert` writes them over its own (#470).
createWith
({ color?: string | null | undefinedcolor: "blue" }).
Relation<Label, ScopesOf<typeof Label>>.findOrCreateBy(attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly color: "string";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>, init?: Init<Label> | undefined): Promise<Label>
The first record with these attributes or, when none has them, one created with them (and handed to `init` before it's saved), as `create` does: check `isPersisted()`. Two requests at once can both create one; `createOrFindBy` is safe from that.
findOrCreateBy
({ name?: string | undefinedname: "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:

import { class LabelLabel } from "./models/label";

const const art: Labelart = await class LabelLabel.
findOrCreateBy<typeof Label>(this: typeof Label, attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly color: "string";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>, init?: Init<Label> | undefined): Promise<Label>
The first record with these attributes or, when none has them, one created with them (and handed to `init` before it's saved), as `create` does: check `isPersisted()`. Two requests at once can both create one; `createOrFindBy` is safe from that.
findOrCreateBy
({ name?: string | undefinedname: "art" }, (label: Labellabel) => {
label: Labellabel.color: string | nullcolor = "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:

import { class LabelLabel } from "./models/label";

const const news: Labelnews = await class LabelLabel.
createOrFindBy<typeof Label>(this: typeof Label, attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly color: "string";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>, init?: Init<Label> | undefined): Promise<Label>
Creates a record with these attributes (handing it to `init` first), as `create` does, or, when a unique index refuses it (`RecordNotUnique`), finds the record with these attributes: safe where two requests create at once, as `findOrCreateBy` isn't. Throws `RecordNotFound` if the index refused a value the attributes don't name. A record `init` gave others to save with it throws its `RecordNotUnique`, which may be theirs.
createOrFindBy
({ name?: string | undefinedname: "news" }); // created, or found

createOrFindByOrThrow throws RecordInvalid when the record is invalid.

Destroying records

Destroy a record with destroy:

import { class UserUser } from "./models/user";

const const user: Useruser = await class UserUser.findByOrThrow<typeof User>(this: typeof User, conditions: SafeSql | Conditions<User>): Promise<User>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ email?: string | readonly string[] | Comparison<string> | undefinedemail: "jane@example.com" });
const const destroyed: false | Userdestroyed = await const user: Useruser.Model.destroy(): Promise<false | User>
Deletes the row and resolves to this record, now a read-only destroyed snapshot. A row that's already gone still counts. `false` means a `beforeDestroy` or `aroundDestroy` callback aborted (or an `aroundDestroy` didn't call `next()`), or a `restrictWithError` association refused.
destroy
(); // the record, or false if a callback aborted
if (const destroyed: false | Userdestroyed) var console: Consoleconsole.Console.log(...data: any[]): void (+1 overload)
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(const destroyed: Userdestroyed.Model.isDestroyed(): boolean
Deleted by this instance; a read-only snapshot of the row.
isDestroyed
()); // true: readable, but can't be saved

It runs the destroy callbacks and the associations’ dependent options, then deletes the row. A destroyed record’s attributes stay readable, but setting one, or calling save, update, destroy, or reload, throws RecordDestroyed.

Destroying many records

Destroy every record a query matches with destroyAll:

import { class PostPost } from "./models/post";
import { class UserUser } from "./models/user";

const const drafts: Post[]drafts = await class PostPost.where<typeof Post>(this: typeof Post, conditions: SafeSql | Conditions<Post>): Relation<Post, ScopesOf<typeof Post>>where({ publishedAt?: Date | readonly (Date | null)[] | Comparison<Date> | null | undefinedpublishedAt: null }).Relation<Post, ScopesOf<typeof Post>>.destroyAll(): Promise<Post[]>
Loads the records this Relation matches and destroys each, callbacks and `dependent:` strategies included, as one write: if one refuses, it throws `RecordNotDestroyed` and nothing is destroyed. Resolves to the records, each once, though a join repeats it (#24). A `none()` Relation sends nothing and resolves to []. Through a hasMany, what its owner loaded is cleared.
destroyAll
(); // the destroyed posts
const const user: Useruser = await class UserUser.findByOrThrow<typeof User>(this: typeof User, conditions: SafeSql | Conditions<User>): Promise<User>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ email?: string | readonly string[] | Comparison<string> | undefinedemail: "jane@example.com" });
await class PostPost.destroyBy<typeof Post>(this: typeof Post, conditions: SafeSql | Conditions<Post>): Promise<Post[]>
Destroys the records matching `conditions`, as `where(conditions).destroyAll()` does.
destroyBy
({ userId?: string | readonly string[] | Comparison<string> | undefineduserId: const user: Useruser.id: stringid }); // 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.

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:

import { class PostPost } from "./models/post";

const const unpublished: Relation<Post, ScopesOf<typeof Post>>unpublished = class PostPost.where<typeof Post>(this: typeof Post, conditions: SafeSql | Conditions<Post>): Relation<Post, ScopesOf<typeof Post>>where({ publishedAt?: Date | readonly (Date | null)[] | Comparison<Date> | null | undefinedpublishedAt: null });
for await (const const batch: Relation<Post, ScopesOf<typeof Post>>batch of const unpublished: Relation<Post, ScopesOf<typeof Post>>unpublished.Relation<Post, ScopesOf<typeof Post>>.inBatches(options?: IterationOptions): AsyncIterable<Relation<Post, ScopesOf<typeof Post>>>
A Relation of each batch's records, in primary-key order (#347), to write a batch at a time: `for await (const posts of drafts.inBatches()) await posts.deleteAll()`.
inBatches
({ IterationOptions.batchSize?: number | undefined
Records in each batch: each is one query. 1000 by default.
batchSize
: 100 })) {
await const batch: Relation<Post, ScopesOf<typeof Post>>batch.Relation<Post, ScopesOf<typeof Post>>.destroyAll(): Promise<Post[]>
Loads the records this Relation matches and destroys each, callbacks and `dependent:` strategies included, as one write: if one refuses, it throws `RecordNotDestroyed` and nothing is destroyed. Resolves to the records, each once, though a join repeats it (#24). A `none()` Relation sends nothing and resolves to []. Through a hasMany, what its owner loaded is cleared.
destroyAll
(); // one write per batch
}

Each batch is its own write, so a batch that fails leaves the earlier batches destroyed.

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:

import { class ArticleArticle } from "./models/article";

const const article: Articlearticle = await class ArticleArticle.
create<typeof Article>(this: typeof Article, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly title: {
        readonly type: "string";
        readonly null: false;
    };
    readonly viewCount: {
        readonly type: "integer";
        readonly null: false;
        readonly default: () => number;
    };
    readonly isPinned: {
        readonly type: "boolean";
        readonly null: false;
        readonly default: () => boolean;
    };
    readonly viewedAt: "datetime";
    readonly updatedAt: "datetime";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: Init<...> | undefined): Promise<...>
Builds a record, awaits `init` with it if it's given, and saves it; resolves to it whether or not it was saved (check `isPersisted()`).
create
({ title?: string | undefinedtitle: "Fresh" }); // logs "New article: Fresh"
await const article: Articlearticle.
Model.update(attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly title: {
        readonly type: "string";
        readonly null: false;
    };
    readonly viewCount: {
        readonly type: "integer";
        readonly null: false;
        readonly default: () => number;
    };
    readonly isPinned: {
        readonly type: "boolean";
        readonly null: false;
        readonly default: () => boolean;
    };
    readonly viewedAt: "datetime";
    readonly updatedAt: "datetime";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>): Promise<boolean>
`assign` then `save`.
update
({ title?: string | undefinedtitle: "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:

import { class UserUser } from "./models/user";

const const user: Useruser = await class UserUser.findByOrThrow<typeof User>(this: typeof User, conditions: SafeSql | Conditions<User>): Promise<User>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ email?: string | readonly string[] | Comparison<string> | undefinedemail: "jane@example.com" });
const user: Useruser.email: stringemail = "changed@example.com"; await const user: Useruser.Model.reload(): Promise<User>
Loads the stored row again, discarding unsaved changes; `RecordNotFound` if it's gone.
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.

Last updated on