From c9165fe3cafc9a66e2513caae381e6864fa0a15b Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Fri, 18 Sep 2020 21:42:27 +0800 Subject: [PATCH] Don't panic when using unmatched vars in query, close #3488 --- clause/expression.go | 4 ++-- clause/expression_test.go | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/clause/expression.go b/clause/expression.go index 49924ef7..6a0dde8d 100644 --- a/clause/expression.go +++ b/clause/expression.go @@ -31,7 +31,7 @@ func (expr Expr) Build(builder Builder) { ) for _, v := range []byte(expr.SQL) { - if v == '?' { + if v == '?' && len(expr.Vars) > idx { if afterParenthesis { if _, ok := expr.Vars[idx].(driver.Valuer); ok { builder.AddVar(builder, expr.Vars[idx]) @@ -122,7 +122,7 @@ func (expr NamedExpr) Build(builder Builder) { } builder.WriteByte(v) - } else if v == '?' { + } else if v == '?' && len(expr.Vars) > idx { builder.AddVar(builder, expr.Vars[idx]) idx++ } else if inName { diff --git a/clause/expression_test.go b/clause/expression_test.go index 53d79c8f..19e30e6c 100644 --- a/clause/expression_test.go +++ b/clause/expression_test.go @@ -76,6 +76,10 @@ func TestNamedExpr(t *testing.T) { Vars: []interface{}{NamedArgument{Name1: "jinzhu", Name2: "jinzhu2"}}, Result: "@@test AND name1 = ? AND name2 = ? AND name3 = ? ?", ExpectedVars: []interface{}{"jinzhu", "jinzhu2", "jinzhu", nil}, + }, { + SQL: "create table ? (? ?, ? ?)", + Vars: []interface{}{}, + Result: "create table ? (? ?, ? ?)", }} for idx, result := range results {