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

Connections

Give a query its database: the Model’s binding, the request’s database, or one you pass.

At a glance

Most apps only use the binding.

How Use it for
The binding User.find(id), with nothing to set up Everyday queries
The request’s database withDatabase(connect(env.DB, …), fn), once per request Read replicas with a Session, per-request onQuery logging, tests, and scripts
An explicit database connect(env.DB).model(User).find(id) Code that passes its database around, or uses two at once

Database resolution explains why there are three, and which one you need.

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

export class Post extends ApplicationRecord {
  user = belongsTo(User);
}
// Generated by `active-record schema` from migrations/ — don't edit.
// schema: f287cc463ec1

import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";

/** posts — last changed by 0001_create_tables.sql */
export const posts = {
  id: { type: "string", null: false, generateId: true },
  userId: { type: "string", null: false },
  title: { type: "string", null: false },
} as const;

/** users — last changed by 0001_create_tables.sql */
export const users = {
  id: { type: "string", null: false, generateId: true },
  email: { type: "string", null: false },
} as const;

/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
export const schema = defineSchema({
  adapter: d1({ binding: "DB" }),
  tables: {
    posts: { attributes: posts, primaryKey: "id" },
    users: { attributes: users, primaryKey: "id" },
  },
  models: { Post: "posts", User: "users" },
});

declare module "../models/post" {
  interface Post extends TableAttributes<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
);
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
);
CREATE TABLE users (
  id UUID PRIMARY KEY,
  email TEXT NOT NULL
);
CREATE UNIQUE INDEX index_users_on_email ON users (email);
CREATE TABLE posts (
  id UUID PRIMARY KEY,
  user_id UUID NOT NULL REFERENCES users (id),
  title TEXT NOT NULL
);

Using the binding

Each Model names the binding it queries, so a Model queries by itself during any request, as the app’s Worker does:

import { User } from "./models/user";

// The app's Worker. No setup: each Model queries the binding its generated schema names.
export const app = {
  async fetch(request) {
    const email = new URL(request.url).searchParams.get("email") ?? "";
    const user = await User.findByOrThrow({ email });
    return Response.json(await user.posts().order({ title: "asc" }).pluck("title"));
  },
} satisfies ExportedHandler<Env>;

active-record schema writes the binding into the generated schema your app’s base class holds. On D1 it comes from your Wrangler config’s d1_databases, and on Postgres from your active-record.jsonc.

Records remember their database, so user.save() and user.posts() use the same one later.

Using the request’s database

Some things belong to one request, such as a D1 Session that reads its own writes, or logging tagged with the request’s ID. Open a database for the request, and run its code inside withDatabase:

import { function withDatabase<R>(databases: AnyDatabase | readonly AnyDatabase[], fn: () => R | Promise<R>): Promise<R>
Runs `fn` with `databases` as the request's own: queries started from a Model inside it (and everything it awaits) use the one on that Model's binding, with its Session and `onQuery`. Usually called once per request, in middleware. Nested calls add to the outer ones. Each call is a scope of its own, even with a Database another request shares. An adapter may hold a connection for the scope (the PostgreSQL adapter does, from a connection string). A nested call with the same Database shares the outer call's scope while that call is running. When `fn` settles, the scope ends, and the adapter lets its connection go once the queries still running on it finish. Work that outlives the scope, such as a `waitUntil` save, gets a connection of its own.
withDatabase
} from "@forestfuture/active-record";
import { function connect(binding: D1Database, options?: ConnectOptions): Databaseconnect } from "@forestfuture/active-record/d1"; import {
const app: {
    fetch(request: Request<unknown, IncomingRequestCfProperties<unknown>>): Promise<Response>;
}
app
} from "./app";
// src/worker.ts: the app's Worker, with a database for each request. export const
const worker: {
    fetch(request: Request<unknown, IncomingRequestCfProperties<unknown>>, env: Env): Promise<Response>;
}
worker
= {
ExportedHandler<Env, unknown, unknown, unknown>.fetch?: ExportedHandlerFetchHandler<Env, unknown, unknown> | undefinedfetch(request: Request<unknown, IncomingRequestCfProperties<unknown>>request, env: Envenv) { const const db: Databasedb = function connect(binding: D1Database, options?: ConnectOptions): Databaseconnect(env: Envenv.Env.DB: D1DatabaseDB, { ConnectOptions.onQuery?: QueryListener | undefined
Called once for every statement sent to D1, with D1's `meta`.
onQuery
: ({ sql: stringsql }) => 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
(sql: stringsql) });
return withDatabase<Response>(databases: AnyDatabase | readonly AnyDatabase[], fn: () => Response | Promise<Response>): Promise<Response>
Runs `fn` with `databases` as the request's own: queries started from a Model inside it (and everything it awaits) use the one on that Model's binding, with its Session and `onQuery`. Usually called once per request, in middleware. Nested calls add to the outer ones. Each call is a scope of its own, even with a Database another request shares. An adapter may hold a connection for the scope (the PostgreSQL adapter does, from a connection string). A nested call with the same Database shares the outer call's scope while that call is running. When `fn` settles, the scope ends, and the adapter lets its connection go once the queries still running on it finish. Work that outlives the scope, such as a `waitUntil` save, gets a connection of its own.
withDatabase
(const db: Databasedb, () =>
const app: {
    fetch(request: Request<unknown, IncomingRequestCfProperties<unknown>>): Promise<Response>;
}
app
.function fetch(request: Request<unknown, IncomingRequestCfProperties<unknown>>): Promise<Response>fetch(request: Request<unknown, IncomingRequestCfProperties<unknown>>request)); // every query inside uses db
}, } satisfies interface ExportedHandler<Env = unknown, QueueHandlerMessage = unknown, CfHostMetadata = unknown, Props = unknown>ExportedHandler<Env>;

Every query started from a Model inside it, and everything it awaits, uses that database instead of the binding.

These pages use a request’s database:

Using an explicit database

Start a query from a database you hold with db.model. It ignores withDatabase:

import { function connect(binding: D1Database, options?: ConnectOptions): Databaseconnect } from "@forestfuture/active-record/d1";
import { class UserUser } from "./models/user";

export async function function findJane(env: Env): Promise<User>findJane(env: Envenv: Env) {
  const const db: Databasedb = function connect(binding: D1Database, options?: ConnectOptions): Databaseconnect(env: Envenv.Env.DB: D1DatabaseDB);
  return const db: Databasedb.AnyDatabase.model<typeof User>(model: typeof User): Relation<User, ScopesOf<typeof User>>
A request-bound Relation over the Model's records, with its scopes as methods.
model
(class UserUser).Relation<User, ScopesOf<typeof User>>.findByOrThrow(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" }); // ignores withDatabase
}

To name your Models once, use db.models:

import { function connect(binding: D1Database, options?: ConnectOptions): Databaseconnect } from "@forestfuture/active-record/d1";
import { class PostPost } from "./models/post";
import { class UserUser } from "./models/user";

export async function function listPosts(env: Env): Promise<string[]>listPosts(env: Envenv: Env) {
  const 
const models: RelationsFor<{
    readonly User: typeof User;
    readonly Post: typeof Post;
}>
models
= function connect(binding: D1Database, options?: ConnectOptions): Databaseconnect(env: Envenv.Env.DB: D1DatabaseDB).
AnyDatabase.models<{
    readonly User: typeof User;
    readonly Post: typeof Post;
}>(models: {
    readonly User: typeof User;
    readonly Post: typeof Post;
}): RelationsFor<{
    readonly User: typeof User;
    readonly Post: typeof Post;
}>
Request-bound relations for several models at once: `db.models({ User }).User`.
models
({ type User: typeof UserUser, type Post: typeof PostPost });
return
const models: RelationsFor<{
    readonly User: typeof User;
    readonly Post: typeof Post;
}>
models
.type Post: Relation<Post, ScopesOf<typeof Post>>Post.Relation<Post, ScopesOf<typeof Post>>.order(spec: SafeSql | OrderSpec<Post>): Relation<Post, ScopesOf<typeof Post>>
Sorts by each key in turn (`{ createdAt: "desc" }`, or `{ role: { direction: "asc", nulls: "last" } }`), or by an `sql` fragment expression. Repeated calls append.
order
({
title?: OrderDirection | {
    direction: OrderDirection;
    nulls?: NullsPlacement;
} | undefined
title
: "asc" }).Relation<Post, ScopesOf<typeof Post>>.pluck<"title">(attribute: "title"): Promise<string[]> (+1 overload)
Converted values of one attribute, or tuples of several, in this Relation's order.
pluck
("title");
}

connect(env.DB, { session, onQuery }) takes the same options as a request’s database.

Batching writes

batch saves and destroys records and runs bulk writes atomically:

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 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<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: "sam@example.com" });
const const post: Postpost = const user: Useruser.User.posts: () => HasManyCollection<Post, ScopesOf<typeof Post>>posts().
Relation<Post, ScopesOf<typeof Post>>.build(attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly userId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly title: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>, init?: ((record: Post) => void) | undefined): Post
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
({ title?: string | undefinedtitle: "Hello" }); // points at the user, saved or not
await batch<readonly [RecordStatement<User>, RecordStatement<Post>]>(build: (b: Batch) => readonly [RecordStatement<User>, RecordStatement<Post>]): Promise<[User, Post]>
`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<User>(record: User, options?: SaveOptions): RecordStatement<User>
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 user: Useruser), b: Batchb.Batch.save<Post>(record: Post, options?: SaveOptions): RecordStatement<Post>
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 post: Postpost)]); // atomic: both written, or neither

batch writes a Model’s rows on the current database. db.batch uses an explicit one. See Bulk writes and batches.

Last updated on