Merge pull request #135 from tbaud0n/master

Add verbose option to print executed sql statements
pull/149/head
Vojtech Vitek 2019-03-04 15:02:13 -05:00 committed by GitHub
commit d431110f17
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 33 additions and 2 deletions

View File

@ -10,8 +10,9 @@ import (
)
var (
flags = flag.NewFlagSet("goose", flag.ExitOnError)
dir = flags.String("dir", ".", "directory with migration files")
flags = flag.NewFlagSet("goose", flag.ExitOnError)
dir = flags.String("dir", ".", "directory with migration files")
verbose = flags.Bool("v", false, "enable verbose mode")
)
func main() {
@ -24,6 +25,10 @@ func main() {
return
}
if *verbose {
goose.SetVerbose(true)
}
switch args[0] {
case "create":
if err := goose.Run("create", nil, *dir, args[1:]...); err != nil {

View File

@ -3,6 +3,7 @@ package goose
import (
"database/sql"
"fmt"
"regexp"
"strconv"
"sync"
)
@ -12,8 +13,15 @@ var (
minVersion = int64(0)
maxVersion = int64((1 << 63) - 1)
timestampFormat = "20060102150405"
verbose = false
reMatchSQLComments = regexp.MustCompile(`(--.*)`)
)
// SetVerbose set the goose verbosity mode
func SetVerbose(v bool) {
verbose = v
}
// Run runs a goose command.
func Run(command string, db *sql.DB, dir string, args ...string) error {
switch command {

View File

@ -168,13 +168,17 @@ func runSQLMigration(db *sql.DB, scriptFile string, v int64, direction bool) err
if useTx {
// TRANSACTION.
printInfo("Begin transaction\n")
tx, err := db.Begin()
if err != nil {
log.Fatal(err)
}
for _, query := range statements {
printInfo("Executing statement : %s\n", cleanStatement(query))
if _, err = tx.Exec(query); err != nil {
printInfo("Rollback transaction\n")
tx.Rollback()
return err
}
@ -182,21 +186,25 @@ func runSQLMigration(db *sql.DB, scriptFile string, v int64, direction bool) err
if direction {
if _, err := tx.Exec(GetDialect().insertVersionSQL(), v, direction); err != nil {
printInfo("Rollback transaction\n")
tx.Rollback()
return err
}
} else {
if _, err := tx.Exec(GetDialect().deleteVersionSQL(), v); err != nil {
printInfo("Rollback transaction\n")
tx.Rollback()
return err
}
}
printInfo("Commit transaction\n")
return tx.Commit()
}
// NO TRANSACTION.
for _, query := range statements {
printInfo("Executing statement : %s\n", cleanStatement(query))
if _, err := db.Exec(query); err != nil {
return err
}
@ -207,3 +215,13 @@ func runSQLMigration(db *sql.DB, scriptFile string, v int64, direction bool) err
return nil
}
func printInfo(s string, args ...interface{}) {
if verbose {
log.Printf(s, args...)
}
}
func cleanStatement(s string) string {
return reMatchSQLComments.ReplaceAllString(s, ``)
}