diff --git a/clause/expression.go b/clause/expression.go index 2bdd4a30..a177c5d8 100644 --- a/clause/expression.go +++ b/clause/expression.go @@ -173,7 +173,12 @@ func (expr NamedExpr) Build(builder Builder) { } if inName { - builder.AddVar(builder, namedMap[string(name)]) + if nv, ok := namedMap[string(name)]; ok { + builder.AddVar(builder, nv) + } else { + builder.WriteByte('@') + builder.WriteString(string(name)) + } } } diff --git a/clause/expression_test.go b/clause/expression_test.go index 1c8217ed..0ccd0771 100644 --- a/clause/expression_test.go +++ b/clause/expression_test.go @@ -60,6 +60,11 @@ func TestNamedExpr(t *testing.T) { Vars: []interface{}{sql.Named("name", "jinzhu")}, Result: "name1 = ? AND name2 = ?", ExpectedVars: []interface{}{"jinzhu", "jinzhu"}, + }, { + SQL: "name1 = @name AND name2 = @@name", + Vars: []interface{}{map[string]interface{}{"name": "jinzhu"}}, + Result: "name1 = ? AND name2 = @@name", + ExpectedVars: []interface{}{"jinzhu"}, }, { SQL: "name1 = @name1 AND name2 = @name2 AND name3 = @name1", Vars: []interface{}{sql.Named("name1", "jinzhu"), sql.Named("name2", "jinzhu2")}, @@ -73,13 +78,13 @@ func TestNamedExpr(t *testing.T) { }, { SQL: "@@test AND name1 = @name1 AND name2 = @name2 AND name3 = @name1 @notexist", Vars: []interface{}{sql.Named("name1", "jinzhu"), sql.Named("name2", "jinzhu2")}, - Result: "@@test AND name1 = ? AND name2 = ? AND name3 = ? ?", - ExpectedVars: []interface{}{"jinzhu", "jinzhu2", "jinzhu", nil}, + Result: "@@test AND name1 = ? AND name2 = ? AND name3 = ? @notexist", + ExpectedVars: []interface{}{"jinzhu", "jinzhu2", "jinzhu"}, }, { - SQL: "@@test AND name1 = @Name1 AND name2 = @Name2 AND name3 = @Name1 @Notexist", + SQL: "@@test AND name1 = @Name1 AND name2 = @Name2 AND name3 = @Name1 @notexist", Vars: []interface{}{NamedArgument{Name1: "jinzhu", Base: Base{Name2: "jinzhu2"}}}, - Result: "@@test AND name1 = ? AND name2 = ? AND name3 = ? ?", - ExpectedVars: []interface{}{"jinzhu", "jinzhu2", "jinzhu", nil}, + Result: "@@test AND name1 = ? AND name2 = ? AND name3 = ? @notexist", + ExpectedVars: []interface{}{"jinzhu", "jinzhu2", "jinzhu"}, }, { SQL: "create table ? (? ?, ? ?)", Vars: []interface{}{},