-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreader_base.go
More file actions
67 lines (60 loc) · 1.64 KB
/
reader_base.go
File metadata and controls
67 lines (60 loc) · 1.64 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
package dalgo2sql
import (
"context"
"database/sql"
"fmt"
"github.com/dal-go/dalgo/dal"
)
type executeQueryFunc func(ctx context.Context, query string, args ...any) (*sql.Rows, error)
type readerBase struct {
rows *sql.Rows
colNames []string
colTypes []*sql.ColumnType
}
func getReaderBase(ctx context.Context, query dal.Query, execute executeQueryFunc) (readerBase, error) {
var a []any
var text string
switch q := query.(type) {
case dal.TextQuery:
text = q.Text()
args := q.Args()
a = make([]any, len(args))
for i, arg := range args {
a[i] = arg
}
case dal.StructuredQuery:
// emitSQL rewrites dalgo's `SELECT TOP N` into ANSI `LIMIT N`
// so SQLite (and Postgres/MySQL) accept the SQL. Stopgap until
// upstream dalgo gains dialect-aware emission — see the
// `dalgo-dialect-aware-sql-emission` Idea.
text = emitSQL(q)
}
rows, err := execute(ctx, text, a...)
if err != nil {
return readerBase{}, err
}
rb := readerBase{
rows: rows,
}
if rb.colNames, err = rb.rows.Columns(); err != nil {
return rb, fmt.Errorf("failed to read column names: %w", err)
}
if rb.colTypes, err = rb.rows.ColumnTypes(); err != nil {
return rb, fmt.Errorf("failed to read column types: %w", err)
}
if len(rb.colNames) != len(rb.colTypes) {
return rb, fmt.Errorf("length if column names and column types don't match")
}
return rb, nil
}
func (rb readerBase) scanValues() (values []any, err error) {
values = make([]any, len(rb.colNames))
scanArgs := make([]any, len(rb.colNames))
for i := range values {
scanArgs[i] = &values[i]
}
if err = rb.rows.Scan(scanArgs...); err != nil {
return nil, err
}
return values, nil
}