Debian Codegraph @

crdb/tx_test.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
16
17 import (
18 "context"
19 "database/sql"
20 "fmt"
21 "sync"
22 "testing"
23
24 "github.com/cockroachdb/cockroach-go/testserver"
25 )
26
27 func TestExecuteTx(t *testing.T) {
28 testExecuteTxInner(t, ExecuteTx)
29 }
30
31 func TestExecuteInTx(t *testing.T) {
32 executeTx := func(
33 ctx context.Context,
34 db *sql.DB,
35 opts *sql.TxOptions,
36 fn func(*sql.Tx) error,
37 ) error {
38 tx, err := db.BeginTx(ctx, opts)
39 if err != nil {
40 return err
41 }
42 return ExecuteInTx(ctx, tx, func() error { return fn(tx) })
43 }
44 testExecuteTxInner(t, executeTx)
45 }
46
47 // TestExecuteTx verifies transaction retry using the classic
48 // example of write skew in bank account balance transfers.
49 func testExecuteTxInner(
50 t *testing.T,
51 executeTxFn func(
52 context.Context,
53 *sql.DB,
54 *sql.TxOptions,
55 func(*sql.Tx) error,
56 ) error,
57 ) {
58 db, stop := testserver.NewDBForTest(t)
59 defer stop()
60
61 initStmt := `
62 CREATE DATABASE d;
63 CREATE TABLE d.t (acct INT PRIMARY KEY, balance INT);
64 INSERT INTO d.t (acct, balance) VALUES (1, 100), (2, 100);
65 `
66 if _, err := db.Exec(initStmt); err != nil {
67 t.Fatal(err)
68 }
69
70 type queryI interface {
71 Query(string, ...interface{}) (*sql.Rows, error)
72 }
73
74 getBalances := func(q queryI) (bal1, bal2 int, err error) {
75 var rows *sql.Rows
76 rows, err = q.Query(`SELECT balance FROM d.t WHERE acct IN (1, 2);`)
77 if err != nil {
78 return
79 }
80 defer rows.Close()
81 balances := []*int{&bal1, &bal2}
82 i := 0
83 for ; rows.Next(); i++ {
84 if err = rows.Scan(balances[i]); err != nil {
85 return
86 }
87 }
88 if i != 2 {
89 err = fmt.Errorf("expected two balances; got %d", i)
90 return
91 }
92 return
93 }
94
95 runTxn := func(wg *sync.WaitGroup, iter *int) <-chan error {
96 errCh := make(chan error, 1)
97 go func() {
98 *iter = 0
99 errCh <- executeTxFn(context.Background(), db, nil, func(tx *sql.Tx) error {
100 *iter++
101 bal1, bal2, err := getBalances(tx)
102 if err != nil {
103 return err
104 }
105 // If this is the first iteration, wait for the other tx to also read.
106 if *iter == 1 {
107 wg.Done()
108 wg.Wait()
109 }
110 // Now, subtract from one account and give to the other.
111 if bal1 > bal2 {
112 if _, err := tx.Exec(`
113 UPDATE d.t SET balance=balance-100 WHERE acct=1;
114 UPDATE d.t SET balance=balance+100 WHERE acct=2;
115 `); err != nil {
116 return err
117 }
118 } else {
119 if _, err := tx.Exec(`
120 UPDATE d.t SET balance=balance+100 WHERE acct=1;
121 UPDATE d.t SET balance=balance-100 WHERE acct=2;
122 `); err != nil {
123 return err
124 }
125 }
126 return nil
127 })
128 }()
129 return errCh
130 }
131
132 var wg sync.WaitGroup
133 wg.Add(2)
134 var iters1, iters2 int
135 txn1Err := runTxn(&wg, &iters1)
136 txn2Err := runTxn(&wg, &iters2)
137 if err := <-txn1Err; err != nil {
138 t.Errorf("expected success in txn1; got %s", err)
139 }
140 if err := <-txn2Err; err != nil {
141 t.Errorf("expected success in txn2; got %s", err)
142 }
143 if iters1+iters2 <= 2 {
144 t.Errorf("expected at least one retry between the competing transactions; "+
145 "got txn1=%d, txn2=%d", iters1, iters2)
146 }
147 bal1, bal2, err := getBalances(db)
148 if err != nil || bal1 != 100 || bal2 != 100 {
149 t.Errorf("expected balances to be restored without error; "+
150 "got acct1=%d, acct2=%d: %s", bal1, bal2, err)
151 }
152 }