MCPcopy Index your code
hub / github.com/coder/coder / InTx

Method InTx

coderd/database/db.go:143–182  ·  view source on GitHub ↗
(function func(Store) error, txOpts *TxOptions)

Source from the content-addressed store, hash-verified

141}
142
143func (q *sqlQuerier) InTx(function func(Store) error, txOpts *TxOptions) error {
144 _, inTx := q.db.(*sqlx.Tx)
145
146 if txOpts == nil {
147 // create a default txOpts if left to nil
148 txOpts = DefaultTXOptions()
149 }
150
151 sqlOpts := &sql.TxOptions{
152 Isolation: txOpts.Isolation,
153 ReadOnly: txOpts.ReadOnly,
154 }
155
156 // If we are not already in a transaction, and we are running in serializable
157 // mode, we need to run the transaction in a retry loop. The caller should be
158 // prepared to allow retries if using serializable mode.
159 // If we are in a transaction already, the parent InTx call will handle the retry.
160 // We do not want to duplicate those retries.
161 if !inTx && sqlOpts.Isolation == sql.LevelSerializable {
162 var err error
163 attempts := 0
164 for attempts = 0; attempts < q.serialRetryCount; attempts++ {
165 txOpts.executionCount++
166 err = q.runTx(function, sqlOpts)
167 if err == nil {
168 // Transaction succeeded.
169 return nil
170 }
171 if !IsSerializedError(err) {
172 // We should only retry if the error is a serialization error.
173 return err
174 }
175 }
176 // Transaction kept failing in serializable mode.
177 return xerrors.Errorf("transaction failed after %d attempts: %w", attempts, err)
178 }
179
180 txOpts.executionCount++
181 return q.runTx(function, sqlOpts)
182}
183
184// InTx performs database operations inside a transaction.
185func (q *sqlQuerier) runTx(function func(Store) error, txOpts *sql.TxOptions) (err error) {

Callers

nothing calls this directly

Calls 4

runTxMethod · 0.95
DefaultTXOptionsFunction · 0.85
IsSerializedErrorFunction · 0.85
ErrorfMethod · 0.45

Tested by

no test coverage detected