-
Notifications
You must be signed in to change notification settings - Fork 0
/
rows.go
58 lines (45 loc) · 1.67 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
// Package clickhouse_go_rows_utils implement utils for working with rows at clickhouse-go.
package clickhouse_go_rows_utils
//go:generate go run go.uber.org/mock/mockgen -destination=./mock/rows_mock.go -package mock github.com/ClickHouse/clickhouse-go/v2/lib/driver Rows
import "github.com/ClickHouse/clickhouse-go/v2/lib/driver"
// CollectableRow is the subset of Rows methods that a RowToFunc is allowed to call.
type CollectableRow interface {
Scan(dest ...any) error
ScanStruct(dest any) error
ColumnTypes() []driver.ColumnType
Totals(dest ...any) error
Columns() []string
}
// RowToFunc is a function that scans or otherwise converts row to a T.
type RowToFunc[T any] func(row CollectableRow) (T, error)
// CollectRows iterates through rows, calling fn for each row, and collecting the results into a slice of T.
func CollectRows[T any](rows driver.Rows, fn RowToFunc[T]) ([]T, error) {
return AppendRows([]T{}, rows, fn)
}
// AppendRows iterates through rows, calling fn for each row, and appending the results into a slice of T.
func AppendRows[T any, S ~[]T](slice S, rows driver.Rows, fn RowToFunc[T]) (S, error) {
err := ForEachRow(rows, func(row CollectableRow) error {
value, err := fn(row)
if err != nil {
return err
}
slice = append(slice, value)
return nil
})
if err != nil {
return nil, err
}
return slice, nil
}
// ForEachRowFunc calls at each row.
type ForEachRowFunc func(row CollectableRow) error
// ForEachRow iterates through rows, calling fn for each row.
func ForEachRow(rows driver.Rows, fn ForEachRowFunc) error {
defer rows.Close() //nolint:errcheck
for rows.Next() {
if err := fn(rows); err != nil {
return err
}
}
return rows.Err()
}