-
Notifications
You must be signed in to change notification settings - Fork 2
/
rows.go
319 lines (284 loc) · 9.45 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
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package fireboltgosdk
import (
"database/sql/driver"
"encoding/hex"
"fmt"
"io"
"math"
"reflect"
"strconv"
"strings"
"time"
)
const (
intType = "int"
longType = "long"
floatType = "float"
doubleType = "double"
textType = "text"
dateType = "date"
pgDateType = "pgdate"
timestampType = "timestamp"
timestampNtzType = "timestampntz"
timestampTzType = "timestamptz"
booleanType = "boolean"
byteaType = "bytea"
geographyType = "geography"
)
type fireboltRows struct {
response []QueryResponse
resultSetPosition int // Position of the result set (for multiple statements)
cursorPosition int // Position of the cursor in current result set
}
// Columns returns a list of Meta names in response
func (f *fireboltRows) Columns() []string {
numColumns := len(f.response[f.resultSetPosition].Meta)
result := make([]string, 0, numColumns)
for _, column := range f.response[f.resultSetPosition].Meta {
result = append(result, column.Name)
}
return result
}
// Close makes the rows unusable
func (f *fireboltRows) Close() error {
f.resultSetPosition = len(f.response) - 1
f.cursorPosition = len(f.response[f.resultSetPosition].Data)
return nil
}
// Next fetches the values of the next row, returns io.EOF if it was the end
func (f *fireboltRows) Next(dest []driver.Value) error {
if f.cursorPosition == len(f.response[f.resultSetPosition].Data) {
return io.EOF
}
for i, column := range f.response[f.resultSetPosition].Meta {
var err error
//log.Printf("Rows.Next: %s, %v", column.Type, f.response.Data[f.cursorPosition][i])
if dest[i], err = parseValue(column.Type, f.response[f.resultSetPosition].Data[f.cursorPosition][i]); err != nil {
return ConstructNestedError("error during fetching Next result", err)
}
}
f.cursorPosition++
return nil
}
// HasNextResultSet reports whether there is another result set available
func (f *fireboltRows) HasNextResultSet() bool {
return len(f.response) > f.resultSetPosition+1
}
// NextResultSet advances to the next result set, if it is available, otherwise returns io.EOF
func (f *fireboltRows) NextResultSet() error {
if !f.HasNextResultSet() {
return io.EOF
}
f.cursorPosition = 0
f.resultSetPosition += 1
return nil
}
// checkTypeValue checks that val type could be changed to columnType
func checkTypeValue(columnType string, val interface{}) error {
switch columnType {
case intType, longType, floatType, doubleType:
if _, ok := val.(float64); !ok {
if columnType == floatType || columnType == doubleType {
for _, v := range []string{"inf", "-inf", "nan", "-nan"} {
if val == v {
return nil
}
}
}
// Allow string values for long columns
if _, is_str := val.(string); !(columnType == longType && is_str) {
return fmt.Errorf("expected to convert a value to float64, but couldn't: %v", val)
}
}
return nil
case textType, dateType, pgDateType, timestampType, timestampNtzType, timestampTzType, byteaType, geographyType:
if _, ok := val.(string); !ok {
return fmt.Errorf("expected to convert a value to string, but couldn't: %v", val)
}
return nil
case booleanType:
if _, ok := val.(bool); !ok {
return fmt.Errorf("expected to convert a value to bool, but couldn't: %v", val)
}
return nil
}
return fmt.Errorf("unknown column type: %s", columnType)
}
func extractStructColumn(columnType string) (string, string, error) {
columnType = strings.TrimSpace(columnType)
if idx := strings.IndexRune(columnType[1:], '`'); strings.HasPrefix(columnType, "`") && idx != -1 {
// We use idx+2 since we found this index in the substring starting from the second character
return strings.Trim(columnType[1:idx+2], " `"), strings.TrimSpace(columnType[idx+2:]), nil
}
field := strings.SplitN(strings.TrimSpace(columnType), " ", 2)
if len(field) < 2 {
return "", "", fmt.Errorf("invalid struct field: %s", columnType)
}
return strings.TrimSpace(field[0]), strings.TrimSpace(field[1]), nil
}
func extractStructColumns(columnTypes string) (map[string]string, error) {
balance := 0
current := strings.Builder{}
columns := make(map[string]string)
for _, char := range columnTypes {
if char == '(' {
balance++
} else if char == ')' {
balance--
}
if balance == 0 && char == ',' {
fieldName, fieldType, err := extractStructColumn(current.String())
if err != nil {
return nil, err
}
columns[fieldName] = fieldType
current.Reset()
} else {
current.WriteRune(char)
}
}
if balance != 0 {
return nil, fmt.Errorf("invalid struct type: %s", columnTypes)
}
fieldName, fieldType, err := extractStructColumn(current.String())
if err != nil {
return nil, err
}
columns[fieldName] = fieldType
return columns, nil
}
func parseStruct(structInnerFields string, val interface{}) (map[string]driver.Value, error) {
fields, err := extractStructColumns(structInnerFields)
if err != nil {
return nil, ConstructNestedError("error during parsing struct type", err)
}
structValue, ok := val.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("unexpected value for struct type: %v", val)
}
res := make(map[string]driver.Value)
if len(fields) != len(structValue) {
return nil, fmt.Errorf("expected %d fields, but got %d", len(fields), len(structValue))
}
for fieldName, fieldType := range fields {
if fieldValue, ok := structValue[fieldName]; ok {
res[fieldName], err = parseValue(fieldType, fieldValue)
if err != nil {
return nil, ConstructNestedError("error during parsing struct field", err)
}
} else {
return nil, fmt.Errorf("field %s is missing in struct value %v", fieldName, structValue)
}
}
return res, nil
}
func parseTimestampTz(value string) (driver.Value, error) {
formats := [...]string{"2006-01-02 15:04:05.000000-07", "2006-01-02 15:04:05.000000-07:00", "2006-01-02 15:04:05.000000-07:00:00",
"2006-01-02 15:04:05-07", "2006-01-02 15:04:05-07:00", "2006-01-02 15:04:05-07:00:00"}
var res time.Time
var err error
for _, format := range formats {
res, err = time.Parse(format, value)
if err == nil {
break
}
}
return res, err
}
// parseDateTimeValue parses different date types
func parseDateTimeValue(columnType string, value string) (driver.Value, error) {
switch columnType {
case dateType, pgDateType:
return time.Parse("2006-01-02", value)
case timestampType:
// Go doesn't use yyyy-mm-dd layout. Instead, it uses the value: Mon Jan 2 15:04:05 MST 2006
return time.Parse("2006-01-02 15:04:05", value)
case timestampNtzType:
return time.Parse("2006-01-02 15:04:05.000000", value)
case timestampTzType:
return parseTimestampTz(value)
}
return nil, fmt.Errorf("type not known: %s", columnType)
}
func parseFloatValue(val interface{}) (float64, error) {
if _, notNum := val.(string); notNum {
switch val.(string) {
case "inf":
return math.Inf(1), nil
case "-inf":
return math.Inf(-1), nil
case "nan":
return math.NaN(), nil
case "-nan":
return math.NaN(), nil
default:
return 0, fmt.Errorf("unknown float value: %s", val)
}
}
return val.(float64), nil
}
// parseSingleValue parses all columns types except arrays
func parseSingleValue(columnType string, val interface{}) (driver.Value, error) {
if err := checkTypeValue(columnType, val); err != nil {
return nil, ConstructNestedError("error during value parsing", err)
}
switch columnType {
case intType:
return int32(val.(float64)), nil
case longType:
// long values as passed as strings by system engine
if unpacked, ok := val.(float64); ok {
return int64(unpacked), nil
}
return strconv.ParseInt(val.(string) /*base*/, 10 /*bitSize*/, 64)
case floatType:
v, err := parseFloatValue(val)
return float32(v), err
case doubleType:
return parseFloatValue(val)
case textType, geographyType:
return val.(string), nil
case dateType, pgDateType, timestampType, timestampNtzType, timestampTzType:
return parseDateTimeValue(columnType, val.(string))
case booleanType:
return val.(bool), nil
case byteaType:
trimmedString := strings.TrimPrefix(val.(string), "\\x")
decoded, err := hex.DecodeString(trimmedString)
if err != nil {
return nil, fmt.Errorf("Unable to parse to hex value: %v", val)
}
return decoded, nil
}
return nil, fmt.Errorf("type not known: %s", columnType)
}
// parseValue treating the val according to the column type and casts it to one of the go native types:
// uint8, uint32, uint64, int32, int64, float32, float64, string, Time or []driver.Value for arrays
func parseValue(columnType string, val interface{}) (driver.Value, error) {
const (
nullableSuffix = " null"
arrayPrefix = "array("
decimalPrefix = "Decimal("
structPrefix = "struct("
suffix = ")"
)
// No need to parse type if the value is nil
if val == nil {
return nil, nil
}
if strings.HasPrefix(columnType, arrayPrefix) && strings.HasSuffix(columnType, suffix) {
s := reflect.ValueOf(val)
res := make([]driver.Value, s.Len())
for i := 0; i < s.Len(); i++ {
res[i], _ = parseValue(columnType[len(arrayPrefix):len(columnType)-len(suffix)], s.Index(i).Interface())
}
return res, nil
} else if strings.HasPrefix(columnType, decimalPrefix) && strings.HasSuffix(columnType, suffix) {
return parseSingleValue("double", val)
} else if strings.HasPrefix(columnType, structPrefix) && strings.HasSuffix(columnType, suffix) {
return parseStruct(columnType[len(structPrefix):len(columnType)-len(suffix)], val)
} else if strings.HasSuffix(columnType, nullableSuffix) {
return parseValue(columnType[0:len(columnType)-len(nullableSuffix)], val)
}
return parseSingleValue(columnType, val)
}