~nilium/sql

ref: 0eb4a8bb965fb3eb0d99f7cd138e665aa322c3c0 sql/vdb/query.go -rw-r--r-- 3.8 KiB
0eb4a8bbNoel Cower Move drivers to top-level package 11 months ago
                                                                                
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
// sql - A tool for querying databases.
// Copyright (C) 2021 Noel Cower
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

package vdb

import (
	"context"
	"database/sql"
	"fmt"

	"github.com/jmoiron/sqlx"
)

type TimeFormat int

const (
	TimeString TimeFormat = iota
	TimeFloat
	TimeUnixNano
	TimeUnixMicro
	TimeUnixMilli
	TimeUnix
	TimeCustom
)

type Results []Records

func (rs Results) Opaque() []interface{} {
	s := make([]interface{}, len(rs))
	for i, v := range rs {
		s[i] = v.Opaque()
	}
	return s
}

type Records []Record

func (rs Records) Opaque() []interface{} {
	s := make([]interface{}, len(rs))
	for i, v := range rs {
		s[i] = v.Opaque()
	}
	return s
}

type Record map[string]*Value

func (r Record) Opaque() map[string]interface{} {
	m := make(map[string]interface{}, len(r))
	for k, v := range r {
		m[k] = v.Dest
	}
	return m
}

type QueryOptions struct {
	TryJSON    bool
	SkipJSON   bool
	TimeFormat TimeFormat
	TimeLayout string // Used if TimeFormat is TimeCustom.
	Compact    bool

	// Query formatting.
	BindType int
}

type Query struct {
	Query string
	Args  [][]interface{}

	Options *QueryOptions
}

func (q *Query) Exec(ctx context.Context, db DB) (results Results, err error) {
	results = make(Results, 0, len(q.Args)*2)
	for i, args := range q.Args {
		results, err = q.execArgSet(ctx, results, db, args)
		if err != nil {
			return nil, fmt.Errorf("error executing query with %d arg set: %w", i+1, err)
		}
	}
	return results, nil
}

func (q *Query) execArgSet(ctx context.Context, results Results, db DB, args []interface{}) (Results, error) {
	query, qargs, err := sqlx.In(q.Query, args...)
	if err != nil {
		// This used to be a log message, but so far I've never seen it
		// come up, so now just return an error. If it shows up as an
		// error, something is probably wrong with an input query.
		return nil, fmt.Errorf("failed to expand query via sqlx.In: %w", err)
	} else {
		query = sqlx.Rebind(q.Options.BindType, query)
	}

	rows, err := db.QueryContext(ctx, query, qargs...)
	if err != nil {
		return nil, fmt.Errorf("query error: %w", err)
	}
	defer rows.Close()

	for i := 1; ; i++ {
		records, err := q.scanRows(ctx, rows)
		if err != nil {
			return nil, fmt.Errorf("error scanning rows in statement %d: %w", i, err)
		}

		results = append(results, records)

		if !rows.NextResultSet() {
			break
		}
	}

	if err = rows.Err(); err != nil {
		return nil, fmt.Errorf("unexpected query error: %w", err)
	}

	return results, nil
}

func (q *Query) scanRows(ctx context.Context, rows *sql.Rows) (Records, error) {
	coltypes, err := rows.ColumnTypes()
	if err != nil {
		return nil, fmt.Errorf("error getting column types: %w", err)
	}

	records := make(Records, 0, 100)
	scanners := make([]interface{}, len(coltypes))

	for i := 1; rows.Next(); i++ {
		record := make(map[string]*Value, len(coltypes))
		for ci, coltype := range coltypes {
			val := &Value{
				Options: q.Options,
				Type:    coltype,
			}
			name := coltype.Name()
			if name == "" || name == "?" {
				name = fmt.Sprintf("__result_%d", ci)
			}
			record[name] = val
			scanners[ci] = val
		}

		if err := rows.Scan(scanners...); err != nil {
			return nil, fmt.Errorf("error scanning row %d: %w", i, err)
		}

		records = append(records, record)
	}

	return records, nil
}