From 514915f4decf02573769a854a2a90034cc9757b8 Mon Sep 17 00:00:00 2001 From: laixintao Date: Thu, 8 Oct 2020 00:37:37 +0800 Subject: [PATCH] bugfix: Select can't handle `AS` statement. close: https://github.com/go-gorm/gorm/issues/3567 Co-authored-by: Aoi-hosizora --- chainable_api.go | 2 +- tests/query_test.go | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/chainable_api.go b/chainable_api.go index ae2ac4f1..5104492d 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{strings.Join(fields, " ")} for _, arg := range args { switch arg := arg.(type) { diff --git a/tests/query_test.go b/tests/query_test.go index 431ccce2..f2dbdf3c 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 resultAlias User + DB.Where("name = ?", user.Name).Select("name as name").Find(&resultAlias) + if resultAlias.ID != 0 { + t.Errorf("Should not have ID because only selected name, %+v", resultAlias.ID) + } + + if user.Name != resultAlias.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()) {