Do not emit ORDER BY for empty values

This restores the behavior from gorm v1, where calling `DB.Order` with
an empty string, nil, or any unexpected type is a no-op.
This commit is contained in:
Walter Scheper 2021-08-06 14:32:44 -04:00
parent 9e5a4e30b4
commit 8f733a6559
2 changed files with 19 additions and 7 deletions

View File

@ -209,13 +209,15 @@ func (db *DB) Order(value interface{}) (tx *DB) {
tx.Statement.AddClause(clause.OrderBy{
Columns: []clause.OrderByColumn{v},
})
default:
case string:
if v != "" {
tx.Statement.AddClause(clause.OrderBy{
Columns: []clause.OrderByColumn{{
Column: clause.Column{Name: fmt.Sprint(value), Raw: true},
Column: clause.Column{Name: v, Raw: true},
}},
})
}
}
return
}

View File

@ -842,7 +842,17 @@ func TestSearchWithEmptyChain(t *testing.T) {
func TestOrder(t *testing.T) {
dryDB := DB.Session(&gorm.Session{DryRun: true})
result := dryDB.Order("age desc, name").Find(&User{})
result := dryDB.Order("").Find(&User{})
if !regexp.MustCompile("SELECT \\* FROM .*users.* IS NULL$").MatchString(result.Statement.SQL.String()) {
t.Fatalf("Build Order condition, but got %v", result.Statement.SQL.String())
}
result = dryDB.Order(nil).Find(&User{})
if !regexp.MustCompile("SELECT \\* FROM .*users.* IS NULL$").MatchString(result.Statement.SQL.String()) {
t.Fatalf("Build Order condition, but got %v", result.Statement.SQL.String())
}
result = dryDB.Order("age desc, name").Find(&User{})
if !regexp.MustCompile("SELECT \\* FROM .*users.* ORDER BY age desc, name").MatchString(result.Statement.SQL.String()) {
t.Fatalf("Build Order condition, but got %v", result.Statement.SQL.String())
}