| 1 |
package gorm |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"database/sql" |
| 6 |
"errors" |
| 7 |
"fmt" |
| 8 |
"reflect" |
| 9 |
"sort" |
| 10 |
"strings" |
| 11 |
|
| 12 |
"gorm.io/gorm/clause" |
| 13 |
"gorm.io/gorm/logger" |
| 14 |
"gorm.io/gorm/schema" |
| 15 |
) |
| 16 |
|
| 17 |
type result struct { |
| 18 |
Result sql.Result |
| 19 |
RowsAffected int64 |
| 20 |
} |
| 21 |
|
| 22 |
func (info *result) ModifyStatement(stmt *Statement) { |
| 23 |
stmt.Result = info |
| 24 |
} |
| 25 |
|
| 26 |
// Build implements clause.Expression interface |
| 27 |
func (result) Build(clause.Builder) { |
| 28 |
} |
| 29 |
|
| 30 |
func WithResult() *result { |
| 31 |
return &result{} |
| 32 |
} |
| 33 |
|
| 34 |
type Interface[T any] interface { |
| 35 |
Raw(sql string, values ...interface{}) ExecInterface[T] |
| 36 |
Exec(ctx context.Context, sql string, values ...interface{}) error |
| 37 |
CreateInterface[T] |
| 38 |
} |
| 39 |
|
| 40 |
type CreateInterface[T any] interface { |
| 41 |
ExecInterface[T] |
| 42 |
// chain methods available at start; Select/Omit keep CreateInterface to allow Create chaining |
| 43 |
Scopes(scopes ...func(db *Statement)) ChainInterface[T] |
| 44 |
Where(query interface{}, args ...interface{}) ChainInterface[T] |
| 45 |
Not(query interface{}, args ...interface{}) ChainInterface[T] |
| 46 |
Or(query interface{}, args ...interface{}) ChainInterface[T] |
| 47 |
Limit(offset int) ChainInterface[T] |
| 48 |
Offset(offset int) ChainInterface[T] |
| 49 |
Joins(query clause.JoinTarget, on func(db JoinBuilder, joinTable clause.Table, curTable clause.Table) error) ChainInterface[T] |
| 50 |
Preload(association string, query func(db PreloadBuilder) error) ChainInterface[T] |
| 51 |
Select(query string, args ...interface{}) CreateInterface[T] |
| 52 |
Omit(columns ...string) CreateInterface[T] |
| 53 |
MapColumns(m map[string]string) ChainInterface[T] |
| 54 |
Distinct(args ...interface{}) ChainInterface[T] |
| 55 |
Group(name string) ChainInterface[T] |
| 56 |
Having(query interface{}, args ...interface{}) ChainInterface[T] |
| 57 |
Order(value interface{}) ChainInterface[T] |
| 58 |
Build(builder clause.Builder) |
| 59 |
|
| 60 |
Delete(ctx context.Context) (rowsAffected int, err error) |
| 61 |
Update(ctx context.Context, name string, value any) (rowsAffected int, err error) |
| 62 |
Updates(ctx context.Context, t T) (rowsAffected int, err error) |
| 63 |
Count(ctx context.Context, column string) (result int64, err error) |
| 64 |
|
| 65 |
Table(name string, args ...interface{}) CreateInterface[T] |
| 66 |
Create(ctx context.Context, r *T) error |
| 67 |
CreateInBatches(ctx context.Context, r *[]T, batchSize int) error |
| 68 |
Set(assignments ...clause.Assigner) SetCreateOrUpdateInterface[T] |
| 69 |
} |
| 70 |
|
| 71 |
type ChainInterface[T any] interface { |
| 72 |
ExecInterface[T] |
| 73 |
Scopes(scopes ...func(db *Statement)) ChainInterface[T] |
| 74 |
Where(query interface{}, args ...interface{}) ChainInterface[T] |
| 75 |
Not(query interface{}, args ...interface{}) ChainInterface[T] |
| 76 |
Or(query interface{}, args ...interface{}) ChainInterface[T] |
| 77 |
Limit(offset int) ChainInterface[T] |
| 78 |
Offset(offset int) ChainInterface[T] |
| 79 |
Joins(query clause.JoinTarget, on func(db JoinBuilder, joinTable clause.Table, curTable clause.Table) error) ChainInterface[T] |
| 80 |
Preload(association string, query func(db PreloadBuilder) error) ChainInterface[T] |
| 81 |
Select(query string, args ...interface{}) ChainInterface[T] |
| 82 |
Omit(columns ...string) ChainInterface[T] |
| 83 |
MapColumns(m map[string]string) ChainInterface[T] |
| 84 |
Distinct(args ...interface{}) ChainInterface[T] |
| 85 |
Group(name string) ChainInterface[T] |
| 86 |
Having(query interface{}, args ...interface{}) ChainInterface[T] |
| 87 |
Order(value interface{}) ChainInterface[T] |
| 88 |
Set(assignments ...clause.Assigner) SetUpdateOnlyInterface[T] |
| 89 |
|
| 90 |
Build(builder clause.Builder) |
| 91 |
|
| 92 |
Table(name string, args ...interface{}) ChainInterface[T] |
| 93 |
Delete(ctx context.Context) (rowsAffected int, err error) |
| 94 |
Update(ctx context.Context, name string, value any) (rowsAffected int, err error) |
| 95 |
Updates(ctx context.Context, t T) (rowsAffected int, err error) |
| 96 |
Count(ctx context.Context, column string) (result int64, err error) |
| 97 |
} |
| 98 |
|
| 99 |
// SetUpdateOnlyInterface is returned by Set after chaining; only Update is allowed |
| 100 |
type SetUpdateOnlyInterface[T any] interface { |
| 101 |
Update(ctx context.Context) (rowsAffected int, err error) |
| 102 |
} |
| 103 |
|
| 104 |
// SetCreateOrUpdateInterface is returned by Set at start; Create or Update are allowed |
| 105 |
type SetCreateOrUpdateInterface[T any] interface { |
| 106 |
Create(ctx context.Context) error |
| 107 |
Update(ctx context.Context) (rowsAffected int, err error) |
| 108 |
} |
| 109 |
|
| 110 |
type ExecInterface[T any] interface { |
| 111 |
Scan(ctx context.Context, r interface{}) error |
| 112 |
First(context.Context) (T, error) |
| 113 |
Last(ctx context.Context) (T, error) |
| 114 |
Take(context.Context) (T, error) |
| 115 |
Find(ctx context.Context) ([]T, error) |
| 116 |
FindInBatches(ctx context.Context, batchSize int, fc func(data []T, batch int) error) error |
| 117 |
Row(ctx context.Context) *sql.Row |
| 118 |
Rows(ctx context.Context) (*sql.Rows, error) |
| 119 |
} |
| 120 |
|
| 121 |
type JoinBuilder interface { |
| 122 |
Select(...string) JoinBuilder |
| 123 |
Omit(...string) JoinBuilder |
| 124 |
Where(query interface{}, args ...interface{}) JoinBuilder |
| 125 |
Not(query interface{}, args ...interface{}) JoinBuilder |
| 126 |
Or(query interface{}, args ...interface{}) JoinBuilder |
| 127 |
} |
| 128 |
|
| 129 |
type PreloadBuilder interface { |
| 130 |
Select(...string) PreloadBuilder |
| 131 |
Omit(...string) PreloadBuilder |
| 132 |
Where(query interface{}, args ...interface{}) PreloadBuilder |
| 133 |
Not(query interface{}, args ...interface{}) PreloadBuilder |
| 134 |
Or(query interface{}, args ...interface{}) PreloadBuilder |
| 135 |
Limit(offset int) PreloadBuilder |
| 136 |
Offset(offset int) PreloadBuilder |
| 137 |
Order(value interface{}) PreloadBuilder |
| 138 |
LimitPerRecord(num int) PreloadBuilder |
| 139 |
} |
| 140 |
|
| 141 |
type op func(*DB) *DB |
| 142 |
|
| 143 |
func G[T any](db *DB, opts ...clause.Expression) Interface[T] { |
| 144 |
v := &g[T]{ |
| 145 |
db: db, |
| 146 |
ops: make([]op, 0, 5), |
| 147 |
} |
| 148 |
|
| 149 |
if len(opts) > 0 { |
| 150 |
v.ops = append(v.ops, func(db *DB) *DB { |
| 151 |
return db.Clauses(opts...) |
| 152 |
}) |
| 153 |
} |
| 154 |
|
| 155 |
v.createG = &createG[T]{ |
| 156 |
chainG: chainG[T]{ |
| 157 |
execG: execG[T]{g: v}, |
| 158 |
}, |
| 159 |
} |
| 160 |
return v |
| 161 |
} |
| 162 |
|
| 163 |
type g[T any] struct { |
| 164 |
*createG[T] |
| 165 |
db *DB |
| 166 |
ops []op |
| 167 |
} |
| 168 |
|
| 169 |
func (g *g[T]) apply(ctx context.Context) *DB { |
| 170 |
db := g.db |
| 171 |
if !db.DryRun { |
| 172 |
db = db.Session(&Session{NewDB: true, Context: ctx}).getInstance() |
| 173 |
} |
| 174 |
|
| 175 |
for _, op := range g.ops { |
| 176 |
db = op(db) |
| 177 |
} |
| 178 |
return db |
| 179 |
} |
| 180 |
|
| 181 |
func (c *g[T]) Raw(sql string, values ...interface{}) ExecInterface[T] { |
| 182 |
return execG[T]{g: &g[T]{ |
| 183 |
db: c.db, |
| 184 |
ops: append(c.ops, func(db *DB) *DB { |
| 185 |
var r T |
| 186 |
return db.Model(r).Raw(sql, values...) |
| 187 |
}), |
| 188 |
}} |
| 189 |
} |
| 190 |
|
| 191 |
func (c *g[T]) Exec(ctx context.Context, sql string, values ...interface{}) error { |
| 192 |
var r T |
| 193 |
return c.apply(ctx).Model(r).Exec(sql, values...).Error |
| 194 |
} |
| 195 |
|
| 196 |
type createG[T any] struct { |
| 197 |
chainG[T] |
| 198 |
} |
| 199 |
|
| 200 |
func (c createG[T]) Table(name string, args ...interface{}) CreateInterface[T] { |
| 201 |
return createG[T]{c.with(func(db *DB) *DB { |
| 202 |
return db.Table(name, args...) |
| 203 |
})} |
| 204 |
} |
| 205 |
|
| 206 |
func (c createG[T]) Select(query string, args ...interface{}) CreateInterface[T] { |
| 207 |
return createG[T]{c.with(func(db *DB) *DB { |
| 208 |
return db.Select(query, args...) |
| 209 |
})} |
| 210 |
} |
| 211 |
|
| 212 |
func (c createG[T]) Omit(columns ...string) CreateInterface[T] { |
| 213 |
return createG[T]{c.with(func(db *DB) *DB { |
| 214 |
return db.Omit(columns...) |
| 215 |
})} |
| 216 |
} |
| 217 |
|
| 218 |
func (c createG[T]) Set(assignments ...clause.Assigner) SetCreateOrUpdateInterface[T] { |
| 219 |
return c.processSet(assignments...) |
| 220 |
} |
| 221 |
|
| 222 |
func (c createG[T]) Create(ctx context.Context, r *T) error { |
| 223 |
return c.g.apply(ctx).Create(r).Error |
| 224 |
} |
| 225 |
|
| 226 |
func (c createG[T]) CreateInBatches(ctx context.Context, r *[]T, batchSize int) error { |
| 227 |
return c.g.apply(ctx).CreateInBatches(r, batchSize).Error |
| 228 |
} |
| 229 |
|
| 230 |
type chainG[T any] struct { |
| 231 |
execG[T] |
| 232 |
} |
| 233 |
|
| 234 |
func (c chainG[T]) getInstance() *DB { |
| 235 |
var r T |
| 236 |
return c.g.apply(context.Background()).Model(r).getInstance() |
| 237 |
} |
| 238 |
|
| 239 |
func (c chainG[T]) with(v op) chainG[T] { |
| 240 |
return chainG[T]{ |
| 241 |
execG: execG[T]{g: &g[T]{ |
| 242 |
db: c.g.db, |
| 243 |
ops: append(append([]op(nil), c.g.ops...), v), |
| 244 |
}}, |
| 245 |
} |
| 246 |
} |
| 247 |
|
| 248 |
func (c chainG[T]) Table(name string, args ...interface{}) ChainInterface[T] { |
| 249 |
return c.with(func(db *DB) *DB { |
| 250 |
return db.Table(name, args...) |
| 251 |
}) |
| 252 |
} |
| 253 |
|
| 254 |
func (c chainG[T]) Scopes(scopes ...func(db *Statement)) ChainInterface[T] { |
| 255 |
return c.with(func(db *DB) *DB { |
| 256 |
for _, fc := range scopes { |
| 257 |
fc(db.Statement) |
| 258 |
} |
| 259 |
return db |
| 260 |
}) |
| 261 |
} |
| 262 |
|
| 263 |
func (c chainG[T]) Where(query interface{}, args ...interface{}) ChainInterface[T] { |
| 264 |
return c.with(func(db *DB) *DB { |
| 265 |
return db.Where(query, args...) |
| 266 |
}) |
| 267 |
} |
| 268 |
|
| 269 |
func (c chainG[T]) Not(query interface{}, args ...interface{}) ChainInterface[T] { |
| 270 |
return c.with(func(db *DB) *DB { |
| 271 |
return db.Not(query, args...) |
| 272 |
}) |
| 273 |
} |
| 274 |
|
| 275 |
func (c chainG[T]) Or(query interface{}, args ...interface{}) ChainInterface[T] { |
| 276 |
return c.with(func(db *DB) *DB { |
| 277 |
return db.Or(query, args...) |
| 278 |
}) |
| 279 |
} |
| 280 |
|
| 281 |
func (c chainG[T]) Limit(offset int) ChainInterface[T] { |
| 282 |
return c.with(func(db *DB) *DB { |
| 283 |
return db.Limit(offset) |
| 284 |
}) |
| 285 |
} |
| 286 |
|
| 287 |
func (c chainG[T]) Offset(offset int) ChainInterface[T] { |
| 288 |
return c.with(func(db *DB) *DB { |
| 289 |
return db.Offset(offset) |
| 290 |
}) |
| 291 |
} |
| 292 |
|
| 293 |
type joinBuilder struct { |
| 294 |
db *DB |
| 295 |
} |
| 296 |
|
| 297 |
func (q *joinBuilder) Where(query interface{}, args ...interface{}) JoinBuilder { |
| 298 |
q.db.Where(query, args...) |
| 299 |
return q |
| 300 |
} |
| 301 |
|
| 302 |
func (q *joinBuilder) Or(query interface{}, args ...interface{}) JoinBuilder { |
| 303 |
q.db.Where(query, args...) |
| 304 |
return q |
| 305 |
} |
| 306 |
|
| 307 |
func (q *joinBuilder) Not(query interface{}, args ...interface{}) JoinBuilder { |
| 308 |
q.db.Where(query, args...) |
| 309 |
return q |
| 310 |
} |
| 311 |
|
| 312 |
func (q *joinBuilder) Select(columns ...string) JoinBuilder { |
| 313 |
q.db.Select(columns) |
| 314 |
return q |
| 315 |
} |
| 316 |
|
| 317 |
func (q *joinBuilder) Omit(columns ...string) JoinBuilder { |
| 318 |
q.db.Omit(columns...) |
| 319 |
return q |
| 320 |
} |
| 321 |
|
| 322 |
type preloadBuilder struct { |
| 323 |
limitPerRecord int |
| 324 |
db *DB |
| 325 |
} |
| 326 |
|
| 327 |
func (q *preloadBuilder) Where(query interface{}, args ...interface{}) PreloadBuilder { |
| 328 |
q.db.Where(query, args...) |
| 329 |
return q |
| 330 |
} |
| 331 |
|
| 332 |
func (q *preloadBuilder) Or(query interface{}, args ...interface{}) PreloadBuilder { |
| 333 |
q.db.Where(query, args...) |
| 334 |
return q |
| 335 |
} |
| 336 |
|
| 337 |
func (q *preloadBuilder) Not(query interface{}, args ...interface{}) PreloadBuilder { |
| 338 |
q.db.Where(query, args...) |
| 339 |
return q |
| 340 |
} |
| 341 |
|
| 342 |
func (q *preloadBuilder) Select(columns ...string) PreloadBuilder { |
| 343 |
q.db.Select(columns) |
| 344 |
return q |
| 345 |
} |
| 346 |
|
| 347 |
func (q *preloadBuilder) Omit(columns ...string) PreloadBuilder { |
| 348 |
q.db.Omit(columns...) |
| 349 |
return q |
| 350 |
} |
| 351 |
|
| 352 |
func (q *preloadBuilder) Limit(limit int) PreloadBuilder { |
| 353 |
q.db.Limit(limit) |
| 354 |
return q |
| 355 |
} |
| 356 |
|
| 357 |
func (q *preloadBuilder) Offset(offset int) PreloadBuilder { |
| 358 |
q.db.Offset(offset) |
| 359 |
return q |
| 360 |
} |
| 361 |
|
| 362 |
func (q *preloadBuilder) Order(value interface{}) PreloadBuilder { |
| 363 |
q.db.Order(value) |
| 364 |
return q |
| 365 |
} |
| 366 |
|
| 367 |
func (q *preloadBuilder) LimitPerRecord(num int) PreloadBuilder { |
| 368 |
q.limitPerRecord = num |
| 369 |
return q |
| 370 |
} |
| 371 |
|
| 372 |
func (c chainG[T]) Joins(jt clause.JoinTarget, on func(db JoinBuilder, joinTable clause.Table, curTable clause.Table) error) ChainInterface[T] { |
| 373 |
return c.with(func(db *DB) *DB { |
| 374 |
if jt.Table == "" { |
| 375 |
jt.Table = clause.JoinTable(strings.Split(jt.Association, ".")...).Name |
| 376 |
} |
| 377 |
|
| 378 |
q := joinBuilder{db: db.Session(&Session{NewDB: true, Initialized: true}).Table(jt.Table)} |
| 379 |
if on != nil { |
| 380 |
if err := on(&q, clause.Table{Name: jt.Table}, clause.Table{Name: clause.CurrentTable}); err != nil { |
| 381 |
db.AddError(err) |
| 382 |
} |
| 383 |
} |
| 384 |
|
| 385 |
j := join{ |
| 386 |
Name: jt.Association, |
| 387 |
Alias: jt.Table, |
| 388 |
Selects: q.db.Statement.Selects, |
| 389 |
Omits: q.db.Statement.Omits, |
| 390 |
JoinType: jt.Type, |
| 391 |
} |
| 392 |
|
| 393 |
if where, ok := q.db.Statement.Clauses["WHERE"].Expression.(clause.Where); ok { |
| 394 |
j.On = &where |
| 395 |
} |
| 396 |
|
| 397 |
if jt.Subquery != nil { |
| 398 |
joinType := j.JoinType |
| 399 |
if joinType == "" { |
| 400 |
joinType = clause.LeftJoin |
| 401 |
} |
| 402 |
|
| 403 |
if db, ok := jt.Subquery.(interface{ getInstance() *DB }); ok { |
| 404 |
stmt := db.getInstance().Statement |
| 405 |
if len(j.Selects) == 0 { |
| 406 |
j.Selects = stmt.Selects |
| 407 |
} |
| 408 |
if len(j.Omits) == 0 { |
| 409 |
j.Omits = stmt.Omits |
| 410 |
} |
| 411 |
} |
| 412 |
|
| 413 |
expr := clause.NamedExpr{SQL: fmt.Sprintf("%s JOIN (?) AS ?", joinType), Vars: []interface{}{jt.Subquery, clause.Table{Name: j.Alias}}} |
| 414 |
|
| 415 |
if j.On != nil { |
| 416 |
expr.SQL += " ON ?" |
| 417 |
expr.Vars = append(expr.Vars, clause.AndConditions{Exprs: j.On.Exprs}) |
| 418 |
} |
| 419 |
|
| 420 |
j.Expression = expr |
| 421 |
} |
| 422 |
|
| 423 |
db.Statement.Joins = append(db.Statement.Joins, j) |
| 424 |
sort.Slice(db.Statement.Joins, func(i, j int) bool { |
| 425 |
return db.Statement.Joins[i].Name < db.Statement.Joins[j].Name |
| 426 |
}) |
| 427 |
return db |
| 428 |
}) |
| 429 |
} |
| 430 |
|
| 431 |
func (c chainG[T]) Select(query string, args ...interface{}) ChainInterface[T] { |
| 432 |
return c.with(func(db *DB) *DB { |
| 433 |
return db.Select(query, args...) |
| 434 |
}) |
| 435 |
} |
| 436 |
|
| 437 |
func (c chainG[T]) Omit(columns ...string) ChainInterface[T] { |
| 438 |
return c.with(func(db *DB) *DB { |
| 439 |
return db.Omit(columns...) |
| 440 |
}) |
| 441 |
} |
| 442 |
|
| 443 |
func (c chainG[T]) MapColumns(m map[string]string) ChainInterface[T] { |
| 444 |
return c.with(func(db *DB) *DB { |
| 445 |
return db.MapColumns(m) |
| 446 |
}) |
| 447 |
} |
| 448 |
|
| 449 |
func (c chainG[T]) Set(assignments ...clause.Assigner) SetUpdateOnlyInterface[T] { |
| 450 |
return c.processSet(assignments...) |
| 451 |
} |
| 452 |
|
| 453 |
func (c chainG[T]) Distinct(args ...interface{}) ChainInterface[T] { |
| 454 |
return c.with(func(db *DB) *DB { |
| 455 |
return db.Distinct(args...) |
| 456 |
}) |
| 457 |
} |
| 458 |
|
| 459 |
func (c chainG[T]) Group(name string) ChainInterface[T] { |
| 460 |
return c.with(func(db *DB) *DB { |
| 461 |
return db.Group(name) |
| 462 |
}) |
| 463 |
} |
| 464 |
|
| 465 |
func (c chainG[T]) Having(query interface{}, args ...interface{}) ChainInterface[T] { |
| 466 |
return c.with(func(db *DB) *DB { |
| 467 |
return db.Having(query, args...) |
| 468 |
}) |
| 469 |
} |
| 470 |
|
| 471 |
func (c chainG[T]) Order(value interface{}) ChainInterface[T] { |
| 472 |
return c.with(func(db *DB) *DB { |
| 473 |
return db.Order(value) |
| 474 |
}) |
| 475 |
} |
| 476 |
|
| 477 |
func (c chainG[T]) Preload(association string, query func(db PreloadBuilder) error) ChainInterface[T] { |
| 478 |
return c.with(func(db *DB) *DB { |
| 479 |
return db.Preload(association, func(tx *DB) *DB { |
| 480 |
q := preloadBuilder{db: tx.getInstance()} |
| 481 |
if query != nil { |
| 482 |
if err := query(&q); err != nil { |
| 483 |
db.AddError(err) |
| 484 |
} |
| 485 |
} |
| 486 |
|
| 487 |
relation, ok := db.Statement.Schema.Relationships.Relations[association] |
| 488 |
if !ok { |
| 489 |
if preloadFields := strings.Split(association, "."); len(preloadFields) > 1 { |
| 490 |
relationships := &db.Statement.Schema.Relationships |
| 491 |
for _, field := range preloadFields { |
| 492 |
var ok bool |
| 493 |
relation, ok = relationships.Relations[field] |
| 494 |
if ok { |
| 495 |
relationships = &relation.FieldSchema.Relationships |
| 496 |
} else { |
| 497 |
db.AddError(fmt.Errorf("relation %s not found", association)) |
| 498 |
return nil |
| 499 |
} |
| 500 |
} |
| 501 |
} else { |
| 502 |
db.AddError(fmt.Errorf("relation %s not found", association)) |
| 503 |
return nil |
| 504 |
} |
| 505 |
} |
| 506 |
|
| 507 |
if q.limitPerRecord > 0 { |
| 508 |
if relation.JoinTable != nil { |
| 509 |
tx.AddError(fmt.Errorf("many2many relation %s don't support LimitPerRecord", association)) |
| 510 |
return tx |
| 511 |
} |
| 512 |
|
| 513 |
refColumns := []clause.Column{} |
| 514 |
for _, rel := range relation.References { |
| 515 |
if rel.OwnPrimaryKey { |
| 516 |
refColumns = append(refColumns, clause.Column{Name: rel.ForeignKey.DBName}) |
| 517 |
} |
| 518 |
} |
| 519 |
|
| 520 |
if len(refColumns) != 0 { |
| 521 |
selectExpr := clause.CommaExpression{} |
| 522 |
for _, column := range q.db.Statement.Selects { |
| 523 |
selectExpr.Exprs = append(selectExpr.Exprs, clause.Expr{SQL: "?", Vars: []interface{}{clause.Column{Name: column}}}) |
| 524 |
} |
| 525 |
|
| 526 |
if len(selectExpr.Exprs) == 0 { |
| 527 |
selectExpr.Exprs = []clause.Expression{clause.Expr{SQL: "*", Vars: []interface{}{}}} |
| 528 |
} |
| 529 |
|
| 530 |
partitionBy := clause.CommaExpression{} |
| 531 |
for _, column := range refColumns { |
| 532 |
partitionBy.Exprs = append(partitionBy.Exprs, clause.Expr{SQL: "?", Vars: []interface{}{clause.Column{Name: column.Name}}}) |
| 533 |
} |
| 534 |
|
| 535 |
rnnColumn := clause.Column{Name: "gorm_preload_rnn"} |
| 536 |
sql := "ROW_NUMBER() OVER (PARTITION BY ? ?)" |
| 537 |
vars := []interface{}{partitionBy} |
| 538 |
if orderBy, ok := q.db.Statement.Clauses["ORDER BY"]; ok { |
| 539 |
vars = append(vars, orderBy) |
| 540 |
} else { |
| 541 |
vars = append(vars, clause.Clause{Name: "ORDER BY", Expression: clause.OrderBy{ |
| 542 |
Columns: []clause.OrderByColumn{{Column: clause.PrimaryColumn, Desc: true}}, |
| 543 |
}}) |
| 544 |
} |
| 545 |
vars = append(vars, rnnColumn) |
| 546 |
|
| 547 |
selectExpr.Exprs = append(selectExpr.Exprs, clause.Expr{SQL: sql + " AS ?", Vars: vars}) |
| 548 |
|
| 549 |
q.db.Clauses(clause.Select{Expression: selectExpr}) |
| 550 |
|
| 551 |
return q.db.Session(&Session{NewDB: true}).Unscoped().Table("(?) t", q.db).Where("? <= ?", rnnColumn, q.limitPerRecord) |
| 552 |
} |
| 553 |
} |
| 554 |
|
| 555 |
return q.db |
| 556 |
}) |
| 557 |
}) |
| 558 |
} |
| 559 |
|
| 560 |
func (c chainG[T]) Delete(ctx context.Context) (rowsAffected int, err error) { |
| 561 |
r := new(T) |
| 562 |
res := c.g.apply(ctx).Delete(r) |
| 563 |
return int(res.RowsAffected), res.Error |
| 564 |
} |
| 565 |
|
| 566 |
func (c chainG[T]) Update(ctx context.Context, name string, value any) (rowsAffected int, err error) { |
| 567 |
var r T |
| 568 |
res := c.g.apply(ctx).Model(r).Update(name, value) |
| 569 |
return int(res.RowsAffected), res.Error |
| 570 |
} |
| 571 |
|
| 572 |
func (c chainG[T]) Updates(ctx context.Context, t T) (rowsAffected int, err error) { |
| 573 |
res := c.g.apply(ctx).Updates(t) |
| 574 |
return int(res.RowsAffected), res.Error |
| 575 |
} |
| 576 |
|
| 577 |
func (c chainG[T]) Count(ctx context.Context, column string) (result int64, err error) { |
| 578 |
var r T |
| 579 |
err = c.g.apply(ctx).Model(r).Select(column).Count(&result).Error |
| 580 |
return |
| 581 |
} |
| 582 |
|
| 583 |
func (c chainG[T]) Build(builder clause.Builder) { |
| 584 |
subdb := c.getInstance() |
| 585 |
subdb.Logger = logger.Discard |
| 586 |
subdb.DryRun = true |
| 587 |
|
| 588 |
if stmt, ok := builder.(*Statement); ok { |
| 589 |
if subdb.Statement.SQL.Len() > 0 { |
| 590 |
var ( |
| 591 |
vars = subdb.Statement.Vars |
| 592 |
sql = subdb.Statement.SQL.String() |
| 593 |
) |
| 594 |
|
| 595 |
subdb.Statement.Vars = make([]interface{}, 0, len(vars)) |
| 596 |
for _, vv := range vars { |
| 597 |
subdb.Statement.Vars = append(subdb.Statement.Vars, vv) |
| 598 |
bindvar := strings.Builder{} |
| 599 |
subdb.BindVarTo(&bindvar, subdb.Statement, vv) |
| 600 |
sql = strings.Replace(sql, bindvar.String(), "?", 1) |
| 601 |
} |
| 602 |
|
| 603 |
subdb.Statement.SQL.Reset() |
| 604 |
subdb.Statement.Vars = stmt.Vars |
| 605 |
if strings.Contains(sql, "@") { |
| 606 |
clause.NamedExpr{SQL: sql, Vars: vars}.Build(subdb.Statement) |
| 607 |
} else { |
| 608 |
clause.Expr{SQL: sql, Vars: vars}.Build(subdb.Statement) |
| 609 |
} |
| 610 |
} else { |
| 611 |
subdb.Statement.Vars = append(stmt.Vars, subdb.Statement.Vars...) |
| 612 |
subdb.callbacks.Query().Execute(subdb) |
| 613 |
} |
| 614 |
|
| 615 |
builder.WriteString(subdb.Statement.SQL.String()) |
| 616 |
stmt.Vars = subdb.Statement.Vars |
| 617 |
} |
| 618 |
} |
| 619 |
|
| 620 |
type execG[T any] struct { |
| 621 |
g *g[T] |
| 622 |
} |
| 623 |
|
| 624 |
func (g execG[T]) First(ctx context.Context) (T, error) { |
| 625 |
var r T |
| 626 |
err := g.g.apply(ctx).First(&r).Error |
| 627 |
return r, err |
| 628 |
} |
| 629 |
|
| 630 |
func (g execG[T]) Scan(ctx context.Context, result interface{}) error { |
| 631 |
var r T |
| 632 |
err := g.g.apply(ctx).Model(r).Find(result).Error |
| 633 |
return err |
| 634 |
} |
| 635 |
|
| 636 |
func (g execG[T]) Last(ctx context.Context) (T, error) { |
| 637 |
var r T |
| 638 |
err := g.g.apply(ctx).Last(&r).Error |
| 639 |
return r, err |
| 640 |
} |
| 641 |
|
| 642 |
func (g execG[T]) Take(ctx context.Context) (T, error) { |
| 643 |
var r T |
| 644 |
err := g.g.apply(ctx).Take(&r).Error |
| 645 |
return r, err |
| 646 |
} |
| 647 |
|
| 648 |
func (g execG[T]) Find(ctx context.Context) ([]T, error) { |
| 649 |
var r []T |
| 650 |
err := g.g.apply(ctx).Find(&r).Error |
| 651 |
return r, err |
| 652 |
} |
| 653 |
|
| 654 |
func (g execG[T]) FindInBatches(ctx context.Context, batchSize int, fc func(data []T, batch int) error) error { |
| 655 |
var data []T |
| 656 |
return g.g.apply(ctx).FindInBatches(&data, batchSize, func(tx *DB, batch int) error { |
| 657 |
return fc(data, batch) |
| 658 |
}).Error |
| 659 |
} |
| 660 |
|
| 661 |
func (g execG[T]) Row(ctx context.Context) *sql.Row { |
| 662 |
return g.g.apply(ctx).Row() |
| 663 |
} |
| 664 |
|
| 665 |
func (g execG[T]) Rows(ctx context.Context) (*sql.Rows, error) { |
| 666 |
return g.g.apply(ctx).Rows() |
| 667 |
} |
| 668 |
|
| 669 |
func (c chainG[T]) processSet(items ...clause.Assigner) setCreateOrUpdateG[T] { |
| 670 |
var ( |
| 671 |
assigns []clause.Assignment |
| 672 |
assocOps []clause.Association |
| 673 |
) |
| 674 |
|
| 675 |
for _, item := range items { |
| 676 |
// Check if it's an AssociationAssigner |
| 677 |
if assocAssigner, ok := item.(clause.AssociationAssigner); ok { |
| 678 |
assocOps = append(assocOps, assocAssigner.AssociationAssignments()...) |
| 679 |
} else { |
| 680 |
assigns = append(assigns, item.Assignments()...) |
| 681 |
} |
| 682 |
} |
| 683 |
|
| 684 |
return setCreateOrUpdateG[T]{ |
| 685 |
c: c, |
| 686 |
assigns: assigns, |
| 687 |
assocOps: assocOps, |
| 688 |
} |
| 689 |
} |
| 690 |
|
| 691 |
// setCreateOrUpdateG[T] is a struct that holds operations to be executed in a batch. |
| 692 |
// It supports regular assignments and association operations. |
| 693 |
type setCreateOrUpdateG[T any] struct { |
| 694 |
c chainG[T] |
| 695 |
assigns []clause.Assignment |
| 696 |
assocOps []clause.Association |
| 697 |
} |
| 698 |
|
| 699 |
func (s setCreateOrUpdateG[T]) Update(ctx context.Context) (rowsAffected int, err error) { |
| 700 |
// Execute association operations |
| 701 |
for _, assocOp := range s.assocOps { |
| 702 |
if err := s.executeAssociationOperation(ctx, assocOp); err != nil { |
| 703 |
return 0, err |
| 704 |
} |
| 705 |
} |
| 706 |
|
| 707 |
// Execute assignment operations |
| 708 |
if len(s.assigns) > 0 { |
| 709 |
var r T |
| 710 |
res := s.c.g.apply(ctx).Model(r).Clauses(clause.Set(s.assigns)).Updates(map[string]interface{}{}) |
| 711 |
return int(res.RowsAffected), res.Error |
| 712 |
} |
| 713 |
|
| 714 |
return 0, nil |
| 715 |
} |
| 716 |
|
| 717 |
func (s setCreateOrUpdateG[T]) Create(ctx context.Context) error { |
| 718 |
// Execute association operations |
| 719 |
for _, assocOp := range s.assocOps { |
| 720 |
if err := s.executeAssociationOperation(ctx, assocOp); err != nil { |
| 721 |
return err |
| 722 |
} |
| 723 |
} |
| 724 |
|
| 725 |
// Execute assignment operations |
| 726 |
if len(s.assigns) > 0 { |
| 727 |
data := make(map[string]interface{}, len(s.assigns)) |
| 728 |
for _, a := range s.assigns { |
| 729 |
data[a.Column.Name] = a.Value |
| 730 |
} |
| 731 |
var r T |
| 732 |
return s.c.g.apply(ctx).Model(r).Create(data).Error |
| 733 |
} |
| 734 |
|
| 735 |
return nil |
| 736 |
} |
| 737 |
|
| 738 |
// executeAssociationOperation executes an association operation |
| 739 |
func (s setCreateOrUpdateG[T]) executeAssociationOperation(ctx context.Context, op clause.Association) error { |
| 740 |
var r T |
| 741 |
base := s.c.g.apply(ctx).Model(r) |
| 742 |
|
| 743 |
switch op.Type { |
| 744 |
case clause.OpCreate: |
| 745 |
return s.handleAssociationCreate(ctx, base, op) |
| 746 |
case clause.OpUnlink, clause.OpDelete, clause.OpUpdate: |
| 747 |
return s.handleAssociation(ctx, base, op) |
| 748 |
default: |
| 749 |
return fmt.Errorf("unknown association operation type: %v", op.Type) |
| 750 |
} |
| 751 |
} |
| 752 |
|
| 753 |
func (s setCreateOrUpdateG[T]) handleAssociationCreate(ctx context.Context, base *DB, op clause.Association) error { |
| 754 |
if len(op.Set) > 0 { |
| 755 |
return s.handleAssociationForOwners(base, ctx, func(owner T, assoc *Association) error { |
| 756 |
data := make(map[string]interface{}, len(op.Set)) |
| 757 |
for _, a := range op.Set { |
| 758 |
data[a.Column.Name] = a.Value |
| 759 |
} |
| 760 |
return assoc.Append(data) |
| 761 |
}, op.Association) |
| 762 |
} |
| 763 |
|
| 764 |
return s.handleAssociationForOwners(base, ctx, func(owner T, assoc *Association) error { |
| 765 |
return assoc.Append(op.Values...) |
| 766 |
}, op.Association) |
| 767 |
} |
| 768 |
|
| 769 |
// handleAssociationForOwners is a helper function that handles associations for all owners |
| 770 |
func (s setCreateOrUpdateG[T]) handleAssociationForOwners(base *DB, ctx context.Context, handler func(owner T, association *Association) error, associationName string) error { |
| 771 |
var owners []T |
| 772 |
if err := base.Find(&owners).Error; err != nil { |
| 773 |
return err |
| 774 |
} |
| 775 |
|
| 776 |
for _, owner := range owners { |
| 777 |
assoc := base.Session(&Session{NewDB: true, Context: ctx}).Model(&owner).Association(associationName) |
| 778 |
if assoc.Error != nil { |
| 779 |
return assoc.Error |
| 780 |
} |
| 781 |
|
| 782 |
if err := handler(owner, assoc); err != nil { |
| 783 |
return err |
| 784 |
} |
| 785 |
} |
| 786 |
return nil |
| 787 |
} |
| 788 |
|
| 789 |
func (s setCreateOrUpdateG[T]) handleAssociation(ctx context.Context, base *DB, op clause.Association) error { |
| 790 |
assoc := base.Association(op.Association) |
| 791 |
if assoc.Error != nil { |
| 792 |
return assoc.Error |
| 793 |
} |
| 794 |
|
| 795 |
var ( |
| 796 |
rel = assoc.Relationship |
| 797 |
assocModel = reflect.New(rel.FieldSchema.ModelType).Interface() |
| 798 |
fkNil = map[string]any{} |
| 799 |
setMap = make(map[string]any, len(op.Set)) |
| 800 |
ownerPKNames []string |
| 801 |
ownerFKNames []string |
| 802 |
primaryColumns []any |
| 803 |
foreignColumns []any |
| 804 |
) |
| 805 |
|
| 806 |
for _, a := range op.Set { |
| 807 |
setMap[a.Column.Name] = a.Value |
| 808 |
} |
| 809 |
|
| 810 |
for _, ref := range rel.References { |
| 811 |
fkNil[ref.ForeignKey.DBName] = nil |
| 812 |
|
| 813 |
if ref.OwnPrimaryKey && ref.PrimaryKey != nil { |
| 814 |
ownerPKNames = append(ownerPKNames, ref.PrimaryKey.DBName) |
| 815 |
primaryColumns = append(primaryColumns, clause.Column{Name: ref.PrimaryKey.DBName}) |
| 816 |
foreignColumns = append(foreignColumns, clause.Column{Name: ref.ForeignKey.DBName}) |
| 817 |
} else if !ref.OwnPrimaryKey && ref.PrimaryKey != nil { |
| 818 |
ownerFKNames = append(ownerFKNames, ref.ForeignKey.DBName) |
| 819 |
primaryColumns = append(primaryColumns, clause.Column{Name: ref.PrimaryKey.DBName}) |
| 820 |
} |
| 821 |
} |
| 822 |
|
| 823 |
assocDB := s.c.g.db.Session(&Session{NewDB: true, Context: ctx}).Model(assocModel).Where(op.Conditions) |
| 824 |
|
| 825 |
switch rel.Type { |
| 826 |
case schema.HasOne, schema.HasMany: |
| 827 |
assocDB = assocDB.Where("? IN (?)", foreignColumns, base.Select(ownerPKNames)) |
| 828 |
switch op.Type { |
| 829 |
case clause.OpUnlink: |
| 830 |
return assocDB.Updates(fkNil).Error |
| 831 |
case clause.OpDelete: |
| 832 |
return assocDB.Delete(assocModel).Error |
| 833 |
case clause.OpUpdate: |
| 834 |
return assocDB.Updates(setMap).Error |
| 835 |
} |
| 836 |
case schema.BelongsTo: |
| 837 |
switch op.Type { |
| 838 |
case clause.OpDelete: |
| 839 |
return base.Transaction(func(tx *DB) error { |
| 840 |
assocDB.Statement.ConnPool = tx.Statement.ConnPool |
| 841 |
base.Statement.ConnPool = tx.Statement.ConnPool |
| 842 |
|
| 843 |
if err := assocDB.Where("? IN (?)", primaryColumns, base.Select(ownerFKNames)).Delete(assocModel).Error; err != nil { |
| 844 |
return err |
| 845 |
} |
| 846 |
return base.Updates(fkNil).Error |
| 847 |
}) |
| 848 |
case clause.OpUnlink: |
| 849 |
return base.Updates(fkNil).Error |
| 850 |
case clause.OpUpdate: |
| 851 |
return assocDB.Where("? IN (?)", primaryColumns, base.Select(ownerFKNames)).Updates(setMap).Error |
| 852 |
} |
| 853 |
case schema.Many2Many: |
| 854 |
joinModel := reflect.New(rel.JoinTable.ModelType).Interface() |
| 855 |
joinDB := base.Session(&Session{NewDB: true, Context: ctx}).Model(joinModel) |
| 856 |
|
| 857 |
// EXISTS owners: owners.pk = join.owner_fk for all owner refs |
| 858 |
ownersExists := base.Session(&Session{NewDB: true, Context: ctx}).Table(rel.Schema.Table).Select("1") |
| 859 |
for _, ref := range rel.References { |
| 860 |
if ref.OwnPrimaryKey && ref.PrimaryKey != nil { |
| 861 |
ownersExists = ownersExists.Where(clause.Eq{ |
| 862 |
Column: clause.Column{Table: rel.Schema.Table, Name: ref.PrimaryKey.DBName}, |
| 863 |
Value: clause.Column{Table: rel.JoinTable.Table, Name: ref.ForeignKey.DBName}, |
| 864 |
}) |
| 865 |
} |
| 866 |
} |
| 867 |
|
| 868 |
// EXISTS related: related.pk = join.rel_fk for all related refs, plus optional conditions |
| 869 |
relatedExists := base.Session(&Session{NewDB: true, Context: ctx}).Table(rel.FieldSchema.Table).Select("1") |
| 870 |
for _, ref := range rel.References { |
| 871 |
if !ref.OwnPrimaryKey && ref.PrimaryKey != nil { |
| 872 |
relatedExists = relatedExists.Where(clause.Eq{ |
| 873 |
Column: clause.Column{Table: rel.FieldSchema.Table, Name: ref.PrimaryKey.DBName}, |
| 874 |
Value: clause.Column{Table: rel.JoinTable.Table, Name: ref.ForeignKey.DBName}, |
| 875 |
}) |
| 876 |
} |
| 877 |
} |
| 878 |
relatedExists = relatedExists.Where(op.Conditions) |
| 879 |
|
| 880 |
switch op.Type { |
| 881 |
case clause.OpUnlink, clause.OpDelete: |
| 882 |
joinDB = joinDB.Where("EXISTS (?)", ownersExists) |
| 883 |
if len(op.Conditions) > 0 { |
| 884 |
joinDB = joinDB.Where("EXISTS (?)", relatedExists) |
| 885 |
} |
| 886 |
return joinDB.Delete(nil).Error |
| 887 |
case clause.OpUpdate: |
| 888 |
// Update related table rows that have join rows matching owners |
| 889 |
relatedDB := base.Session(&Session{NewDB: true, Context: ctx}).Table(rel.FieldSchema.Table).Where(op.Conditions) |
| 890 |
|
| 891 |
// correlated join subquery: join.rel_fk = related.pk AND EXISTS owners |
| 892 |
joinSub := base.Session(&Session{NewDB: true, Context: ctx}).Table(rel.JoinTable.Table).Select("1") |
| 893 |
for _, ref := range rel.References { |
| 894 |
if !ref.OwnPrimaryKey && ref.PrimaryKey != nil { |
| 895 |
joinSub = joinSub.Where(clause.Eq{ |
| 896 |
Column: clause.Column{Table: rel.JoinTable.Table, Name: ref.ForeignKey.DBName}, |
| 897 |
Value: clause.Column{Table: rel.FieldSchema.Table, Name: ref.PrimaryKey.DBName}, |
| 898 |
}) |
| 899 |
} |
| 900 |
} |
| 901 |
joinSub = joinSub.Where("EXISTS (?)", ownersExists) |
| 902 |
return relatedDB.Where("EXISTS (?)", joinSub).Updates(setMap).Error |
| 903 |
} |
| 904 |
} |
| 905 |
return errors.New("unsupported relationship") |
| 906 |
} |