| 1 |
package callbacks |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"reflect" |
| 6 |
"strings" |
| 7 |
|
| 8 |
"gorm.io/gorm" |
| 9 |
"gorm.io/gorm/clause" |
| 10 |
"gorm.io/gorm/schema" |
| 11 |
"gorm.io/gorm/utils" |
| 12 |
) |
| 13 |
|
| 14 |
func Query(db *gorm.DB) { |
| 15 |
if db.Error == nil { |
| 16 |
BuildQuerySQL(db) |
| 17 |
|
| 18 |
if !db.DryRun && db.Error == nil { |
| 19 |
rows, err := db.Statement.ConnPool.QueryContext(db.Statement.Context, db.Statement.SQL.String(), db.Statement.Vars...) |
| 20 |
if err != nil { |
| 21 |
db.AddError(err) |
| 22 |
return |
| 23 |
} |
| 24 |
defer func() { |
| 25 |
db.AddError(rows.Close()) |
| 26 |
}() |
| 27 |
gorm.Scan(rows, db, 0) |
| 28 |
|
| 29 |
if db.Statement.Result != nil { |
| 30 |
db.Statement.Result.RowsAffected = db.RowsAffected |
| 31 |
} |
| 32 |
} |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
func BuildQuerySQL(db *gorm.DB) { |
| 37 |
if db.Statement.Schema != nil { |
| 38 |
for _, c := range db.Statement.Schema.QueryClauses { |
| 39 |
db.Statement.AddClause(c) |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
if db.Statement.SQL.Len() == 0 { |
| 44 |
db.Statement.SQL.Grow(100) |
| 45 |
clauseSelect := clause.Select{Distinct: db.Statement.Distinct} |
| 46 |
|
| 47 |
if db.Statement.ReflectValue.Kind() == reflect.Struct && db.Statement.ReflectValue.Type() == db.Statement.Schema.ModelType { |
| 48 |
var conds []clause.Expression |
| 49 |
for _, primaryField := range db.Statement.Schema.PrimaryFields { |
| 50 |
if v, isZero := primaryField.ValueOf(db.Statement.Context, db.Statement.ReflectValue); !isZero { |
| 51 |
conds = append(conds, clause.Eq{Column: clause.Column{Table: db.Statement.Table, Name: primaryField.DBName}, Value: v}) |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
if len(conds) > 0 { |
| 56 |
db.Statement.AddClause(clause.Where{Exprs: conds}) |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
if len(db.Statement.Selects) > 0 { |
| 61 |
clauseSelect.Columns = make([]clause.Column, len(db.Statement.Selects)) |
| 62 |
for idx, name := range db.Statement.Selects { |
| 63 |
if db.Statement.Schema == nil { |
| 64 |
clauseSelect.Columns[idx] = clause.Column{Name: name, Raw: true} |
| 65 |
} else if f := db.Statement.Schema.LookUpField(name); f != nil { |
| 66 |
clauseSelect.Columns[idx] = clause.Column{Name: f.DBName} |
| 67 |
} else { |
| 68 |
clauseSelect.Columns[idx] = clause.Column{Name: name, Raw: true} |
| 69 |
} |
| 70 |
} |
| 71 |
} else if db.Statement.Schema != nil && len(db.Statement.Omits) > 0 { |
| 72 |
selectColumns, _ := db.Statement.SelectAndOmitColumns(false, false) |
| 73 |
clauseSelect.Columns = make([]clause.Column, 0, len(db.Statement.Schema.DBNames)) |
| 74 |
for _, dbName := range db.Statement.Schema.DBNames { |
| 75 |
if v, ok := selectColumns[dbName]; (ok && v) || !ok { |
| 76 |
clauseSelect.Columns = append(clauseSelect.Columns, clause.Column{Table: db.Statement.Table, Name: dbName}) |
| 77 |
} |
| 78 |
} |
| 79 |
} else if db.Statement.Schema != nil && db.Statement.ReflectValue.IsValid() { |
| 80 |
queryFields := db.QueryFields |
| 81 |
if !queryFields { |
| 82 |
switch db.Statement.ReflectValue.Kind() { |
| 83 |
case reflect.Struct: |
| 84 |
queryFields = db.Statement.ReflectValue.Type() != db.Statement.Schema.ModelType |
| 85 |
case reflect.Slice: |
| 86 |
queryFields = db.Statement.ReflectValue.Type().Elem() != db.Statement.Schema.ModelType |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
if queryFields { |
| 91 |
stmt := gorm.Statement{DB: db} |
| 92 |
// smaller struct |
| 93 |
if err := stmt.Parse(db.Statement.Dest); err == nil && (db.QueryFields || stmt.Schema.ModelType != db.Statement.Schema.ModelType) { |
| 94 |
clauseSelect.Columns = make([]clause.Column, len(stmt.Schema.DBNames)) |
| 95 |
|
| 96 |
for idx, dbName := range stmt.Schema.DBNames { |
| 97 |
clauseSelect.Columns[idx] = clause.Column{Table: db.Statement.Table, Name: dbName} |
| 98 |
} |
| 99 |
} |
| 100 |
} |
| 101 |
} |
| 102 |
|
| 103 |
// inline joins |
| 104 |
fromClause := clause.From{} |
| 105 |
if v, ok := db.Statement.Clauses["FROM"].Expression.(clause.From); ok { |
| 106 |
fromClause = v |
| 107 |
} |
| 108 |
|
| 109 |
if len(db.Statement.Joins) != 0 || len(fromClause.Joins) != 0 { |
| 110 |
if len(db.Statement.Selects) == 0 && len(db.Statement.Omits) == 0 && db.Statement.Schema != nil { |
| 111 |
clauseSelect.Columns = make([]clause.Column, len(db.Statement.Schema.DBNames)) |
| 112 |
for idx, dbName := range db.Statement.Schema.DBNames { |
| 113 |
clauseSelect.Columns[idx] = clause.Column{Table: db.Statement.Table, Name: dbName} |
| 114 |
} |
| 115 |
} |
| 116 |
|
| 117 |
specifiedRelationsName := map[string]string{clause.CurrentTable: clause.CurrentTable} |
| 118 |
for _, join := range db.Statement.Joins { |
| 119 |
if db.Statement.Schema != nil { |
| 120 |
var isRelations bool // is relations or raw sql |
| 121 |
var relations []*schema.Relationship |
| 122 |
relation, ok := db.Statement.Schema.Relationships.Relations[join.Name] |
| 123 |
if ok { |
| 124 |
isRelations = true |
| 125 |
relations = append(relations, relation) |
| 126 |
} else { |
| 127 |
// handle nested join like "Manager.Company" |
| 128 |
nestedJoinNames := strings.Split(join.Name, ".") |
| 129 |
if len(nestedJoinNames) > 1 { |
| 130 |
isNestedJoin := true |
| 131 |
guessNestedRelations := make([]*schema.Relationship, 0, len(nestedJoinNames)) |
| 132 |
currentRelations := db.Statement.Schema.Relationships.Relations |
| 133 |
for _, relname := range nestedJoinNames { |
| 134 |
// incomplete match, only treated as raw sql |
| 135 |
if relation, ok = currentRelations[relname]; ok { |
| 136 |
guessNestedRelations = append(guessNestedRelations, relation) |
| 137 |
currentRelations = relation.FieldSchema.Relationships.Relations |
| 138 |
} else { |
| 139 |
isNestedJoin = false |
| 140 |
break |
| 141 |
} |
| 142 |
} |
| 143 |
|
| 144 |
if isNestedJoin { |
| 145 |
isRelations = true |
| 146 |
relations = guessNestedRelations |
| 147 |
} |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
if isRelations { |
| 152 |
genJoinClause := func(joinType clause.JoinType, tableAliasName string, parentTableName string, relation *schema.Relationship) clause.Join { |
| 153 |
columnStmt := gorm.Statement{ |
| 154 |
Table: tableAliasName, DB: db, Schema: relation.FieldSchema, |
| 155 |
Selects: join.Selects, Omits: join.Omits, |
| 156 |
} |
| 157 |
|
| 158 |
selectColumns, restricted := columnStmt.SelectAndOmitColumns(false, false) |
| 159 |
for _, s := range relation.FieldSchema.DBNames { |
| 160 |
if v, ok := selectColumns[s]; (ok && v) || (!ok && !restricted) { |
| 161 |
clauseSelect.Columns = append(clauseSelect.Columns, clause.Column{ |
| 162 |
Table: tableAliasName, |
| 163 |
Name: s, |
| 164 |
Alias: utils.NestedRelationName(tableAliasName, s), |
| 165 |
}) |
| 166 |
} |
| 167 |
} |
| 168 |
|
| 169 |
if join.Expression != nil { |
| 170 |
return clause.Join{ |
| 171 |
Type: join.JoinType, |
| 172 |
Expression: join.Expression, |
| 173 |
} |
| 174 |
} |
| 175 |
|
| 176 |
exprs := make([]clause.Expression, len(relation.References)) |
| 177 |
for idx, ref := range relation.References { |
| 178 |
if ref.OwnPrimaryKey { |
| 179 |
exprs[idx] = clause.Eq{ |
| 180 |
Column: clause.Column{Table: parentTableName, Name: ref.PrimaryKey.DBName}, |
| 181 |
Value: clause.Column{Table: tableAliasName, Name: ref.ForeignKey.DBName}, |
| 182 |
} |
| 183 |
} else { |
| 184 |
if ref.PrimaryValue == "" { |
| 185 |
exprs[idx] = clause.Eq{ |
| 186 |
Column: clause.Column{Table: parentTableName, Name: ref.ForeignKey.DBName}, |
| 187 |
Value: clause.Column{Table: tableAliasName, Name: ref.PrimaryKey.DBName}, |
| 188 |
} |
| 189 |
} else { |
| 190 |
exprs[idx] = clause.Eq{ |
| 191 |
Column: clause.Column{Table: tableAliasName, Name: ref.ForeignKey.DBName}, |
| 192 |
Value: ref.PrimaryValue, |
| 193 |
} |
| 194 |
} |
| 195 |
} |
| 196 |
} |
| 197 |
|
| 198 |
{ |
| 199 |
onStmt := gorm.Statement{Table: tableAliasName, DB: db, Clauses: map[string]clause.Clause{}} |
| 200 |
for _, c := range relation.FieldSchema.QueryClauses { |
| 201 |
onStmt.AddClause(c) |
| 202 |
} |
| 203 |
|
| 204 |
if join.On != nil { |
| 205 |
onStmt.AddClause(join.On) |
| 206 |
} |
| 207 |
|
| 208 |
if cs, ok := onStmt.Clauses["WHERE"]; ok { |
| 209 |
if where, ok := cs.Expression.(clause.Where); ok { |
| 210 |
where.Build(&onStmt) |
| 211 |
|
| 212 |
if onSQL := onStmt.SQL.String(); onSQL != "" { |
| 213 |
vars := onStmt.Vars |
| 214 |
for idx, v := range vars { |
| 215 |
bindvar := strings.Builder{} |
| 216 |
onStmt.Vars = vars[0 : idx+1] |
| 217 |
db.Dialector.BindVarTo(&bindvar, &onStmt, v) |
| 218 |
onSQL = strings.Replace(onSQL, bindvar.String(), "?", 1) |
| 219 |
} |
| 220 |
|
| 221 |
exprs = append(exprs, clause.Expr{SQL: onSQL, Vars: vars}) |
| 222 |
} |
| 223 |
} |
| 224 |
} |
| 225 |
} |
| 226 |
|
| 227 |
return clause.Join{ |
| 228 |
Type: joinType, |
| 229 |
Table: clause.Table{Name: relation.FieldSchema.Table, Alias: tableAliasName}, |
| 230 |
ON: clause.Where{Exprs: exprs}, |
| 231 |
} |
| 232 |
} |
| 233 |
|
| 234 |
parentTableName := clause.CurrentTable |
| 235 |
for idx, rel := range relations { |
| 236 |
// joins table alias like "Manager, Company, Manager__Company" |
| 237 |
curAliasName := rel.Name |
| 238 |
if parentTableName != clause.CurrentTable { |
| 239 |
curAliasName = utils.NestedRelationName(parentTableName, curAliasName) |
| 240 |
} |
| 241 |
|
| 242 |
if _, ok := specifiedRelationsName[curAliasName]; !ok { |
| 243 |
aliasName := curAliasName |
| 244 |
if idx == len(relations)-1 && join.Alias != "" { |
| 245 |
aliasName = join.Alias |
| 246 |
} |
| 247 |
|
| 248 |
fromClause.Joins = append(fromClause.Joins, genJoinClause(join.JoinType, aliasName, specifiedRelationsName[parentTableName], rel)) |
| 249 |
specifiedRelationsName[curAliasName] = aliasName |
| 250 |
} |
| 251 |
|
| 252 |
parentTableName = curAliasName |
| 253 |
} |
| 254 |
} else { |
| 255 |
fromClause.Joins = append(fromClause.Joins, clause.Join{ |
| 256 |
Expression: clause.NamedExpr{SQL: join.Name, Vars: join.Conds}, |
| 257 |
}) |
| 258 |
} |
| 259 |
} else { |
| 260 |
fromClause.Joins = append(fromClause.Joins, clause.Join{ |
| 261 |
Expression: clause.NamedExpr{SQL: join.Name, Vars: join.Conds}, |
| 262 |
}) |
| 263 |
} |
| 264 |
} |
| 265 |
|
| 266 |
db.Statement.AddClause(fromClause) |
| 267 |
} else { |
| 268 |
db.Statement.AddClauseIfNotExists(clause.From{}) |
| 269 |
} |
| 270 |
|
| 271 |
db.Statement.AddClauseIfNotExists(clauseSelect) |
| 272 |
|
| 273 |
db.Statement.Build(db.Statement.BuildClauses...) |
| 274 |
} |
| 275 |
} |
| 276 |
|
| 277 |
func Preload(db *gorm.DB) { |
| 278 |
if db.Error == nil && len(db.Statement.Preloads) > 0 { |
| 279 |
if db.Statement.Schema == nil { |
| 280 |
db.AddError(fmt.Errorf("%w when using preload", gorm.ErrModelValueRequired)) |
| 281 |
return |
| 282 |
} |
| 283 |
|
| 284 |
joins := make([]string, 0, len(db.Statement.Joins)) |
| 285 |
for _, join := range db.Statement.Joins { |
| 286 |
joins = append(joins, join.Name) |
| 287 |
} |
| 288 |
|
| 289 |
tx := preloadDB(db, db.Statement.ReflectValue, db.Statement.Dest) |
| 290 |
if tx.Error != nil { |
| 291 |
return |
| 292 |
} |
| 293 |
|
| 294 |
db.AddError(preloadEntryPoint(tx, joins, &tx.Statement.Schema.Relationships, db.Statement.Preloads, db.Statement.Preloads[clause.Associations])) |
| 295 |
} |
| 296 |
} |
| 297 |
|
| 298 |
func AfterQuery(db *gorm.DB) { |
| 299 |
// clear the joins after query because preload need it |
| 300 |
if v, ok := db.Statement.Clauses["FROM"].Expression.(clause.From); ok { |
| 301 |
fromClause := db.Statement.Clauses["FROM"] |
| 302 |
fromClause.Expression = clause.From{Tables: v.Tables, Joins: utils.RTrimSlice(v.Joins, len(db.Statement.Joins))} // keep the original From Joins |
| 303 |
db.Statement.Clauses["FROM"] = fromClause |
| 304 |
} |
| 305 |
if db.Error == nil && db.Statement.Schema != nil && !db.Statement.SkipHooks && db.Statement.Schema.AfterFind && db.RowsAffected > 0 { |
| 306 |
callMethod(db, func(value interface{}, tx *gorm.DB) bool { |
| 307 |
if i, ok := value.(AfterFindInterface); ok { |
| 308 |
db.AddError(i.AfterFind(tx)) |
| 309 |
return true |
| 310 |
} |
| 311 |
return false |
| 312 |
}) |
| 313 |
} |
| 314 |
} |