From 7faf1ca80fa00e0737f0c2efb2c57fb036adebdf Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Fri, 9 Oct 2020 11:52:12 +0800 Subject: [PATCH] Fix Select with AS, close #3581, #3567 --- chainable_api.go | 2 +- tests/go.mod | 2 +- tests/query_test.go | 10 ++++++++++ 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/chainable_api.go b/chainable_api.go index ae2ac4f1..c3a02d20 100644 --- a/chainable_api.go +++ b/chainable_api.go @@ -97,7 +97,7 @@ func (db *DB) Select(query interface{}, args ...interface{}) (tx *DB) { // normal field names if len(fields) == 1 || (len(fields) == 3 && strings.ToUpper(fields[1]) == "AS") { - tx.Statement.Selects = fields + tx.Statement.Selects = []string{v} for _, arg := range args { switch arg := arg.(type) { diff --git a/tests/go.mod b/tests/go.mod index cbafcd7e..9b36f1ed 100644 --- a/tests/go.mod +++ b/tests/go.mod @@ -6,7 +6,7 @@ require ( github.com/google/uuid v1.1.1 github.com/jinzhu/now v1.1.1 github.com/lib/pq v1.6.0 - gorm.io/driver/mysql v1.0.1 + gorm.io/driver/mysql v1.0.2 gorm.io/driver/postgres v1.0.2 gorm.io/driver/sqlite v1.1.3 gorm.io/driver/sqlserver v1.0.4 diff --git a/tests/query_test.go b/tests/query_test.go index 431ccce2..bb9aa26d 100644 --- a/tests/query_test.go +++ b/tests/query_test.go @@ -475,6 +475,16 @@ func TestSelect(t *testing.T) { t.Errorf("Should have user Name when selected it") } + var result2 User + DB.Where("name = ?", user.Name).Select("name as name").Find(&result2) + if result2.ID != 0 { + t.Errorf("Should not have ID because only selected name, %+v", result2.ID) + } + + if user.Name != result2.Name { + t.Errorf("Should have user Name when selected it") + } + dryDB := DB.Session(&gorm.Session{DryRun: true}) r := dryDB.Select("name", "age").Find(&User{}) if !regexp.MustCompile("SELECT .*name.*,.*age.* FROM .*users.*").MatchString(r.Statement.SQL.String()) {