-
-
Notifications
You must be signed in to change notification settings - Fork 49
/
rows.go
323 lines (283 loc) · 7.54 KB
/
rows.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
package pgxmock
import (
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
)
// CSVColumnParser is a function which converts trimmed csv
// column string to a []byte representation. Currently
// transforms NULL to nil
var CSVColumnParser = func(s string) interface{} {
switch {
case strings.ToLower(s) == "null":
return nil
}
return s
}
// connRow implements the Row interface for Conn.QueryRow.
type connRow rowSets
func (r *connRow) Scan(dest ...any) (err error) {
rows := (*rowSets)(r)
if rows.Err() != nil {
return rows.Err()
}
for _, d := range dest {
if _, ok := d.(*pgtype.DriverBytes); ok {
rows.Close()
return fmt.Errorf("cannot scan into *pgtype.DriverBytes from QueryRow")
}
}
if !rows.Next() {
if rows.Err() == nil {
return pgx.ErrNoRows
}
return rows.Err()
}
defer rows.Close()
return errors.Join(rows.Scan(dest...), rows.Err())
}
type rowSets struct {
sets []*Rows
RowSetNo int
ex *ExpectedQuery
}
func (rs *rowSets) Conn() *pgx.Conn {
return nil
}
func (rs *rowSets) Err() error {
r := rs.sets[rs.RowSetNo]
return r.nextErr[r.recNo-1]
}
func (rs *rowSets) CommandTag() pgconn.CommandTag {
return rs.sets[rs.RowSetNo].commandTag
}
func (rs *rowSets) FieldDescriptions() []pgconn.FieldDescription {
return rs.sets[rs.RowSetNo].defs
}
// func (rs *rowSets) Columns() []string {
// return rs.sets[rs.pos].cols
// }
func (rs *rowSets) Close() {
if rs.ex != nil {
rs.ex.rowsWereClosed = true
}
// return rs.sets[rs.pos].closeErr
}
// advances to next row
func (rs *rowSets) Next() bool {
r := rs.sets[rs.RowSetNo]
r.recNo++
return r.recNo <= len(r.rows)
}
// Values returns the decoded row values. As with Scan(), it is an error to
// call Values without first calling Next() and checking that it returned
// true.
func (rs *rowSets) Values() ([]interface{}, error) {
r := rs.sets[rs.RowSetNo]
return r.rows[r.recNo-1], r.nextErr[r.recNo-1]
}
func (rs *rowSets) Scan(dest ...interface{}) error {
r := rs.sets[rs.RowSetNo]
if len(dest) == 1 {
if rc, ok := dest[0].(pgx.RowScanner); ok {
return rc.ScanRow(rs)
}
}
if len(dest) != len(r.defs) {
return fmt.Errorf("Incorrect argument number %d for columns %d", len(dest), len(r.defs))
}
if len(r.rows) == 0 {
return pgx.ErrNoRows
}
for i, col := range r.rows[r.recNo-1] {
if dest[i] == nil {
//behave compatible with pgx
continue
}
destVal := reflect.ValueOf(dest[i])
if destVal.Kind() != reflect.Ptr {
return fmt.Errorf("Destination argument must be a pointer for column %s", r.defs[i].Name)
}
if col == nil {
dest[i] = nil
continue
}
val := reflect.ValueOf(col)
if _, ok := dest[i].(*interface{}); ok || val.Type().AssignableTo(destVal.Elem().Type()) {
if destElem := destVal.Elem(); destElem.CanSet() {
destElem.Set(val)
} else {
return fmt.Errorf("Cannot set destination value for column %s", r.defs[i].Name)
}
} else {
// Try to use Scanner interface
scanner, ok := destVal.Interface().(interface{ Scan(interface{}) error })
if !ok {
return fmt.Errorf("Destination kind '%v' not supported for value kind '%v' of column '%s'",
destVal.Elem().Kind(), val.Kind(), string(r.defs[i].Name))
}
if err := scanner.Scan(val.Interface()); err != nil {
return fmt.Errorf("Scanning value error for column '%s': %w", string(r.defs[i].Name), err)
}
}
}
return r.nextErr[r.recNo-1]
}
func (rs *rowSets) RawValues() [][]byte {
r := rs.sets[rs.RowSetNo]
dest := make([][]byte, len(r.defs))
for i, col := range r.rows[r.recNo-1] {
if b, ok := rawBytes(col); ok {
dest[i] = b
continue
}
dest[i] = []byte(fmt.Sprintf("%v", col))
}
return dest
}
// transforms to debuggable printable string
func (rs *rowSets) String() string {
if rs.empty() {
return "\t- returns no data"
}
msg := "\t- returns data:\n"
if len(rs.sets) == 1 {
for n, row := range rs.sets[0].rows {
msg += fmt.Sprintf("\t\trow %d - %+v\n", n, row)
}
return msg
}
for i, set := range rs.sets {
msg += fmt.Sprintf("\t\tresult set: %d\n", i)
for n, row := range set.rows {
msg += fmt.Sprintf("\t\t\trow %d: %+v\n", n, row)
}
}
return msg
}
func (rs *rowSets) empty() bool {
for _, set := range rs.sets {
if len(set.rows) > 0 {
return false
}
}
return true
}
func rawBytes(col interface{}) (_ []byte, ok bool) {
val, err := json.Marshal(col)
if err != nil || len(val) == 0 {
return nil, false
}
// Copy the bytes from the mocked row into a shared raw buffer, which we'll replace the content of later
b := make([]byte, len(val))
copy(b, val)
return b, true
}
// Rows is a mocked collection of rows to
// return for Query result
type Rows struct {
commandTag pgconn.CommandTag
defs []pgconn.FieldDescription
rows [][]interface{}
recNo int
nextErr map[int]error
closeErr error
}
// NewRows allows Rows to be created from a
// sql interface{} slice or from the CSV string and
// to be used as sql driver.Rows.
// Use pgxmock.NewRows instead if using a custom converter
func NewRows(columns []string) *Rows {
var coldefs []pgconn.FieldDescription
for _, column := range columns {
coldefs = append(coldefs, pgconn.FieldDescription{Name: column})
}
return &Rows{
defs: coldefs,
nextErr: make(map[int]error),
}
}
// CloseError allows to set an error
// which will be returned by rows.Close
// function.
//
// The close error will be triggered only in cases
// when rows.Next() EOF was not yet reached, that is
// a default sql library behavior
func (r *Rows) CloseError(err error) *Rows {
r.closeErr = err
return r
}
// RowError allows to set an error
// which will be returned when a given
// row number is read
func (r *Rows) RowError(row int, err error) *Rows {
r.nextErr[row] = err
return r
}
// AddRow composed from database interface{} slice
// return the same instance to perform subsequent actions.
// Note that the number of values must match the number
// of columns
func (r *Rows) AddRow(values ...any) *Rows {
if len(values) != len(r.defs) {
panic("Expected number of values to match number of columns")
}
row := make([]interface{}, len(r.defs))
copy(row, values)
r.rows = append(r.rows, row)
return r
}
// AddRows adds multiple rows composed from any slice and
// returns the same instance to perform subsequent actions.
func (r *Rows) AddRows(values ...[]any) *Rows {
for _, value := range values {
r.AddRow(value...)
}
return r
}
// AddCommandTag will add a command tag to the result set
func (r *Rows) AddCommandTag(tag pgconn.CommandTag) *Rows {
r.commandTag = tag
return r
}
// FromCSVString build rows from csv string.
// return the same instance to perform subsequent actions.
// Note that the number of values must match the number
// of columns
func (r *Rows) FromCSVString(s string) *Rows {
res := strings.NewReader(strings.TrimSpace(s))
csvReader := csv.NewReader(res)
for {
res, err := csvReader.Read()
if err != nil || res == nil {
break
}
row := make([]interface{}, len(r.defs))
for i, v := range res {
row[i] = CSVColumnParser(strings.TrimSpace(v))
}
r.rows = append(r.rows, row)
}
return r
}
// Kind returns rows corresponding to the interface pgx.Rows
// useful for testing entities that implement an interface pgx.RowScanner
func (r *Rows) Kind() pgx.Rows {
return &rowSets{
sets: []*Rows{r},
}
}
// NewRowsWithColumnDefinition return rows with columns metadata
func NewRowsWithColumnDefinition(columns ...pgconn.FieldDescription) *Rows {
return &Rows{
defs: columns,
nextErr: make(map[int]error),
}
}