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

Bulk writes and batches

Write many rows in one statement, and send several writes that all succeed or all fail.

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:

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

export class Comment extends ApplicationRecord {
  article = belongsTo(Article);
}
// 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<typeof articles, (typeof Article)["attributes"]> {}
}

declare module "../models/author" {
  interface Author extends TableAttributes<typeof authors, (typeof Author)["attributes"]> {}
}

declare module "../models/comment" {
  interface Comment extends TableAttributes<typeof comments, (typeof Comment)["attributes"]> {}
}
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
);
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:

import { function column(attribute: string): ColumnReference
Names the column of `attribute` inside an `sql` fragment, quoted and mapped (ADR-0004).
column
, function sql(strings: TemplateStringsArray, ...values: unknown[]): SafeSqlsql } from "@forestfuture/active-record";
import { class ArticleArticle } from "./models/article"; import { class CommentComment } from "./models/comment"; 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: "Getting started" });
const const deleted: numberdeleted = await class CommentComment.where<typeof Comment>(this: typeof Comment, conditions: SafeSql | Conditions<Comment>): Relation<Comment, ScopesOf<typeof Comment>>where({ articleId?: string | readonly string[] | Comparison<string> | undefinedarticleId: const article: Articlearticle.id: stringid }).Relation<Comment, ScopesOf<typeof Comment>>.deleteAll(): Promise<number>
Deletes every row this Relation matches, now, resolving to the number of rows. On a hasMany association itself (`user.posts().deleteAll()`), the rows' foreign key is set to NULL instead unless its `dependent:` deletes. A `none()` Relation sends nothing and resolves to 0.
deleteAll
(); // how many
await class ArticleArticle.where<typeof Article>(this: typeof Article, conditions: SafeSql | Conditions<Article>): Relation<Article, ScopesOf<typeof Article>>where({ id?: string | readonly string[] | Comparison<string> | undefinedid: const article: Articlearticle.id: stringid }).
Relation<Article, ScopesOf<typeof Article>>.updateAll(changes: SafeSql | Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly authorId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly title: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>): Promise<number>
Updates every row this Relation matches, now, setting attribute values or an `sql` fragment: ``updateAll(sql`${column("views")} = ${column("views")} + 1`)``. Resolves to the number of rows updated. Skips validations and callbacks, and leaves `updatedAt` alone. A `none()` Relation sends nothing and resolves to 0.
updateAll
({ title?: string | undefinedtitle: "Edited" });
await class ArticleArticle.where<typeof Article>(this: typeof Article, conditions: SafeSql | Conditions<Article>): Relation<Article, ScopesOf<typeof Article>>where({ id?: string | readonly string[] | Comparison<string> | undefinedid: const article: Articlearticle.id: stringid }).
Relation<Article, ScopesOf<typeof Article>>.updateAll(changes: SafeSql | Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly authorId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly title: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>): Promise<number>
Updates every row this Relation matches, now, setting attribute values or an `sql` fragment: ``updateAll(sql`${column("views")} = ${column("views")} + 1`)``. Resolves to the number of rows updated. Skips validations and callbacks, and leaves `updatedAt` alone. A `none()` Relation sends nothing and resolves to 0.
updateAll
(
function sql(strings: TemplateStringsArray, ...values: unknown[]): SafeSqlsql`${function column(attribute: string): ColumnReference
Names the column of `attribute` inside an `sql` fragment, quoted and mapped (ADR-0004).
column
("title")} = upper(${function column(attribute: string): ColumnReference
Names the column of `attribute` inside an `sql` fragment, quoted and mapped (ADR-0004).
column
("title")})`,
); const { const rowsAffected: numberrowsAffected,
const rows: (Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly articleId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly body: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly articleId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly body: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<...> | undefined>>, "id" | ... 1 more ... | "body">)[]
rows
} = await class CommentComment.
insert<typeof Comment>(this: typeof Comment, attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly articleId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly body: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>, options?: (InsertOptions<Comment> & {
    returning?: Returning<Comment> | undefined;
}) | undefined): Promise<...>
Inserts one row now: `await db.model(Post).insert({ title })`. Resolves to how many rows it wrote and the `returning` attributes of each (the primary key by default; `false` for none). Skips validations and callbacks; declared defaults, generated ids, and timestamps apply, and this Relation's equality conditions are inserted over the given attributes (#470). A duplicate throws, unless `onDuplicate: "skip"`. `b.insert` is the same write, for a batch.
insert
({ articleId?: string | undefinedarticleId: const article: Articlearticle.id: stringid, body?: string | undefinedbody: "First!" });
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 deleted: numberdeleted, const rowsAffected: numberrowsAffected,
const rows: (Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly articleId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly body: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly articleId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly body: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<...> | undefined>>, "id" | ... 1 more ... | "body">)[]
rows
[0]?.id?: string | undefinedid); // 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.

Inserting many rows

Insert many rows at once with insertAll:

import { class ArticleArticle } from "./models/article";
import { class AuthorAuthor } from "./models/author";
import { class CommentComment } from "./models/comment";

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: "Getting started" });
await class CommentComment.
insertAll<typeof Comment>(this: typeof Comment, rows: readonly Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly articleId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly body: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>[], options?: (InsertOptions<Comment> & {
    returning?: Returning<Comment> | undefined;
}) | undefined): Promise<...>
Inserts several rows with the same attributes now: in one statement, or several in one atomic batch when they pass the database's cap on one value.
insertAll
([
{ articleId?: string | undefinedarticleId: const article: Articlearticle.id: stringid, body?: string | undefinedbody: "One" }, { articleId?: string | undefinedarticleId: const article: Articlearticle.id: stringid, body?: string | undefinedbody: "Two" }, ]); await class AuthorAuthor.
upsert<typeof Author>(this: typeof Author, attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>, options?: (UpsertOptions<Author> & {
    returning?: Returning<Author> | undefined;
}) | undefined): Promise<...>
Inserts a row now, or updates it when it clashes with the unique index on `uniqueBy` (the primary key by default): every given attribute and every value this Relation writes into the row (#475), except the `uniqueBy` ones and `createdAt`, with `updatedAt` set. Resolves as `insert` does, returning inserted and updated rows.
upsert
({ name?: string | undefinedname: "Jane Doe", email?: string | undefinedemail: "jane@example.com" }, { UpsertOptions<Author>.uniqueBy?: "id" | "name" | "email" | readonly ("id" | "name" | "email")[] | undefineduniqueBy: "email" }); // renames Jane
await class AuthorAuthor.
insert<typeof Author>(this: typeof Author, attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>, options?: (InsertOptions<Author> & {
    returning?: Returning<Author> | undefined;
}) | undefined): Promise<...>
Inserts one row now: `await db.model(Post).insert({ title })`. Resolves to how many rows it wrote and the `returning` attributes of each (the primary key by default; `false` for none). Skips validations and callbacks; declared defaults, generated ids, and timestamps apply, and this Relation's equality conditions are inserted over the given attributes (#470). A duplicate throws, unless `onDuplicate: "skip"`. `b.insert` is the same write, for a batch.
insert
({ name?: string | undefinedname: "Jane", email?: string | undefinedemail: "jane@example.com" }, { InsertOptions<M = unknown>.onDuplicate?: "skip" | undefinedonDuplicate: "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.

Returning attributes

Inserts and upserts return the primary key of each row they write. Name other attributes with returning:

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

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: "Getting started" });
const {
const rows: (Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly articleId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly body: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly articleId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly body: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<...> | undefined>>, "id" | ... 1 more ... | "body">)[]
rows
} = await class CommentComment.
insertAll<typeof Comment>(this: typeof Comment, rows: readonly Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly articleId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly body: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>[], options?: (InsertOptions<Comment> & {
    returning?: Returning<Comment> | undefined;
}) | undefined): Promise<...>
Inserts several rows with the same attributes now: in one statement, or several in one atomic batch when they pass the database's cap on one value.
insertAll
(
[ { articleId?: string | undefinedarticleId: const article: Articlearticle.id: stringid, body?: string | undefinedbody: "One" }, { articleId?: string | undefinedarticleId: const article: Articlearticle.id: stringid, body?: string | undefinedbody: "Two" }, ], { returning?: Returning<Comment> | undefinedreturning: ["id", "body"] }, ); for (const { const id: string | undefinedid, const body: string | undefinedbody } of
const rows: (Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly articleId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly body: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly articleId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly body: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<...> | undefined>>, "id" | ... 1 more ... | "body">)[]
rows
) 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 id: string | undefinedid, const body: string | undefinedbody);
await class CommentComment.
insert<typeof Comment>(this: typeof Comment, attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly articleId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly body: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>, options?: (InsertOptions<Comment> & {
    returning?: Returning<Comment> | undefined;
}) | undefined): Promise<...>
Inserts one row now: `await db.model(Post).insert({ title })`. Resolves to how many rows it wrote and the `returning` attributes of each (the primary key by default; `false` for none). Skips validations and callbacks; declared defaults, generated ids, and timestamps apply, and this Relation's equality conditions are inserted over the given attributes (#470). A duplicate throws, unless `onDuplicate: "skip"`. `b.insert` is the same write, for a batch.
insert
({ articleId?: string | undefinedarticleId: const article: Articlearticle.id: stringid, body?: string | undefinedbody: "Three" }, { returning?: Returning<Comment> | undefinedreturning: 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.

Batching writes

Prepare several writes in batch’s callback to write them atomically:

import { function batch<const T extends readonly BatchEntry[]>(build: (b: Batch) => T): Promise<BatchResults<T>>
`db.batch`, on the current database: `batch((b) => [b.updateAll(Product, …), b.save(product)])`. A Model's rows are looked up on the current database, and a Relation or record runs on the one it came from. Atomic, as `db.batch` is; writes on two databases throw `IncompatibleRelation`.
batch
} from "@forestfuture/active-record";
import { class ArticleArticle } from "./models/article"; import { class AuthorAuthor } from "./models/author"; const const authorId: `${string}-${string}-${string}-${string}-${string}`authorId = var crypto: Crypto
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/crypto)
crypto
.Crypto.randomUUID(): `${string}-${string}-${string}-${string}-${string}`
The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator. Available only in secure contexts. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID)
randomUUID
(); // generated in code, so the rows can point at it
await
batch<readonly [Statement<Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>>, Statement<Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly authorId: {
        ...;
    };
    readonly title: {
        ...;
    };
}, Readonly<...> | undefined>>>>, Statement<...>]>(build: (b: Batch) => readonly [...]): Promise<...>
`db.batch`, on the current database: `batch((b) => [b.updateAll(Product, …), b.save(product)])`. A Model's rows are looked up on the current database, and a Relation or record runs on the one it came from. Atomic, as `db.batch` is; writes on two databases throw `IncompatibleRelation`.
batch
((b: Batchb) => [
b: Batchb.
Batch.insert<Author, undefined>(target: BatchTarget<Author>, attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>, options?: InsertOptions<Author> & {
    ...;
}): Statement<...>
Inserts one row, as `insert` does when it runs alone.
insert
(class AuthorAuthor, { id?: string | undefinedid: const authorId: `${string}-${string}-${string}-${string}-${string}`authorId, name?: string | undefinedname: "Alex", email?: string | undefinedemail: "alex@example.com" }),
b: Batchb.
Batch.insert<Article, undefined>(target: BatchTarget<Article>, attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly authorId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly title: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>, options?: InsertOptions<Article> & {
    ...;
}): Statement<...>
Inserts one row, as `insert` does when it runs alone.
insert
(class ArticleArticle, { authorId?: string | undefinedauthorId, title?: string | undefinedtitle: "Hello" }),
b: Batchb.
Batch.updateAll<Article>(target: BatchTarget<Article>, changes: SafeSql | Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly authorId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly title: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>): Statement
Updates every row `target` matches, as `updateAll` does: `b.updateAll(Post, { published: true })`.
updateAll
(class ArticleArticle.where<typeof Article>(this: typeof Article, conditions: SafeSql | Conditions<Article>): Relation<Article, ScopesOf<typeof Article>>where({ title?: string | readonly string[] | Comparison<string> | undefinedtitle: "Getting started" }), { authorId?: string | undefinedauthorId }), // 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.
  • 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.

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:

import { function batch<const T extends readonly BatchEntry[]>(build: (b: Batch) => T): Promise<BatchResults<T>>
`db.batch`, on the current database: `batch((b) => [b.updateAll(Product, …), b.save(product)])`. A Model's rows are looked up on the current database, and a Relation or record runs on the one it came from. Atomic, as `db.batch` is; writes on two databases throw `IncompatibleRelation`.
batch
} from "@forestfuture/active-record";
import { class ArticleArticle } from "./models/article"; import { class AuthorAuthor } from "./models/author"; import { class CommentComment } from "./models/comment"; 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: "Getting started" });
const article: Articlearticle.title: stringtitle = "Getting started, again"; const const author: Authorauthor = class AuthorAuthor.
build<typeof Author>(this: typeof Author, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: ((record: Author) => void) | undefined): Author
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
({ name?: string | undefinedname: "Kim", email?: string | undefinedemail: "kim@example.com" });
const const leaving: Authorleaving = await class AuthorAuthor.findByOrThrow<typeof Author>(this: typeof Author, conditions: SafeSql | Conditions<Author>): Promise<Author>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ email?: string | readonly string[] | Comparison<string> | undefinedemail: "sam@example.com" });
const [const savedArticle: ArticlesavedArticle, const savedAuthor: AuthorsavedAuthor] = await batch<readonly [RecordStatement<Article>, RecordStatement<Author>, RecordStatement<Author>, Statement<never>]>(build: (b: Batch) => readonly [RecordStatement<Article>, RecordStatement<Author>, RecordStatement<Author>, Statement<never>]): Promise<[Article, Author, Author, WriteResult<never>]>
`db.batch`, on the current database: `batch((b) => [b.updateAll(Product, …), b.save(product)])`. A Model's rows are looked up on the current database, and a Relation or record runs on the one it came from. Atomic, as `db.batch` is; writes on two databases throw `IncompatibleRelation`.
batch
((b: Batchb) => [
b: Batchb.Batch.save<Article>(record: Article, options?: SaveOptions): RecordStatement<Article>
Saves `record`, its autosaved associations included. Its validations and before-callbacks run when the batch runs, before anything is written, and its after-callbacks once it is. `context` validates it in that context (`"signup"`), as `save({ context })` does; one its Model doesn't list throws `TypeError` here.
save
(const article: Articlearticle),
b: Batchb.Batch.save<Author>(record: Author, options?: SaveOptions): RecordStatement<Author>
Saves `record`, its autosaved associations included. Its validations and before-callbacks run when the batch runs, before anything is written, and its after-callbacks once it is. `context` validates it in that context (`"signup"`), as `save({ context })` does; one its Model doesn't list throws `TypeError` here.
save
(const author: Authorauthor),
b: Batchb.Batch.destroy<Author>(record: Author): RecordStatement<Author>
Destroys `record`, with its dependents, its callbacks running as `save`'s do.
destroy
(const leaving: Authorleaving), // with Sam's articles and their comments
b: Batchb.Batch.deleteAll<Comment>(target: BatchTarget<Comment>): Statement
Deletes every row `target` matches, as `deleteAll` does (through a hasMany, it may nullify).
deleteAll
(class CommentComment.where<typeof Comment>(this: typeof Comment, conditions: SafeSql | Conditions<Comment>): Relation<Comment, ScopesOf<typeof Comment>>where({ articleId?: string | readonly string[] | Comparison<string> | undefinedarticleId: const article: Articlearticle.id: stringid })),
]);

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 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, pass the context to b.save, such as b.save(member, { context: "signup" }).

Last updated on