-
Notifications
You must be signed in to change notification settings - Fork 3
/
schema.go
56 lines (48 loc) · 1.06 KB
/
schema.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package schema
import (
"database/sql"
"errors"
"fmt"
"sync"
)
// A global mutex to prevent simultaneous
// migrations
var mutex = &sync.Mutex{}
// DefaultTableName defines the name of the database table which will
// hold the status of applied migrations
const DefaultTableName = "schema_migrations"
// ErrNilDB is thrown when the database pointer is nil
var ErrNilDB = errors.New("DB pointer is nil")
// Queryer is something which can execute a Query (either a sql.DB
// or a sql.Tx))
type Queryer interface {
Query(sql string, args ...interface{}) (*sql.Rows, error)
}
// transaction wraps the supplied function in a transaction with the supplied
// database connecion
//
func transaction(db *sql.DB, f func(*sql.Tx) error) (err error) {
if db == nil {
return ErrNilDB
}
tx, err := db.Begin()
if err != nil {
return
}
defer func() {
if p := recover(); p != nil {
switch p := p.(type) {
case error:
err = p
default:
err = fmt.Errorf("%s", p)
}
}
if err != nil {
tx.Rollback()
return
}
err = tx.Commit()
}()
return f(tx)
}