Repository navigation
Expand file tree
/
Copy pathexample_sqltransaction_test.go
More file actions
115 lines (89 loc) · 2.25 KB
/
Copy pathexample_sqltransaction_test.go
File metadata and controls
115 lines (89 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package sqltransaction_test
import (
"context"
"database/sql"
"errors"
"fmt"
"github.com/DATA-DOG/go-sqlmock"
"github.com/tecnickcom/nurago/pkg/sqltransaction"
)
func ExampleExec() {
// A real program would use a *sql.DB from sql.Open. The mock keeps the
// example self-contained and its output deterministic.
db, mock, err := sqlmock.New()
if err != nil {
fmt.Println(err)
return
}
defer func() { _ = db.Close() }()
mock.ExpectBegin()
mock.ExpectExec("UPDATE balance").WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectCommit()
// The transaction is committed when run returns nil, and rolled back
// when it returns an error or panics.
err = sqltransaction.Exec(
context.TODO(),
db,
func(ctx context.Context, tx *sql.Tx) error {
_, err := tx.ExecContext(ctx, "UPDATE balance SET amount = amount - 10 WHERE id = 1")
if err != nil {
return fmt.Errorf("debiting account: %w", err)
}
return nil
},
)
fmt.Println("committed:", err)
// Output:
// committed: <nil>
}
func ExampleExec_rollback() {
db, mock, err := sqlmock.New()
if err != nil {
fmt.Println(err)
return
}
defer func() { _ = db.Close() }()
mock.ExpectBegin()
mock.ExpectRollback()
// Returning an error from run rolls the transaction back. The error is
// wrapped, so errors.Is and errors.As still match the original.
err = sqltransaction.Exec(
context.TODO(),
db,
func(_ context.Context, _ *sql.Tx) error {
return errors.New("insufficient funds")
},
)
fmt.Println("rolled back:", err)
// Output:
// rolled back: failed executing a function inside SQL transaction: insufficient funds
}
func ExampleExecWithOptions() {
db, mock, err := sqlmock.New()
if err != nil {
fmt.Println(err)
return
}
defer func() { _ = db.Close() }()
mock.ExpectBegin()
mock.ExpectQuery("SELECT SUM").WillReturnRows(
sqlmock.NewRows([]string{"total"}).AddRow(42),
)
mock.ExpectCommit()
opts := &sql.TxOptions{
Isolation: sql.LevelSerializable,
ReadOnly: true,
}
var total int
err = sqltransaction.ExecWithOptions(
context.TODO(),
db,
func(ctx context.Context, tx *sql.Tx) error {
return tx.QueryRowContext(ctx, "SELECT SUM(amount) FROM balance").Scan(&total)
},
opts,
)
fmt.Println(total, err)
// Output:
// 42 <nil>
}