~nilium/sql

ref: cc8c8b8cb4992e5fe47a107d6f31e1d9c15d8ae3 sql/vdb/query.go -rw-r--r-- 5.5 KiB
cc8c8b8cNoel Cower Additional refactoring for use in chisel 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
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
// 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"
	"errors"
	"fmt"

	"github.com/jmoiron/sqlx"
)

type TimeFormat int

var ErrNilOptions = errors.New("options must not be nil")

const (
	TimeString    TimeFormat = 0
	TimeFloat     TimeFormat = 1
	TimeUnixNano  TimeFormat = 2
	TimeUnixMicro TimeFormat = 3
	TimeUnixMilli TimeFormat = 4
	TimeUnix      TimeFormat = 5
	TimeCustom    TimeFormat = 6
)

func (t TimeFormat) MarshalText() ([]byte, error) {
	switch t {
	case TimeString:
		return []byte("rfc3339"), nil
	case TimeFloat:
		return []byte("fsec"), nil
	case TimeUnixNano:
		return []byte("unixns"), nil
	case TimeUnixMicro:
		return []byte("unixus"), nil
	case TimeUnixMilli:
		return []byte("unixms"), nil
	case TimeUnix:
		return []byte("unix"), nil
	case TimeCustom:
		return []byte("layout"), nil
	default:
		return nil, fmt.Errorf("unrecognized TimeFormat %d", t)
	}
}

func (t *TimeFormat) UnmarshalText(p []byte) error {
	switch s := string(p); s {
	case "ts", "rfc3339", "str":
		*t = TimeString
	case "unix", "s", "sec":
		*t = TimeUnix
	case "unixns", "ns", "nsec":
		*t = TimeUnixNano
	case "unixus", "us", "usec":
		*t = TimeUnixMicro
	case "unixms", "ms", "msec":
		*t = TimeUnixMilli
	case "unixf", "fs", "fsec", "float":
		*t = TimeFloat
	case "layout":
		*t = TimeCustom
	default:
		return fmt.Errorf("unrecognized time format %q", s)
	}
	return nil
}

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.Opaque()
	}
	return m
}

type QueryOptions struct {
	TryJSON    bool       `json:"try_json"`
	SkipJSON   bool       `json:"skip_json"`
	TimeFormat TimeFormat `json:"time_format"`
	TimeLayout string     `json:"time_layout,omitempty"` // Used if TimeFormat is TimeCustom.
	Compact    bool       `json:"compact"`

	// Query formatting. This should be set depending on the driver, not
	// user-customizable.
	BindType int `json:"-"`
}

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

	Options *QueryOptions
}

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

func Query(ctx context.Context, options *QueryOptions, db DB, query string, args ...interface{}) (Results, error) {
	return execArgSet(ctx, make(Results, 0, 1), options, db, query, args)
}

func execArgSet(ctx context.Context, results Results, options *QueryOptions, db DB, query string, args []interface{}) (Results, error) {
	if options == nil {
		return nil, ErrNilOptions
	}
	query, qargs, err := sqlx.In(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(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 := ScanRows(ctx, rows, options)
		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 ScanRows(ctx context.Context, rows *sql.Rows, options *QueryOptions) (Records, error) {
	if options == nil {
		return nil, ErrNilOptions
	}
	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: 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
}