---
title: Command line
description: "Generate your schema, write migrations and Models, and apply migrations from the command line."
seo:
  description: "The active-record command: initialize a project, generate the schema from your migrations, write migrations and Models, open a console, and apply migrations."
---

## Running the command

The `active-record` command comes with `@forestfuture/active-record`, and `ffar` is its short name. Run it from your project’s folder:

```sh
npx active-record --help
```

Every command reads your databases, and the adapter each one uses, from `active-record.jsonc`. `active-record init` writes it.

It needs Node.js 22.5 or later. On D1, it needs 22.13 or later, for Node’s built-in SQLite. [Generators](/generators) shows it step by step.

## `active-record init`

Write `active-record.jsonc` for your project:

```sh
npx active-record init
```

It reads your Wrangler config. Each database in its `d1_databases` gets a D1 entry. Each Hyperdrive binding gets a PostgreSQL entry, whose `url` is the binding’s `localConnectionString`.

Run it again after you add a database to your Wrangler config. It adds each database the file doesn’t name yet, and leaves the rest of the file as you wrote it, comments included:

```text
Added LOGS to active-record.jsonc (on d1)
```

It adds only databases on the adapters the file already uses. To add another adapter’s databases, name it with `--adapter`.

| Option             |                                                                                                                                           |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `--adapter <name>` | The adapter, `d1` or `postgresql`, when your Wrangler config has both, or neither. With the file there, it adds that adapter’s databases. |
| `--config <file>`  | Write this file, in place of `active-record.jsonc`.                                                                                       |

With `--adapter postgresql` and no Hyperdrive binding, it writes a `DATABASE_URL` entry, with a guess at your local database’s `url` for you to correct.

## Declaring your databases

`active-record.jsonc` sits beside your `package.json`. It names each of your databases by its binding, and the adapter it uses:

```jsonc
{
  "$schema": "./node_modules/@forestfuture/active-record/config-schema.json",
  "databases": {
    "DB": { "adapter": "d1" },
  },
}
```

Your generated schema names each database by its binding. The `$schema` line lets your editor complete and check the file. Each database names its own adapter, so one project can use D1 and Postgres together, as [Multiple databases](/several-databases#using-databases-on-different-adapters) shows.

On D1, the rest of a database’s settings stay in your Wrangler config’s `d1_databases`, which must have its binding. A D1 database there that the file doesn’t name is left out, and every command notes it.

By default, that’s the Wrangler config beside the file. If your Worker’s config is in another folder, name it with `wranglerConfig`. The path is relative to `active-record.jsonc`:

```jsonc
{
  "databases": {
    "DB": { "adapter": "d1", "wranglerConfig": "../worker/wrangler.jsonc" },
  },
}
```

The database’s migrations folder and its local data in `.wrangler/state` are then beside that config, where `wrangler dev` finds them. `migrate` and the console run the `wrangler` installed there, or else your project’s.

On Postgres, the file holds a database’s settings:

```jsonc
{
  "databases": {
    "HYPERDRIVE": {
      "adapter": "postgresql",
      "migrationsDir": "migrations",
      "url": "postgres://localhost/shop_development",
      "remoteUrl": "${PRODUCTION_DATABASE_URL}",
    },
  },
}
```

| Setting         |                                                                           |
| --------------- | ------------------------------------------------------------------------- |
| `adapter`       | `d1` or `postgresql`.                                                     |
| `migrationsDir` | Its migrations folder, relative to the file (`migrations` by default).    |
| `url`           | The local database: what `migrate` and the console use.                   |
| `remoteUrl`     | The real database, for `--remote`.                                        |
| `schemaUrl`     | A server the schema may be read on, for an extension PGlite doesn’t have. |

`${NAME}` reads a variable from the environment, so a password stays out of the file. The command never prints a connection string, only its database and host. `--config` names another file.

On Postgres, the command needs `pg` installed, and PGlite to read your schema. It says what to install when either is missing.

## `active-record schema`

Generate the schema file from your migrations:

```sh
npx active-record schema
```

It applies your migrations, in order, to an in-memory database, and writes each table’s columns to `src/db/schema.ts`. On D1 that’s SQLite. On Postgres it’s [PGlite](https://pglite.dev), so it needs no server.

| Option               |                                                                                    |
| -------------------- | ---------------------------------------------------------------------------------- |
| `--check`            | Write nothing: fail (exit 1) if the schema file is out of date. For CI.            |
| `--watch`            | Regenerate whenever a migration or a Model file changes.                           |
| `--out <file>`       | Write the schema here instead. With several databases, a folder for one file each. |
| `--migrations <dir>` | Read migrations from here instead of the config’s folder (one database only).      |
| `--models <dir>`     | Where your Models and `application-record.ts` are (`src/models/` by default).      |
| `--config <file>`    | Use this config file, in place of `active-record.jsonc`.                           |

**What it reads:** each database in `active-record.jsonc`. On Postgres, from its `migrationsDir`. On D1, from its entry in the Wrangler config’s `d1_databases`, with its `binding`, `migrations_dir` (default `migrations/`), `migrations_pattern` (for migrations in folders), and `migrations_table` (left out of the schema). Migrations apply in the order of the numbers their names start with (`9_…` before `10_…`), as Wrangler applies them. It also loads the Model files in `--models`, using your project’s own `@forestfuture/active-record`, to find each Model and its table, so code at a Model file’s top level runs.

**What it writes:**

- **The schema file:** each table’s attributes, as a document, with a header naming the migrations and a fingerprint. Then `schema`, with the binding, every table, and your Models, and type declarations adding each table’s attributes to its Model. `--check` compares fingerprints, so formatting the file doesn’t make it stale, but adding or renaming a Model does.
- **The base class**, `application-record.ts`, when it’s missing: `abstract class ApplicationRecord extends Model`, holding the schema. It’s never written over, so it’s yours to edit.
- **With several databases:** one schema file per binding (`src/db/DB.ts`, `src/db/LOGS.ts`), and one base class each, named after it (`DB` → `DbRecord`, `LOGS` → `LogsRecord`).

> **Compared with Rails**
>
> The schema file plays the part of Rails’ `schema.rb`, and each base class is named as Rails names a second database’s.

**What it refuses**, writing nothing:

- A file it didn’t write (one without its “Generated by” header), such as a Drizzle schema.
- A file beside a folder of the same name (`src/db/schema.ts` next to `src/db/schema/`), which would take over that folder’s imports.
- Two bindings whose names would give the same base class (`DB` and `db`).
- A migration the database rejects: the error names the file, and the last good schema is kept.
- A Model whose table the migrations don’t make, a Model file that fails to load, or a Model exported as `default`. The error names the file, and the last good schema is kept.

:::warning[Coming from Drizzle or Prisma?]
Their schemas often live at `src/db/schema.ts` or `src/db/schema/`. Write Active Record’s somewhere else, with `--out src/db/d1-record.ts`, and, if `application-record.ts` already exists, point its `import { schema }` at it (a new one is written importing the right file).
:::

## `active-record console`

Open your database with your Models in a console, or `active-record c` for short ([Console](/console) shows a session). It opens the local one unless you pass `--remote`:

```sh
npx active-record console
```

| Option              |                                                                                       |
| ------------------- | ------------------------------------------------------------------------------------- |
| `--database <name>` | The database to open, by its binding, when the config has several.                    |
| `--models <path>`   | Where the Models are: a folder (`src/models`) or one file (`src/models.ts`).          |
| `--config <file>`   | Use this config file, in place of `active-record.jsonc`.                              |
| `--no-history`      | Don’t keep what you type (in `.wrangler/` on D1, `node_modules/.cache/` on Postgres). |
| `--verbose`         | Print each statement a line runs. `.verbose` turns it on and off in the console.      |
| `-e, --eval <code>` | Run this code, print its result (alone, on stdout), and exit; a failure exits 1.      |
| `--remote`          | Open your remote database instead, after you type its name.                           |
| `--yes`             | With `--remote`, don’t ask first (also how to open it without a terminal).            |
| `--history`         | Keep what you type in a remote session, which isn’t kept unless you ask.              |

It reads TypeScript Models and uses your project’s own `@forestfuture/active-record` and its adapter. On D1, it opens the database through your project’s `wrangler`. On Postgres, it opens a connection to the database’s `url`, or with `--remote` its `remoteUrl`, and closes it when you leave. It refuses, printing why, when there’s no config, with several databases and no `--database`, with no Models, or with the library not installed. On D1, it also refuses without `wrangler` installed, or with `--remote` when the binding has no `database_id`. On Postgres, it refuses when the database has no `url` (or, with `--remote`, no `remoteUrl`), or names a variable that isn’t set. With `--remote`, it refuses when you don’t confirm it, or aren’t on a terminal and didn’t pass `--yes`. `--yes` only goes with `--remote`, `--history` can’t be combined with `--no-history`, and `-e` takes one piece of code, once.

## `active-record migrate`

Apply your pending migrations to the local database:

```sh
npx active-record migrate
```

| Option              |                                                                               |
| ------------------- | ----------------------------------------------------------------------------- |
| `--database <name>` | The database to migrate, when the config has several.                         |
| `--remote`          | Migrate your remote database instead, after you type its name.                |
| `--yes`             | With `--remote`, don’t ask first (also how to migrate it without a terminal). |
| `--config <file>`   | Use this config file.                                                         |

On D1, it runs your project’s `wrangler d1 migrations apply` for the database, `--local` or `--remote`, and prints what Wrangler prints. It exits with Wrangler’s code.

On Postgres, it applies them itself, to the database’s `url`, or with `--remote` its `remoteUrl`. It runs the migrations folder’s `.sql` files in the order of their versions and records each one’s version in `schema_migrations`. A version is the number a file’s name starts with:

```text
Local database HYPERDRIVE (shop_development on localhost)
Applied 20261108090503_create_products.sql
Applied 20261108090504_add_sku_to_products.sql
```

- **Each migration runs in a transaction** with its version, so one that fails is rolled back whole, and the ones after it don’t run. A statement Postgres can’t run in a transaction, such as `CREATE INDEX CONCURRENTLY`, fails.
- **A second run at the same time is refused**, through an advisory lock, so each migration runs once. Run it again once the first is done.
- **A file whose name doesn’t start with a number** is refused before any migration runs, as are two files with the same number.
- **A migration with its own `BEGIN`, `COMMIT` or `ROLLBACK`** is refused too, since it would end the transaction the migration runs in. A function’s `BEGIN … END` is fine.

:::note[Migrating the real database on Postgres]
On D1, `--remote` reaches your database through Cloudflare, signed in with Wrangler. On Postgres, it connects to the database itself, so the machine that runs it needs the `remoteUrl`’s variable, password included, and a network route to the server. That’s usually your CI, with the URL as a secret. If the database is only reachable through a Cloudflare Tunnel, open a local port to it with `cloudflared access tcp --hostname db.example.com --url localhost:5433`, and point `remoteUrl` at `localhost:5433`.
:::

## Mapping columns to attributes

On D1, each column becomes an attribute by the first of these that applies:

1. **An override in the Model:** `static override attributes = { available: "boolean" } as const`.
2. **The column’s declared type:**

   | Declared as                                         | Attribute                                        |
   | --------------------------------------------------- | ------------------------------------------------ |
   | `INTEGER`, `INT`, `BIGINT`, … (anything with `INT`) | `integer`                                        |
   | `TEXT`, `VARCHAR(…)`, `CHAR(…)`, `CLOB`             | `string`                                         |
   | `REAL`, `FLOAT`, `DOUBLE`                           | `real`                                           |
   | `NUMERIC`, `DECIMAL`                                | `decimal`, with a size’s `precision` and `scale` |
   | `BOOLEAN`                                           | `boolean`                                        |
   | `DATETIME`, `TIMESTAMP`                             | `datetime`                                       |
   | `DATE`                                              | `date`                                           |
   | `TIME`                                              | `time`                                           |
   | `TEXT` with `CHECK (json_valid(column))`            | `json`                                           |
   | `JSON`                                              | `json`                                           |
   | `BLOB`                                              | `binary`                                         |
   | anything else                                       | `string`                                         |

3. **The column’s name**, only for a column declared exactly `TEXT` or `INTEGER`: `…_at` `TEXT` is a `datetime`, and `is_…` or `has_…` `INTEGER` is a `boolean` (with a note, since it’s a guess).

Also:

- **Names:** `price_cents` becomes `priceCents`. A column whose name doesn’t come back the same from camelCase gets `column: "…"`.
- **`NOT NULL`** becomes `null: false`. A primary key is never null.
- **Primary keys:** the key column is the Model’s `primaryKey`. A `TEXT` key gets `generateId: true`, so the Model’s [`generateId`](/models#generating-ids) makes it; an `INTEGER PRIMARY KEY` is left to D1. A table with no key, or a key of several columns, is an error.
- **Defaults:** literal defaults (numbers, strings, `TRUE`/`FALSE`, JSON) are copied, so a new record shows them before it’s saved. A decimal’s, a date’s, or a time’s is copied in its type’s form (`1.50` as `"1.5"`). Expressions such as `CURRENT_TIMESTAMP` are left to D1.
- **Foreign keys** take the referenced column’s type. They don’t create associations, which are behavior you declare.
- **Enums:** a `TEXT` column with `CHECK (column IN ('open', 'done'))` gets `enum: ["open", "done"]`, with its methods off until the Model turns them on. See [Reading enums from the database](/enums#reading-enums-from-the-database).
- **Left out:** SQLite’s own tables, Cloudflare’s (`_cf_…`), the migrations table, and virtual tables.

**Notes it prints** when the schema is written:

- an `INTEGER` read as a `boolean` from its name;
- for migrations written by Drizzle or Prisma (recognized by their config files or the lines they write): a note naming the tool, then one for each column worth checking, such as an `INTEGER` named `…_at` that may hold a Unix timestamp (the note shows the [`storage` override](/adopt-a-database#reading-unix-timestamps) for it), or a `TEXT` named like JSON without a `json_valid` check;
- a `DATETIME` column whose default is a number or `unixepoch()`, with the [`storage` override](/adopt-a-database#reading-unix-timestamps);
- for migrations written by Drizzle or Prisma, a `DATETIME` column whose default is `CURRENT_TIMESTAMP` or `datetime('now')`, since it writes a different date text from Active Record’s and the two [compare as text](/adopt-a-database#comparing-dates-in-two-forms);
- migrations in folders with no `migrations_pattern` to find them.

### Mapping Postgres’s columns

On Postgres, an override in the Model still comes first. Otherwise each column’s type decides, since Postgres’s types are real:

| Type                                         | Attribute                                      |
| -------------------------------------------- | ---------------------------------------------- |
| `smallint`, `integer`, `bigint`              | `integer`                                      |
| `real`, `double precision`                   | `real`                                         |
| `numeric`                                    | `decimal`, with its `precision` and `scale`    |
| `boolean`                                    | `boolean`                                      |
| `timestamptz`, `timestamp`                   | `datetime`                                     |
| `date`                                       | `date`                                         |
| `time`                                       | `time`                                         |
| `json`, `jsonb`                              | `json`                                         |
| `bytea`                                      | `binary`                                       |
| `text`, `varchar`, `char`, `citext`, `uuid`  | `string`                                       |
| an enum type                                 | `string`, with the enum’s labels as its `enum` |
| an array                                     | An error: not supported                        |
| anything else (`inet`, `interval`, `timetz`) | `string`, with a note                          |

A domain maps as the type it’s built on. Names, `NOT NULL`, keys, and `CHECK (column IN (…))` work as on D1, and an enum type’s labels keep their order. A string key gets `generateId: true` unless it has a literal default, even when Postgres has a default such as `gen_random_uuid()`. Literal defaults (`'draft'`, `0`, `true`, `'{}'::jsonb`) are copied, and functions such as `now()` are left to Postgres. Views, other schemas, and `schema_migrations` are left out.

**Extensions:** a migration can `CREATE EXTENSION` any of the extensions PGlite has its own build of, such as `citext`, `uuid-ossp`, `pg_trgm`, `pgcrypto`, `hstore`, and `ltree`. For any other, such as PostGIS, set `schemaUrl` to a Postgres server that has it, such as a local one. The schema is then read there, in a database of its own:

```jsonc
{ "databases": { "HYPERDRIVE": { "schemaUrl": "postgres://localhost/postgres" } } }
```

The migrations run in one transaction that’s rolled back, and the database is dropped afterwards, so a `CREATE ROLE` leaves nothing behind. It needs permission to create databases. A note says which server was read. Without `schemaUrl`, the command says to set one, and never uses `url` for it.

Stopping the command with Ctrl-C drops the database too. A command killed outright can leave one behind, named `active_record_schema_…`, which you can drop yourself.

## `active-record g model` and `g migration`

```sh
npx active-record g model <Name> [columns] [options]
npx active-record g migration <Name> [columns] [options]
```

`generate` is the same as `g`.

| Option                 |                                                                                                                        |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `--id integer\|text`   | `integer`: a key the database generates. `text` (the default): a key generated in code.                                |
| `--no-timestamps`      | Leave out `created_at` and `updated_at`.                                                                               |
| `--models <path>`      | Write Models in this folder (importing `application-record.ts` from it), or append them to one file (`src/models.ts`). |
| `--database <binding>` | The database to use, when the config has several.                                                                      |
| `--out <file>`         | The schema file to regenerate, as for `active-record schema` (for a Drizzle project’s `src/db/d1-record.ts`, say).     |
| `--config <file>`      | Use this config file.                                                                                                  |

### Column syntax

`name[:type][!][=value][:unique|:index]`

| Type                   | D1                                | Postgres           |
| ---------------------- | --------------------------------- | ------------------ |
| `string` (the default) | `TEXT`                            | `TEXT`             |
| `integer`              | `INTEGER`                         | `BIGINT`           |
| `real`                 | `REAL`                            | `DOUBLE PRECISION` |
| `decimal`              | `DECIMAL`                         | `NUMERIC`          |
| `boolean`              | `BOOLEAN`                         | `BOOLEAN`          |
| `datetime`             | `DATETIME`                        | `TIMESTAMPTZ`      |
| `date`                 | `DATE`                            | `DATE`             |
| `time`                 | `TIME`                            | `TIME`             |
| `json`                 | `TEXT CHECK (json_valid(column))` | `JSONB`            |
| `binary`               | `BLOB`                            | `BYTEA`            |

A `references` column is `<name>_id`, typed like the referenced table’s key, with `REFERENCES <plural> (id)` and an index.

The key `g model` writes:

| Key                 | D1                             | Postgres                                                 |
| ------------------- | ------------------------------ | -------------------------------------------------------- |
| generated in code   | `id TEXT PRIMARY KEY NOT NULL` | `id UUID PRIMARY KEY`                                    |
| with `--id integer` | `id INTEGER PRIMARY KEY`       | `id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY` |

Timestamps are `created_at` and `updated_at`, `NOT NULL`, as `DATETIME` on D1 and `TIMESTAMPTZ` on Postgres.

- **`!`** makes the column `NOT NULL`. A `references` column is `NOT NULL` in a new table, and can be `NULL` when added to an existing one.
- **`=value`** is a literal default, for `string`, `integer`, `real`, `decimal`, `boolean`, `date`, and `time` columns (`=draft`, `=0`, `=1.5`, `=true`, `=2026-01-02`, `=09:00`).
- **`{precision,scale}`** after `decimal` gives a decimal’s size: `'price:decimal{10,2}'` writes `DECIMAL(10, 2)` on D1 and `NUMERIC(10, 2)` on Postgres, and `decimal{6}` a precision alone. Quote it, so the shell doesn’t expand the braces.
- **`:unique`** adds a unique index, and **`:index`** an index, named like `index_products_on_sku`.
- **Names** can be written `priceCents` or `price_cents`; columns are always snake_case. Names the database reserves (`order`, `group`, and on Postgres `user`) are quoted.

> **Beyond Rails**
>
> `=value` is Active Record’s own addition: Rails’ generators can’t give a column a default.

### Migration names

| Name                          | Writes                                                                    |
| ----------------------------- | ------------------------------------------------------------------------- |
| `Create<Table>`               | `CREATE TABLE`, as `g model` does                                         |
| `Add<Anything>To<Table>`      | `ADD COLUMN` for each column, then their indexes                          |
| `Remove<Anything>From<Table>` | `DROP COLUMN`, after `DROP INDEX IF EXISTS` for its generated index on D1 |
| anything else                 | An empty migration, to write yourself                                     |

A name can be written `AddSkuToProducts` or `add_sku_to_products`, and the table in it is made plural (`CreateWidget` creates `widgets`). A Model’s name is made singular, with a note (`g model line_items` writes `LineItem`). Names are letters, digits, and `_`, starting with a letter.

**File names** start with the UTC time they’re written, to the second (`20261108090503_add_sku_to_products.sql`), so migrations written on two branches don’t clash. Files numbered `0001_…` still run first.

### What’s checked first

Nothing is written unless all of these hold:

- the new migration applies after the existing ones (in memory, as `active-record schema` applies them);
- the Model’s file doesn’t exist yet (or, with one models file, doesn’t have the class yet);
- the config’s `migrations_pattern`, if it has one, would match the new file, so Wrangler would apply it;
- the schema file can be written (see [What it refuses](#active-record-schema));
- on D1, it isn’t a required column added without a default, which SQLite can’t add.

Then the generator writes the files, regenerates the schema, and prints the next step: `npx active-record migrate`.

## Exit codes

Every command exits with `0` on success, and `1` when anything was refused or failed, or, with `--check`, when the schema is out of date. Messages go to standard output, and say what to do next.
