Move everything into the transaction

This commit is contained in:
Nise Void 2017-04-19 15:39:48 +02:00
parent 0234500a89
commit 65c3956b60

View File

@ -36,31 +36,33 @@ func Migrate(db *sql.DB, version int, o Options, asset AssetFunc) error {
o.TableName = DefaultTableName o.TableName = DefaultTableName
} }
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
table := o.TableName table := o.TableName
if o.Schema != `` { if o.Schema != `` {
table = o.Schema + `.` + table table = o.Schema + `.` + table
fmt.Println(`Switching to schema:`, o.Schema) _, err = tx.Exec(`CREATE SCHEMA IF NOT EXISTS ` + o.Schema)
_, err := db.Exec(`CREATE SCHEMA IF NOT EXISTS ` + o.Schema)
if err != nil { if err != nil {
return err return err
} }
_, err = db.Exec(`SET search_path TO ` + o.Schema + `,public`) _, err = tx.Exec(`SET search_path TO ` + o.Schema + `,public`)
if err != nil { if err != nil {
return err return err
} }
} }
_, err := db.Exec(`CREATE TABLE IF NOT EXISTS ` + table + ` (Version integer NOT NULL PRIMARY KEY)`) _, err = tx.Exec(`CREATE TABLE IF NOT EXISTS ` + table + ` (Version integer NOT NULL PRIMARY KEY)`)
if err != nil { if err != nil {
return err return err
} }
row := db.QueryRow(`SELECT Version FROM ` + table + ` ORDER BY Version DESC`) row := tx.QueryRow(`SELECT Version FROM ` + table + ` ORDER BY Version DESC`)
if err != nil {
return err
}
var v int var v int
err = row.Scan(&v) err = row.Scan(&v)
@ -72,12 +74,6 @@ func Migrate(db *sql.DB, version int, o Options, asset AssetFunc) error {
return ErrDatabaseNewer return ErrDatabaseNewer
} }
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
for i := v + 1; i <= version; i++ { for i := v + 1; i <= version; i++ {
script, err := asset(fmt.Sprintf(o.AssetPrefix+fileFormat, i)) script, err := asset(fmt.Sprintf(o.AssetPrefix+fileFormat, i))
if err != nil { if err != nil {