From a870486c4f967d732b2786f320886b0230053c18 Mon Sep 17 00:00:00 2001 From: Walter Scheper Date: Mon, 9 Aug 2021 01:14:23 -0400 Subject: [PATCH] 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. --- chainable_api.go | 14 ++++++++------ tests/query_test.go | 12 +++++++++++- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/chainable_api.go b/chainable_api.go index e17d9bb2..d5a0907d 100644 --- a/chainable_api.go +++ b/chainable_api.go @@ -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 } diff --git a/tests/query_test.go b/tests/query_test.go index 34999337..36046aee 100644 --- a/tests/query_test.go +++ b/tests/query_test.go @@ -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()) }