Debian Codegraph @

finisher_api.go

raw
1 package gorm
2
3 import (
4 "context"
5 "database/sql"
6 "errors"
7 "fmt"
8 "hash/maphash"
9 "reflect"
10 "strings"
11
12 "gorm.io/gorm/clause"
13 "gorm.io/gorm/logger"
14 "gorm.io/gorm/schema"
15 "gorm.io/gorm/utils"
16 )
17
18 // Create inserts value, returning the inserted data's primary key in value's id
19 func (db *DB) Create(value interface{}) (tx *DB) {
20 if db.CreateBatchSize > 0 {
21 return db.CreateInBatches(value, db.CreateBatchSize)
22 }
23
24 tx = db.getInstance()
25 tx.Statement.Dest = value
26 return tx.callbacks.Create().Execute(tx)
27 }
28
29 // CreateInBatches inserts value in batches of batchSize
30 func (db *DB) CreateInBatches(value interface{}, batchSize int) (tx *DB) {
31 reflectValue := reflect.Indirect(reflect.ValueOf(value))
32
33 switch reflectValue.Kind() {
34 case reflect.Slice, reflect.Array:
35 var rowsAffected int64
36 tx = db.getInstance()
37
38 // the reflection length judgment of the optimized value
39 reflectLen := reflectValue.Len()
40
41 callFc := func(tx *DB) error {
42 for i := 0; i < reflectLen; i += batchSize {
43 ends := i + batchSize
44 if ends > reflectLen {
45 ends = reflectLen
46 }
47
48 subtx := tx.getInstance()
49 subtx.Statement.Dest = reflectValue.Slice(i, ends).Interface()
50 subtx.callbacks.Create().Execute(subtx)
51 if subtx.Error != nil {
52 return subtx.Error
53 }
54 rowsAffected += subtx.RowsAffected
55 }
56 return nil
57 }
58
59 if tx.SkipDefaultTransaction || reflectLen <= batchSize {
60 tx.AddError(callFc(tx.Session(&Session{})))
61 } else {
62 tx.AddError(tx.Transaction(callFc))
63 }
64
65 tx.RowsAffected = rowsAffected
66 default:
67 tx = db.getInstance()
68 tx.Statement.Dest = value
69 tx = tx.callbacks.Create().Execute(tx)
70 }
71 return
72 }
73
74 // Save updates value in database. If value doesn't contain a matching primary key, value is inserted.
75 func (db *DB) Save(value interface{}) (tx *DB) {
76 tx = db.getInstance()
77 tx.Statement.Dest = value
78
79 reflectValue := reflect.Indirect(reflect.ValueOf(value))
80 for reflectValue.Kind() == reflect.Ptr || reflectValue.Kind() == reflect.Interface {
81 reflectValue = reflect.Indirect(reflectValue)
82 }
83
84 switch reflectValue.Kind() {
85 case reflect.Slice, reflect.Array:
86 if _, ok := tx.Statement.Clauses["ON CONFLICT"]; !ok {
87 tx = tx.Clauses(clause.OnConflict{UpdateAll: true})
88 }
89 tx = tx.callbacks.Create().Execute(tx.Set("gorm:update_track_time", true))
90 case reflect.Struct:
91 if err := tx.Statement.Parse(value); err == nil && tx.Statement.Schema != nil {
92 for _, pf := range tx.Statement.Schema.PrimaryFields {
93 if _, isZero := pf.ValueOf(tx.Statement.Context, reflectValue); isZero {
94 return tx.callbacks.Create().Execute(tx)
95 }
96 }
97 }
98
99 fallthrough
100 default:
101 selectedUpdate := len(tx.Statement.Selects) != 0
102 // when updating, use all fields including those zero-value fields
103 if !selectedUpdate {
104 tx.Statement.Selects = append(tx.Statement.Selects, "*")
105 }
106
107 updateTx := tx.callbacks.Update().Execute(tx.Session(&Session{Initialized: true}))
108
109 if updateTx.Error == nil && updateTx.RowsAffected == 0 && !updateTx.DryRun && !selectedUpdate {
110 return tx.Session(&Session{SkipHooks: true}).Clauses(clause.OnConflict{UpdateAll: true}).Create(value)
111 }
112
113 return updateTx
114 }
115
116 return
117 }
118
119 // First finds the first record ordered by primary key, matching given conditions conds
120 func (db *DB) First(dest interface{}, conds ...interface{}) (tx *DB) {
121 tx = db.Limit(1).Order(clause.OrderByColumn{
122 Column: clause.Column{Table: clause.CurrentTable, Name: clause.PrimaryKey},
123 })
124 if len(conds) > 0 {
125 if exprs := tx.Statement.BuildCondition(conds[0], conds[1:]...); len(exprs) > 0 {
126 tx.Statement.AddClause(clause.Where{Exprs: exprs})
127 }
128 }
129 tx.Statement.RaiseErrorOnNotFound = true
130 tx.Statement.Dest = dest
131 return tx.callbacks.Query().Execute(tx)
132 }
133
134 // Take finds the first record returned by the database in no specified order, matching given conditions conds
135 func (db *DB) Take(dest interface{}, conds ...interface{}) (tx *DB) {
136 tx = db.Limit(1)
137 if len(conds) > 0 {
138 if exprs := tx.Statement.BuildCondition(conds[0], conds[1:]...); len(exprs) > 0 {
139 tx.Statement.AddClause(clause.Where{Exprs: exprs})
140 }
141 }
142 tx.Statement.RaiseErrorOnNotFound = true
143 tx.Statement.Dest = dest
144 return tx.callbacks.Query().Execute(tx)
145 }
146
147 // Last finds the last record ordered by primary key, matching given conditions conds
148 func (db *DB) Last(dest interface{}, conds ...interface{}) (tx *DB) {
149 tx = db.Limit(1).Order(clause.OrderByColumn{
150 Column: clause.Column{Table: clause.CurrentTable, Name: clause.PrimaryKey},
151 Desc: true,
152 })
153 if len(conds) > 0 {
154 if exprs := tx.Statement.BuildCondition(conds[0], conds[1:]...); len(exprs) > 0 {
155 tx.Statement.AddClause(clause.Where{Exprs: exprs})
156 }
157 }
158 tx.Statement.RaiseErrorOnNotFound = true
159 tx.Statement.Dest = dest
160 return tx.callbacks.Query().Execute(tx)
161 }
162
163 // Find finds all records matching given conditions conds
164 func (db *DB) Find(dest interface{}, conds ...interface{}) (tx *DB) {
165 tx = db.getInstance()
166 if len(conds) > 0 {
167 if exprs := tx.Statement.BuildCondition(conds[0], conds[1:]...); len(exprs) > 0 {
168 tx.Statement.AddClause(clause.Where{Exprs: exprs})
169 }
170 }
171 tx.Statement.Dest = dest
172 return tx.callbacks.Query().Execute(tx)
173 }
174
175 // FindInBatches finds all records in batches of batchSize
176 func (db *DB) FindInBatches(dest interface{}, batchSize int, fc func(tx *DB, batch int) error) *DB {
177 var (
178 tx = db.Order(clause.OrderByColumn{
179 Column: clause.Column{Table: clause.CurrentTable, Name: clause.PrimaryKey},
180 }).Session(&Session{})
181 queryDB = tx
182 rowsAffected int64
183 batch int
184 )
185
186 // user specified offset or limit
187 var totalSize int
188 if c, ok := tx.Statement.Clauses["LIMIT"]; ok {
189 if limit, ok := c.Expression.(clause.Limit); ok {
190 if limit.Limit != nil {
191 totalSize = *limit.Limit
192 }
193
194 if totalSize > 0 && batchSize > totalSize {
195 batchSize = totalSize
196 }
197
198 // reset to offset to 0 in next batch
199 tx = tx.Offset(-1).Session(&Session{})
200 }
201 }
202
203 for {
204 result := queryDB.Limit(batchSize).Find(dest)
205 rowsAffected += result.RowsAffected
206 batch++
207
208 if result.Error == nil && result.RowsAffected != 0 {
209 fcTx := result.Session(&Session{NewDB: true})
210 fcTx.RowsAffected = result.RowsAffected
211 tx.AddError(fc(fcTx, batch))
212 } else if result.Error != nil {
213 tx.AddError(result.Error)
214 }
215
216 if tx.Error != nil || int(result.RowsAffected) < batchSize {
217 break
218 }
219
220 if totalSize > 0 {
221 if totalSize <= int(rowsAffected) {
222 break
223 }
224 if totalSize/batchSize == batch {
225 batchSize = totalSize % batchSize
226 }
227 }
228
229 // Optimize for-break
230 resultsValue := reflect.Indirect(reflect.ValueOf(dest))
231 if result.Statement.Schema.PrioritizedPrimaryField == nil {
232 tx.AddError(ErrPrimaryKeyRequired)
233 break
234 }
235
236 primaryValue, zero := result.Statement.Schema.PrioritizedPrimaryField.ValueOf(tx.Statement.Context, resultsValue.Index(resultsValue.Len()-1))
237 if zero {
238 tx.AddError(ErrPrimaryKeyRequired)
239 break
240 }
241 queryDB = tx.Clauses(clause.Gt{Column: clause.Column{Table: clause.CurrentTable, Name: clause.PrimaryKey}, Value: primaryValue})
242 }
243
244 tx.RowsAffected = rowsAffected
245 return tx
246 }
247
248 func (db *DB) assignInterfacesToValue(values ...interface{}) {
249 for _, value := range values {
250 switch v := value.(type) {
251 case []clause.Expression:
252 for _, expr := range v {
253 if eq, ok := expr.(clause.Eq); ok {
254 switch column := eq.Column.(type) {
255 case string:
256 if field := db.Statement.Schema.LookUpField(column); field != nil {
257 db.AddError(field.Set(db.Statement.Context, db.Statement.ReflectValue, eq.Value))
258 }
259 case clause.Column:
260 if field := db.Statement.Schema.LookUpField(column.Name); field != nil {
261 db.AddError(field.Set(db.Statement.Context, db.Statement.ReflectValue, eq.Value))
262 }
263 }
264 } else if andCond, ok := expr.(clause.AndConditions); ok {
265 db.assignInterfacesToValue(andCond.Exprs)
266 }
267 }
268 case clause.Expression, map[string]string, map[interface{}]interface{}, map[string]interface{}:
269 if exprs := db.Statement.BuildCondition(value); len(exprs) > 0 {
270 db.assignInterfacesToValue(exprs)
271 }
272 default:
273 if s, err := schema.Parse(value, db.cacheStore, db.NamingStrategy); err == nil {
274 reflectValue := reflect.Indirect(reflect.ValueOf(value))
275 switch reflectValue.Kind() {
276 case reflect.Struct:
277 for _, f := range s.Fields {
278 if f.Readable {
279 if v, isZero := f.ValueOf(db.Statement.Context, reflectValue); !isZero {
280 if field := db.Statement.Schema.LookUpField(f.Name); field != nil {
281 db.AddError(field.Set(db.Statement.Context, db.Statement.ReflectValue, v))
282 }
283 }
284 }
285 }
286 }
287 } else if len(values) > 0 {
288 if exprs := db.Statement.BuildCondition(values[0], values[1:]...); len(exprs) > 0 {
289 db.assignInterfacesToValue(exprs)
290 }
291 return
292 }
293 }
294 }
295 }
296
297 // FirstOrInit finds the first matching record, otherwise if not found initializes a new instance with given conds.
298 // Each conds must be a struct or map.
299 //
300 // FirstOrInit never modifies the database. It is often used with Assign and Attrs.
301 //
302 // // assign an email if the record is not found
303 // db.Where(User{Name: "non_existing"}).Attrs(User{Email: "[email protected]"}).FirstOrInit(&user)
304 // // user -> User{Name: "non_existing", Email: "[email protected]"}
305 //
306 // // assign email regardless of if record is found
307 // db.Where(User{Name: "jinzhu"}).Assign(User{Email: "[email protected]"}).FirstOrInit(&user)
308 // // user -> User{Name: "jinzhu", Age: 20, Email: "[email protected]"}
309 func (db *DB) FirstOrInit(dest interface{}, conds ...interface{}) (tx *DB) {
310 queryTx := db.Limit(1).Order(clause.OrderByColumn{
311 Column: clause.Column{Table: clause.CurrentTable, Name: clause.PrimaryKey},
312 })
313
314 if tx = queryTx.Find(dest, conds...); tx.RowsAffected == 0 {
315 if c, ok := tx.Statement.Clauses["WHERE"]; ok {
316 if where, ok := c.Expression.(clause.Where); ok {
317 tx.assignInterfacesToValue(where.Exprs)
318 }
319 }
320
321 // initialize with attrs, conds
322 if len(tx.Statement.attrs) > 0 {
323 tx.assignInterfacesToValue(tx.Statement.attrs...)
324 }
325 }
326
327 // initialize with attrs, conds
328 if len(tx.Statement.assigns) > 0 {
329 tx.assignInterfacesToValue(tx.Statement.assigns...)
330 }
331 return
332 }
333
334 // FirstOrCreate finds the first matching record, otherwise if not found creates a new instance with given conds.
335 // Each conds must be a struct or map.
336 //
337 // Using FirstOrCreate in conjunction with Assign will result in an update to the database even if the record exists.
338 //
339 // // assign an email if the record is not found
340 // result := db.Where(User{Name: "non_existing"}).Attrs(User{Email: "[email protected]"}).FirstOrCreate(&user)
341 // // user -> User{Name: "non_existing", Email: "[email protected]"}
342 // // result.RowsAffected -> 1
343 //
344 // // assign email regardless of if record is found
345 // result := db.Where(User{Name: "jinzhu"}).Assign(User{Email: "[email protected]"}).FirstOrCreate(&user)
346 // // user -> User{Name: "jinzhu", Age: 20, Email: "[email protected]"}
347 // // result.RowsAffected -> 1
348 func (db *DB) FirstOrCreate(dest interface{}, conds ...interface{}) (tx *DB) {
349 tx = db.getInstance()
350 queryTx := db.Session(&Session{}).Limit(1).Order(clause.OrderByColumn{
351 Column: clause.Column{Table: clause.CurrentTable, Name: clause.PrimaryKey},
352 })
353
354 result := queryTx.Find(dest, conds...)
355 if result.Error != nil {
356 tx.Error = result.Error
357 return tx
358 }
359
360 if result.RowsAffected == 0 {
361 if c, ok := result.Statement.Clauses["WHERE"]; ok {
362 if where, ok := c.Expression.(clause.Where); ok {
363 result.assignInterfacesToValue(where.Exprs)
364 }
365 }
366
367 // initialize with attrs, conds
368 if len(db.Statement.attrs) > 0 {
369 result.assignInterfacesToValue(db.Statement.attrs...)
370 }
371
372 // initialize with attrs, conds
373 if len(db.Statement.assigns) > 0 {
374 result.assignInterfacesToValue(db.Statement.assigns...)
375 }
376
377 return tx.Create(dest)
378 } else if len(db.Statement.assigns) > 0 {
379 exprs := tx.Statement.BuildCondition(db.Statement.assigns[0], db.Statement.assigns[1:]...)
380 assigns := map[string]interface{}{}
381 for i := 0; i < len(exprs); i++ {
382 expr := exprs[i]
383
384 if eq, ok := expr.(clause.AndConditions); ok {
385 exprs = append(exprs, eq.Exprs...)
386 } else if eq, ok := expr.(clause.Eq); ok {
387 switch column := eq.Column.(type) {
388 case string:
389 assigns[column] = eq.Value
390 case clause.Column:
391 assigns[column.Name] = eq.Value
392 }
393 }
394 }
395
396 return tx.Model(dest).Updates(assigns)
397 }
398
399 return tx
400 }
401
402 // Update updates column with value using callbacks. Reference: https://gorm.io/docs/update.html#Update-Changed-Fields
403 func (db *DB) Update(column string, value interface{}) (tx *DB) {
404 tx = db.getInstance()
405 tx.Statement.Dest = map[string]interface{}{column: value}
406 return tx.callbacks.Update().Execute(tx)
407 }
408
409 // Updates updates attributes using callbacks. values must be a struct or map. Reference: https://gorm.io/docs/update.html#Update-Changed-Fields
410 func (db *DB) Updates(values interface{}) (tx *DB) {
411 tx = db.getInstance()
412 tx.Statement.Dest = values
413 return tx.callbacks.Update().Execute(tx)
414 }
415
416 func (db *DB) UpdateColumn(column string, value interface{}) (tx *DB) {
417 tx = db.getInstance()
418 tx.Statement.Dest = map[string]interface{}{column: value}
419 tx.Statement.SkipHooks = true
420 return tx.callbacks.Update().Execute(tx)
421 }
422
423 func (db *DB) UpdateColumns(values interface{}) (tx *DB) {
424 tx = db.getInstance()
425 tx.Statement.Dest = values
426 tx.Statement.SkipHooks = true
427 return tx.callbacks.Update().Execute(tx)
428 }
429
430 // Delete deletes value matching given conditions. If value contains primary key it is included in the conditions. If
431 // value includes a deleted_at field, then Delete performs a soft delete instead by setting deleted_at with the current
432 // time if null.
433 func (db *DB) Delete(value interface{}, conds ...interface{}) (tx *DB) {
434 tx = db.getInstance()
435 if len(conds) > 0 {
436 if exprs := tx.Statement.BuildCondition(conds[0], conds[1:]...); len(exprs) > 0 {
437 tx.Statement.AddClause(clause.Where{Exprs: exprs})
438 }
439 }
440 tx.Statement.Dest = value
441 return tx.callbacks.Delete().Execute(tx)
442 }
443
444 func (db *DB) Count(count *int64) (tx *DB) {
445 tx = db.getInstance()
446 if tx.Statement.Model == nil {
447 tx.Statement.Model = tx.Statement.Dest
448 defer func() {
449 tx.Statement.Model = nil
450 }()
451 }
452
453 if selectClause, ok := db.Statement.Clauses["SELECT"]; ok {
454 defer func() {
455 tx.Statement.Clauses["SELECT"] = selectClause
456 }()
457 } else {
458 defer delete(tx.Statement.Clauses, "SELECT")
459 }
460
461 if len(tx.Statement.Selects) == 0 {
462 tx.Statement.AddClause(clause.Select{Expression: clause.Expr{SQL: "count(*)"}})
463 } else if !strings.HasPrefix(strings.TrimSpace(strings.ToLower(tx.Statement.Selects[0])), "count(") {
464 expr := clause.Expr{SQL: "count(*)"}
465
466 if len(tx.Statement.Selects) == 1 {
467 dbName := tx.Statement.Selects[0]
468 fields := strings.FieldsFunc(dbName, utils.IsInvalidDBNameChar)
469 if len(fields) == 1 || (len(fields) == 3 && (strings.ToUpper(fields[1]) == "AS" || fields[1] == ".")) {
470 if tx.Statement.Parse(tx.Statement.Model) == nil {
471 if f := tx.Statement.Schema.LookUpField(dbName); f != nil {
472 dbName = f.DBName
473 }
474 }
475
476 if tx.Statement.Distinct {
477 expr = clause.Expr{SQL: "COUNT(DISTINCT(?))", Vars: []interface{}{clause.Column{Name: dbName}}}
478 } else if dbName != "*" {
479 expr = clause.Expr{SQL: "COUNT(?)", Vars: []interface{}{clause.Column{Name: dbName}}}
480 }
481 }
482 }
483
484 tx.Statement.AddClause(clause.Select{Expression: expr})
485 }
486
487 if orderByClause, ok := db.Statement.Clauses["ORDER BY"]; ok {
488 if _, ok := db.Statement.Clauses["GROUP BY"]; !ok {
489 delete(tx.Statement.Clauses, "ORDER BY")
490 defer func() {
491 tx.Statement.Clauses["ORDER BY"] = orderByClause
492 }()
493 }
494 }
495
496 tx.Statement.Dest = count
497 tx = tx.callbacks.Query().Execute(tx)
498
499 if _, ok := db.Statement.Clauses["GROUP BY"]; ok || tx.RowsAffected != 1 {
500 *count = tx.RowsAffected
501 }
502
503 return
504 }
505
506 func (db *DB) Row() *sql.Row {
507 tx := db.getInstance().Set("rows", false)
508 tx = tx.callbacks.Row().Execute(tx)
509 row, ok := tx.Statement.Dest.(*sql.Row)
510 if !ok && tx.DryRun {
511 db.Logger.Error(tx.Statement.Context, ErrDryRunModeUnsupported.Error())
512 }
513 return row
514 }
515
516 func (db *DB) Rows() (*sql.Rows, error) {
517 tx := db.getInstance().Set("rows", true)
518 tx = tx.callbacks.Row().Execute(tx)
519 rows, ok := tx.Statement.Dest.(*sql.Rows)
520 if !ok && tx.DryRun && tx.Error == nil {
521 tx.Error = ErrDryRunModeUnsupported
522 }
523 return rows, tx.Error
524 }
525
526 // Scan scans selected value to the struct dest
527 func (db *DB) Scan(dest interface{}) (tx *DB) {
528 config := *db.Config
529 currentLogger, newLogger := config.Logger, logger.Recorder.New()
530 config.Logger = newLogger
531
532 tx = db.getInstance()
533 tx.Config = &config
534
535 if rows, err := tx.Rows(); err == nil {
536 if rows.Next() {
537 tx.ScanRows(rows, dest)
538 } else {
539 tx.RowsAffected = 0
540 tx.AddError(rows.Err())
541 }
542 tx.AddError(rows.Close())
543 }
544
545 currentLogger.Trace(tx.Statement.Context, newLogger.BeginAt, func() (string, int64) {
546 return newLogger.SQL, tx.RowsAffected
547 }, tx.Error)
548 tx.Logger = currentLogger
549 return
550 }
551
552 // Pluck queries a single column from a model, returning in the slice dest. E.g.:
553 //
554 // var ages []int64
555 // db.Model(&users).Pluck("age", &ages)
556 func (db *DB) Pluck(column string, dest interface{}) (tx *DB) {
557 tx = db.getInstance()
558 if tx.Statement.Model != nil {
559 if tx.Statement.Parse(tx.Statement.Model) == nil {
560 if f := tx.Statement.Schema.LookUpField(column); f != nil {
561 column = f.DBName
562 }
563 }
564 }
565
566 if len(tx.Statement.Selects) != 1 {
567 fields := strings.FieldsFunc(column, utils.IsInvalidDBNameChar)
568 tx.Statement.AddClauseIfNotExists(clause.Select{
569 Distinct: tx.Statement.Distinct,
570 Columns: []clause.Column{{Name: column, Raw: len(fields) != 1}},
571 })
572 }
573 tx.Statement.Dest = dest
574 return tx.callbacks.Query().Execute(tx)
575 }
576
577 func (db *DB) ScanRows(rows *sql.Rows, dest interface{}) error {
578 tx := db.getInstance()
579 if err := tx.Statement.Parse(dest); !errors.Is(err, schema.ErrUnsupportedDataType) {
580 tx.AddError(err)
581 }
582 tx.Statement.Dest = dest
583 tx.Statement.ReflectValue = reflect.ValueOf(dest)
584 for tx.Statement.ReflectValue.Kind() == reflect.Ptr {
585 elem := tx.Statement.ReflectValue.Elem()
586 if !elem.IsValid() {
587 elem = reflect.New(tx.Statement.ReflectValue.Type().Elem())
588 tx.Statement.ReflectValue.Set(elem)
589 }
590 tx.Statement.ReflectValue = elem
591 }
592 Scan(rows, tx, ScanInitialized)
593 return tx.Error
594 }
595
596 // Connection uses a db connection to execute an arbitrary number of commands in fc. When finished, the connection is
597 // returned to the connection pool.
598 func (db *DB) Connection(fc func(tx *DB) error) (err error) {
599 if db.Error != nil {
600 return db.Error
601 }
602
603 tx := db.getInstance()
604 sqlDB, err := tx.DB()
605 if err != nil {
606 return
607 }
608
609 conn, err := sqlDB.Conn(tx.Statement.Context)
610 if err != nil {
611 return
612 }
613
614 defer conn.Close()
615 tx.Statement.ConnPool = conn
616 return fc(tx)
617 }
618
619 // Transaction start a transaction as a block, return error will rollback, otherwise to commit. Transaction executes an
620 // arbitrary number of commands in fc within a transaction. On success the changes are committed; if an error occurs
621 // they are rolled back.
622 func (db *DB) Transaction(fc func(tx *DB) error, opts ...*sql.TxOptions) (err error) {
623 panicked := true
624
625 if committer, ok := db.Statement.ConnPool.(TxCommitter); ok && committer != nil {
626 // nested transaction
627 if !db.DisableNestedTransaction {
628 spID := new(maphash.Hash).Sum64()
629 err = db.SavePoint(fmt.Sprintf("sp%d", spID)).Error
630 if err != nil {
631 return
632 }
633 defer func() {
634 // Make sure to rollback when panic, Block error or Commit error
635 if panicked || err != nil {
636 db.RollbackTo(fmt.Sprintf("sp%d", spID))
637 }
638 }()
639 }
640 err = fc(db.Session(&Session{NewDB: db.clone == 1}))
641 } else {
642 tx := db.Begin(opts...)
643 if tx.Error != nil {
644 return tx.Error
645 }
646
647 defer func() {
648 // Make sure to rollback when panic, Block error or Commit error
649 if panicked || err != nil {
650 tx.Rollback()
651 }
652 }()
653
654 if err = fc(tx); err == nil {
655 panicked = false
656 return tx.Commit().Error
657 }
658 }
659
660 panicked = false
661 return
662 }
663
664 // Begin begins a transaction with any transaction options opts
665 func (db *DB) Begin(opts ...*sql.TxOptions) *DB {
666 var (
667 // clone statement
668 tx = db.getInstance().Session(&Session{Context: db.Statement.Context, NewDB: db.clone == 1})
669 opt *sql.TxOptions
670 err error
671 )
672
673 if len(opts) > 0 {
674 opt = opts[0]
675 }
676
677 ctx := tx.Statement.Context
678 if db.DefaultTransactionTimeout > 0 {
679 if _, ok := ctx.Deadline(); !ok {
680 ctx, _ = context.WithTimeout(ctx, db.DefaultTransactionTimeout)
681 }
682 }
683
684 switch beginner := tx.Statement.ConnPool.(type) {
685 case TxBeginner:
686 tx.Statement.ConnPool, err = beginner.BeginTx(ctx, opt)
687 case ConnPoolBeginner:
688 tx.Statement.ConnPool, err = beginner.BeginTx(ctx, opt)
689 default:
690 err = ErrInvalidTransaction
691 }
692
693 if err != nil {
694 tx.AddError(err)
695 }
696
697 return tx
698 }
699
700 // Commit commits the changes in a transaction
701 func (db *DB) Commit() *DB {
702 if committer, ok := db.Statement.ConnPool.(TxCommitter); ok && committer != nil && !reflect.ValueOf(committer).IsNil() {
703 db.AddError(committer.Commit())
704 } else {
705 db.AddError(ErrInvalidTransaction)
706 }
707 return db
708 }
709
710 // Rollback rollbacks the changes in a transaction
711 func (db *DB) Rollback() *DB {
712 if committer, ok := db.Statement.ConnPool.(TxCommitter); ok && committer != nil {
713 if !reflect.ValueOf(committer).IsNil() {
714 db.AddError(committer.Rollback())
715 }
716 } else {
717 db.AddError(ErrInvalidTransaction)
718 }
719 return db
720 }
721
722 func (db *DB) SavePoint(name string) *DB {
723 if savePointer, ok := db.Dialector.(SavePointerDialectorInterface); ok {
724 // close prepared statement, because SavePoint not support prepared statement.
725 // e.g. mysql8.0 doc: https://dev.mysql.com/doc/refman/8.0/en/sql-prepared-statements.html
726 var (
727 preparedStmtTx *PreparedStmtTX
728 isPreparedStmtTx bool
729 )
730 // close prepared statement, because SavePoint not support prepared statement.
731 if preparedStmtTx, isPreparedStmtTx = db.Statement.ConnPool.(*PreparedStmtTX); isPreparedStmtTx {
732 db.Statement.ConnPool = preparedStmtTx.Tx
733 }
734 db.AddError(savePointer.SavePoint(db, name))
735 // restore prepared statement
736 if isPreparedStmtTx {
737 db.Statement.ConnPool = preparedStmtTx
738 }
739 } else {
740 db.AddError(ErrUnsupportedDriver)
741 }
742 return db
743 }
744
745 func (db *DB) RollbackTo(name string) *DB {
746 if savePointer, ok := db.Dialector.(SavePointerDialectorInterface); ok {
747 // close prepared statement, because RollbackTo not support prepared statement.
748 // e.g. mysql8.0 doc: https://dev.mysql.com/doc/refman/8.0/en/sql-prepared-statements.html
749 var (
750 preparedStmtTx *PreparedStmtTX
751 isPreparedStmtTx bool
752 )
753 // close prepared statement, because SavePoint not support prepared statement.
754 if preparedStmtTx, isPreparedStmtTx = db.Statement.ConnPool.(*PreparedStmtTX); isPreparedStmtTx {
755 db.Statement.ConnPool = preparedStmtTx.Tx
756 }
757 db.AddError(savePointer.RollbackTo(db, name))
758 // restore prepared statement
759 if isPreparedStmtTx {
760 db.Statement.ConnPool = preparedStmtTx
761 }
762 } else {
763 db.AddError(ErrUnsupportedDriver)
764 }
765 return db
766 }
767
768 // Exec executes raw sql
769 func (db *DB) Exec(sql string, values ...interface{}) (tx *DB) {
770 tx = db.getInstance()
771 tx.Statement.SQL = strings.Builder{}
772
773 if strings.Contains(sql, "@") {
774 clause.NamedExpr{SQL: sql, Vars: values}.Build(tx.Statement)
775 } else {
776 clause.Expr{SQL: sql, Vars: values}.Build(tx.Statement)
777 }
778
779 return tx.callbacks.Raw().Execute(tx)
780 }