Skip to content

Commit ee7cc65

Browse files
committed
Add custom TxError to add clarity to tx-related error messages.
1 parent 8dc77fb commit ee7cc65

1 file changed

Lines changed: 40 additions & 4 deletions

File tree

migrate.go

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,18 @@ var tableName = "gorp_migrations"
2929
var schemaName = ""
3030
var numberPrefixRegex = regexp.MustCompile(`^(\d+).*$`)
3131

32+
// TxError is returned when any error is encountered during a database
33+
// transaction. It contains the relevant *Migration and notes it's Id in the
34+
// Error function output.
35+
type TxError struct {
36+
Migration *Migration
37+
Err error
38+
}
39+
40+
func (e *TxError) Error() string {
41+
return e.Err.Error() + " handling " + e.Migration.Id
42+
}
43+
3244
// Set the name of the table used to store migration info.
3345
//
3446
// Should be called before any other call such as (Exec, ExecMax, ...).
@@ -266,13 +278,23 @@ func ExecMax(db *sql.DB, dialect string, m MigrationSource, dir MigrationDirecti
266278
for _, migration := range migrations {
267279
trans, err := dbMap.Begin()
268280
if err != nil {
281+
err := &TxError{
282+
Migration: migration.Migration,
283+
Err: err,
284+
}
285+
269286
return applied, err
270287
}
271288

272289
for _, stmt := range migration.Queries {
273-
_, err := trans.Exec(stmt)
274-
if err != nil {
290+
if _, err := trans.Exec(stmt); err != nil {
275291
trans.Rollback()
292+
293+
err := &TxError{
294+
Migration: migration.Migration,
295+
Err: err,
296+
}
297+
276298
return applied, err
277299
}
278300
}
@@ -283,21 +305,35 @@ func ExecMax(db *sql.DB, dialect string, m MigrationSource, dir MigrationDirecti
283305
AppliedAt: time.Now(),
284306
})
285307
if err != nil {
308+
err := &TxError{
309+
Migration: migration.Migration,
310+
Err: err,
311+
}
312+
286313
return applied, err
287314
}
288315
} else if dir == Down {
289316
_, err := trans.Delete(&MigrationRecord{
290317
Id: migration.Id,
291318
})
292319
if err != nil {
320+
err := &TxError{
321+
Migration: migration.Migration,
322+
Err: err,
323+
}
324+
293325
return applied, err
294326
}
295327
} else {
296328
panic("Not possible")
297329
}
298330

299-
err = trans.Commit()
300-
if err != nil {
331+
if err := trans.Commit(); err != nil {
332+
err := &TxError{
333+
Migration: migration.Migration,
334+
Err: err,
335+
}
336+
301337
return applied, err
302338
}
303339

0 commit comments

Comments
 (0)