-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmodel.go
458 lines (384 loc) · 11.4 KB
/
model.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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
package questdb
import (
"database/sql"
"fmt"
"reflect"
"regexp"
"strings"
"time"
)
// Model represents a struct's model
type Model struct {
tableName string
fields []*field
indexFields []*field
typ reflect.Type
val reflect.Value
designatedTS *field
createTableOptions *CreateTableOptions
}
// field struct represents a field within a valid qdb tagged struct
type field struct {
isZero bool
name string
qdbName string
qdbType QuestDBType
typ reflect.Type
value reflect.Value
valueSerialized string
tagOptions tagOptions
}
// PartitionOption is a string which is used in CreateTableOptions struct
// for specifying the partition by strategy
type PartitionOption string
const (
None PartitionOption = "NONE"
Year PartitionOption = "YEAR"
Month PartitionOption = "MONTH"
Day PartitionOption = "DAY"
Hour PartitionOption = "HOUR"
)
// CreateTableOptions struct is a struct which specifies options for creating
// a QuestDB table
type CreateTableOptions struct {
PartitionBy PartitionOption
// Deprecated: QuestDB >= v7.0.0 no longer requires this option
MaxUncommittedRows int
// Deprecated: QuestDB >= v7.0.0 no longer requires this option
CommitLag string
}
// String func prints out the CreateTableOptions in string format which would be appended
// to the sql create table statement
func (c *CreateTableOptions) String() string {
out := ""
if c.PartitionBy != "" {
out += fmt.Sprintf("PARTITION BY %s ", c.PartitionBy)
}
if c.MaxUncommittedRows != 0 {
out += fmt.Sprintf("WITH maxUncommittedRows=%d ", c.MaxUncommittedRows)
}
if c.CommitLag != "" {
if c.MaxUncommittedRows != 0 {
out += ", "
}
out += fmt.Sprintf("commitLag=%s ", c.CommitLag)
}
return out
}
// CreateTableOptioner is an interface which has a single method
// CreateTableOptions which returns the CreateTableOptions struct.
// This is used when specifying specific options for creating a table
// in QuestDB world.
type CreateTableOptioner interface {
CreateTableOptions() CreateTableOptions
}
// NewModel func takes a struct and returns the Model representation of
// that struct or an optional error
func NewModel(a interface{}) (*Model, error) {
ty := reflect.TypeOf(a)
val := reflect.ValueOf(a)
if ty.Kind() == reflect.Ptr {
ty = ty.Elem()
}
if ty.Kind() != reflect.Struct {
return nil, fmt.Errorf("only structs allowed")
}
tableName := fmt.Sprintf("%ss", toSnakeCase(ty.Name()))
aTableNamer, ok := a.(TableNamer)
if ok {
tableName = aTableNamer.TableName()
}
m := &Model{
typ: ty,
val: val,
tableName: tableName,
}
aCreateTableOptioner, ok := a.(CreateTableOptioner)
if ok {
opts := aCreateTableOptioner.CreateTableOptions()
m.createTableOptions = &opts
}
fields, err := structToFieldSlice("", "", ty, val)
if err != nil {
return nil, fmt.Errorf("could not parse field: %w", err)
}
for _, field := range fields {
if field.tagOptions.designatedTS {
if m.designatedTS != nil {
return nil, fmt.Errorf("multiple designated timestamp fields found")
}
field2 := field
m.designatedTS = field2
}
if field.tagOptions.index {
m.indexFields = append(m.indexFields, field)
}
}
m.fields = fields
if err := m.serialize(); err != nil {
return nil, err
}
return m, nil
}
func structToFieldSlice(fieldPrefix, colPrefix string, ty reflect.Type, val reflect.Value) ([]*field, error) {
if ty.Kind() == reflect.Ptr {
ty = ty.Elem()
}
fields := []*field{}
for i := 0; i < ty.NumField(); i++ {
fieldType := ty.Field(i)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
fieldValue := reflect.ValueOf(nil)
if val.IsValid() {
fieldValue = val.Field(i)
}
fieldName := fieldPrefix + fieldType.Name
tagStr := fieldType.Tag.Get(tagName)
// skip fields that are marked to ignore
if tagStr == "-" {
continue
}
tagProps := strings.Split(tagStr, ";")
if len(tagProps) < 2 {
return nil, fmt.Errorf("%s: invalid tag length (expected 2 to 3 semicolon delimited items but got %d)", fieldName, len(tagProps))
}
columnName := colPrefix + tagProps[0]
columnType := tagProps[1]
f := &field{
name: fieldName,
qdbName: columnName,
qdbType: QuestDBType(columnType),
typ: fieldType.Type,
value: fieldValue,
valueSerialized: "",
tagOptions: tagOptions{},
}
if len(tagProps) > 2 {
if err := ensureOptionsAreValid(tagProps[2:]); err != nil {
return nil, fmt.Errorf("%s: invalid tag: %w", fieldName, err)
}
opts, err := makeTagOptions(f, tagProps[2:])
if err != nil {
return nil, fmt.Errorf("%s: %w", fieldName, err)
}
f.tagOptions = opts
}
if columnType != "embedded" && !isValidAndSupportedQuestDBType(f.qdbType) {
return nil, fmt.Errorf("%s: unsupported qdb type %s", fieldName, f.qdbType)
}
if columnType == "embedded" && f.tagOptions.embeddedPrefix == "" {
return nil, fmt.Errorf("%s: 'embeddedPrefix' is required if type is embedded", fieldName)
}
if columnType == "embedded" {
embeddedFields, err := structToFieldSlice(f.name+".", f.tagOptions.embeddedPrefix, f.typ, f.value)
if err != nil {
return nil, err
}
fields = append(fields, embeddedFields...)
continue
}
fields = append(fields, f)
}
return fields, nil
}
func (m *Model) serialize() error {
for _, field := range m.fields {
fieldValue := field.value
// if fieldValue kind is pointer, get its underlying poited to value
if fieldValue.Kind() == reflect.Ptr {
fieldValue = fieldValue.Elem()
}
if !fieldValue.IsValid() || fieldValue.IsZero() {
field.isZero = true
}
if field.isZero && !field.tagOptions.commitZeroValue {
continue
}
valStr, err := serializeValue(fieldValue.Interface(), field.qdbType)
if err != nil {
return fmt.Errorf("%s: %w", field.name, err)
}
field.valueSerialized = valStr
}
return nil
}
// Columns func will take return all the model's fields in column format
// i.e. "column_1, column_2, column_3, ..."
func (m *Model) Columns() string {
out := ""
for i, field := range m.fields {
out += field.qdbName
if i != len(m.fields)-1 {
out += ", "
}
}
return out
}
// ScanInto func is a helper function which takes a *sql.Row and a dest (an valid qdb model struct)
// and scans the row values into dest. This will typically be used in conjunction with a select statement
// which has used (Model).Columns() to specify the columns for selecting.
func ScanInto(row *sql.Row, dest interface{}) (err error) {
m, err := NewModel(dest)
if err != nil {
return fmt.Errorf("could not make model from dest: %w", err)
}
return row.Scan(m.destinations()...)
}
// ScanInto func is a helper function which takes a *sql.Row and a dest (an valid qdb model struct)
// and scans the row values into dest. This will typically be used in conjunction with a select statement
// which has used (Model).Columns() to specify the columns for selecting.
func ScanRows(rows *sql.Rows, dest interface{}) (err error) {
m, err := NewModel(dest)
if err != nil {
return fmt.Errorf("could not make model from dest: %w", err)
}
return rows.Scan(m.destinations()...)
}
func (m *Model) destinations() []interface{} {
addrs := []interface{}{}
for _, field := range m.fields {
if !field.value.IsValid() {
fmt.Println(field.name)
}
v := field.value.Addr().Interface()
qdbScanner, ok := v.(Scanner)
if ok {
v = newIntermediate(qdbScanner)
}
addrs = append(addrs, v)
}
return addrs
}
// CreateTableIfNotExistStatement func returns the sql create table statement for
// the Model
func (m *Model) CreateTableIfNotExistStatement() string {
out := fmt.Sprintf(`CREATE TABLE IF NOT EXISTS "%s" ( `, m.tableName)
// add each qdb column to the create table statement's column definition
for i, field := range m.fields {
qdbType := field.qdbType
// currently encoding binary as base64 encoded string
if qdbType == Binary || qdbType == JSON {
qdbType = String
}
out += fmt.Sprintf("\"%s\" %s", field.qdbName, qdbType)
if i != len(m.fields)-1 {
out += ", "
}
}
// add default designated timestamp field
if m.designatedTS == nil {
out += ", \"timestamp\" timestamp"
}
out += " ) "
// if index fields, add them to statement
indexFieldsLen := len(m.indexFields)
if indexFieldsLen > 0 {
out += ", "
for i, field := range m.indexFields {
out += fmt.Sprintf("index(%s)", field.qdbName)
if i != indexFieldsLen-1 {
out += ", "
} else {
out += " "
}
}
}
// if designatedTS is specified, add to statement, else use default designated TS field
if m.designatedTS == nil {
out += "timestamp(timestamp) "
} else {
out += fmt.Sprintf("timestamp(%s) ", m.designatedTS.qdbName)
}
// if some create table options exists, add them to statement
if m.createTableOptions != nil {
out += m.createTableOptions.String()
}
// end statement
out += ";"
return out
}
func (m *Model) buildSymbols() string {
if len(m.fields) == 0 {
return ""
}
fields := []*field{}
for _, field := range m.fields {
if field.qdbType == Symbol && (!field.isZero || (field.isZero && field.tagOptions.commitZeroValue)) {
fields = append(fields, field)
}
}
out := ""
n := 0
for _, field := range fields {
out += fmt.Sprintf("%s=%s", field.qdbName, field.valueSerialized)
if n != len(fields)-1 {
out += ","
}
n++
}
return out
}
func (m *Model) buildColumns() string {
if len(m.fields) == 0 {
return ""
}
fields := []*field{}
for _, field := range m.fields {
if field.qdbType != Symbol && (!field.isZero || (field.isZero && field.tagOptions.commitZeroValue)) {
fields = append(fields, field)
}
}
fieldsSerialized := []string{}
for _, field := range fields {
// skip including this in columns field as it will be included in the timestamp section of
// line message:
// <table name>,<symbols,...> <columns,...> <timestamp>
// here ----^
if field.tagOptions.designatedTS {
continue
}
fieldsSerialized = append(fieldsSerialized, fmt.Sprintf("%s=%s", field.qdbName, field.valueSerialized))
}
return strings.Join(fieldsSerialized, ",")
}
func (m *Model) buildTimestamp() string {
if m.designatedTS != nil && m.designatedTS.value.IsValid() {
designatedTSTime, ok := m.designatedTS.value.Interface().(time.Time)
if ok {
if !designatedTSTime.IsZero() {
return fmt.Sprintf("%d", designatedTSTime.UnixNano())
}
}
}
return ""
}
// MarshalLine func marshals Model's underlying struct values into Influx Line Protocol
// message serialization format to be written to the QuestDB ILP port for ingestion.
func (m *Model) MarshalLine() (msg []byte) {
m.serialize()
symbolsString := m.buildSymbols()
columnsString := m.buildColumns()
timestampString := m.buildTimestamp()
outString := m.tableName
if symbolsString != "" {
outString += fmt.Sprintf(",%s", symbolsString)
}
if columnsString != "" {
outString += fmt.Sprintf(" %s", columnsString)
}
if timestampString != "" {
outString += fmt.Sprintf(" %s", timestampString)
}
outString += "\n"
return []byte(outString)
}
var matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)")
var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])")
// toSnakeCase func takes a string and returns it's snake case form
func toSnakeCase(str string) string {
snake := matchFirstCap.ReplaceAllString(str, "${1}_${2}")
snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}")
return strings.ToLower(snake)
}