From 0ec10d4907762e94ac942903670184a93e7ed456 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Mon, 14 Sep 2020 12:37:16 +0800 Subject: [PATCH] Fix format SQL log, close #3465 --- logger/sql.go | 16 ++++++++++++++-- logger/sql_test.go | 6 ++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/logger/sql.go b/logger/sql.go index 096b9407..69a6b10e 100644 --- a/logger/sql.go +++ b/logger/sql.go @@ -96,9 +96,21 @@ func ExplainSQL(sql string, numericPlaceholder *regexp.Regexp, escaper string, a } if numericPlaceholder == nil { - for _, v := range vars { - sql = strings.Replace(sql, "?", v, 1) + var idx int + var newSQL strings.Builder + + for _, v := range []byte(sql) { + if v == '?' { + if len(vars) > idx { + newSQL.WriteString(vars[idx]) + idx++ + continue + } + } + newSQL.WriteByte(v) } + + sql = newSQL.String() } else { sql = numericPlaceholder.ReplaceAllString(sql, "$$$1$$") for idx, v := range vars { diff --git a/logger/sql_test.go b/logger/sql_test.go index 180570b8..b78f761c 100644 --- a/logger/sql_test.go +++ b/logger/sql_test.go @@ -29,6 +29,12 @@ func TestExplainSQL(t *testing.T) { Vars: []interface{}{"jinzhu", 1, 999.99, true, []byte("12345"), tt, &tt, nil, "w@g.\"com", myrole, pwd}, Result: `create table users (name, age, height, actived, bytes, create_at, update_at, deleted_at, email, role, pass) values ("jinzhu", 1, 999.990000, true, "12345", "2020-02-23 11:10:10", "2020-02-23 11:10:10", NULL, "w@g.\"com", "admin", "pass")`, }, + { + SQL: "create table users (name, age, height, actived, bytes, create_at, update_at, deleted_at, email, role, pass) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + NumericRegexp: nil, + Vars: []interface{}{"jinzhu?", 1, 999.99, true, []byte("12345"), tt, &tt, nil, "w@g.\"com", myrole, pwd}, + Result: `create table users (name, age, height, actived, bytes, create_at, update_at, deleted_at, email, role, pass) values ("jinzhu?", 1, 999.990000, true, "12345", "2020-02-23 11:10:10", "2020-02-23 11:10:10", NULL, "w@g.\"com", "admin", "pass")`, + }, { SQL: "create table users (name, age, height, actived, bytes, create_at, update_at, deleted_at, email, role, pass) values (@p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10, @p11)", NumericRegexp: regexp.MustCompile(`@p(\d+)`),