Print the SQL statement on error

pull/150/head
Vojtech Vitek 2019-03-04 21:13:40 -05:00
parent 1a52cca438
commit 3de24458e7
2 changed files with 13 additions and 8 deletions

View File

@ -3,7 +3,6 @@ package goose
import ( import (
"database/sql" "database/sql"
"fmt" "fmt"
"regexp"
"strconv" "strconv"
"sync" "sync"
) )
@ -14,7 +13,6 @@ var (
maxVersion = int64((1 << 63) - 1) maxVersion = int64((1 << 63) - 1)
timestampFormat = "20060102150405" timestampFormat = "20060102150405"
verbose = false verbose = false
reMatchSQLComments = regexp.MustCompile(`(--.*)`)
) )
// SetVerbose set the goose verbosity mode // SetVerbose set the goose verbosity mode

View File

@ -7,6 +7,7 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"regexp"
"strings" "strings"
"sync" "sync"
@ -178,11 +179,11 @@ func runSQLMigration(db *sql.DB, sqlFile string, v int64, direction bool) error
} }
for _, query := range statements { for _, query := range statements {
printInfo("Executing statement : %s\n", cleanStatement(query)) printInfo("Executing statement: %s\n", clearStatement(query))
if _, err = tx.Exec(query); err != nil { if _, err = tx.Exec(query); err != nil {
printInfo("Rollback transaction\n") printInfo("Rollback transaction\n")
tx.Rollback() tx.Rollback()
return errors.Wrapf(err, "failed to execute SQL query:\n%v", cleanStatement(query)) return errors.Wrapf(err, "failed to execute SQL query %q", clearStatement(query))
} }
} }
@ -210,9 +211,9 @@ func runSQLMigration(db *sql.DB, sqlFile string, v int64, direction bool) error
// NO TRANSACTION. // NO TRANSACTION.
for _, query := range statements { for _, query := range statements {
printInfo("Executing statement : %s\n", cleanStatement(query)) printInfo("Executing statement: %s\n", clearStatement(query))
if _, err := db.Exec(query); err != nil { if _, err := db.Exec(query); err != nil {
return errors.Wrapf(err, "failed to execute SQL query statement\n%v", cleanStatement(query)) return errors.Wrapf(err, "failed to execute SQL query %q", clearStatement(query))
} }
} }
if _, err := db.Exec(GetDialect().insertVersionSQL(), v, direction); err != nil { if _, err := db.Exec(GetDialect().insertVersionSQL(), v, direction); err != nil {
@ -228,6 +229,12 @@ func printInfo(s string, args ...interface{}) {
} }
} }
func cleanStatement(s string) string { var (
return reMatchSQLComments.ReplaceAllString(s, ``) matchSQLComments = regexp.MustCompile(`(?m)^--.*$[\r\n]*`)
matchEmptyLines = regexp.MustCompile(`(?m)^$[\r\n]*`)
)
func clearStatement(s string) string {
s = matchSQLComments.ReplaceAllString(s, ``)
return matchEmptyLines.ReplaceAllString(s, ``)
} }