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

Existing databases

Use Active Record with a D1 database whose tables you already have.

Using Drizzle’s migrations

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

{
  "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:

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.

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.

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:

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:

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.

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:

# 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.

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:

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.

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:

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 Dates.

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

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:

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

Find the cells by their SQLite type:

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

Then fix the cause:

  • If the column holds Unix times, declare the storage 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.

Last updated on