---
title: Existing databases
description: "Use Active Record with a D1 database whose tables you already have."
seo:
  description: "Use Active Record with an existing D1 database managed by Drizzle or Prisma, or with no migrations at all, and fix columns of the wrong type with overrides."
---

## Using Drizzle’s migrations

Drizzle writes its migrations to `drizzle/`, its `out` setting. Tell Wrangler where they are:

```jsonc wrangler.jsonc
{
  "d1_databases": [
    // Migrations as drizzle/0000_name.sql:
    { "binding": "DB", "database_name": "my-app-db", "migrations_dir": "drizzle" },
    // Or, as drizzle/<timestamp>_name/migration.sql:
    // { …, "migrations_pattern": "drizzle/*/migration.sql" },
  ],
}
```

Drizzle’s own schema often lives at `src/db/schema.ts` or in `src/db/schema/`, where Active Record writes its schema by default. Generate Active Record’s elsewhere:

```sh
npx active-record schema --out src/db/d1-record.ts
```

If `src/models/application-record.ts` already exists, point it at the new file with `import { tables } from "../db/d1-record";`. A new one imports it already.

Pass `--out` to every later `schema` and `g` command, or keep it in a `package.json` script.

:::note
Without `--out`, Active Record refuses to write over a file it didn’t write, or beside a folder of the same name, so Drizzle’s schema is safe.
:::

## Using Prisma’s migrations

With D1, Prisma’s migrations are usually Wrangler’s own: files in `migrations/`, written by `prisma migrate diff`. `npx active-record schema` reads them as they are.

Prisma names tables after its models, such as `User`, and columns in camelCase, such as `createdAt`. Active Record keeps both names, so the Model sets its table, `static override table = "User"`, and has attributes such as `createdAt`.

:::warning[Two date formats in one column]
Prisma writes a `DateTime` as `2026-10-12T06:38:30.325+00:00`, and a `DEFAULT CURRENT_TIMESTAMP` fills `2026-10-12 06:38:30`. Active Record reads both as UTC, but SQLite compares dates as text, so a column with both needs the steps in [Comparing dates in two forms](#comparing-dates-in-two-forms).
:::

## Comparing dates in two forms

A column can hold SQLite’s own date text (`2026-10-12 06:38:30`, from a `DEFAULT CURRENT_TIMESTAMP`) beside ISO text (`2026-10-12T06:38:30.000Z`). Active Record reads both as UTC, but SQLite compares them as text. On a column with both, `order` and `between` can misplace values within a day, and a condition on one instant misses the row written in the other form.

To make the rows match, rewrite them once in a migration, with your own table and column:

```sql
UPDATE reminders
SET created_at = strftime('%Y-%m-%dT%H:%M:%fZ', created_at)
WHERE strftime('%Y-%m-%dT%H:%M:%fZ', created_at) <> created_at;
```

It writes Active Record’s form for every row SQLite can read as a date, and leaves NULLs and anything else as they were. Running it again changes nothing. The rewrite is permanent, so export the table first. Conditions on the column then use its index.

If another tool still writes the other form, compare through `strftime` in a fragment instead:

```ts
import { column, sql } from "@forestfuture/active-record";

export function createdSince(since: Date) {
  const createdAt = column("createdAt");
  return Reminder.where(
    sql`strftime('%Y-%m-%dT%H:%M:%fZ', ${createdAt}) >= ${createdAt.value(since)}`,
  );
}

export function oldestFirst() {
  const createdAt = column("createdAt");
  return Reminder.order(sql`strftime('%Y-%m-%dT%H:%M:%fZ', ${createdAt})`);
}
```

`strftime` reads every form SQLite knows and writes Active Record’s ISO text, so rows in either form compare and sort as the times they are.

:::note
A wrapped column can’t use its index for that condition, so SQLite reads the whole table.
:::

## Starting with no migrations

For a database built by hand, or by `drizzle-kit push`, export a snapshot of its schema as the first migration, and mark it as applied:

```sh
# The tables, without their data, as a first migration:
npx wrangler d1 export my-app-db --remote --no-data --output migrations/0001_baseline.sql

# Create Wrangler's record of applied migrations, and mark the snapshot as applied,
# so Wrangler never runs it against the database it came from:
npx wrangler d1 migrations list my-app-db --remote
npx wrangler d1 execute my-app-db --remote --command "INSERT INTO d1_migrations (name) VALUES ('0001_baseline.sql')"
```

From then on, change tables with new migrations. See [Schema changes](/change-a-table).

## Checking the generated attributes

Other tools can store values differently, so a column can become the wrong attribute type, and fail when it’s read. When `active-record schema` recognizes Drizzle’s or Prisma’s migrations, it prints a note for each column worth checking:

```
Note: these migrations look like Drizzle's. Some columns may convert to the wrong type and fail when read, especially numeric timestamps: check the generated types (…)
Note: posts.metadata: read as a string; if it holds JSON, override it as "json" in its Model
```

Fix a column’s type with an override in its Model. It changes how the column is read and written, never the table:

```ts
export class Post extends ApplicationRecord {
  static override attributes = {
    metadata: "json", // text({ mode: "json" }): JSON in a plain TEXT column
    archived: "boolean", // integer({ mode: "boolean" }): 0 or 1
    legacyNotes: false, // a column this app no longer uses: never read or written
  } as const;
}
```

A Postgres enum type or a `CHECK (column IN (…))` makes its column an enum of the names it lists. Its type and its checks come from the database. Its methods stay off until you turn them on with `enum: true`. See [Reading enums from the database](/enums#reading-enums-from-the-database).

## Reading Unix timestamps

Read a Unix timestamp column as a `Date` by overriding it as a `datetime` with the matching `storage`. Drizzle’s `integer({ mode: "timestamp" })` stores seconds, and `"timestamp_ms"` stores milliseconds:

```ts
import { gte } from "@forestfuture/active-record";

export class Article extends ApplicationRecord {
  static override attributes = {
    publishedAt: { type: "datetime", storage: "unixSeconds" }, // timestamp: seconds
    updatedAt: { type: "datetime", storage: "unixMilliseconds" }, // timestamp_ms: milliseconds
  } as const;
}

export function publishedSince(since: Date) {
  return Article.where({ publishedAt: gte(since) });
}
```

| Drizzle mode     | `storage`            |
| ---------------- | -------------------- |
| `"timestamp"`    | `"unixSeconds"`      |
| `"timestamp_ms"` | `"unixMilliseconds"` |

The column stays an `INTEGER`. `createdAt` and `updatedAt` declared this way are written as integers too, and `where` and `between` take `Date`s.

Under `unixSeconds`, a `Date` is stored to the second, so a condition such as `lt(date)` compares to the second too.

:::warning[A Date in an sql fragment]
A `Date` beside that column in a `sql` fragment throws `TypeError`: a fragment has no attribute, so it would bind as ISO text. Use `column("publishedAt").value(date)`, which writes it as the attribute stores it. See [Writing SQL fragments](/conditions#writing-sql-fragments).
:::

:::note
In a raw `env.DB.prepare(...)` statement, bind `Article.typeForAttribute("publishedAt").serialize(date)`, and read a cell with `deserialize`. See [Raw statements](/raw-statements).
:::

:::note
Prisma’s dates need no override. On D1, Prisma writes a `DateTime` as ISO text, which Active Record reads as it is.
:::

> **Beyond Rails**
>
> Rails has no option for a date kept as an integer; there it takes a custom attribute type. Here it’s a `storage` on the `datetime`.

## Fixing cells of the wrong type

A cell that isn’t the attribute’s type fails when the record loads or `pluck` reads it, naming the Model and attribute:

```text
TypeError: Article: 1767323045 isn't a datetime for "publishedAt"
```

Find the cells by their SQLite type:

```sql
SELECT typeof(published_at), count(*) FROM articles GROUP BY 1;
```

Then fix the cause:

- If the column holds Unix times, declare the [`storage`](#reading-unix-timestamps) so they’re read as one.
- If the attribute’s type is wrong, override it with the type the column holds.
- If a few rows hold the wrong thing, `UPDATE` them.
- If the column isn’t used, ignore it with `false` in the override.

:::note
SQLite converts a value to the column’s declared type only when it can: `'42'` in an `INTEGER` column is stored as 42, and `'abc'` stays text.
:::
