Skip to content

Commit 969836b

Browse files
committed
Merge pull request #24 from daved/add/mig_id_to_err0
Add custom TxError to add clarity to tx-related error messages.
2 parents 8dc77fb + 27a4a8d commit 969836b

1 file changed

Lines changed: 26 additions & 9 deletions

File tree

migrate.go

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,25 @@ 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 newTxError(migration *PlannedMigration, err error) error {
41+
return &TxError{
42+
Migration: migration.Migration,
43+
Err: err,
44+
}
45+
}
46+
47+
func (e *TxError) Error() string {
48+
return e.Err.Error() + " handling " + e.Migration.Id
49+
}
50+
3251
// Set the name of the table used to store migration info.
3352
//
3453
// Should be called before any other call such as (Exec, ExecMax, ...).
@@ -266,14 +285,13 @@ func ExecMax(db *sql.DB, dialect string, m MigrationSource, dir MigrationDirecti
266285
for _, migration := range migrations {
267286
trans, err := dbMap.Begin()
268287
if err != nil {
269-
return applied, err
288+
return applied, newTxError(migration, err)
270289
}
271290

272291
for _, stmt := range migration.Queries {
273-
_, err := trans.Exec(stmt)
274-
if err != nil {
292+
if _, err := trans.Exec(stmt); err != nil {
275293
trans.Rollback()
276-
return applied, err
294+
return applied, newTxError(migration, err)
277295
}
278296
}
279297

@@ -283,22 +301,21 @@ func ExecMax(db *sql.DB, dialect string, m MigrationSource, dir MigrationDirecti
283301
AppliedAt: time.Now(),
284302
})
285303
if err != nil {
286-
return applied, err
304+
return applied, newTxError(migration, err)
287305
}
288306
} else if dir == Down {
289307
_, err := trans.Delete(&MigrationRecord{
290308
Id: migration.Id,
291309
})
292310
if err != nil {
293-
return applied, err
311+
return applied, newTxError(migration, err)
294312
}
295313
} else {
296314
panic("Not possible")
297315
}
298316

299-
err = trans.Commit()
300-
if err != nil {
301-
return applied, err
317+
if err := trans.Commit(); err != nil {
318+
return applied, newTxError(migration, err)
302319
}
303320

304321
applied++

0 commit comments

Comments
 (0)