Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions docs/decisions/177-the-migrate-commands-name-their-database.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
id: 177
title: "The migrate commands name their database"
area: migrations
status: active
tags: [migrate, dsn, DATABASE_URL, output]
issues: [342]
related: [11, 60]
changed_by: []
code: [migrate/cli.go, migrate/config.go]
tests: [tests/features/migrations/target_test.go]
---

# 177. The migrate commands name their database

**In short:** The commands that apply, record, repair, list or seed migrations show the connected server address and database name, along with the DSN source.

## Decision

An application may build its connection from its own configuration while a migrate command silently uses a different `DATABASE_URL` (#342). `up`, `status`, `baseline`, `repair` and `seed` now print the database name, the address of the server the driver reached, and which DSN source supplied the connection. The address comes from the connected socket, so it works for both URL and keyword connection strings and reflects the endpoint actually reached when the driver falls back to another server. The notice includes only the quoted database name, the quoted address when available, and a fixed source label. If the name cannot be read, the command reports it as unknown and continues. `up --dry-run` keeps its existing output.

The order remains `--dsn`, `DATABASE_URL`, then `Config.DSN`, and the program still does not load `.env`: either change would alter existing programs. A program can load its own configuration and pass its DSN, or call `migrate.Up` on the connection it already opened.
10 changes: 6 additions & 4 deletions docs/decisions/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ On 2026-11-20 the decisions moved from one file, `docs/DECISIONS.md`, to a file
| [172](172-an-enum-value-renames-in-place.md) | An enum value renames in place | active | `enum` `rename` `RENAME VALUE` `Hint` `diff` `schema-diff` `migrations` |
| [173](173-drift-names-the-types-the-models-use-and-do-not-create.md) | drift names the types the models use and do not create | active | `drift` `adopt` `domain` `extension` `types` `migrations` |
| [174](174-drift-checks-the-views-that-view-models-read.md) | drift checks the views that view models read | active | `drift` `view` `materialized-view` `db-show` `migrations` |
| [177](177-the-migrate-commands-name-their-database.md) | The migrate commands name their database | active | `migrate` `dsn` `DATABASE_URL` `output` |

#### Performance

Expand Down Expand Up @@ -419,8 +420,8 @@ Before changing a file, read the decisions about it.
| `json_test.go` | [42](042-converters-are-scanner-and-valuer.md) [95](095-in-means-eq-and-other-value-rules.md) [109](109-numbers-inside-an-interface-read-as-json-number.md) [151](151-deletedat-is-a-time-or-null-in-json.md) |
| `merge.go` | [80](080-every-write-moves-the-version-on.md) [89](089-one-column-one-value.md) [90](090-merge-keeps-what-other-writes-keep.md) [150](150-a-zero-key-nothing-fills-is-refused.md) [166](166-find-reads-the-row-after-a-bulk-delete.md) |
| `metrics/metrics.go` | [176](176-ants-structs-have-camelcase-json-keys.md) |
| `migrate/cli.go` | [11](011-migration-model.md) [55](055-renames.md) [58](058-squashing-needs-no-coordination.md) [59](059-adopting-an-existing-database.md) [116](116-code-files-rerun-after-versioned-migrations.md) [117](117-the-migrate-program-takes-the-applications-options.md) [127](127-commands-refuse-to-guess-which-migration-is-meant.md) [129](129-status-check-fails-a-deploy-gate.md) [144](144-script-stops-before-a-go-migration.md) [172](172-an-enum-value-renames-in-place.md) [174](174-drift-checks-the-views-that-view-models-read.md) |
| `migrate/config.go` | [11](011-migration-model.md) [60](060-one-program-two-jobs.md) [117](117-the-migrate-program-takes-the-applications-options.md) |
| `migrate/cli.go` | [11](011-migration-model.md) [55](055-renames.md) [58](058-squashing-needs-no-coordination.md) [59](059-adopting-an-existing-database.md) [116](116-code-files-rerun-after-versioned-migrations.md) [117](117-the-migrate-program-takes-the-applications-options.md) [127](127-commands-refuse-to-guess-which-migration-is-meant.md) [129](129-status-check-fails-a-deploy-gate.md) [144](144-script-stops-before-a-go-migration.md) [172](172-an-enum-value-renames-in-place.md) [174](174-drift-checks-the-views-that-view-models-read.md) [177](177-the-migrate-commands-name-their-database.md) |
| `migrate/config.go` | [11](011-migration-model.md) [60](060-one-program-two-jobs.md) [117](117-the-migrate-program-takes-the-applications-options.md) [177](177-the-migrate-commands-name-their-database.md) |
| `migrate/engine.go` | [50](050-three-layers-for-migrations.md) [56](056-failure.md) [58](058-squashing-needs-no-coordination.md) [115](115-a-file-outside-a-transaction-is-recorded-before-it-runs.md) [116](116-code-files-rerun-after-versioned-migrations.md) [126](126-a-migration-runs-as-it-says-or-not-at-all.md) [127](127-commands-refuse-to-guess-which-migration-is-meant.md) |
| `migrate/generate.go` | [55](055-renames.md) [58](058-squashing-needs-no-coordination.md) [59](059-adopting-an-existing-database.md) [82](082-a-rename-must-land-on-a-name-the-models-have.md) [127](127-commands-refuse-to-guess-which-migration-is-meant.md) [128](128-adopt-leaves-out-roles.md) |
| `migrate/history.go` | [115](115-a-file-outside-a-transaction-is-recorded-before-it-runs.md) |
Expand Down Expand Up @@ -521,6 +522,7 @@ Before changing a file, read the decisions about it.
| `tests/features/migrations/sequence_drift_test.go` | [158](158-drift-compares-two-explicit-serial-defaults.md) |
| `tests/features/migrations/source_test.go` | [11](011-migration-model.md) [60](060-one-program-two-jobs.md) [113](113-a-missing-versions-folder-is-an-error.md) |
| `tests/features/migrations/squash_test.go` | [58](058-squashing-needs-no-coordination.md) |
| `tests/features/migrations/target_test.go` | [177](177-the-migrate-commands-name-their-database.md) |
| `tests/features/migrations/team_test.go` | [127](127-commands-refuse-to-guess-which-migration-is-meant.md) |
| `tests/features/migrations/uint64_test.go` | [138](138-a-uint64-column-on-postgresql-is-numeric.md) |
| `tests/features/migrations/up_test.go` | [11](011-migration-model.md) [50](050-three-layers-for-migrations.md) [56](056-failure.md) [115](115-a-file-outside-a-transaction-is-recorded-before-it-runs.md) [126](126-a-migration-runs-as-it-says-or-not-at-all.md) [129](129-status-check-fails-a-deploy-gate.md) [133](133-a-concurrent-build-clears-its-leftover.md) |
Expand Down Expand Up @@ -668,7 +670,7 @@ Tags on two or more decisions. Search the headers for the rest: `rg -l '^tags: .
- `Discriminator`: [66](066-several-models-can-share-a-table.md) [90](090-merge-keeps-what-other-writes-keep.md)
- `DoUpdate`: [80](080-every-write-moves-the-version-on.md) [89](089-one-column-one-value.md) [98](098-an-explicit-write-refuses-the-columns-ant-keeps.md) [103](103-an-upserts-update-stamps-updatedat.md) [170](170-insertfrom-takes-a-conflict-clause.md)
- `drift`: [55](055-renames.md) [57](057-drift-compares-what-the-server-stored.md) [59](059-adopting-an-existing-database.md) [72](072-partitions-are-not-migrations.md) [73](073-drift-compares-what-models-declare.md) [114](114-an-identity-columns-default-is-not-ants-to-change.md) [119](119-an-upserts-update-writes-the-zero-a-default-field-holds.md) [130](130-partitioning-is-part-of-the-table.md) [133](133-a-concurrent-build-clears-its-leftover.md) [158](158-drift-compares-two-explicit-serial-defaults.md) [173](173-drift-names-the-types-the-models-use-and-do-not-create.md) [174](174-drift-checks-the-views-that-view-models-read.md)
- `dsn`: [118](118-a-sqlite-dsn-says-whether-foreign-keys-are-on.md) [159](159-a-sqlite-dsn-names-its-lock-behavior.md)
- `dsn`: [118](118-a-sqlite-dsn-says-whether-foreign-keys-are-on.md) [159](159-a-sqlite-dsn-names-its-lock-behavior.md) [177](177-the-migrate-commands-name-their-database.md)
- `Each`: [6](006-return-shapes-and-tracking.md) [27](027-all-returns-t.md) [141](141-a-statement-inside-an-each-loop-on-one-connection-is-refused.md)
- `embed`: [60](060-one-program-two-jobs.md) [113](113-a-missing-versions-folder-is-an-error.md)
- `embedded`: [87](087-an-embedded-field-must-be-a-struct-value.md) [125](125-open-refuses-a-model-it-would-misread.md) [139](139-a-field-can-not-ask-for-two-things-ant-can-not-both-do.md)
Expand Down Expand Up @@ -726,7 +728,7 @@ Tags on two or more decisions. Search the headers for the rest: `rg -l '^tags: .
- `mariadb`: [13](013-mariadb-shares-the-mysql-package.md) [75](075-generated-values-without-returning.md) [91](091-an-upsert-checks-a-copys-version-on-mysql-and-mariadb.md) [164](164-explain-reads-each-databases-plan-statement.md)
- `MaxOf`: [145](145-helpers-take-a-field-of-any-type.md) [160](160-sqlite-time-aggregates-read-text.md)
- `Merge`: [80](080-every-write-moves-the-version-on.md) [89](089-one-column-one-value.md) [90](090-merge-keeps-what-other-writes-keep.md) [166](166-find-reads-the-row-after-a-bulk-delete.md)
- `migrate`: [11](011-migration-model.md) [50](050-three-layers-for-migrations.md) [60](060-one-program-two-jobs.md) [113](113-a-missing-versions-folder-is-an-error.md)
- `migrate`: [11](011-migration-model.md) [50](050-three-layers-for-migrations.md) [60](060-one-program-two-jobs.md) [113](113-a-missing-versions-folder-is-an-error.md) [177](177-the-migrate-commands-name-their-database.md)
- `migrate-up`: [115](115-a-file-outside-a-transaction-is-recorded-before-it-runs.md) [116](116-code-files-rerun-after-versioned-migrations.md)
- `migrations`: [49](049-postgresql-first.md) [58](058-squashing-needs-no-coordination.md) [82](082-a-rename-must-land-on-a-name-the-models-have.md) [94](094-migrations-keep-a-columns-dependents-working-while-it.md) [172](172-an-enum-value-renames-in-place.md) [173](173-drift-names-the-types-the-models-use-and-do-not-create.md) [174](174-drift-checks-the-views-that-view-models-read.md)
- `MonthlyPartitions`: [72](072-partitions-are-not-migrations.md) [161](161-a-month-is-read-from-its-bounds.md)
Expand Down
53 changes: 52 additions & 1 deletion migrate/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@ import (
"flag"
"fmt"
"io"
"net"
"os"
"os/signal"
"slices"
"strings"
"syscall"
"text/tabwriter"

"github.com/jackc/pgx/v5"

"github.com/skudra-go/ant"
"github.com/skudra-go/ant/dialect"
"github.com/skudra-go/ant/schema"
Expand Down Expand Up @@ -59,7 +62,9 @@ Running them (needs a database):
--seed run seeders afterwards

Flags for commands that need a database:
--dsn <dsn> connection string; the default is $DATABASE_URL
--dsn <dsn> connection string (then $DATABASE_URL, then Config.DSN)

The program does not read .env, so load it in your code or export DATABASE_URL.
`

// Main is the CLI. Call it from a main function in your module, and run that with
Expand Down Expand Up @@ -232,12 +237,16 @@ func Run[DB any](ctx context.Context, d dialect.Dialect, args []string, config .
return fmt.Errorf("unknown command %q. Run help for the list", command)
}

dsnSource := "--dsn"

if dsn == "" {
dsn = os.Getenv("DATABASE_URL")
dsnSource = "DATABASE_URL"
}

if dsn == "" {
dsn = c.DSN
dsnSource = "Config.DSN"
}

if dsn == "" {
Expand All @@ -257,6 +266,12 @@ func Run[DB any](ctx context.Context, d dialect.Dialect, args []string, config .
return err
}

targetCommands := []string{"status", "baseline", "repair", "seed"}

if command == "up" && !dry || slices.Contains(targetCommands, command) {
e.sayDatabaseTarget(ctx, dsnSource)
}

switch command {
case "up":
if err := e.knows(ctx, to); err != nil {
Expand Down Expand Up @@ -300,6 +315,42 @@ func Run[DB any](ctx context.Context, d dialect.Dialect, args []string, config .
return err
}

// sayDatabaseTarget reads the name and address from the same connection. The
// driver already resolves URL and keyword connection strings, including fallbacks.
func (e *engine) sayDatabaseTarget(ctx context.Context, source string) {
conn, err := e.pool.Conn(ctx)
if err != nil {
e.say("Database: unknown (from %s)", source)

return
}
defer conn.Close()

name, err := e.d.Database(ctx, conn)
if err != nil {
e.say("Database: unknown (from %s)", source)

return
}

var address net.Addr

_ = conn.Raw(func(driverConn any) error {
if pg, ok := driverConn.(interface{ Conn() *pgx.Conn }); ok {
address = pg.Conn().PgConn().Conn().RemoteAddr()
}

return nil
})

switch address.(type) {
case *net.TCPAddr, *net.UnixAddr:
e.say("Database: %q at %q (from %s)", name, address.String(), source)
default:
e.say("Database: %q (from %s)", name, source)
}
}

// expected is what the database should hold: the snapshot, since that is what
// migrations produce, or the models if nothing was generated yet. Migrations do
// not create views, so the views always come from the models (#232).
Expand Down
1 change: 1 addition & 0 deletions migrate/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ type Config struct {

// DSN connects the commands that need a database. The --dsn flag and the
// DATABASE_URL variable come first and second, and this is the last resort.
// Main and Run do not load .env files; the application may load one itself.
DSN string
// Options are those the application gives ant.Open. Main and Run pass them
// to ant.SchemaOf and ant.Open, so that WithNaming and WithConvention name
Expand Down
10 changes: 9 additions & 1 deletion skills/ant/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -485,10 +485,18 @@ If the application opens with `ant.WithNaming` or `ant.WithConvention`, pass the

```bash
go run ./cmd/migrate diff add_bio # writes migrations/versions/0002_add_bio.up.sql
go run ./cmd/migrate up # needs DATABASE_URL or --dsn
go run ./cmd/migrate up # connects using --dsn, DATABASE_URL, or Config.DSN
go run ./cmd/migrate check # in CI: fails if a struct changed without a migration
```

The migrate program can build its DSN from the same application configuration and
pass it as `migrate.Config{DSN: appDSN}`. A non-empty `--dsn` wins, followed by
`DATABASE_URL`, then `Config.DSN`. Load `.env` in the application before calling
`Main` or export its values beforehand. `up`, `status`, `baseline`, `repair` and
`seed` print the server address, the database name and a fixed source label. `up --dry-run`
keeps its existing output. Call `migrate.Up(ctx, db, config)` at startup to use the
application's existing connection.

After changing a model, run `diff` and show the user the SQL; don't hand-write the
migration it would generate. `db.EnsureCreated(ctx)` creates tables straight from the
structs, for experiments and tests only.
Expand Down
135 changes: 135 additions & 0 deletions tests/features/migrations/target_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
package migrations

import (
"bytes"
"fmt"
"io"
"net/url"
"os"
"strings"
"testing"

"github.com/stretchr/testify/require"

"github.com/skudra-go/ant/dialect/postgres"
"github.com/skudra-go/ant/migrate"
"github.com/skudra-go/ant/tests/features/fixture"
)

// The CLI names the connected database and the source it chose without
// printing a DSN, even when more than one source is set.
func TestDatabaseTargetAndDSNPriority(t *testing.T) {
fixture.Serial(t)

each(t, func(t *testing.T, p *project) {
database := scalar[string](p, "SELECT current_database()")
u, err := url.Parse(p.target.DSN)
require.NoError(t, err)

query := u.Query()
query.Set("application_name", "private_application_value_342")
u.RawQuery = query.Encode()
valid := u.String()

port := u.Port()
if port == "" {
port = "5432"
}

query.Set("host", u.Hostname())
query.Set("port", port)
query.Set("dbname", database)

if u.User != nil {
query.Set("user", u.User.Username())

if password, ok := u.User.Password(); ok {
query.Set("password", password)
}
}

escape := strings.NewReplacer("\\", "\\\\", "'", "\\'")

var keywords []string

for key := range query {
keywords = append(keywords, key+"='"+escape.Replace(query.Get(key))+"'")
}

keywordDSN := strings.Join(keywords, " ")
unused := "postgres://private_user:private_password@127.0.0.1:1/other?sslmode=disable"

cases := []struct {
name string
args []string
env string
config string
source string
}{
{"flag wins", []string{"seed", "--dsn", valid}, unused, unused, "--dsn"},
{
"environment wins with keyword DSN",
[]string{"seed"},
keywordDSN,
unused,
"DATABASE_URL",
},
{"config fallback", []string{"seed"}, "", valid, "Config.DSN"},
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("DATABASE_URL", tc.env)

var out bytes.Buffer

config := p.config
config.DSN = tc.config
config.Out = &out
err := migrate.Run[V1DB](t.Context(), p.target.Dialect, tc.args, config)
require.NoError(t, err)

require.Contains(t, out.String(), fmt.Sprintf("Database: %q at ", database))

require.Contains(
t,
out.String(),
fmt.Sprintf(":%s\" (from %s)\nNo seeders are registered.\n", port, tc.source),
)

require.NotContains(t, out.String(), valid)
require.NotContains(t, out.String(), "private_application_value_342")
})
}

t.Setenv("DATABASE_URL", "")

p.config.DSN = valid
must[V1DB](p, "diff", "start")
dryRun := must[V1DB](p, "up", "--dry-run")
require.NotContains(t, dryRun, "Database:") // stdout is SQL for a pipe

for _, command := range [][]string{{"up"}, {"status"}, {"baseline"}, {"repair"}, {"seed"}} {
out := must[V1DB](p, command...)
require.Contains(t, out, fmt.Sprintf("Database: %q at ", database))
require.Contains(t, out, fmt.Sprintf(":%s\" (from Config.DSN)\n", port))
require.NotContains(t, out, valid)
require.NotContains(t, out, "private_application_value_342")
}
})
}

func TestMigrateDoesNotLoadDotEnv(t *testing.T) {
fixture.Serial(t)
t.Setenv("DATABASE_URL", "")
t.Chdir(t.TempDir())
require.NoError(t, os.WriteFile(".env", []byte("DATABASE_URL=postgres://ignored\n"), 0o600))

err := migrate.Run[V1DB](
t.Context(),
postgres.Dialect,
[]string{"seed"},
migrate.Config{Out: io.Discard},
)
require.ErrorContains(t, err, "seed needs a database")
}