From 045b4d6d2aec55681bfea250c69287884f36a5e8 Mon Sep 17 00:00:00 2001 From: Constantin Schomburg Date: Sun, 4 Jan 2015 13:47:25 +0100 Subject: [PATCH] Fix error when chaining empty where conditions --- query_test.go | 19 +++++++++++++++++++ scope_private.go | 12 +++++++++--- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/query_test.go b/query_test.go index a7e3c325..be309ed7 100644 --- a/query_test.go +++ b/query_test.go @@ -229,6 +229,25 @@ func TestSearchWithMap(t *testing.T) { } } +func TestSearchWithEmptyChain(t *testing.T) { + user1 := User{Name: "ChainSearchUser1", Age: 1, Birthday: now.MustParse("2000-1-1")} + user2 := User{Name: "ChainearchUser2", Age: 10, Birthday: now.MustParse("2010-1-1")} + user3 := User{Name: "ChainearchUser3", Age: 20, Birthday: now.MustParse("2020-1-1")} + DB.Save(&user1).Save(&user2).Save(&user3) + + if DB.Where("").Where("").First(&User{}).Error != nil { + t.Errorf("Should not raise any error if searching with empty strings") + } + + if DB.Where(&User{}).Where("name = ?", user1.Name).First(&User{}).Error != nil { + t.Errorf("Should not raise any error if searching with empty struct") + } + + if DB.Where(map[string]interface{}{}).Where("name = ?", user1.Name).First(&User{}).Error != nil { + t.Errorf("Should not raise any error if searching with empty map") + } +} + func TestSelect(t *testing.T) { user1 := User{Name: "SelectUser1"} DB.Save(&user1) diff --git a/scope_private.go b/scope_private.go index c2a1428e..a109b5ae 100644 --- a/scope_private.go +++ b/scope_private.go @@ -176,15 +176,21 @@ func (scope *Scope) whereSql() (sql string) { } for _, clause := range scope.Search.WhereConditions { - andConditions = append(andConditions, scope.buildWhereCondition(clause)) + if sql := scope.buildWhereCondition(clause); sql != "" { + andConditions = append(andConditions, sql) + } } for _, clause := range scope.Search.OrConditions { - orConditions = append(orConditions, scope.buildWhereCondition(clause)) + if sql := scope.buildWhereCondition(clause); sql != "" { + orConditions = append(orConditions, sql) + } } for _, clause := range scope.Search.NotConditions { - andConditions = append(andConditions, scope.buildNotCondition(clause)) + if sql := scope.buildNotCondition(clause); sql != "" { + andConditions = append(andConditions, sql) + } } orSql := strings.Join(orConditions, " OR ")