Skip to main content

Adopting a database

ant doesn't generate structs from a database, because the mapping is ambiguous: a text column could be a string, a pointer, a named type or an enum, and foreign keys don't say which relations you want. You or an AI assistant write the models from a dump, and drift checks them. The database and whatever runs it today stay untouched until the last step.

Dump the schema​

pg_dump --schema-only --no-owner --no-privileges "$DATABASE_URL" > schema.sql

--no-owner and --no-privileges leave out the roles of the server you dumped, which another database, such as CI's or a teammate's, may not have.

Write the models​

Write them by hand or with the prompt below, and add a cmd/migrate/main.go.

Compare until nothing is left​

With no snapshot yet, drift compares the live database with your models. Here the database has an accounts table whose name is varchar(50), and a legacy_log table the models don't mention:

go run ./cmd/migrate drift
The database differs from the models. To match, it would need to:
drop table legacy_log
change column accounts.name: type character varying(50) to text
add unique accounts_email_key on accounts
Error: ant: database differs from the migrations: 3 differences

Each line is something the models get wrong. accounts.name is varchar(50), so the model gets Length(50). The database has no unique constraint on email, so the tag comes off. A column that draws from a sequence is compared by the sequence it names, so a serial column the models give another sequence is a difference: change column invoices.number: default nextval('legacy_numbers'::regclass) to nextval('invoice_numbers'::regclass).

type Account struct {
ID int64
Name string
Email string
}

var Accounts = ant.Fields[Account]()

func (Account) Configure(b *ant.ModelBuilder[Account]) {
b.Column(&Accounts.Name).Length(50)
}

Leave tables out​

List a table you don't model in Config.Ignore, which takes names and patterns such as legacy_* or users.handmade_idx, or give its model b.ExcludeFromMigrations().

cmd/migrate/main.go
package main

import (
_ "github.com/jackc/pgx/v5/stdlib"

"github.com/skudra-go/ant/dialect/postgres"
"github.com/skudra-go/ant/migrate"

"example.com/app/models"
)

func main() {
migrate.Main[models.AppDB](postgres.Dialect, migrate.Config{Ignore: []string{"legacy_*"}})
}

Repeat until drift prints:

No drift: the database matches the models.

Start the history​

From the dump​

This is usually the right choice: a new database gets everything, including what your models don't describe. adopt strips the psql commands recent pg_dump versions write, such as \restrict, and the lines that give tables to roles or grant to them (OWNER TO, GRANT, REVOKE), which a database owned by another role could not run. It says how many it left out, and records a snapshot from your models. Put the grants an application needs in a migration of their own.

go run ./cmd/migrate adopt schema.sql
Wrote migrations/versions/0001_baseline.up.sql, and the snapshot from your models.
New databases run that file. On each database that already has this schema, run: baseline 0001

From the models​

If the models cover everything:

go run ./cmd/migrate diff baseline

The baseline holds only what the models describe: tables, keys, indexes, enums and sequences. It has no triggers, functions or views, and no domain or other type that a column names but the models don't create. A column typed .Type("year") after a domain matches the old database, so drift passes, and the baseline then fails on a new database with type "year" does not exist. drift lists such types after its verdict, without failing:

The models name types they do not create, which an empty database lacks:
year, a domain: items.year
A migration made from the models alone fails without them: create them in one of your own (diff --empty) before the tables that use them, or adopt the database's dump.

If the database has any of these, start from the dump, or create them in a migration of your own before the baseline's tables.

From your existing files​

To keep the history, copy the files into migrations/versions, then run snapshot. 0001_x.up.sql, 0001_x.sql and V1__x.sql work as they are, and .down.sql files are ignored. Goose and dbmate keep up and down in one file: split those first, or a new database runs the down part.

Mark each existing database as done​

baseline records the migrations as applied without running them, through the version you give. It adds the ant_migrations table and touches nothing else. Run it once on every database that already has the schema, with the version of the baseline, so a database adopted after more migrations were written runs those with up.

go run ./cmd/migrate baseline 0001
Recorded 0001_baseline as applied, without running it.

A new database skips this step and runs up. From here on, diff and up work as in any project. With no version, baseline records only when one migration is left to record, and otherwise refuses and names the version to give.

go run ./cmd/migrate status
MIGRATION STATE APPLIED
0001_baseline applied 2026-11-08 15:15:18 UTC

Keep your current runner​

If another tool applies the migrations, run snapshot instead of the last two steps and use only diff and check. Config.Name and Config.Parse can name the files the way your tool expects.

A prompt for your assistant​

Paste this with schema.sql, and adjust it to your project.

This is the schema of an existing PostgreSQL database, from pg_dump. Write Go
models for it using the ant ORM, in one file per table, in package models. Do not
change the database: the models must describe it exactly as it is.

Rules:

- Models are plain structs. Embed nothing unless every table really has id,
created_at, and updated_at as bigint and timestamptz.
- Field names convert to snake_case column names, and type names to plural
snake_case table names. If that gives the wrong name, use ant:"column=name" or
b.Table("name") in Configure.
- A column that allows NULL must be a pointer or sql.Null[T]. A NOT NULL column
must not be.
- bigint is int64, integer is int32, smallint is int16, boolean is bool, text is
string, timestamptz is time.Time, jsonb is ant.JSON[T], bytea is []byte,
interval is time.Duration, inet is netip.Addr, cidr is netip.Prefix, and an
array such as text[] or bigint[] is a slice such as []string or []int64. A
netip.Addr or netip.Prefix column allows NULL, so add
b.Column(&X.Field).NotNull() in Configure for a NOT NULL one. For any other
type, including varchar(n), numeric(p,s), date, enums, and domains, use
b.Column(&X.Field).Type("the type as written") in Configure.
- Declare each model's probe, named after the model in the plural: var Users = ant.Fields[User]().
- A primary key named id is found by convention. For anything else use b.Key or
b.CompositeKey. A key that is not an identity or serial column needs
.NotGenerated(). An identity or serial key needs no Default. If the constraint
is not named table_pkey, add b.KeyName("name").
- For each foreign key, add a relation with b.BelongsTo, and the other side with
b.HasMany where it is useful. Set .OnDelete and .OnUpdate to match. If the
constraint is not named table_column_fkey, add .ConstraintName("name"). If the
column has no index, add .NoIndex().
- A join table with only two foreign keys is b.ManyToMany(...).Through("table").
With other columns, model it as a table.
- A unique constraint is ant:"unique", or b.Column(&X.F).Unique("name") if it is
not named table_column_key. A unique index that is not a constraint is
b.Index(&X.F).Unique().Name("name").
- Add b.Index for each index, with .Name, .Desc, .Where, .Using, and .Include as
needed. Use b.IndexExpr for an expression.
- Add b.Check for each check constraint, using its name.
- Add b.Column(&X.F).Default("expr") for each default, and .Generated("expr") for
each generated column. A default also leaves a zero value to the database on
insert, so a bool or number field with one never inserts false or 0: where the
zero must be stored, make the field a pointer with .NotNull() and
.Default("expr"), and nil takes the default.
- Views are b.View("name"). Leave triggers, functions, and types out of the models.
- A context struct embeds ant.Context, and has an ant.Table[T] field for each model.

Then I will run `go run ./cmd/migrate drift`, which lists every remaining difference
between the models and the database. When I paste its output, fix the models. Each
line says what the database would need to do to match, so the models are what is
wrong. Never suggest changing the database. We are done when it prints "No drift".