Debian Codegraph @

crdb/tx.go

raw symbols SCIP
1 // Copyright 2016 The Cockroach Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12 // implied. See the License for the specific language governing
13 // permissions and limitations under the License.
14
15 // Package crdb provides helpers for using CockroachDB in client
16 // applications.
17 package crdb
18
19 import (
20 "context"
21 "database/sql"
22 "fmt"
23
24 "github.com/lib/pq"
25 )
26
27 // AmbiguousCommitError represents an error that left a transaction in an
28 // ambiguous state: unclear if it committed or not.
29 type AmbiguousCommitError struct {
30 error
31 }
32
33 // ExecuteTx runs fn inside a transaction and retries it as needed.
34 // On non-retryable failures, the transaction is aborted and rolled
35 // back; on success, the transaction is committed.
36 // There are cases where the state of a transaction is inherently ambiguous: if
37 // we err on RELEASE with a communication error it's unclear if the transaction
38 // has been committed or not (similar to erroring on COMMIT in other databases).
39 // In that case, we return AmbiguousCommitError.
40 //
41 // For more information about CockroachDB's transaction model see
42 // https://cockroachlabs.com/docs/stable/transactions.html.
43 //
44 // NOTE: the supplied exec closure should not have external side
45 // effects beyond changes to the database.
46 func ExecuteTx(ctx context.Context, db *sql.DB, txopts *sql.TxOptions, fn func(*sql.Tx) error) error {
47 // Start a transaction.
48 tx, err := db.BeginTx(ctx, txopts)
49 if err != nil {
50 return err
51 }
52 return ExecuteInTx(ctx, tx, func() error { return fn(tx) })
53 }
54
55 // Tx is used to permit clients to implement custom transaction logic.
56 type Tx interface {
57 ExecContext(context.Context, string, ...interface{}) (sql.Result, error)
58 Commit() error
59 Rollback() error
60 }
61
62 // ExecuteInTx runs fn inside tx which should already have begun.
63 // *WARNING*: Do not execute any statements on the supplied tx before calling this function.
64 // ExecuteInTx will only retry statements that are performed within the supplied
65 // closure (fn). Any statements performed on the tx before ExecuteInTx is invoked will *not*
66 // be re-run if the transaction needs to be retried.
67 func ExecuteInTx(ctx context.Context, tx Tx, fn func() error) (err error) {
68 defer func() {
69 if err == nil {
70 // Ignore commit errors. The tx has already been committed by RELEASE.
71 _ = tx.Commit()
72 } else {
73 // We always need to execute a Rollback() so sql.DB releases the
74 // connection.
75 _ = tx.Rollback()
76 }
77 }()
78 // Specify that we intend to retry this txn in case of CockroachDB retryable
79 // errors.
80 if _, err = tx.ExecContext(ctx, "SAVEPOINT cockroach_restart"); err != nil {
81 return err
82 }
83
84 for {
85 released := false
86 err = fn()
87 if err == nil {
88 // RELEASE acts like COMMIT in CockroachDB. We use it since it gives us an
89 // opportunity to react to retryable errors, whereas tx.Commit() doesn't.
90 released = true
91 if _, err = tx.ExecContext(ctx, "RELEASE SAVEPOINT cockroach_restart"); err == nil {
92 return nil
93 }
94 }
95 // We got an error; let's see if it's a retryable one and, if so, restart. We look
96 // for either the standard PG errcode SerializationFailureError:40001 or the Cockroach extension
97 // errcode RetriableError:CR000. The Cockroach extension has been removed server-side, but support
98 // for it has been left here for now to maintain backwards compatibility.
99 pqErr, ok := err.(*pq.Error)
100 if retryable := ok && (pqErr.Code == "CR000" || pqErr.Code == "40001"); !retryable {
101 if released {
102 err = &AmbiguousCommitError{err}
103 }
104 return err
105 }
106 if _, err = tx.ExecContext(ctx, "ROLLBACK TO SAVEPOINT cockroach_restart"); err != nil {
107 // ROLLBACK TO SAVEPOINT failed. If it failed with a lib/pq error, we want
108 // to pass this error to the client, but also include the original error
109 // message and code. So, we'll do some surgery on lib/pq errors in
110 // particular.
111 // If it failed with any other error (e.g. the "driver: bad connection" is
112 // untyped), we overwrite the error.
113 msgPattern := "restarting txn failed. ROLLBACK TO SAVEPOINT encountered error: %s. " +
114 "Original error (code: %s): %s."
115 if rollbackPQErr, ok := err.(*pq.Error); ok {
116 rollbackPQErr.Message = fmt.Sprintf(msgPattern, rollbackPQErr, pqErr.Code, pqErr)
117 return rollbackPQErr
118 }
119 return fmt.Errorf(msgPattern, err, pqErr.Code, pqErr)
120 }
121 }
122 }