diff --git a/docs/decisions/162-a-failed-migration-names-its-statement.md b/docs/decisions/162-a-failed-migration-names-its-statement.md new file mode 100644 index 0000000..d358353 --- /dev/null +++ b/docs/decisions/162-a-failed-migration-names-its-statement.md @@ -0,0 +1,29 @@ +--- +id: 162 +title: "A failed migration names its statement even when the driver sends no position" +area: migrations +status: active +tags: [migration, failure, error, line, statement, Explain, Split, DDL] +issues: [303] +related: [56] +changed_by: [] +code: [migrate/engine.go] +tests: [tests/features/migrations/up_test.go] +--- + +# 162. A failed migration names its statement even when the driver sends no position + +**In short:** A transactional file migration runs statement by statement inside its transaction, so a failure names the statement and its line even when PostgreSQL sends no position, which it does not for most DDL and constraint errors. + +## Decision + +`up` runs a file migration as one string inside its transaction. A failure then says `failed and was rolled back` and nothing else, unless the driver sends a position: PostgreSQL sends one for expression and cast errors but not for most DDL and constraint errors, which are the common failures of a generated file. A file can have twenty statements, and the troubleshooting page reads the line and the statement off that message (#303). + +A transactional file migration now runs its statements one at a time, inside the same transaction, which leaves the all-or-nothing rollback as it was. The cost is one round trip per statement instead of one per file, which a large data migration notices: 5,000 statements over a 1 ms link take about 5 s longer. That is the price of naming the line. The failing statement and its line come from the statement that raised the error. A comment before a statement stays with it, as `Split` keeps it, so the line is the first that carries code, not the first comment: a `--` line and a block comment, over however many lines it runs, are both passed over. When the driver does send a position, it is relative to the statement, so the line is that statement's first line plus the lines the position is into it. + +Two things keep the old path. A Go migration, and a `-- ant:no-transaction` file, run as before: the first is code, the second has no transaction to run inside. A file whose statements `Split` cannot place in the script, because it rebuilt them so that they are not substrings, runs whole as it did, so nothing regresses; no line is then named unless the driver sends a position. + +Rejected: + +- Running the file statement by statement after a failure, inside the same rolled-back transaction, to find the one that fails: it would run every earlier statement twice, and a statement that changed the session could fail differently the second time. +- Matching the object the error names against the statements: the message names relations and columns, not always uniquely, and a match is a guess where running the statements one by one is a fact. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 35d617f..c2264e6 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -276,6 +276,7 @@ On 2026-11-20 the decisions moved from one file, `docs/DECISIONS.md`, to a file | [144](144-script-stops-before-a-go-migration.md) | script stops before a Go migration, and starts from a version | active | `script` `Go-migrations` `no-transaction` `from` `guarded` `OutOfOrder` | | [158](158-drift-compares-two-explicit-serial-defaults.md) | Drift compares two explicit serial defaults | active | `drift` `identity` `serial` `nextval` `sequence` `postgres` | | [161](161-a-month-is-read-from-its-bounds.md) | A month of a partitioned table is read from its bounds, not its name | active | `partitions` `MonthlyPartitions` `DropBefore` `Ensure` `List` `postgres` `bounds` | +| [162](162-a-failed-migration-names-its-statement.md) | A failed migration names its statement even when the driver sends no position | active | `migration` `failure` `error` `line` `statement` `Explain` `Split` `DDL` | | [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` | @@ -421,7 +422,7 @@ Before changing a file, read the decisions about it. | `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/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/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) [162](162-a-failed-migration-names-its-statement.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) | | `migrate/internal_test.go` | [55](055-renames.md) [56](056-failure.md) | @@ -523,7 +524,7 @@ Before changing a file, read the decisions about it. | `tests/features/migrations/squash_test.go` | [58](058-squashing-needs-no-coordination.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) | +| `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) [162](162-a-failed-migration-names-its-statement.md) | | `tests/features/model_definition/configure_test.go` | [21](021-configuration-runs-when-a-context-opens.md) [66](066-several-models-can-share-a-table.md) | | `tests/features/model_definition/conflicting_tags_test.go` | [139](139-a-field-can-not-ask-for-two-things-ant-can-not-both-do.md) | | `tests/features/model_definition/custom_types_test.go` | [42](042-converters-are-scanner-and-valuer.md) | @@ -682,6 +683,7 @@ Tags on two or more decisions. Search the headers for the rest: `rg -l '^tags: . - `ErrTxDone`: [31](031-failed-saves.md) [155](155-a-bound-transaction-settles-what-its-contexts-did.md) - `ErrUnsupported`: [50](050-three-layers-for-migrations.md) [74](074-dialects-state-their-differences.md) - `ErrWrongModel`: [4](004-conditions-are-not-tied-to-a-model.md) [18](018-wrong-model-detection.md) +- `Explain`: [162](162-a-failed-migration-names-its-statement.md) [164](164-explain-reads-each-databases-plan-statement.md) - `Expr`: [35](035-typed-expressions.md) [146](146-ne-matches-null-as-go-does.md) - `extension`: [73](073-drift-compares-what-models-declare.md) [173](173-drift-names-the-types-the-models-use-and-do-not-create.md) - `Fields`: [21](021-configuration-runs-when-a-context-opens.md) [100](100-probes-are-named-after-their-model-in-the-plural.md) diff --git a/migrate/engine.go b/migrate/engine.go index 8f89325..bf2b408 100644 --- a/migrate/engine.go +++ b/migrate/engine.go @@ -562,7 +562,7 @@ func (e *engine) applyInTx(ctx context.Context, conn *sql.Conn, m Migration, r * } defer tx.Rollback() - if err := e.run(ctx, tx, m); err != nil { + if err := e.ran(ctx, tx, m); err != nil { return e.explain(m, err) } @@ -660,22 +660,227 @@ func (e *engine) run(ctx context.Context, tx *sql.Tx, m Migration) error { return m.run(ctx, db, tx) } +// ran runs a file's statements one at a time inside tx. PostgreSQL runs a whole +// file as one string, but a failure then says nothing about which statement it +// was unless the driver sends a position, which DDL and constraint errors do not +// (#303). Running them one by one, in the same transaction, lets the failing +// statement and its line be named. It is one round trip per statement instead of +// one per file, which a large data migration notices. +// +// A file that ends its own transaction never gets here: checkBody has refused it +// before the transaction began. +func (e *engine) ran(ctx context.Context, tx *sql.Tx, m Migration) error { + if m.run != nil || m.noTransaction { + return e.run(ctx, tx, m) + } + + lines, ok := splitWithLines(e.d.Split(m.SQL), m.SQL) + if !ok || len(lines) == 0 { + return e.run(ctx, tx, m) + } + + for _, s := range lines { + if _, err := tx.ExecContext(ctx, s.text); err != nil { + return &statementError{ + line: s.line, + skipped: s.skipped, + text: s.text, + err: err, + } + } + } + + return nil +} + +// statementError is a statement that failed, with where it starts in the file. +// line is the statement's first line that carries code; skipped counts the +// leading comment and blank lines before it, which a position, counted from the +// statement's text, still includes. +type statementError struct { + line int + skipped int + text string + err error +} + +func (e *statementError) Error() string { return e.err.Error() } +func (e *statementError) Unwrap() error { return e.err } + +// lineOf returns the line in the file that offset points at, where offset is a +// position within this statement in characters from 1, as a driver sends it, or +// the statement's first code line when it is past the text. The offset counts +// from the statement's text, comment lines included, so the lines skipped before +// its code come off. +func (e *statementError) lineOf(offset int) int { + runes := []rune(e.text) + if offset < 1 || offset > len(runes) { + return e.line + } + + return e.line - e.skipped + strings.Count(string(runes[:offset-1]), "\n") +} + +// splitWithLines matches each statement Split returns back to the line it starts +// on, by finding it in the script in order. Split keeps the comments before a +// statement with it, so the line is the first that carries code, not the first +// comment. A statement Split rebuilt so that it is not a substring of the script +// leaves ok false, and the caller runs the file whole, as before. +func splitWithLines(statements []string, script string) ([]splitLine, bool) { + out := make([]splitLine, 0, len(statements)) + + offset := 0 + + for _, statement := range statements { + begin, ok := findStatement(script, statement, offset) + if !ok { + return nil, false + } + + code := lineOfCode(script[begin : begin+len(statement)]) + out = append(out, splitLine{ + line: strings.Count(script[:begin], "\n") + code, + skipped: code - 1, + text: statement, + }) + + // Look past this statement for the next, so two alike are told apart. + offset = begin + len(statement) + } + + return out, true +} + +// findStatement returns where the statement starts in script at or after from. +// +// A statement starts where the one before it ended: at the top of the file, or +// after the semicolon that closed the previous statement. A match anywhere else, +// as inside a comment that quotes the statement, is another occurrence, and the +// search moves past it rather than taking it, so a comment above cannot claim the +// statement's line. +func findStatement(script, statement string, from int) (int, bool) { + for from <= len(script) { + at := strings.Index(script[from:], statement) + if at < 0 { + return 0, false + } + + begin := from + at + if beginsStatement(script, begin) { + return begin, true + } + + from = begin + 1 + } + + return 0, false +} + +// beginsStatement reports whether i is where a statement starts: at the top of +// the script, or after the semicolon that ended the one before, with only +// whitespace or a comment between. +func beginsStatement(script string, i int) bool { + if i == 0 { + return true + } + + for j := i - 1; j >= 0; j-- { + switch script[j] { + case ' ', '\t', '\r', '\n': + continue + case ';': + return true + default: + return false + } + } + + return true +} + +// lineOfCode returns the line within text that first carries code, counting +// from 1, skipping the blank lines and the comments before it: a line comment to +// its line's end, and a block comment to where it closes, over the lines it +// runs and the block comments nested in it, as PostgreSQL reads them. Text that +// is all comment gives its last line. +func lineOfCode(text string) int { + i := 0 + + for i < len(text) { + switch { + case text[i] == ' ' || text[i] == '\t' || text[i] == '\r' || text[i] == '\n': + i++ + case strings.HasPrefix(text[i:], "--"): + end := strings.IndexByte(text[i:], '\n') + if end < 0 { + return 1 + strings.Count(text, "\n") + } + + i += end + 1 + case strings.HasPrefix(text[i:], "/*"): + i = afterBlockComment(text, i) + default: + return 1 + strings.Count(text[:i], "\n") + } + } + + return 1 + strings.Count(text, "\n") +} + +// afterBlockComment returns where the block comment that opens at i ends, past +// its closing mark, or the end of text when it is never closed. +func afterBlockComment(text string, i int) int { + depth := 0 + + for i < len(text) { + switch { + case strings.HasPrefix(text[i:], "/*"): + depth++ + i += 2 + case strings.HasPrefix(text[i:], "*/"): + depth-- + i += 2 + + if depth == 0 { + return i + } + default: + i++ + } + } + + return len(text) +} + +type splitLine struct { + line int + skipped int + text string +} + // explain adds the failing migration, its line, and the database's own detail to -// err. PostgreSQL gets a whole file at once, so without this a message says nothing -// about where. +// err. A driver that sends a position gives the line within the text it ran; a +// statement ran() ran alone is positioned within that statement, so the file +// before it is added. A driver that sends no position, as for most DDL and +// constraint errors, leaves it to the statement that failed, which ran() knows. func (e *engine) explain(m Migration, err error) error { failure := e.d.Explain(err) where, more := "", "" - if runes := []rune(m.SQL); failure.Offset > 0 && failure.Offset <= len(runes) { - line := strings.Count(string(runes[:failure.Offset-1]), "\n") + 1 - where = fmt.Sprintf(", at line %d", line) + failed, isStatement := errors.AsType[*statementError](err) - more = fmt.Sprintf( - "\n\n %d | %s", - line, - strings.TrimSpace(strings.Split(m.SQL, "\n")[line-1]), - ) + switch { + case failure.Offset > 0 && isStatement: + if line := failed.lineOf(failure.Offset); line > 0 { + where, more = lineText(m.SQL, line) + } + case failure.Offset > 0: + if runes := []rune(m.SQL); failure.Offset <= len(runes) { + line := strings.Count(string(runes[:failure.Offset-1]), "\n") + 1 + where, more = lineText(m.SQL, line) + } + case isStatement: + where, more = lineText(m.SQL, failed.line) } if failure.Detail != "" { @@ -694,3 +899,18 @@ func (e *engine) explain(m Migration, err error) error { more, ) } + +// lineText returns the ", at line N" part and the numbered source line, for a +// line of the file, or nothing when it is out of range. +func lineText(script string, line int) (string, string) { + lines := strings.Split(script, "\n") + if line < 1 || line > len(lines) { + return "", "" + } + + return fmt.Sprintf(", at line %d", line), fmt.Sprintf( + "\n\n %d | %s", + line, + strings.TrimSpace(lines[line-1]), + ) +} diff --git a/tests/features/migrations/up_test.go b/tests/features/migrations/up_test.go index 328e46d..b1bc005 100644 --- a/tests/features/migrations/up_test.go +++ b/tests/features/migrations/up_test.go @@ -157,6 +157,146 @@ func TestFailedMigration(t *testing.T) { }) } +// A failure PostgreSQL reports no position for, as most DDL and constraint +// errors, still says which statement and which line it was (#303). +func TestFailedMigrationWithoutAPosition(t *testing.T) { + each(t, func(t *testing.T, p *project) { + p.write("versions/0001_good.up.sql", "CREATE TABLE first (id int);") + + // The second statement names a relation that does not exist. PostgreSQL + // reports no position for that, so the line has to come from the + // statement the plan for. + p.write( + "versions/0002_bad.up.sql", + "CREATE TABLE alpha (id int);\n\n"+ + "ALTER TABLE beta ADD COLUMN note text;\n\n"+ + "CREATE TABLE gamma (id int);\n", + ) + + _, err := run[V1DB](p, "up") + require.Error(t, err) + + t.Run("the error names the line and the statement", func(t *testing.T) { + require.ErrorContains(t, err, "failed and was rolled back, at line 3") + require.ErrorContains(t, err, "ALTER TABLE beta ADD COLUMN note text;") + }) + + t.Run("nothing of it remains", func(t *testing.T) { + require.Empty(t, p.columns("alpha")) + }) + + t.Run("fixing the statement is enough", func(t *testing.T) { + p.write("versions/0002_bad.up.sql", "CREATE TABLE alpha (id int);\n") + must[V1DB](p, "up") + require.NotEmpty(t, p.columns("alpha")) + }) + }) +} + +// A comment before a statement stays with it, so the line names where the +// statement's own code is, not where its comment is (#303). +func TestFailedMigrationUnderAComment(t *testing.T) { + each(t, func(t *testing.T, p *project) { + p.write("versions/0001_good.up.sql", "CREATE TABLE first (id int);") + + p.write( + "versions/0002_bad.up.sql", + "CREATE TABLE alpha (id int);\n\n"+ + "-- what the next statement adds\n\n"+ + "ALTER TABLE beta ADD COLUMN note text;\n", + ) + + _, err := run[V1DB](p, "up") + require.Error(t, err) + require.ErrorContains(t, err, "failed and was rolled back, at line 5") + require.ErrorContains(t, err, "5 | ALTER TABLE beta ADD COLUMN note text;") + }) +} + +// A position the driver sends is counted from the statement's text, comments +// included, so a comment above the statement does not shift the line it names +// (#303). +func TestFailedMigrationWithAPositionUnderAComment(t *testing.T) { + each(t, func(t *testing.T, p *project) { + p.write("versions/0001_good.up.sql", "CREATE TABLE first (id int);") + + // The cast fails at a position inside the last line of the statement, + // which is line 6 of the file. + p.write( + "versions/0002_bad.up.sql", + "CREATE TABLE alpha (n int);\n\n"+ + "-- the values to add\n"+ + "INSERT INTO alpha (n)\nVALUES\n('abc'::int);\n", + ) + + _, err := run[V1DB](p, "up") + require.Error(t, err) + require.ErrorContains(t, err, "failed and was rolled back, at line 6") + require.ErrorContains(t, err, "6 | ('abc'::int);") + }) +} + +// A block comment before a statement stays with it as a line comment does, over +// however many lines it runs and whatever it nests, so the line is still the +// statement's own (#303). +func TestFailedMigrationUnderABlockComment(t *testing.T) { + each(t, func(t *testing.T, p *project) { + p.write("versions/0001_good.up.sql", "CREATE TABLE first (id int);") + + p.write( + "versions/0002_bad.up.sql", + "CREATE TABLE alpha (id int);\n\n"+ + "/* what the next statement adds,\n"+ + " /* nested */ over three lines\n"+ + "*/\n"+ + "ALTER TABLE beta ADD COLUMN note text;\n", + ) + + _, err := run[V1DB](p, "up") + require.Error(t, err) + require.ErrorContains(t, err, "failed and was rolled back, at line 6") + require.ErrorContains(t, err, "6 | ALTER TABLE beta ADD COLUMN note text;") + }) +} + +// Code that follows a block comment on the same line is on that line (#303). +func TestFailedMigrationAfterABlockCommentOnItsLine(t *testing.T) { + each(t, func(t *testing.T, p *project) { + p.write("versions/0001_good.up.sql", "CREATE TABLE first (id int);") + + p.write( + "versions/0002_bad.up.sql", + "CREATE TABLE alpha (id int);\n\n"+ + "/* why */ ALTER TABLE beta ADD COLUMN note text;\n", + ) + + _, err := run[V1DB](p, "up") + require.Error(t, err) + require.ErrorContains(t, err, "failed and was rolled back, at line 3") + }) +} + +// A position under a block comment is counted as under a line comment: from the +// statement's text, the comment's lines included (#303). +func TestFailedMigrationWithAPositionUnderABlockComment(t *testing.T) { + each(t, func(t *testing.T, p *project) { + p.write("versions/0001_good.up.sql", "CREATE TABLE first (id int);") + + // The cast fails inside the last line of the statement, line 7 of the file. + p.write( + "versions/0002_bad.up.sql", + "CREATE TABLE alpha (n int);\n\n"+ + "/* the values\n to add */\n"+ + "INSERT INTO alpha (n)\nVALUES\n('abc'::int);\n", + ) + + _, err := run[V1DB](p, "up") + require.Error(t, err) + require.ErrorContains(t, err, "failed and was rolled back, at line 7") + require.ErrorContains(t, err, "7 | ('abc'::int);") + }) +} + // -- ant:no-transaction is for statements PostgreSQL refuses in a transaction. func TestNoTransaction(t *testing.T) { each(t, func(t *testing.T, p *project) {