-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema.go
More file actions
697 lines (603 loc) · 18 KB
/
schema.go
File metadata and controls
697 lines (603 loc) · 18 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
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
package streamhouse
import (
"encoding/json"
"fmt"
"reflect"
"strconv"
"strings"
"sync"
"time"
)
// CompiledValidator represents a pre-compiled validator for a schema
type CompiledValidator struct {
schema *DataSchema
fieldKeys []string // Pre-computed field keys for iteration
}
// ValidateAndConvert validates and converts data in a single pass
func (cv *CompiledValidator) ValidateAndConvert(data map[string]interface{}) (map[string]interface{}, error) {
result := make(map[string]interface{}, len(cv.schema.Fields))
// Check required fields and convert values
for _, fieldName := range cv.fieldKeys {
fieldConfig := cv.schema.Fields[fieldName]
value, exists := data[fieldName]
if !exists {
if fieldConfig.Required {
return nil, NewValidationError(fieldName, nil, "required field missing")
}
// Set default value if provided
if fieldConfig.Default != nil {
convertedValue, err := convertValueDirect(fieldConfig.Default, fieldConfig.Type)
if err != nil {
return nil, fmt.Errorf("field %s default conversion failed: %w", fieldName, err)
}
result[fieldName] = convertedValue
}
continue
}
// Validate and convert field value
convertedValue, err := convertValueDirect(value, fieldConfig.Type)
if err != nil {
return nil, NewValidationError(fieldName, value, err.Error())
}
// Run custom validator if provided
if fieldConfig.Validator != nil {
if err := fieldConfig.Validator(convertedValue); err != nil {
return nil, NewValidationError(fieldName, value, fmt.Sprintf("custom validation failed: %v", err))
}
}
result[fieldName] = convertedValue
}
return result, nil
}
// convertValueDirect performs direct conversion without interface overhead
func convertValueDirect(value interface{}, fieldType FieldType) (interface{}, error) {
if value == nil {
return nil, nil
}
switch fieldType {
case FieldTypeString:
switch v := value.(type) {
case string:
return v, nil
case []byte:
return string(v), nil
default:
return fmt.Sprintf("%v", v), nil
}
case FieldTypeInt:
switch v := value.(type) {
case int:
return int64(v), nil
case int8:
return int64(v), nil
case int16:
return int64(v), nil
case int32:
return int64(v), nil
case int64:
return v, nil
case uint:
return int64(v), nil
case uint8:
return int64(v), nil
case uint16:
return int64(v), nil
case uint32:
return int64(v), nil
case uint64:
return int64(v), nil
case float32:
return int64(v), nil
case float64:
return int64(v), nil
case string:
return strconv.ParseInt(v, 10, 64)
default:
return nil, fmt.Errorf("cannot convert %T to int", value)
}
case FieldTypeFloat:
switch v := value.(type) {
case float32:
return float64(v), nil
case float64:
return v, nil
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
return float64(reflect.ValueOf(v).Convert(reflect.TypeOf(float64(0))).Float()), nil
case string:
return strconv.ParseFloat(v, 64)
default:
return nil, fmt.Errorf("cannot convert %T to float", value)
}
case FieldTypeBool:
switch v := value.(type) {
case bool:
return v, nil
case string:
return strconv.ParseBool(v)
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
return reflect.ValueOf(v).Convert(reflect.TypeOf(int64(0))).Int() != 0, nil
default:
return nil, fmt.Errorf("cannot convert %T to bool", value)
}
case FieldTypeDatetime:
switch v := value.(type) {
case time.Time:
return v, nil
case string:
// Try multiple time formats
formats := []string{
time.RFC3339,
time.RFC3339Nano,
"2006-01-02T15:04:05",
"2006-01-02 15:04:05",
"2006-01-02",
}
for _, format := range formats {
if t, err := time.Parse(format, v); err == nil {
return t, nil
}
}
return nil, fmt.Errorf("cannot parse datetime: %s", v)
case int64:
// Unix timestamp
return time.Unix(v, 0), nil
default:
return nil, fmt.Errorf("cannot convert %T to datetime", value)
}
case FieldTypeJSON:
// Fast-path: if it's already a string, assume it's valid JSON
if str, ok := value.(string); ok {
return str, nil
}
// Convert to JSON string for non-string values
jsonBytes, err := json.Marshal(value)
if err != nil {
return nil, fmt.Errorf("failed to marshal JSON: %w", err)
}
return string(jsonBytes), nil
default:
return nil, fmt.Errorf("unknown field type: %s", fieldType)
}
}
// SchemaRegistry manages registered schemas
type SchemaRegistry struct {
schemas map[string]*DataSchema
compiledValidators map[string]*CompiledValidator
mu sync.RWMutex
}
// NewSchemaRegistry creates a new schema registry
func NewSchemaRegistry() *SchemaRegistry {
return &SchemaRegistry{
schemas: make(map[string]*DataSchema),
compiledValidators: make(map[string]*CompiledValidator),
}
}
// Register registers a new schema
func (sr *SchemaRegistry) Register(schema *DataSchema) error {
if schema == nil {
return NewSchemaError("", "", fmt.Errorf("schema cannot be nil"))
}
if schema.Name == "" {
return NewSchemaError("", "", fmt.Errorf("schema name cannot be empty"))
}
if err := sr.validateSchema(schema); err != nil {
return NewSchemaError(schema.Name, "", err)
}
sr.mu.Lock()
defer sr.mu.Unlock()
if _, exists := sr.schemas[schema.Name]; exists {
return NewSchemaError(schema.Name, "", ErrSchemaAlreadyExists)
}
// Add default fields if not present
sr.addDefaultFields(schema)
sr.schemas[schema.Name] = schema
// Create compiled validator
fieldKeys := make([]string, 0, len(schema.Fields))
for fieldName := range schema.Fields {
fieldKeys = append(fieldKeys, fieldName)
}
sr.compiledValidators[schema.Name] = &CompiledValidator{
schema: schema,
fieldKeys: fieldKeys,
}
return nil
}
// Get retrieves a schema by name
func (sr *SchemaRegistry) Get(name string) (*DataSchema, error) {
sr.mu.RLock()
defer sr.mu.RUnlock()
schema, exists := sr.schemas[name]
if !exists {
return nil, NewSchemaError(name, "", ErrSchemaNotFound)
}
return schema, nil
}
// GetCompiledValidator retrieves a compiled validator by schema name
func (sr *SchemaRegistry) GetCompiledValidator(name string) (*CompiledValidator, error) {
sr.mu.RLock()
defer sr.mu.RUnlock()
validator, exists := sr.compiledValidators[name]
if !exists {
return nil, NewSchemaError(name, "", ErrSchemaNotFound)
}
return validator, nil
}
// List returns all registered schema names
func (sr *SchemaRegistry) List() []string {
sr.mu.RLock()
defer sr.mu.RUnlock()
names := make([]string, 0, len(sr.schemas))
for name := range sr.schemas {
names = append(names, name)
}
return names
}
// Unregister removes a schema
func (sr *SchemaRegistry) Unregister(name string) error {
sr.mu.Lock()
defer sr.mu.Unlock()
if _, exists := sr.schemas[name]; !exists {
return NewSchemaError(name, "", ErrSchemaNotFound)
}
delete(sr.schemas, name)
delete(sr.compiledValidators, name)
return nil
}
// ValidateData validates data against a registered schema
func (sr *SchemaRegistry) ValidateData(schemaName string, data map[string]interface{}) error {
schema, err := sr.Get(schemaName)
if err != nil {
return err
}
return sr.validateDataAgainstSchema(schema, data)
}
// validateSchema validates the schema definition itself
func (sr *SchemaRegistry) validateSchema(schema *DataSchema) error {
if len(schema.Fields) == 0 {
return fmt.Errorf("schema must have at least one field")
}
for fieldName, fieldConfig := range schema.Fields {
if fieldName == "" {
return fmt.Errorf("field name cannot be empty")
}
if !sr.isValidFieldType(fieldConfig.Type) {
return NewValidationError(fieldName, fieldConfig.Type, "invalid field type")
}
// Validate default value type if provided
if fieldConfig.Default != nil {
if err := sr.validateFieldValue(fieldName, fieldConfig.Default, fieldConfig.Type); err != nil {
return fmt.Errorf("invalid default value for field %s: %w", fieldName, err)
}
}
}
// Validate index fields exist
for _, indexField := range schema.IndexFields {
if _, exists := schema.Fields[indexField]; !exists {
return fmt.Errorf("index field '%s' does not exist in schema", indexField)
}
}
// Validate partition fields exist
for _, partitionField := range schema.Partitions {
if _, exists := schema.Fields[partitionField]; !exists {
return fmt.Errorf("partition field '%s' does not exist in schema", partitionField)
}
}
return nil
}
// validateDataAgainstSchema validates data against a specific schema
func (sr *SchemaRegistry) validateDataAgainstSchema(schema *DataSchema, data map[string]interface{}) error {
// Check required fields
for fieldName, fieldConfig := range schema.Fields {
value, exists := data[fieldName]
if !exists {
if fieldConfig.Required {
return NewValidationError(fieldName, nil, "required field missing")
}
// Set default value if provided
if fieldConfig.Default != nil {
data[fieldName] = fieldConfig.Default
}
continue
}
// Validate field value
if err := sr.validateFieldValue(fieldName, value, fieldConfig.Type); err != nil {
return err
}
// Run custom validator if provided
if fieldConfig.Validator != nil {
if err := fieldConfig.Validator(value); err != nil {
return NewValidationError(fieldName, value, fmt.Sprintf("custom validation failed: %v", err))
}
}
}
return nil
}
// validateFieldValue validates a field value against its type
func (sr *SchemaRegistry) validateFieldValue(fieldName string, value interface{}, fieldType FieldType) error {
if value == nil {
return nil // nil values are handled by required field check
}
switch fieldType {
case FieldTypeString:
if _, ok := value.(string); !ok {
return NewValidationError(fieldName, value, "expected string")
}
case FieldTypeInt:
switch v := value.(type) {
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
// Valid integer types
case float64:
// JSON numbers are float64, check if it's actually an integer
if v != float64(int64(v)) {
return NewValidationError(fieldName, value, "expected integer")
}
case string:
// Try to parse string as integer
if _, err := strconv.ParseInt(v, 10, 64); err != nil {
return NewValidationError(fieldName, value, "expected integer")
}
default:
return NewValidationError(fieldName, value, "expected integer")
}
case FieldTypeFloat:
switch v := value.(type) {
case float32, float64:
// Valid float types
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
// Integers can be converted to floats
case string:
// Try to parse string as float
if _, err := strconv.ParseFloat(v, 64); err != nil {
return NewValidationError(fieldName, value, "expected float")
}
default:
return NewValidationError(fieldName, value, "expected float")
}
case FieldTypeBool:
switch v := value.(type) {
case bool:
// Valid boolean
case string:
// Try to parse string as boolean
if _, err := strconv.ParseBool(v); err != nil {
return NewValidationError(fieldName, value, "expected boolean")
}
default:
return NewValidationError(fieldName, value, "expected boolean")
}
case FieldTypeDatetime:
switch v := value.(type) {
case time.Time:
// Valid time
case string:
// Try to parse string as time
if _, err := time.Parse(time.RFC3339, v); err != nil {
return NewValidationError(fieldName, value, "expected datetime in RFC3339 format")
}
default:
return NewValidationError(fieldName, value, "expected datetime")
}
case FieldTypeJSON:
// JSON can be any type, but let's ensure it's serializable
if _, err := json.Marshal(value); err != nil {
return NewValidationError(fieldName, value, "value is not JSON serializable")
}
default:
return NewValidationError(fieldName, value, "unknown field type")
}
return nil
}
// isValidFieldType checks if a field type is valid
func (sr *SchemaRegistry) isValidFieldType(fieldType FieldType) bool {
switch fieldType {
case FieldTypeString, FieldTypeInt, FieldTypeFloat, FieldTypeBool, FieldTypeDatetime, FieldTypeJSON:
return true
default:
return false
}
}
// addDefaultFields adds standard fields to the schema if not present
func (sr *SchemaRegistry) addDefaultFields(schema *DataSchema) {
if schema.Fields == nil {
schema.Fields = make(map[string]FieldConfig)
}
// Add ID field if not present
if _, exists := schema.Fields["id"]; !exists {
schema.Fields["id"] = FieldConfig{
Type: FieldTypeString,
Required: true,
Index: true,
Description: "Unique identifier for the event",
}
}
// Add timestamp field if not present
if _, exists := schema.Fields["timestamp"]; !exists {
schema.Fields["timestamp"] = FieldConfig{
Type: FieldTypeDatetime,
Required: true,
Index: true,
Description: "Event timestamp",
}
}
}
// ConvertValue converts a value to the appropriate type based on field configuration
func (sr *SchemaRegistry) ConvertValue(value interface{}, fieldType FieldType) (interface{}, error) {
if value == nil {
return nil, nil
}
switch fieldType {
case FieldTypeString:
return sr.convertToString(value)
case FieldTypeInt:
return sr.convertToInt(value)
case FieldTypeFloat:
return sr.convertToFloat(value)
case FieldTypeBool:
return sr.convertToBool(value)
case FieldTypeDatetime:
return sr.convertToDatetime(value)
case FieldTypeJSON:
return sr.convertToJSON(value)
default:
return nil, fmt.Errorf("unknown field type: %s", fieldType)
}
}
// convertToJSON handles JSON field conversion with fast-path for strings
func (sr *SchemaRegistry) convertToJSON(value interface{}) (interface{}, error) {
if value == nil {
return nil, nil
}
// Fast-path: if it's already a string, assume it's valid JSON
if str, ok := value.(string); ok {
return str, nil
}
// Convert to JSON string for non-string values
jsonBytes, err := json.Marshal(value)
if err != nil {
return nil, fmt.Errorf("failed to marshal JSON: %w", err)
}
return string(jsonBytes), nil
}
// Helper conversion functions
func (sr *SchemaRegistry) convertToString(value interface{}) (string, error) {
switch v := value.(type) {
case string:
return v, nil
case []byte:
return string(v), nil
default:
return fmt.Sprintf("%v", v), nil
}
}
func (sr *SchemaRegistry) convertToInt(value interface{}) (int64, error) {
switch v := value.(type) {
case int:
return int64(v), nil
case int8:
return int64(v), nil
case int16:
return int64(v), nil
case int32:
return int64(v), nil
case int64:
return v, nil
case uint:
return int64(v), nil
case uint8:
return int64(v), nil
case uint16:
return int64(v), nil
case uint32:
return int64(v), nil
case uint64:
return int64(v), nil
case float32:
return int64(v), nil
case float64:
return int64(v), nil
case string:
return strconv.ParseInt(v, 10, 64)
default:
return 0, fmt.Errorf("cannot convert %T to int", value)
}
}
func (sr *SchemaRegistry) convertToFloat(value interface{}) (float64, error) {
switch v := value.(type) {
case float32:
return float64(v), nil
case float64:
return v, nil
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
return float64(reflect.ValueOf(v).Convert(reflect.TypeOf(float64(0))).Float()), nil
case string:
return strconv.ParseFloat(v, 64)
default:
return 0, fmt.Errorf("cannot convert %T to float", value)
}
}
func (sr *SchemaRegistry) convertToBool(value interface{}) (bool, error) {
switch v := value.(type) {
case bool:
return v, nil
case string:
return strconv.ParseBool(v)
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
return reflect.ValueOf(v).Convert(reflect.TypeOf(int64(0))).Int() != 0, nil
default:
return false, fmt.Errorf("cannot convert %T to bool", value)
}
}
func (sr *SchemaRegistry) convertToDatetime(value interface{}) (time.Time, error) {
switch v := value.(type) {
case time.Time:
return v, nil
case string:
// Try multiple time formats
formats := []string{
time.RFC3339,
time.RFC3339Nano,
"2006-01-02T15:04:05",
"2006-01-02 15:04:05",
"2006-01-02",
}
for _, format := range formats {
if t, err := time.Parse(format, v); err == nil {
return t, nil
}
}
return time.Time{}, fmt.Errorf("cannot parse datetime: %s", v)
case int64:
// Unix timestamp
return time.Unix(v, 0), nil
default:
return time.Time{}, fmt.Errorf("cannot convert %T to datetime", value)
}
}
// GenerateClickHouseSchema generates ClickHouse CREATE TABLE statement from schema
func (sr *SchemaRegistry) GenerateClickHouseSchema(schema *DataSchema, tableName string) string {
var fields []string
for fieldName, fieldConfig := range schema.Fields {
clickHouseType := sr.getClickHouseType(fieldConfig.Type)
if !fieldConfig.Required {
clickHouseType = fmt.Sprintf("Nullable(%s)", clickHouseType)
}
fields = append(fields, fmt.Sprintf(" `%s` %s", fieldName, clickHouseType))
}
sql := fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (\n%s\n)", tableName, strings.Join(fields, ",\n"))
// Add engine and partitioning
engine := "ENGINE = MergeTree()"
if len(schema.Partitions) > 0 {
partitionBy := strings.Join(schema.Partitions, ", ")
engine = fmt.Sprintf("ENGINE = MergeTree() PARTITION BY (%s)", partitionBy)
}
// Add order by clause (use index fields or timestamp)
orderBy := "timestamp"
if len(schema.IndexFields) > 0 {
orderBy = strings.Join(schema.IndexFields, ", ")
}
sql += fmt.Sprintf("\n%s\nORDER BY (%s)", engine, orderBy)
// Add TTL if specified
if schema.TTL != nil {
sql += fmt.Sprintf("\nTTL timestamp + INTERVAL %d SECOND", int(schema.TTL.Seconds()))
}
return sql
}
// getClickHouseType converts field type to ClickHouse type
func (sr *SchemaRegistry) getClickHouseType(fieldType FieldType) string {
switch fieldType {
case FieldTypeString:
return "String"
case FieldTypeInt:
return "Int64"
case FieldTypeFloat:
return "Float64"
case FieldTypeBool:
return "UInt8"
case FieldTypeDatetime:
return "DateTime"
case FieldTypeJSON:
return "String" // Store JSON as string in ClickHouse
default:
return "String"
}
}