-
Notifications
You must be signed in to change notification settings - Fork 0
/
iterateScan.go
96 lines (85 loc) · 2.05 KB
/
iterateScan.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
package sqlt
import "database/sql"
// IterateScan scans given rows ony by one passing obtained data to
// callback function.
func IterateScan(rows *sql.Rows, callback func([]string, []*sql.ColumnType, []any)) error {
if rows == nil {
return sql.ErrNoRows
}
if callback == nil {
return nil // No error
}
// Reading column names
columnNames, err := rows.Columns()
if err != nil {
return err
}
columnTypes, err := rows.ColumnTypes()
if err != nil {
return err
}
columnCount := len(columnNames)
processed := false
for rows.Next() {
// Building columns and their pointers for
// sql.Scan func.
columns := make([]any, columnCount)
columnPointers := make([]any, columnCount)
for i := range columns {
columnPointers[i] = &columns[i]
}
// Scanning the result into the column pointers...
if err := rows.Scan(columnPointers...); err != nil {
return err
}
callback(columnNames, columnTypes, columns)
processed = true
}
if !processed {
return sql.ErrNoRows
}
return nil
}
// IterateScanE scans given rows ony by one passing obtained data to
// callback function. On any error stops iteration and returns it.
func IterateScanE(rows *sql.Rows, callback func([]string, []*sql.ColumnType, []any) error) error {
if rows == nil {
return sql.ErrNoRows
}
if callback == nil {
return nil // No error
}
// Reading column names
columnNames, err := rows.Columns()
if err != nil {
return err
}
columnTypes, err := rows.ColumnTypes()
if err != nil {
return err
}
columnCount := len(columnNames)
processed := false
for rows.Next() {
// Building columns and their pointers for
// sql.Scan func.
columns := make([]any, columnCount)
columnPointers := make([]any, columnCount)
for i := range columns {
columnPointers[i] = &columns[i]
}
// Scanning the result into the column pointers...
if err := rows.Scan(columnPointers...); err != nil {
return err
}
err = callback(columnNames, columnTypes, columns)
if err != nil {
return err
}
processed = true
}
if !processed {
return sql.ErrNoRows
}
return nil
}