gorm/callbacks/query.go

49 lines
1.1 KiB
Go
Raw Normal View History

2020-02-02 09:40:44 +03:00
package callbacks
2020-02-04 03:56:15 +03:00
import (
2020-02-23 16:22:35 +03:00
"reflect"
2020-02-04 03:56:15 +03:00
"github.com/jinzhu/gorm"
"github.com/jinzhu/gorm/clause"
)
2020-02-02 09:40:44 +03:00
func Query(db *gorm.DB) {
2020-02-22 15:57:29 +03:00
if db.Statement.SQL.String() == "" {
db.Statement.AddClauseIfNotExists(clause.Select{})
db.Statement.AddClauseIfNotExists(clause.From{})
db.Statement.Build("SELECT", "FROM", "WHERE", "GROUP BY", "ORDER BY", "LIMIT", "FOR")
}
2020-02-04 03:56:15 +03:00
2020-02-23 16:22:35 +03:00
_, err := db.DB.QueryContext(db.Context, db.Statement.SQL.String(), db.Statement.Vars...)
2020-02-23 14:41:29 +03:00
db.AddError(err)
2020-02-02 09:40:44 +03:00
}
func Preload(db *gorm.DB) {
}
func AfterQuery(db *gorm.DB) {
2020-02-23 16:22:35 +03:00
if db.Statement.Schema != nil && db.Statement.Schema.AfterFind {
callMethod := func(value interface{}) bool {
if db.Statement.Schema.AfterFind {
if i, ok := value.(gorm.AfterFindInterface); ok {
i.AfterFind(db)
return true
}
}
return false
}
if ok := callMethod(db.Statement.Dest); !ok {
switch db.Statement.ReflectValue.Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i <= db.Statement.ReflectValue.Len(); i++ {
callMethod(db.Statement.ReflectValue.Index(i).Interface())
}
case reflect.Struct:
callMethod(db.Statement.ReflectValue.Interface())
}
}
}
2020-02-02 09:40:44 +03:00
}