Do not emit ORDER BY for empty values (#4592)

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-09 01:14:23 -04:00 committed by GitHub
parent 9e5a4e30b4
commit a870486c4f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 7 deletions

View File

@ -209,12 +209,14 @@ func (db *DB) Order(value interface{}) (tx *DB) {
tx.Statement.AddClause(clause.OrderBy{
Columns: []clause.OrderByColumn{v},
})
default:
tx.Statement.AddClause(clause.OrderBy{
Columns: []clause.OrderByColumn{{
Column: clause.Column{Name: fmt.Sprint(value), Raw: true},
}},
})
case string:
if v != "" {
tx.Statement.AddClause(clause.OrderBy{
Columns: []clause.OrderByColumn{{
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())
}