Don't panic when using unmatched vars in query, close #3488

This commit is contained in:
Jinzhu 2020-09-18 21:42:27 +08:00
parent 072f1de83a
commit c9165fe3ca
2 changed files with 6 additions and 2 deletions

View File

@ -31,7 +31,7 @@ func (expr Expr) Build(builder Builder) {
) )
for _, v := range []byte(expr.SQL) { for _, v := range []byte(expr.SQL) {
if v == '?' { if v == '?' && len(expr.Vars) > idx {
if afterParenthesis { if afterParenthesis {
if _, ok := expr.Vars[idx].(driver.Valuer); ok { if _, ok := expr.Vars[idx].(driver.Valuer); ok {
builder.AddVar(builder, expr.Vars[idx]) builder.AddVar(builder, expr.Vars[idx])
@ -122,7 +122,7 @@ func (expr NamedExpr) Build(builder Builder) {
} }
builder.WriteByte(v) builder.WriteByte(v)
} else if v == '?' { } else if v == '?' && len(expr.Vars) > idx {
builder.AddVar(builder, expr.Vars[idx]) builder.AddVar(builder, expr.Vars[idx])
idx++ idx++
} else if inName { } else if inName {

View File

@ -76,6 +76,10 @@ func TestNamedExpr(t *testing.T) {
Vars: []interface{}{NamedArgument{Name1: "jinzhu", Name2: "jinzhu2"}}, Vars: []interface{}{NamedArgument{Name1: "jinzhu", Name2: "jinzhu2"}},
Result: "@@test AND name1 = ? AND name2 = ? AND name3 = ? ?", Result: "@@test AND name1 = ? AND name2 = ? AND name3 = ? ?",
ExpectedVars: []interface{}{"jinzhu", "jinzhu2", "jinzhu", nil}, ExpectedVars: []interface{}{"jinzhu", "jinzhu2", "jinzhu", nil},
}, {
SQL: "create table ? (? ?, ? ?)",
Vars: []interface{}{},
Result: "create table ? (? ?, ? ?)",
}} }}
for idx, result := range results { for idx, result := range results {