From 496db1f13e51ef20db2a68f6591047df6b20e292 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Mon, 31 Aug 2020 15:45:56 +0800 Subject: [PATCH] Fix named argument with multiple line SQL, fix #3336 --- clause/expression.go | 2 +- prepare_stmt.go | 2 +- tests/go.mod | 2 ++ tests/named_argument_test.go | 14 +++++++++++++- 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/clause/expression.go b/clause/expression.go index 4d5e328b..3b914e68 100644 --- a/clause/expression.go +++ b/clause/expression.go @@ -94,7 +94,7 @@ func (expr NamedExpr) Build(builder Builder) { if v == '@' && !inName { inName = true name = []byte{} - } else if v == ' ' || v == ',' || v == ')' || v == '"' || v == '\'' || v == '`' { + } else if v == ' ' || v == ',' || v == ')' || v == '"' || v == '\'' || v == '`' || v == '\n' { if inName { if nv, ok := namedMap[string(name)]; ok { builder.AddVar(builder, nv) diff --git a/prepare_stmt.go b/prepare_stmt.go index 7c80bafe..de7e2a26 100644 --- a/prepare_stmt.go +++ b/prepare_stmt.go @@ -116,7 +116,7 @@ func (tx *PreparedStmtTX) ExecContext(ctx context.Context, query string, args .. func (tx *PreparedStmtTX) QueryContext(ctx context.Context, query string, args ...interface{}) (rows *sql.Rows, err error) { stmt, err := tx.PreparedStmtDB.prepare(ctx, query) if err == nil { - rows, err = tx.Tx.StmtContext(ctx, stmt).QueryContext(ctx, args...) + rows, err = tx.Tx.Stmt(stmt).QueryContext(ctx, args...) if err != nil { tx.PreparedStmtDB.Mux.Lock() stmt.Close() diff --git a/tests/go.mod b/tests/go.mod index c09747ab..f3dd6dbc 100644 --- a/tests/go.mod +++ b/tests/go.mod @@ -14,3 +14,5 @@ require ( ) replace gorm.io/gorm => ../ + +replace github.com/jackc/pgx/v4 => github.com/jinzhu/pgx/v4 v4.8.2 diff --git a/tests/named_argument_test.go b/tests/named_argument_test.go index 56fad5f4..d0a6f915 100644 --- a/tests/named_argument_test.go +++ b/tests/named_argument_test.go @@ -48,10 +48,22 @@ func TestNamedArg(t *testing.T) { t.Errorf("failed to update with named arg") } + namedUser.Name1 = "jinzhu-new" + namedUser.Name2 = "jinzhu-new2" + namedUser.Name3 = "jinzhu-new" + var result5 NamedUser if err := DB.Raw("SELECT * FROM named_users WHERE (name1 = @name AND name3 = @name) AND name2 = @name2", map[string]interface{}{"name": "jinzhu-new", "name2": "jinzhu-new2"}).Find(&result5).Error; err != nil { t.Errorf("failed to update with named arg") } - AssertEqual(t, result4, namedUser) + AssertEqual(t, result5, namedUser) + + var result6 NamedUser + if err := DB.Raw(`SELECT * FROM named_users WHERE (name1 = @name + AND name3 = @name) AND name2 = @name2`, map[string]interface{}{"name": "jinzhu-new", "name2": "jinzhu-new2"}).Find(&result6).Error; err != nil { + t.Errorf("failed to update with named arg") + } + + AssertEqual(t, result6, namedUser) }