-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatement.go
302 lines (258 loc) · 8.58 KB
/
statement.go
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
package db
import (
"context"
"database/sql"
"github.com/bdlm/errors/v2"
"github.com/bdlm/log/v2"
nr "github.com/newrelic/go-agent/v3/newrelic"
)
// Statement defines the prepared statement structure and API.
type Statement struct {
// Bind params
binds []sql.NamedArg
ctx context.Context
// Reference to the database instance that spawned this statement
db *DB
// Keeps track of the last error that occurred
lastErr error
// The NewRelic transaction agent
nrtxn *nr.Transaction
// Reference to the result object for inspection
// https://golang.org/pkg/database/sql/#Result
result sql.Result
// Reference to the data rows object for iteration
// https://golang.org/pkg/database/sql/#Rows
rows *sql.Rows
// The SQL query string
sql string
// The Stmt struct from the database/sql package
// https://golang.org/pkg/database/sql/#Stmt
stmt *sql.Stmt
// The transaction instance used to manage this statement
// https://golang.org/pkg/database/sql/#Tx
txn *sql.Tx
}
// Bind provides a concise way to bind values to named arguments.
func (statement *Statement) Bind(key string, value interface{}) *Statement {
statement.binds = append(statement.binds, sql.Named(key, value))
return statement
}
// Close closes the current prepared statement and all related items.
func (statement *Statement) Close() error {
var err error
var errList []error
if nil != statement.rows {
if err = statement.rows.Close(); nil != err {
errList = append(errList, errors.Wrap(err, "error closing rows"))
}
}
if err = statement.txn.Rollback(); nil != err {
errList = append(errList, errors.Wrap(err, "error rolling back transaction"))
}
if err = statement.stmt.Close(); nil != err {
errList = append(errList, errors.Wrap(err, "error closing statement"))
}
if 0 < len(errList) {
err = errList[0]
for _, e := range errList[1:] {
err = errors.WrapE(err, e)
}
statement.lastErr = err
}
if nil != statement.nrtxn {
statement.nrtxn.End()
}
return err
}
// Commit commits the current transaction to the database.
func (statement *Statement) Commit() error {
_ = statement.txn.Commit()
return nil
}
// Err returns the error, if any, that was encountered during iteration.
// Err may be called after an explicit or implicit Close.
// https://golang.org/pkg/database/sql/#Rows.Err
func (statement *Statement) Err() error {
if nil == statement.rows {
return nil
}
err := statement.rows.Err()
if nil != err {
statement.lastErr = err
}
return err
}
// Exec executes the prepared statement with any arguments that have been
// added using Bind() calls.
func (statement *Statement) Exec(args ...interface{}) (sql.Result, error) {
return statement.ExecContext(statement.ctx, args...)
}
// ExecContext executes the prepared statement with any arguments that have been
// added using Bind() calls.
func (statement *Statement) ExecContext(ctx context.Context, args ...interface{}) (sql.Result, error) {
var err error
var binds []interface{}
for _, bind := range statement.binds {
binds = append(binds, bind)
}
binds = append(binds, args...)
statement.result, err = statement.stmt.ExecContext(ctx, binds...)
if nil != err {
statement.lastErr = err
}
statement.binds = []sql.NamedArg{}
return statement.result, err
}
// LastErr returns the last error encountered by this statement.
func (statement *Statement) LastErr() error {
return statement.lastErr
}
// MapNext prepares the next result row for reading with the Scan method(). It
// returns true on success, or false if there is no next result row or an
// error happened while preparing it. Statement.Err should be consulted
// to distinguish between the two cases.
// https://golang.org/pkg/database/sql/#Rows.Next
//
// This also performs a Scan operation. Scan copies the columns in the
// current row into the values pointed at by dest. The number of values in
// dest must be the same as the number of columns in Rows.
// https://golang.org/pkg/database/sql/#Rows.Scan
func (statement *Statement) MapNext(dest map[string]interface{}) bool {
if nil == statement.rows {
statement.lastErr = errors.Errorf("no cursor found. did you remember to run `statement.Query()`?")
log.WithError(statement.lastErr).Error("cursor not found")
return false
}
if !statement.rows.Next() {
err := statement.Err()
if nil != err {
statement.lastErr = err
}
return false
}
err := statement.MapScan(dest)
if nil != err {
statement.lastErr = err
return false
}
return true
}
// MapScan copies the columns in the current row into the values pointed at by
// dest. The number of values in dest must be the same as the number of
// columns in Rows.
// https://golang.org/pkg/database/sql/#Rows.Scan
func (statement *Statement) MapScan(dest map[string]interface{}) error {
columns, err := statement.rows.Columns()
if err != nil {
return errors.Wrap(err, "failed to list result columns")
}
values := make([]interface{}, len(columns))
for i := range values {
values[i] = new(interface{})
}
err = statement.rows.Scan(values...)
if err != nil {
return errors.Wrap(err, "failed to scan result values")
}
for a, column := range columns {
dest[column] = *(values[a].(*interface{}))
}
return statement.rows.Err()
}
// Next prepares the next result row for reading with the Scan method(). It
// returns true on success, or false if there is no next result row or an
// error happened while preparing it. Statement.Err should be consulted
// to distinguish between the two cases.
// https://golang.org/pkg/database/sql/#Rows.Next
//
// This also performs a Scan operation. Scan copies the columns in the
// current row into the values pointed at by dest. The number of values in
// dest must be the same as the number of columns in Rows.
// https://golang.org/pkg/database/sql/#Rows.Scan
func (statement *Statement) Next(dest ...interface{}) bool {
if nil == statement.rows {
statement.lastErr = errors.Errorf("no cursor found. did you remember to run `statement.Query()`?")
log.WithError(statement.lastErr).Error("cursor not found")
return false
}
if !statement.rows.Next() {
err := statement.Err()
if nil != err {
statement.lastErr = err
}
return false
}
err := statement.Scan(dest...)
if nil != err {
statement.lastErr = err
return false
}
return true
}
// Query executes the prepared statement with any arguments that have been
// added using Bind() calls. Query stores a cursor to the result of the SQL
// query.
func (statement *Statement) Query(args ...interface{}) (*sql.Rows, error) {
return statement.QueryContext(statement.ctx, args...)
}
// QueryContext executes the prepared statement with any arguments that have been
// added using Bind() calls. Query stores a cursor to the result of the SQL
// query.
func (statement *Statement) QueryContext(ctx context.Context, args ...interface{}) (*sql.Rows, error) {
var err error
var binds []interface{}
for _, bind := range statement.binds {
binds = append(binds, bind)
}
binds = append(binds, args...)
statement.rows, err = statement.stmt.QueryContext(ctx, binds...)
if nil != err {
statement.lastErr = err
}
statement.binds = []sql.NamedArg{}
return statement.rows, err
}
// QueryRow executes the prepared statement with any arguments that have been
// added using Bind() calls. Query stores a cursor to the result of the SQL
// query.
func (statement *Statement) QueryRow(args ...interface{}) *sql.Row {
return statement.QueryRowContext(statement.ctx, args...)
}
// QueryRowContext executes the prepared statement with any arguments that have been
// added using Bind() calls. Query stores a cursor to the result of the SQL
// query.
func (statement *Statement) QueryRowContext(ctx context.Context, args ...interface{}) *sql.Row {
var binds []interface{}
for _, bind := range statement.binds {
binds = append(binds, bind)
}
binds = append(binds, args...)
return statement.stmt.QueryRowContext(ctx, binds...)
}
// Result returns the internal sql.Result struct.
func (statement *Statement) Result() sql.Result {
return statement.result
}
// Rollback aborts the current transaction.
func (statement *Statement) Rollback() error {
err := statement.txn.Rollback()
if nil != err {
statement.lastErr = err
}
return err
}
// Rows returns the internal sql.Rows pointer.
func (statement *Statement) Rows() *sql.Rows {
return statement.rows
}
// Scan copies the columns in the current row into the values pointed at by
// dest. The number of values in dest must be the same as the number of
// columns in Rows.
// https://golang.org/pkg/database/sql/#Rows.Scan
func (statement *Statement) Scan(dest ...interface{}) error {
err := statement.rows.Scan(dest...)
if nil != err {
statement.lastErr = err
}
return err
}