Refactor QueryFields Option

This commit is contained in:
Jinzhu 2020-11-20 15:44:39 +08:00
parent 47ffd0bef4
commit dec8748512
1 changed files with 7 additions and 18 deletions

View File

@ -72,31 +72,20 @@ func BuildQuerySQL(db *gorm.DB) {
} }
} }
} else if db.Statement.Schema != nil && db.Statement.ReflectValue.IsValid() { } else if db.Statement.Schema != nil && db.Statement.ReflectValue.IsValid() {
if !db.QueryFields { queryFields := db.QueryFields
smallerStruct := false if !queryFields {
switch db.Statement.ReflectValue.Kind() { switch db.Statement.ReflectValue.Kind() {
case reflect.Struct: case reflect.Struct:
smallerStruct = db.Statement.ReflectValue.Type() != db.Statement.Schema.ModelType queryFields = db.Statement.ReflectValue.Type() != db.Statement.Schema.ModelType
case reflect.Slice: case reflect.Slice:
smallerStruct = db.Statement.ReflectValue.Type().Elem() != db.Statement.Schema.ModelType queryFields = db.Statement.ReflectValue.Type().Elem() != db.Statement.Schema.ModelType
} }
}
if smallerStruct { if queryFields {
stmt := gorm.Statement{DB: db}
// smaller struct
if err := stmt.Parse(db.Statement.Dest); err == nil && stmt.Schema.ModelType != db.Statement.Schema.ModelType {
clauseSelect.Columns = make([]clause.Column, len(stmt.Schema.DBNames))
for idx, dbName := range stmt.Schema.DBNames {
clauseSelect.Columns[idx] = clause.Column{Name: dbName}
}
}
}
} else {
// Execute the query with all the fields of the table
stmt := gorm.Statement{DB: db} stmt := gorm.Statement{DB: db}
// smaller struct // smaller struct
if err := stmt.Parse(db.Statement.Dest); err == nil { if err := stmt.Parse(db.Statement.Dest); err == nil && (db.QueryFields || stmt.Schema.ModelType != db.Statement.Schema.ModelType) {
clauseSelect.Columns = make([]clause.Column, len(stmt.Schema.DBNames)) clauseSelect.Columns = make([]clause.Column, len(stmt.Schema.DBNames))
for idx, dbName := range stmt.Schema.DBNames { for idx, dbName := range stmt.Schema.DBNames {