---
title: Connections
description: "Give a query its database: the Model’s binding, the request’s database, or one you pass."
seo:
  description: "How Active Record queries find their database: the Model’s binding, withDatabase for one request, connect(env.DB), and why new User() throws NoDatabase."
---

## At a glance

Most apps only use the binding.

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

[Database resolution](/query-databases) explains why there are three, and [which one you need](/query-databases#which-do-i-need).

## The Models

The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates:

```ts user.ts
import { hasMany } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Post } from "./post";

export class User extends ApplicationRecord {
  posts = hasMany(Post);
}
```

```ts post.ts
import { belongsTo } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { User } from "./user";

export class Post extends ApplicationRecord {
  user = belongsTo(User);
}
```

```ts schema.ts
// Generated by `active-record schema` from migrations/ — don't edit.
// schema: f287cc463ec1

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

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

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

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

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

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

```sql D1
CREATE TABLE users (
  id TEXT PRIMARY KEY NOT NULL,
  email TEXT NOT NULL
);
CREATE UNIQUE INDEX index_users_on_email ON users (email);
CREATE TABLE posts (
  id TEXT PRIMARY KEY NOT NULL,
  user_id TEXT NOT NULL REFERENCES users (id),
  title TEXT NOT NULL
);
```

```sql Postgres
CREATE TABLE users (
  id UUID PRIMARY KEY,
  email TEXT NOT NULL
);
CREATE UNIQUE INDEX index_users_on_email ON users (email);
CREATE TABLE posts (
  id UUID PRIMARY KEY,
  user_id UUID NOT NULL REFERENCES users (id),
  title TEXT NOT NULL
);
```

:::note
The examples use D1’s `connect`, from `@forestfuture/active-record/d1`. On Postgres, `connect` comes from `@forestfuture/active-record/postgresql` and takes your Hyperdrive binding. See [PostgreSQL](/postgresql#connecting).
:::

## Using the binding

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

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

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

:::warning[Build records, never `new`]
Build records with `User.build(…)`. A record made with `new User()` has no database, so saving it throws `NoDatabase`.
:::

:::note
The binding is only there during a request, inside a Worker. Tests and scripts that run in Node get their database from `withDatabase`. See [Testing](/testing).
:::

## Using the request’s database

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

```ts
import { withDatabase } from "@forestfuture/active-record";
import { connect } from "@forestfuture/active-record/d1";
import { app } from "./app";

// src/worker.ts: the app's Worker, with a database for each request.
export const worker = {
  fetch(request, env) {
    const db = connect(env.DB, { onQuery: ({ sql }) => console.log(sql) });
    return withDatabase(db, () => app.fetch(request)); // every query inside uses db
  },
} satisfies ExportedHandler<Env>;
```

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

:::warning[Node.js compatibility]
`withDatabase` uses Workers’ `AsyncLocalStorage`. It’s on by default for compatibility dates from 2026-08-04. For an earlier date, add `"compatibility_flags": ["nodejs_compat"]` to your Wrangler config, or `withDatabase` throws `NoDatabase`. On D1, only `withDatabase` and [`noTouching`](/touching#turning-touches-off) need it. On Postgres, `pg` needs it too.
:::

These pages use a request’s database:

- **[Read replicas](/read-your-own-writes):** a D1 Session per request.
- **[Logging](/logging):** one request’s queries, tagged with its ID.
- **[Testing](/testing):** a database for Models outside a Worker.
- **[Multiple databases](/several-databases):** `withDatabase([...])`, matched to each Model’s binding.

## Using an explicit database

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

```ts
import { connect } from "@forestfuture/active-record/d1";
import { User } from "./models/user";

export async function findJane(env: Env) {
  const db = connect(env.DB);
  return db.model(User).findByOrThrow({ email: "jane@example.com" }); // ignores withDatabase
}
```

To name your Models once, use `db.models`:

```ts
import { connect } from "@forestfuture/active-record/d1";
import { Post } from "./models/post";
import { User } from "./models/user";

export async function listPosts(env: Env) {
  const models = connect(env.DB).models({ User, Post });
  return models.Post.order({ title: "asc" }).pluck("title");
}
```

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

## Batching writes

`batch` saves and destroys records and runs bulk writes atomically:

```ts
import { batch } from "@forestfuture/active-record";
import { User } from "./models/user";

const user = User.build({ email: "sam@example.com" });
const post = user.posts().build({ title: "Hello" }); // points at the user, saved or not
await batch((b) => [b.save(user), b.save(post)]); // atomic: both written, or neither
```

`batch` writes a Model’s rows on the current database. `db.batch` uses an explicit one. See [Bulk writes and batches](/batches).
