-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.go
More file actions
964 lines (793 loc) · 26.8 KB
/
Copy pathfunctions.go
File metadata and controls
964 lines (793 loc) · 26.8 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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
package mist
import (
"fmt"
"math"
"regexp"
"strconv"
"strings"
"time"
"github.com/abbychau/mysql-parser/ast"
)
// FunctionType represents different categories of built-in functions
type FunctionType int
const (
FuncString FunctionType = iota
FuncDateTime
FuncMath
FuncConditional
FuncTypeConversion
)
// BuiltinFunction represents a built-in function implementation
type BuiltinFunction struct {
Name string
Type FunctionType
MinArgs int
MaxArgs int // -1 for unlimited
Executor func(args []interface{}) (interface{}, error)
}
// Registry of all built-in functions
var builtinFunctions = map[string]*BuiltinFunction{
// String Functions
"CONCAT": {Name: "CONCAT", Type: FuncString, MinArgs: 1, MaxArgs: -1, Executor: execConcat},
"SUBSTRING": {Name: "SUBSTRING", Type: FuncString, MinArgs: 2, MaxArgs: 3, Executor: execSubstring},
"LENGTH": {Name: "LENGTH", Type: FuncString, MinArgs: 1, MaxArgs: 1, Executor: execLength},
"UPPER": {Name: "UPPER", Type: FuncString, MinArgs: 1, MaxArgs: 1, Executor: execUpper},
"LOWER": {Name: "LOWER", Type: FuncString, MinArgs: 1, MaxArgs: 1, Executor: execLower},
"TRIM": {Name: "TRIM", Type: FuncString, MinArgs: 1, MaxArgs: 1, Executor: execTrim},
// Date/Time Functions
"NOW": {Name: "NOW", Type: FuncDateTime, MinArgs: 0, MaxArgs: 0, Executor: execNow},
"CURDATE": {Name: "CURDATE", Type: FuncDateTime, MinArgs: 0, MaxArgs: 0, Executor: execCurdate},
"YEAR": {Name: "YEAR", Type: FuncDateTime, MinArgs: 1, MaxArgs: 1, Executor: execYear},
"MONTH": {Name: "MONTH", Type: FuncDateTime, MinArgs: 1, MaxArgs: 1, Executor: execMonth},
"DAY": {Name: "DAY", Type: FuncDateTime, MinArgs: 1, MaxArgs: 1, Executor: execDay},
"DATE_FORMAT": {Name: "DATE_FORMAT", Type: FuncDateTime, MinArgs: 2, MaxArgs: 2, Executor: execDateFormat},
// Math Functions
"ABS": {Name: "ABS", Type: FuncMath, MinArgs: 1, MaxArgs: 1, Executor: execAbs},
"ROUND": {Name: "ROUND", Type: FuncMath, MinArgs: 1, MaxArgs: 2, Executor: execRound},
"CEILING": {Name: "CEILING", Type: FuncMath, MinArgs: 1, MaxArgs: 1, Executor: execCeiling},
"FLOOR": {Name: "FLOOR", Type: FuncMath, MinArgs: 1, MaxArgs: 1, Executor: execFloor},
"MOD": {Name: "MOD", Type: FuncMath, MinArgs: 2, MaxArgs: 2, Executor: execMod},
"POWER": {Name: "POWER", Type: FuncMath, MinArgs: 2, MaxArgs: 2, Executor: execPower},
// Conditional Functions
"IF": {Name: "IF", Type: FuncConditional, MinArgs: 3, MaxArgs: 3, Executor: execIf},
"COALESCE": {Name: "COALESCE", Type: FuncConditional, MinArgs: 1, MaxArgs: -1, Executor: execCoalesce},
"IFNULL": {Name: "IFNULL", Type: FuncConditional, MinArgs: 2, MaxArgs: 2, Executor: execIfnull},
"NULLIF": {Name: "NULLIF", Type: FuncConditional, MinArgs: 2, MaxArgs: 2, Executor: execNullif},
// Type Conversion Functions
"CAST": {Name: "CAST", Type: FuncTypeConversion, MinArgs: 2, MaxArgs: 2, Executor: execCast},
"CONVERT": {Name: "CONVERT", Type: FuncTypeConversion, MinArgs: 2, MaxArgs: 2, Executor: execConvert},
}
// GetBuiltinFunction returns a builtin function by name
func GetBuiltinFunction(name string) (*BuiltinFunction, bool) {
fn, exists := builtinFunctions[strings.ToUpper(name)]
return fn, exists
}
// ExecuteFunction executes a function call with the given arguments
func ExecuteFunction(funcName string, args []interface{}) (interface{}, error) {
fn, exists := GetBuiltinFunction(funcName)
if !exists {
return nil, fmt.Errorf("unknown function: %s", funcName)
}
// Validate argument count
if len(args) < fn.MinArgs {
return nil, fmt.Errorf("function %s requires at least %d arguments, got %d", funcName, fn.MinArgs, len(args))
}
if fn.MaxArgs != -1 && len(args) > fn.MaxArgs {
return nil, fmt.Errorf("function %s accepts at most %d arguments, got %d", funcName, fn.MaxArgs, len(args))
}
return fn.Executor(args)
}
// String Function Implementations
func execConcat(args []interface{}) (interface{}, error) {
var result strings.Builder
for _, arg := range args {
if arg == nil {
return nil, nil // MySQL behavior: CONCAT with NULL returns NULL
}
result.WriteString(fmt.Sprintf("%v", arg))
}
return result.String(), nil
}
func execSubstring(args []interface{}) (interface{}, error) {
if args[0] == nil {
return nil, nil
}
str := fmt.Sprintf("%v", args[0])
start, err := toInt64(args[1])
if err != nil {
return nil, fmt.Errorf("SUBSTRING: invalid start position: %v", err)
}
// MySQL uses 1-based indexing
startIndex := int(start - 1)
if startIndex < 0 {
startIndex = 0
}
if startIndex >= len(str) {
return "", nil
}
if len(args) == 2 {
// SUBSTRING(str, start) - return from start to end
return str[startIndex:], nil
}
// SUBSTRING(str, start, length)
length, err := toInt64(args[2])
if err != nil {
return nil, fmt.Errorf("SUBSTRING: invalid length: %v", err)
}
if length <= 0 {
return "", nil
}
endIndex := startIndex + int(length)
if endIndex > len(str) {
endIndex = len(str)
}
return str[startIndex:endIndex], nil
}
func execLength(args []interface{}) (interface{}, error) {
if args[0] == nil {
return nil, nil
}
str := fmt.Sprintf("%v", args[0])
return int64(len(str)), nil
}
func execUpper(args []interface{}) (interface{}, error) {
if args[0] == nil {
return nil, nil
}
str := fmt.Sprintf("%v", args[0])
return strings.ToUpper(str), nil
}
func execLower(args []interface{}) (interface{}, error) {
if args[0] == nil {
return nil, nil
}
str := fmt.Sprintf("%v", args[0])
return strings.ToLower(str), nil
}
func execTrim(args []interface{}) (interface{}, error) {
if args[0] == nil {
return nil, nil
}
str := fmt.Sprintf("%v", args[0])
return strings.TrimSpace(str), nil
}
// Date/Time Function Implementations
func execNow(args []interface{}) (interface{}, error) {
return time.Now().Format("2006-01-02 15:04:05"), nil
}
func execCurdate(args []interface{}) (interface{}, error) {
return time.Now().Format("2006-01-02"), nil
}
func execYear(args []interface{}) (interface{}, error) {
if args[0] == nil {
return nil, nil
}
dateStr := fmt.Sprintf("%v", args[0])
t, err := parseDateTime(dateStr)
if err != nil {
return nil, fmt.Errorf("YEAR: invalid date format: %v", err)
}
return int64(t.Year()), nil
}
func execMonth(args []interface{}) (interface{}, error) {
if args[0] == nil {
return nil, nil
}
dateStr := fmt.Sprintf("%v", args[0])
t, err := parseDateTime(dateStr)
if err != nil {
return nil, fmt.Errorf("MONTH: invalid date format: %v", err)
}
return int64(t.Month()), nil
}
func execDay(args []interface{}) (interface{}, error) {
if args[0] == nil {
return nil, nil
}
dateStr := fmt.Sprintf("%v", args[0])
t, err := parseDateTime(dateStr)
if err != nil {
return nil, fmt.Errorf("DAY: invalid date format: %v", err)
}
return int64(t.Day()), nil
}
func execDateFormat(args []interface{}) (interface{}, error) {
if args[0] == nil || args[1] == nil {
return nil, nil
}
dateStr := fmt.Sprintf("%v", args[0])
formatStr := fmt.Sprintf("%v", args[1])
t, err := parseDateTime(dateStr)
if err != nil {
return nil, fmt.Errorf("DATE_FORMAT: invalid date format: %v", err)
}
// Convert MySQL format specifiers to Go format
goFormat := convertMySQLFormatToGo(formatStr)
return t.Format(goFormat), nil
}
// Math Function Implementations
func execAbs(args []interface{}) (interface{}, error) {
if args[0] == nil {
return nil, nil
}
num, err := toFloat64(args[0])
if err != nil {
return nil, fmt.Errorf("ABS: invalid numeric value: %v", err)
}
return math.Abs(num), nil
}
func execRound(args []interface{}) (interface{}, error) {
if args[0] == nil {
return nil, nil
}
num, err := toFloat64(args[0])
if err != nil {
return nil, fmt.Errorf("ROUND: invalid numeric value: %v", err)
}
if len(args) == 1 {
return math.Round(num), nil
}
// ROUND(num, decimals)
decimals, err := toInt64(args[1])
if err != nil {
return nil, fmt.Errorf("ROUND: invalid decimal places: %v", err)
}
multiplier := math.Pow(10, float64(decimals))
return math.Round(num*multiplier) / multiplier, nil
}
func execCeiling(args []interface{}) (interface{}, error) {
if args[0] == nil {
return nil, nil
}
num, err := toFloat64(args[0])
if err != nil {
return nil, fmt.Errorf("CEILING: invalid numeric value: %v", err)
}
return math.Ceil(num), nil
}
func execFloor(args []interface{}) (interface{}, error) {
if args[0] == nil {
return nil, nil
}
num, err := toFloat64(args[0])
if err != nil {
return nil, fmt.Errorf("FLOOR: invalid numeric value: %v", err)
}
return math.Floor(num), nil
}
func execMod(args []interface{}) (interface{}, error) {
if args[0] == nil || args[1] == nil {
return nil, nil
}
dividend, err := toFloat64(args[0])
if err != nil {
return nil, fmt.Errorf("MOD: invalid dividend: %v", err)
}
divisor, err := toFloat64(args[1])
if err != nil {
return nil, fmt.Errorf("MOD: invalid divisor: %v", err)
}
if divisor == 0 {
return nil, nil // MySQL behavior: MOD by zero returns NULL
}
return math.Mod(dividend, divisor), nil
}
func execPower(args []interface{}) (interface{}, error) {
if args[0] == nil || args[1] == nil {
return nil, nil
}
base, err := toFloat64(args[0])
if err != nil {
return nil, fmt.Errorf("POWER: invalid base: %v", err)
}
exponent, err := toFloat64(args[1])
if err != nil {
return nil, fmt.Errorf("POWER: invalid exponent: %v", err)
}
return math.Pow(base, exponent), nil
}
// Conditional Function Implementations
func execIf(args []interface{}) (interface{}, error) {
condition := args[0]
trueValue := args[1]
falseValue := args[2]
if isTruthy(condition) {
return trueValue, nil
}
return falseValue, nil
}
func execCoalesce(args []interface{}) (interface{}, error) {
for _, arg := range args {
if arg != nil {
return arg, nil
}
}
return nil, nil
}
func execIfnull(args []interface{}) (interface{}, error) {
if args[0] != nil {
return args[0], nil
}
return args[1], nil
}
func execNullif(args []interface{}) (interface{}, error) {
if compareValues(args[0], args[1]) == 0 {
return nil, nil
}
return args[0], nil
}
// Type Conversion Function Implementations
func execCast(args []interface{}) (interface{}, error) {
value := args[0]
targetType := fmt.Sprintf("%v", args[1])
if value == nil {
return nil, nil
}
switch strings.ToUpper(targetType) {
case "CHAR", "VARCHAR", "TEXT":
return fmt.Sprintf("%v", value), nil
case "INT", "INTEGER", "BIGINT":
return toInt64(value)
case "DECIMAL", "FLOAT", "DOUBLE":
return toFloat64(value)
case "DATE":
dateStr := fmt.Sprintf("%v", value)
t, err := parseDateTime(dateStr)
if err != nil {
return nil, fmt.Errorf("CAST: cannot convert to DATE: %v", err)
}
return t.Format("2006-01-02"), nil
case "DATETIME", "TIMESTAMP":
dateStr := fmt.Sprintf("%v", value)
t, err := parseDateTime(dateStr)
if err != nil {
return nil, fmt.Errorf("CAST: cannot convert to DATETIME: %v", err)
}
return t.Format("2006-01-02 15:04:05"), nil
default:
return nil, fmt.Errorf("CAST: unsupported target type: %s", targetType)
}
}
func execConvert(args []interface{}) (interface{}, error) {
// CONVERT is essentially the same as CAST in MySQL
return execCast(args)
}
// Helper Functions
func toInt64(value interface{}) (int64, error) {
if value == nil {
return 0, fmt.Errorf("cannot convert NULL to integer")
}
switch v := value.(type) {
case int:
return int64(v), nil
case int32:
return int64(v), nil
case int64:
return v, nil
case float32:
return int64(v), nil
case float64:
return int64(v), nil
case string:
return strconv.ParseInt(v, 10, 64)
default:
str := fmt.Sprintf("%v", value)
return strconv.ParseInt(str, 10, 64)
}
}
func parseDateTime(dateStr string) (time.Time, error) {
// Try common MySQL date/time formats
formats := []string{
"2006-01-02 15:04:05",
"2006-01-02",
"15:04:05",
"2006-01-02T15:04:05Z",
"2006-01-02T15:04:05",
}
for _, format := range formats {
if t, err := time.Parse(format, dateStr); err == nil {
return t, nil
}
}
return time.Time{}, fmt.Errorf("invalid date/time format: %s", dateStr)
}
func convertMySQLFormatToGo(mysqlFormat string) string {
// Convert MySQL format specifiers to Go time format
// This is a simplified implementation covering common cases
replacements := map[string]string{
"%Y": "2006", // 4-digit year
"%y": "06", // 2-digit year
"%m": "01", // Month (01-12)
"%d": "02", // Day (01-31)
"%H": "15", // Hour (00-23)
"%i": "04", // Minutes (00-59)
"%s": "05", // Seconds (00-59)
"%M": "January", // Full month name
"%b": "Jan", // Abbreviated month name
"%W": "Monday", // Full weekday name
"%a": "Mon", // Abbreviated weekday name
}
result := mysqlFormat
for mysql, goFmt := range replacements {
result = strings.ReplaceAll(result, mysql, goFmt)
}
return result
}
// evaluateFunctionCall evaluates a function call expression
func evaluateFunctionCall(funcCall *ast.FuncCallExpr, table *Table, row Row) (interface{}, error) {
funcName := funcCall.FnName.L
// Evaluate arguments
var args []interface{}
for _, arg := range funcCall.Args {
value, err := evaluateExpressionInRow(arg, table, row)
if err != nil {
return nil, fmt.Errorf("error evaluating function argument: %v", err)
}
args = append(args, value)
}
// Execute the function
return ExecuteFunction(funcName, args)
}
// evaluateFunctionCallOnJoinResult evaluates a function call in JOIN context
func evaluateFunctionCallOnJoinResult(funcCall *ast.FuncCallExpr, joinResult *JoinResult, row []interface{}) (interface{}, error) {
funcName := funcCall.FnName.L
// Evaluate arguments
var args []interface{}
for _, arg := range funcCall.Args {
value, err := evaluateExpressionOnJoinResult(arg, nil, joinResult, row)
if err != nil {
return nil, fmt.Errorf("error evaluating function argument: %v", err)
}
args = append(args, value)
}
// Execute the function
return ExecuteFunction(funcName, args)
}
// evaluateCaseExpression evaluates a CASE expression
func evaluateCaseExpression(caseExpr *ast.CaseExpr, table *Table, row Row) (interface{}, error) {
// CASE expr WHEN value1 THEN result1 [WHEN value2 THEN result2 ...] [ELSE result] END
var caseValue interface{}
var err error
if caseExpr.Value != nil {
// Simple CASE: CASE expr WHEN value THEN result
caseValue, err = evaluateExpressionInRow(caseExpr.Value, table, row)
if err != nil {
return nil, fmt.Errorf("error evaluating CASE value: %v", err)
}
}
// Evaluate each WHEN clause
for _, whenClause := range caseExpr.WhenClauses {
var conditionMet bool
if caseExpr.Value != nil {
// Simple CASE: compare with case value
whenValue, err := evaluateExpressionInRow(whenClause.Expr, table, row)
if err != nil {
return nil, fmt.Errorf("error evaluating WHEN expression: %v", err)
}
conditionMet = (compareValues(caseValue, whenValue) == 0)
} else {
// Searched CASE: evaluate condition as boolean
conditionResult, err := evaluateWhereCondition(whenClause.Expr, table, row)
if err != nil {
return nil, fmt.Errorf("error evaluating WHEN condition: %v", err)
}
conditionMet = conditionResult
}
if conditionMet {
// Return the THEN result
return evaluateExpressionInRow(whenClause.Result, table, row)
}
}
// If no WHEN clause matched, return ELSE result or NULL
if caseExpr.ElseClause != nil {
return evaluateExpressionInRow(caseExpr.ElseClause, table, row)
}
return nil, nil
}
// evaluateCaseExpressionOnJoinResult evaluates a CASE expression in JOIN context
func evaluateCaseExpressionOnJoinResult(caseExpr *ast.CaseExpr, db *Database, joinResult *JoinResult, row []interface{}) (interface{}, error) {
// CASE expr WHEN value1 THEN result1 [WHEN value2 THEN result2 ...] [ELSE result] END
var caseValue interface{}
var err error
if caseExpr.Value != nil {
// Simple CASE: CASE expr WHEN value THEN result
caseValue, err = evaluateExpressionOnJoinResult(caseExpr.Value, db, joinResult, row)
if err != nil {
return nil, fmt.Errorf("error evaluating CASE value: %v", err)
}
}
// Evaluate each WHEN clause
for _, whenClause := range caseExpr.WhenClauses {
var conditionMet bool
if caseExpr.Value != nil {
// Simple CASE: compare with case value
whenValue, err := evaluateExpressionOnJoinResult(whenClause.Expr, db, joinResult, row)
if err != nil {
return nil, fmt.Errorf("error evaluating WHEN expression: %v", err)
}
conditionMet = (compareValues(caseValue, whenValue) == 0)
} else {
// Searched CASE: evaluate condition as boolean
conditionResult, err := evaluateWhereConditionOnJoinResult(whenClause.Expr, db, joinResult, row)
if err != nil {
return nil, fmt.Errorf("error evaluating WHEN condition: %v", err)
}
conditionMet = conditionResult
}
if conditionMet {
// Return the THEN result
return evaluateExpressionOnJoinResult(whenClause.Result, db, joinResult, row)
}
}
// If no WHEN clause matched, return ELSE result or NULL
if caseExpr.ElseClause != nil {
return evaluateExpressionOnJoinResult(caseExpr.ElseClause, db, joinResult, row)
}
return nil, nil
}
// Pattern Matching Functions
// evaluateRegexpOperation evaluates REGEXP/RLIKE pattern matching
func evaluateRegexpOperation(value, pattern interface{}) (bool, error) {
// Handle NULL values - REGEXP with NULL returns NULL (false in boolean context)
if value == nil || pattern == nil {
return false, nil
}
// Convert to strings
valueStr := fmt.Sprintf("%v", value)
patternStr := fmt.Sprintf("%v", pattern)
// Compile and match the regular expression
matched, err := regexp.MatchString(patternStr, valueStr)
if err != nil {
return false, fmt.Errorf("invalid REGEXP pattern: %v", err)
}
return matched, nil
}
// evaluateRegexpExpression evaluates REGEXP pattern matching
func evaluateRegexpExpression(regexpExpr *ast.PatternRegexpExpr, table *Table, row Row) (bool, error) {
// Evaluate the expression being tested
value, err := evaluateExpressionInRow(regexpExpr.Expr, table, row)
if err != nil {
return false, err
}
// Evaluate the pattern
pattern, err := evaluateExpressionInRow(regexpExpr.Pattern, table, row)
if err != nil {
return false, err
}
// Handle NULL values - REGEXP with NULL returns NULL (false in boolean context)
if value == nil || pattern == nil {
return false, nil
}
// Convert to strings
valueStr := fmt.Sprintf("%v", value)
patternStr := fmt.Sprintf("%v", pattern)
// Compile and match the regular expression
matched, err := regexp.MatchString(patternStr, valueStr)
if err != nil {
return false, fmt.Errorf("invalid REGEXP pattern: %v", err)
}
// Handle NOT REGEXP
if regexpExpr.Not {
return !matched, nil
}
return matched, nil
}
// evaluateRegexpExpressionOnJoinResult evaluates REGEXP in JOIN context
func evaluateRegexpExpressionOnJoinResult(regexpExpr *ast.PatternRegexpExpr, joinResult *JoinResult, row []interface{}) (bool, error) {
// Evaluate the expression being tested
value, err := evaluateExpressionOnJoinResult(regexpExpr.Expr, nil, joinResult, row)
if err != nil {
return false, err
}
// Evaluate the pattern
pattern, err := evaluateExpressionOnJoinResult(regexpExpr.Pattern, nil, joinResult, row)
if err != nil {
return false, err
}
// Handle NULL values - REGEXP with NULL returns NULL (false in boolean context)
if value == nil || pattern == nil {
return false, nil
}
// Convert to strings
valueStr := fmt.Sprintf("%v", value)
patternStr := fmt.Sprintf("%v", pattern)
// Compile and match the regular expression
matched, err := regexp.MatchString(patternStr, valueStr)
if err != nil {
return false, fmt.Errorf("invalid REGEXP pattern: %v", err)
}
// Handle NOT REGEXP
if regexpExpr.Not {
return !matched, nil
}
return matched, nil
}
// evaluateLikeExpression evaluates LIKE pattern matching
func evaluateLikeExpression(likeExpr *ast.PatternLikeOrIlikeExpr, table *Table, row Row) (bool, error) {
// Evaluate the expression being tested
value, err := evaluateExpressionInRow(likeExpr.Expr, table, row)
if err != nil {
return false, err
}
// Evaluate the pattern
pattern, err := evaluateExpressionInRow(likeExpr.Pattern, table, row)
if err != nil {
return false, err
}
// Handle NULL values - LIKE with NULL returns NULL (false in boolean context)
if value == nil || pattern == nil {
return false, nil
}
// Convert to strings
valueStr := fmt.Sprintf("%v", value)
patternStr := fmt.Sprintf("%v", pattern)
// Convert SQL LIKE pattern to Go regex
regexPattern := convertLikePatternToRegex(patternStr)
// Compile and match
matched, err := regexp.MatchString(regexPattern, valueStr)
if err != nil {
return false, fmt.Errorf("invalid LIKE pattern: %v", err)
}
// Handle NOT LIKE
if likeExpr.Not {
return !matched, nil
}
return matched, nil
}
// evaluateLikeExpressionOnJoinResult evaluates LIKE in JOIN context
func evaluateLikeExpressionOnJoinResult(likeExpr *ast.PatternLikeOrIlikeExpr, joinResult *JoinResult, row []interface{}) (bool, error) {
// Evaluate the expression being tested
value, err := evaluateExpressionOnJoinResult(likeExpr.Expr, nil, joinResult, row)
if err != nil {
return false, err
}
// Evaluate the pattern
pattern, err := evaluateExpressionOnJoinResult(likeExpr.Pattern, nil, joinResult, row)
if err != nil {
return false, err
}
// Handle NULL values - LIKE with NULL returns NULL (false in boolean context)
if value == nil || pattern == nil {
return false, nil
}
// Convert to strings
valueStr := fmt.Sprintf("%v", value)
patternStr := fmt.Sprintf("%v", pattern)
// Convert SQL LIKE pattern to Go regex
regexPattern := convertLikePatternToRegex(patternStr)
// Compile and match
matched, err := regexp.MatchString(regexPattern, valueStr)
if err != nil {
return false, fmt.Errorf("invalid LIKE pattern: %v", err)
}
// Handle NOT LIKE
if likeExpr.Not {
return !matched, nil
}
return matched, nil
}
// convertLikePatternToRegex converts SQL LIKE pattern to Go regex pattern
func convertLikePatternToRegex(likePattern string) string {
// First handle escaped wildcards (literal % and _ in the pattern)
// In SQL, \% matches literal %, \_ matches literal _
// Replace them with placeholders that don't contain wildcards
escaped := strings.ReplaceAll(likePattern, "\\%", "〈LITERAL-PERCENT〉")
escaped = strings.ReplaceAll(escaped, "\\_", "〈LITERAL-UNDERSCORE〉")
// Replace SQL wildcards with special placeholders that won't be escaped
escaped = strings.ReplaceAll(escaped, "%", "〈WILDCARD-PERCENT〉")
escaped = strings.ReplaceAll(escaped, "_", "〈WILDCARD-UNDERSCORE〉")
// Now escape all special regex characters
escaped = regexp.QuoteMeta(escaped)
// Replace placeholders with actual regex patterns
escaped = strings.ReplaceAll(escaped, "〈WILDCARD-PERCENT〉", ".*")
escaped = strings.ReplaceAll(escaped, "〈WILDCARD-UNDERSCORE〉", ".")
// Restore escaped wildcards as literal characters
escaped = strings.ReplaceAll(escaped, "〈LITERAL-PERCENT〉", "%")
escaped = strings.ReplaceAll(escaped, "〈LITERAL-UNDERSCORE〉", "_")
// Anchor the pattern to match the entire string
return "^" + escaped + "$"
}
// Subquery Functions
// evaluateExistsExpression evaluates EXISTS subquery
func evaluateExistsExpression(existsExpr *ast.ExistsSubqueryExpr, db *Database, table *Table, row Row) (bool, error) {
// Execute the subquery
// Cast Sel to SubqueryExpr
subqueryExpr, ok := existsExpr.Sel.(*ast.SubqueryExpr)
if !ok {
return false, fmt.Errorf("EXISTS Sel must be a SubqueryExpr")
}
// Cast Query to SelectStmt
subquery, ok := subqueryExpr.Query.(*ast.SelectStmt)
if !ok {
return false, fmt.Errorf("EXISTS subquery must be a SELECT statement")
}
subqueryResult, err := executeSubqueryForExists(db, subquery, table, row)
if err != nil {
return false, fmt.Errorf("error executing EXISTS subquery: %v", err)
}
// EXISTS returns true if subquery returns any rows
hasRows := len(subqueryResult.Rows) > 0
// Handle NOT EXISTS
if existsExpr.Not {
return !hasRows, nil
}
return hasRows, nil
}
// evaluateExistsExpressionOnJoinResult evaluates EXISTS in JOIN context
func evaluateExistsExpressionOnJoinResult(existsExpr *ast.ExistsSubqueryExpr, db *Database, joinResult *JoinResult, row []interface{}) (bool, error) {
// For JOIN context, we need to create a virtual table context
// This is more complex as we need to simulate the current row context
virtualTable := createVirtualTableFromJoinResult(joinResult, row)
virtualRow := Row{Values: row}
// Execute the subquery
// Cast Sel to SubqueryExpr
subqueryExpr, ok := existsExpr.Sel.(*ast.SubqueryExpr)
if !ok {
return false, fmt.Errorf("EXISTS Sel must be a SubqueryExpr")
}
// Cast Query to SelectStmt
subquery, ok := subqueryExpr.Query.(*ast.SelectStmt)
if !ok {
return false, fmt.Errorf("EXISTS subquery must be a SELECT statement")
}
subqueryResult, err := executeSubqueryForExists(db, subquery, virtualTable, virtualRow)
if err != nil {
return false, fmt.Errorf("error executing EXISTS subquery in JOIN: %v", err)
}
// EXISTS returns true if subquery returns any rows
hasRows := len(subqueryResult.Rows) > 0
// Handle NOT EXISTS
if existsExpr.Not {
return !hasRows, nil
}
return hasRows, nil
}
// executeSubqueryForExists executes a subquery in the context of EXISTS
func executeSubqueryForExists(db *Database, subquery *ast.SelectStmt, outerTable *Table, outerRow Row) (*SelectResult, error) {
// Create a new execution context that includes both the outer table context
// and access to all tables in the database
// Execute the subquery with correlated context
result, err := ExecuteSelectWithCorrelatedContext(db, subquery, outerTable, outerRow)
if err != nil {
return nil, err
}
return result, nil
}
// createVirtualTableFromJoinResult creates a virtual table context for JOIN EXISTS
func createVirtualTableFromJoinResult(joinResult *JoinResult, row []interface{}) *Table {
// Create a virtual table that represents the current JOIN result row
virtualTable := &Table{
Name: "virtual_join_context",
Columns: make([]Column, len(joinResult.Columns)),
Rows: []Row{{Values: row}},
}
// Create column definitions based on the JOIN result
for i, colName := range joinResult.Columns {
virtualTable.Columns[i] = Column{
Name: colName,
Type: TypeText, // Default to text type
}
}
return virtualTable
}
// Logical NOT Functions
// evaluateNotExpression evaluates logical NOT
func evaluateNotExpression(notExpr *ast.UnaryOperationExpr, table *Table, row Row) (bool, error) {
// Evaluate the inner expression
result, err := evaluateWhereCondition(notExpr.V, table, row)
if err != nil {
return false, err
}
// Return the logical negation
return !result, nil
}
// evaluateNotExpressionOnJoinResult evaluates logical NOT in JOIN context
func evaluateNotExpressionOnJoinResult(notExpr *ast.UnaryOperationExpr, db *Database, joinResult *JoinResult, row []interface{}) (bool, error) {
// Evaluate the inner expression
result, err := evaluateWhereConditionOnJoinResult(notExpr.V, db, joinResult, row)
if err != nil {
return false, err
}
// Return the logical negation
return !result, nil
}