applyMigration applies a single migration in a transaction
(ctx context.Context, migration Migration)
| 164 | |
| 165 | // applyMigration applies a single migration in a transaction |
| 166 | func (m *Migrator) applyMigration(ctx context.Context, migration Migration) error { |
| 167 | tx, err := m.conn.Begin(ctx) |
| 168 | if err != nil { |
| 169 | return fmt.Errorf("failed to begin transaction: %w", err) |
| 170 | } |
| 171 | defer func() { |
| 172 | if err := tx.Rollback(ctx); err != nil && !errors.Is(err, pgx.ErrTxClosed) { |
| 173 | log.Printf("Failed to rollback migration transaction: %v", err) |
| 174 | } |
| 175 | }() |
| 176 | |
| 177 | // Execute the migration SQL |
| 178 | _, err = tx.Exec(ctx, migration.SQL) |
| 179 | if err != nil { |
| 180 | return fmt.Errorf("failed to execute migration SQL: %w", err) |
| 181 | } |
| 182 | |
| 183 | // Record the migration as applied |
| 184 | _, err = tx.Exec(ctx, |
| 185 | "INSERT INTO schema_migrations (version, name) VALUES ($1, $2)", |
| 186 | migration.Version, migration.Name) |
| 187 | if err != nil { |
| 188 | return fmt.Errorf("failed to record migration: %w", err) |
| 189 | } |
| 190 | |
| 191 | return tx.Commit(ctx) |
| 192 | } |