Fix error when chaining empty where conditions

This commit is contained in:
Constantin Schomburg 2015-01-04 13:47:25 +01:00
parent 0219fb1cc0
commit 045b4d6d2a
2 changed files with 28 additions and 3 deletions

View File

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

View File

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