forked from mirror/gorm
When using the LogMode(true), the SQL produced during the log message, places the bounded variables in the wrong location, this is due to the fact that the current implementation splits the values with a regex similar to: ($\d+)|?.
That works well for ? placeholders because they should be replaced in order. However, the numeric placeholders should be replaced based on their value, for instance: SELECT name,last FROM contact WHERE name=$2 and age=$1 Should NOT be replaced in order, because it will yield an incorrectly formed SQL command, which is not very useful for debugging. Fixes issue: #1249
This commit is contained in:
parent
f26fa242cc
commit
7f328975cd
25
logger.go
25
logger.go
|
@ -12,8 +12,9 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
defaultLogger = Logger{log.New(os.Stdout, "\r\n", 0)}
|
defaultLogger = Logger{log.New(os.Stdout, "\r\n", 0)}
|
||||||
sqlRegexp = regexp.MustCompile(`(\$\d+)|\?`)
|
sqlRegexp = regexp.MustCompile(`\?`)
|
||||||
|
numericPlaceHolderRegexp = regexp.MustCompile(`\$\d+`)
|
||||||
)
|
)
|
||||||
|
|
||||||
type logger interface {
|
type logger interface {
|
||||||
|
@ -71,11 +72,21 @@ func (logger Logger) Print(values ...interface{}) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var formattedValuesLength = len(formattedValues)
|
// differentiate between $n placeholders or else treat like ?
|
||||||
for index, value := range sqlRegexp.Split(values[3].(string), -1) {
|
if numericPlaceHolderRegexp.MatchString(values[3].(string)) {
|
||||||
sql += value
|
sql = values[3].(string)
|
||||||
if index < formattedValuesLength {
|
for index, value := range formattedValues {
|
||||||
sql += formattedValues[index]
|
placeholder := fmt.Sprintf(`\$%d`, index+1)
|
||||||
|
subre := regexp.MustCompile(placeholder)
|
||||||
|
sql = subre.ReplaceAllString(sql, value)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
var formattedValuesLength = len(formattedValues)
|
||||||
|
for index, value := range sqlRegexp.Split(values[3].(string), -1) {
|
||||||
|
sql += value
|
||||||
|
if index < formattedValuesLength {
|
||||||
|
sql += formattedValues[index]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue