---
title: Connections
description: "Give a query its database: the Model’s binding, the request’s database, or one you pass."
seo:
  description: "How Arbor queries find their database: the Model’s binding, withDatabase for one request, its cache of identical reads, connect(env.DB), and 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 | Caching identical reads, 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 `arbor schema` generates:

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

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

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

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

```ts schema.ts
// Generated by `arbor schema` from migrations/ — don't edit.
// schema: 1f26c9d5602a

import { defineSchema, type TableAttributes } from "@forestfuture/arbor";
import { d1 } from "@forestfuture/arbor/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/arbor/d1`. On Postgres, `connect` comes from `@forestfuture/arbor/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>;
```

`arbor 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 `arbor.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/arbor";
import { connect } from "@forestfuture/arbor/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.

## Caching identical reads

Inside `withDatabase`, a read you’ve already sent is answered from memory, with no round trip:

```ts
import { withDatabase } from "@forestfuture/arbor";
import { connect } from "@forestfuture/arbor/d1";
import { User } from "./models/user";

export async function findTwice(env: Env) {
  return withDatabase(connect(env.DB), async () => {
    const user = await User.findByOrThrow({ email: "jane@example.com" }); // sent
    const again = await User.findByOrThrow({ email: "jane@example.com" }); // answered from memory
    return [user, again] as const;
  });
}
```

- Each answer is new records, so changing one changes no other.
- Any write Arbor sends inside the call clears the cache: a save, a destroy, a bulk write, or a batch, through any database handle. So a request always reads its own writes.
- `reload()` always reads the database, and clears the cache too.
- The cache ends with the `withDatabase` call. Requests never share it.
- It keeps the 100 answers used last. [Batch iteration](/batch-iteration) doesn’t keep its batches, so walking a big table doesn’t fill it.
- [`onQuery`](/logging#seeing-a-cached-answer) hears each cached answer, with `cached: true`.

:::note[Caching needs `withDatabase`]
A Model’s queries outside `withDatabase` use the binding, which every request running at once shares, so they’re never cached. To cache a request’s reads, run it inside `withDatabase`, as the example does.
:::

To send every read, turn the cache off:

```ts
import { connect } from "@forestfuture/arbor/d1";

export function uncachedDatabase(env: Env) {
  return connect(env.DB, { cache: { request: false } }); // every read is sent
}
```

### Clearing the cache

Arbor only sees the writes it sends. After SQL you send on the binding yourself, clear the cache with `clearRequestCache()`:

```ts
import { withDatabase } from "@forestfuture/arbor";
import { connect } from "@forestfuture/arbor/d1";
import { Post } from "./models/post";

export async function renamePost(env: Env, id: string) {
  const db = connect(env.DB);
  return withDatabase(db, async () => {
    const post = await Post.find(id);
    await env.DB.prepare("UPDATE posts SET title = ? WHERE id = ?").bind("Hello again", id).run();
    db.clearRequestCache(); // the UPDATE didn't go through Arbor
    return Post.find(post.id); // sent, so it reads "Hello again"
  });
}
```

> **Compared with Rails**
>
> This is Rails’ query cache. Rails turns it on for each request with its executor; here `withDatabase` does. `clearRequestCache()` is `clear_query_cache`, and `cache: { request: false }` stands in for `uncached`. Like Rails, it keeps 100 answers, dropping the least recently used.

## Using an explicit database

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

```ts
import { connect } from "@forestfuture/arbor/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/arbor/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, cache })` 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/arbor";
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).
