Repository navigation
Expand file tree
/
Copy pathexample_sqlxtransaction_test.go
More file actions
122 lines (93 loc) · 2.4 KB
/
Copy pathexample_sqlxtransaction_test.go
File metadata and controls
122 lines (93 loc) · 2.4 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
116
117
118
119
120
121
122
package sqlxtransaction_test
import (
"context"
"database/sql"
"errors"
"fmt"
"github.com/DATA-DOG/go-sqlmock"
"github.com/jmoiron/sqlx"
"github.com/tecnickcom/nurago/pkg/sqlxtransaction"
)
func ExampleExec() {
// A real program would use a *sqlx.DB from sqlx.Connect. The mock keeps
// the example self-contained and its output deterministic.
mockDB, mock, err := sqlmock.New()
if err != nil {
fmt.Println(err)
return
}
db := sqlx.NewDb(mockDB, "sqlmock")
defer func() { _ = db.Close() }()
mock.ExpectBegin()
mock.ExpectExec("INSERT INTO audit").WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectCommit()
// The transaction is committed when run returns nil, and rolled back
// when it returns an error or panics.
err = sqlxtransaction.Exec(
context.TODO(),
db,
func(ctx context.Context, tx *sqlx.Tx) error {
_, err := tx.ExecContext(ctx, "INSERT INTO audit (event) VALUES ('login')")
if err != nil {
return fmt.Errorf("writing audit row: %w", err)
}
return nil
},
)
fmt.Println("committed:", err)
// Output:
// committed: <nil>
}
func ExampleExec_rollback() {
mockDB, mock, err := sqlmock.New()
if err != nil {
fmt.Println(err)
return
}
db := sqlx.NewDb(mockDB, "sqlmock")
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 = sqlxtransaction.Exec(
context.TODO(),
db,
func(_ context.Context, _ *sqlx.Tx) error {
return errors.New("validation failed")
},
)
fmt.Println("rolled back:", err)
// Output:
// rolled back: failed executing a function inside SQLX transaction: validation failed
}
func ExampleExecWithOptions() {
mockDB, mock, err := sqlmock.New()
if err != nil {
fmt.Println(err)
return
}
db := sqlx.NewDb(mockDB, "sqlmock")
defer func() { _ = db.Close() }()
mock.ExpectBegin()
mock.ExpectQuery("SELECT name").WillReturnRows(
sqlmock.NewRows([]string{"name"}).AddRow("alice"),
)
mock.ExpectCommit()
opts := &sql.TxOptions{
Isolation: sql.LevelReadCommitted,
ReadOnly: true,
}
var names []string
err = sqlxtransaction.ExecWithOptions(
context.TODO(),
db,
func(ctx context.Context, tx *sqlx.Tx) error {
return tx.SelectContext(ctx, &names, "SELECT name FROM users")
},
opts,
)
fmt.Println(names, err)
// Output:
// [alice] <nil>
}