Fix Select with AS, close #3581, #3567

This commit is contained in:
Jinzhu 2020-10-09 11:52:12 +08:00
parent dbc6b34dce
commit 7faf1ca80f
3 changed files with 12 additions and 2 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{v}
for _, arg := range args {
switch arg := arg.(type) {

View File

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

View File

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