Fix named argument with multiple line SQL, fix #3336

This commit is contained in:
Jinzhu 2020-08-31 15:45:56 +08:00
parent 9b0ad4730f
commit 496db1f13e
4 changed files with 17 additions and 3 deletions

View File

@ -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)

View File

@ -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()

View File

@ -14,3 +14,5 @@ require (
)
replace gorm.io/gorm => ../
replace github.com/jackc/pgx/v4 => github.com/jinzhu/pgx/v4 v4.8.2

View File

@ -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)
}