bugfix: Select can't handle AS statement.

close: https://github.com/go-gorm/gorm/issues/3567

Co-authored-by: Aoi-hosizora <aoihosizora@hotmail.com>
This commit is contained in:
laixintao 2020-10-08 00:37:37 +08:00
parent dbc6b34dce
commit 514915f4de
No known key found for this signature in database
GPG Key ID: 4E7314AC219D7FE4
2 changed files with 11 additions and 1 deletions

View File

@ -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) {

View File

@ -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()) {