|
| 1 | +package sql |
| 2 | + |
| 3 | +import "time" |
| 4 | + |
| 5 | +type TransactionOption func(options *TransactionOptions) |
| 6 | + |
| 7 | +type TransactionOptions struct { |
| 8 | + propagation Propagation |
| 9 | + timeout time.Duration |
| 10 | + readOnly bool |
| 11 | + isolationLevel IsolationLevel |
| 12 | +} |
| 13 | + |
| 14 | +func (o *TransactionOptions) Propagation() Propagation { |
| 15 | + return o.propagation |
| 16 | +} |
| 17 | + |
| 18 | +func (o *TransactionOptions) Timeout() time.Duration { |
| 19 | + return o.timeout |
| 20 | +} |
| 21 | + |
| 22 | +func (o *TransactionOptions) IsReadOnly() bool { |
| 23 | + return o.readOnly |
| 24 | +} |
| 25 | + |
| 26 | +func (o *TransactionOptions) IsolationLevel() IsolationLevel { |
| 27 | + return o.isolationLevel |
| 28 | +} |
| 29 | + |
| 30 | +func (o *TransactionOptions) Merge(options *TransactionOptions) *TransactionOptions { |
| 31 | + copyOptions := new(TransactionOptions) |
| 32 | + *copyOptions = *o |
| 33 | + |
| 34 | + copyOptions.propagation = options.propagation |
| 35 | + copyOptions.timeout = options.timeout |
| 36 | + copyOptions.readOnly = options.readOnly |
| 37 | + copyOptions.isolationLevel = options.isolationLevel |
| 38 | + |
| 39 | + return copyOptions |
| 40 | +} |
| 41 | + |
| 42 | +func (o *TransactionOptions) Override(options ...TransactionOption) *TransactionOptions { |
| 43 | + copyOptions := new(TransactionOptions) |
| 44 | + *copyOptions = *o |
| 45 | + |
| 46 | + for _, option := range options { |
| 47 | + option(copyOptions) |
| 48 | + } |
| 49 | + |
| 50 | + return copyOptions |
| 51 | +} |
| 52 | + |
| 53 | +func DefaultTransactionOptions() *TransactionOptions { |
| 54 | + return &TransactionOptions{ |
| 55 | + propagation: PropagationRequired, |
| 56 | + timeout: -1, |
| 57 | + readOnly: false, |
| 58 | + isolationLevel: LevelDefault, |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +func NewTransactionOptions(opts ...TransactionOption) *TransactionOptions { |
| 63 | + return DefaultTransactionOptions().Override(opts...) |
| 64 | +} |
| 65 | + |
| 66 | +func WithPropagation(propagation Propagation) TransactionOption { |
| 67 | + return func(options *TransactionOptions) { |
| 68 | + options.propagation = propagation |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +func WithTimeout(timeout time.Duration) TransactionOption { |
| 73 | + return func(options *TransactionOptions) { |
| 74 | + options.timeout = timeout |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +func WithReadOnly(readOnly bool) TransactionOption { |
| 79 | + return func(options *TransactionOptions) { |
| 80 | + options.readOnly = readOnly |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +func WithIsolation(isolationLevel IsolationLevel) TransactionOption { |
| 85 | + return func(options *TransactionOptions) { |
| 86 | + options.isolationLevel = isolationLevel |
| 87 | + } |
| 88 | +} |
0 commit comments