Begin begins a transaction with any transaction options opts
(opts ...*sql.TxOptions)
| 678 | |
| 679 | // Begin begins a transaction with any transaction options opts |
| 680 | func (db *DB) Begin(opts ...*sql.TxOptions) *DB { |
| 681 | var ( |
| 682 | // clone statement |
| 683 | tx = db.getInstance().Session(&Session{Context: db.Statement.Context, NewDB: db.clone == 1}) |
| 684 | opt *sql.TxOptions |
| 685 | err error |
| 686 | ) |
| 687 | |
| 688 | if len(opts) > 0 { |
| 689 | opt = opts[0] |
| 690 | } |
| 691 | |
| 692 | ctx := tx.Statement.Context |
| 693 | if db.DefaultTransactionTimeout > 0 { |
| 694 | if _, ok := ctx.Deadline(); !ok { |
| 695 | ctx, _ = context.WithTimeout(ctx, db.DefaultTransactionTimeout) |
| 696 | } |
| 697 | } |
| 698 | |
| 699 | switch beginner := tx.Statement.ConnPool.(type) { |
| 700 | case TxBeginner: |
| 701 | tx.Statement.ConnPool, err = beginner.BeginTx(ctx, opt) |
| 702 | case ConnPoolBeginner: |
| 703 | tx.Statement.ConnPool, err = beginner.BeginTx(ctx, opt) |
| 704 | default: |
| 705 | err = ErrInvalidTransaction |
| 706 | } |
| 707 | |
| 708 | if err != nil { |
| 709 | tx.AddError(err) |
| 710 | } |
| 711 | |
| 712 | return tx |
| 713 | } |
| 714 | |
| 715 | // Commit commits the changes in a transaction |
| 716 | func (db *DB) Commit() *DB { |