fix: tolerate duplicate column errors in migration runner
The previous SAVEPOINT approach failed because Go's tx.Exec() stops at the first error and never reaches the ROLLBACK TO statements. This caused every subsequent startup to re-run migration 0002, fail on the first ALTER (column already exists from a prior partial run), and crash. Fix runMigration() to: - Execute migrations without a wrapping transaction (DDL in SQLite is auto-commit anyway) - Treat "duplicate column name" / "already exists" errors as success and record the migration anyway, covering cases where a previous failed attempt already partially modified the schema Also simplify 0002_nfs_structured.sql back to plain ALTER TABLE statements (no SAVEPOINT needed with the new Go-level tolerance). Bump VERSION 0.1.9 -> 0.1.10
This commit is contained in:
+17
-13
@@ -100,25 +100,29 @@ func (d *DB) isMigrationApplied(name string) (bool, error) {
|
||||
}
|
||||
|
||||
func (d *DB) runMigration(name, content string) error {
|
||||
tx, err := d.conn.Begin()
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin transaction: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
if _, err := tx.Exec(content); err != nil {
|
||||
return fmt.Errorf("execute: %w", err)
|
||||
if _, err := d.conn.Exec(content); err != nil {
|
||||
if isIgnorableMigrationError(err) {
|
||||
// Schema is already in target state (e.g. columns already added
|
||||
// by a previous partial run). Continue to record the migration.
|
||||
} else {
|
||||
return fmt.Errorf("execute: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(
|
||||
if _, err := d.conn.Exec(
|
||||
"INSERT INTO schema_migrations (name) VALUES (?)",
|
||||
name,
|
||||
); err != nil {
|
||||
return fmt.Errorf("record migration: %w", err)
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("commit: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isIgnorableMigrationError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
msg := strings.ToLower(err.Error())
|
||||
return strings.Contains(msg, "duplicate column name") ||
|
||||
strings.Contains(msg, "already exists")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user