Skip to content

Commit

Permalink
fix: ensure migration transaction is commited or rolled back
Browse files Browse the repository at this point in the history
  • Loading branch information
fmartingr committed Dec 11, 2024
1 parent 4ec2412 commit 8aecb98
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions internal/database/pg.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,42 +25,44 @@ var postgresMigrations = []migration{
if err != nil {
return fmt.Errorf("failed to start transaction: %w", err)
}
defer tx.Rollback()

_, err = tx.Exec(`ALTER TABLE bookmark ADD COLUMN has_content BOOLEAN DEFAULT FALSE NOT NULL`)
if err != nil {
// Check if this is a "column already exists" error (PostgreSQL error code 42701)
// If it's not, return error.
// This is needed for users upgrading from >1.5.4 directly into this version.
pqErr, ok := err.(*pq.Error)
if ok && pqErr.Code == "42701" {
tx.Rollback()
} else {
return fmt.Errorf("failed to add has_content column to bookmark table: %w", err)
}
}

if errCommit := tx.Commit(); errCommit != nil {
return fmt.Errorf("failed to commit transaction: %w", errCommit)
} else {
if err := tx.Commit(); err != nil {
return fmt.Errorf("failed to commit transaction: %w", err)

Check warning on line 42 in internal/database/pg.go

View check run for this annotation

Codecov / codecov/patch

internal/database/pg.go#L38-L42

Added lines #L38 - L42 were not covered by tests
}
}

tx, err = db.Begin()
if err != nil {
return fmt.Errorf("failed to start transaction: %w", err)
}
defer tx.Rollback()

_, err = tx.Exec(`ALTER TABLE account ADD COLUMN config JSONB NOT NULL DEFAULT '{}'`)
if err != nil {
// Check if this is a "column already exists" error (PostgreSQL error code 42701)
// If it's not, return error
// This is needed for users upgrading from >1.5.4 directly into this version.
pqErr, ok := err.(*pq.Error)
if ok && pqErr.Code == "42701" {
tx.Rollback()
} else {
return fmt.Errorf("failed to add config column to account table: %w", err)
}
}

if errCommit := tx.Commit(); errCommit != nil {
return fmt.Errorf("failed to commit transaction: %w", errCommit)
} else {
if err := tx.Commit(); err != nil {
return fmt.Errorf("failed to commit transaction: %w", err)

Check warning on line 64 in internal/database/pg.go

View check run for this annotation

Codecov / codecov/patch

internal/database/pg.go#L60-L64

Added lines #L60 - L64 were not covered by tests
}
}

return nil
Expand Down

0 comments on commit 8aecb98

Please sign in to comment.