forked from SPANDigital/cel2sql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcel2sql.go
More file actions
2732 lines (2443 loc) · 85 KB
/
cel2sql.go
File metadata and controls
2732 lines (2443 loc) · 85 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
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package cel2sql converts CEL (Common Expression Language) expressions to SQL conditions.
// It supports multiple SQL dialects through the dialect interface, with PostgreSQL as the default.
//
// Modified by Observe, Inc. (2026): Added WithJSONVariables and WithColumnAliases options.
// Original source: github.com/SPANDigital/cel2sql
package cel2sql
import (
"context"
"fmt"
"log/slog"
"math"
"slices"
"strconv"
"strings"
"time"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/common/operators"
"github.com/google/cel-go/common/overloads"
exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
"github.com/observeinc/cel2sql/v3/dialect"
"github.com/observeinc/cel2sql/v3/dialect/postgres"
"github.com/observeinc/cel2sql/v3/schema"
)
// Implementations based on `google/cel-go`'s unparser
// https://github.com/google/cel-go/blob/master/parser/unparser.go
// Resource limit constants.
const (
// defaultMaxRecursionDepth is the default maximum recursion depth for visit()
// to prevent stack overflow from deeply nested expressions (CWE-674: Uncontrolled Recursion).
defaultMaxRecursionDepth = 100
// maxComprehensionDepth is the maximum nesting depth for CEL comprehensions
// to prevent resource exhaustion from deeply nested UNNEST/subquery operations (CWE-400).
maxComprehensionDepth = 3
// maxByteArrayLength is the maximum allowed length for byte arrays in non-parameterized mode
// to prevent memory exhaustion from large hex-encoded SQL strings (CWE-400).
// Each byte expands to ~4 characters in hex format (e.g., \xDE).
// 10,000 bytes → ~40KB SQL output.
maxByteArrayLength = 10000
// defaultMaxSQLOutputLength is the default maximum length of generated SQL output
// to prevent resource exhaustion from extremely large SQL queries (CWE-400).
defaultMaxSQLOutputLength = 50000
)
// ConvertOption is a functional option for configuring the Convert function.
type ConvertOption func(*convertOptions)
// convertOptions holds configuration options for the Convert function.
type convertOptions struct {
schemas map[string]schema.Schema
jsonVars map[string]bool // Variable names that are JSONB columns
columnAlias map[string]string // CEL variable name → SQL column name
ctx context.Context
logger *slog.Logger
maxDepth int // Maximum recursion depth (0 = use default)
maxOutputLen int // Maximum SQL output length (0 = use default)
dialect dialect.Dialect // SQL dialect (nil = PostgreSQL default)
paramStartIndex int // First placeholder index for ConvertParameterized (1 = $1, $2, ...; 5 = $5, $6, ...)
}
// WithDialect sets the SQL dialect for conversion.
// If not provided, PostgreSQL is used as the default dialect.
//
// Example:
//
// import "github.com/observeinc/cel2sql/v3/dialect/mysql"
//
// sql, err := cel2sql.Convert(ast, cel2sql.WithDialect(mysql.New()))
func WithDialect(d dialect.Dialect) ConvertOption {
return func(o *convertOptions) {
o.dialect = d
}
}
// WithSchemas provides schema information for proper JSON/JSONB field handling.
// This option is required for correct SQL generation when using JSON/JSONB fields.
//
// Example:
//
// schemas := provider.GetSchemas()
// sql, err := cel2sql.Convert(ast, cel2sql.WithSchemas(schemas))
func WithSchemas(schemas map[string]schema.Schema) ConvertOption {
return func(o *convertOptions) {
o.schemas = schemas
}
}
// WithJSONVariables declares CEL variable names that correspond to JSONB columns.
// When a variable is marked as JSONB, field access via dot notation (context.host)
// and bracket notation (context["host"]) will produce PostgreSQL JSONB operators
// (e.g., context->>'host') instead of plain dot notation (context.host).
//
// Example:
//
// result, err := cel2sql.ConvertParameterized(ast,
// cel2sql.WithJSONVariables("context"))
// // CEL: context.host == "web-1"
// // SQL: context->>'host' = $1
func WithJSONVariables(vars ...string) ConvertOption {
return func(o *convertOptions) {
if o.jsonVars == nil {
o.jsonVars = make(map[string]bool, len(vars))
}
for _, v := range vars {
o.jsonVars[v] = true
}
}
}
// WithColumnAliases maps CEL variable names to SQL column names.
// When a CEL identifier matches a key in the alias map, the SQL output
// uses the mapped column name instead. This is useful when the database
// column names differ from the user-facing CEL variable names (e.g.,
// prefixed column names in views or tables).
//
// Example:
//
// result, err := cel2sql.ConvertParameterized(ast,
// cel2sql.WithColumnAliases(map[string]string{
// "name": "usr_name",
// "active": "usr_active",
// }))
// // CEL: name == "Alice"
// // SQL: usr_name = $1
func WithColumnAliases(aliases map[string]string) ConvertOption {
return func(o *convertOptions) {
o.columnAlias = aliases
}
}
// WithContext provides a context for cancellation and timeout support.
// If not provided, operations will run without cancellation checks.
// This allows long-running conversions to be cancelled and enables timeout protection.
//
// Example with timeout:
//
// ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
// defer cancel()
// sql, err := cel2sql.Convert(ast, cel2sql.WithContext(ctx))
//
// Example with cancellation:
//
// ctx, cancel := context.WithCancel(context.Background())
// defer cancel()
// sql, err := cel2sql.Convert(ast, cel2sql.WithContext(ctx), cel2sql.WithSchemas(schemas))
func WithContext(ctx context.Context) ConvertOption {
return func(o *convertOptions) {
o.ctx = ctx
}
}
// WithLogger provides a logger for observability and debugging.
// If not provided, logging is disabled with zero overhead using slog.DiscardHandler.
//
// The logger enables visibility into:
// - JSON path detection decisions (table, field, operator selection)
// - Comprehension type identification (all, exists, filter, map)
// - Schema lookups (hits/misses, field types)
// - Performance metrics (conversion duration)
// - Regex pattern transformations (RE2 to POSIX)
// - Operator mapping decisions
// - Error contexts with full details
//
// Example with JSON output:
//
// logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))
// sql, err := cel2sql.Convert(ast, cel2sql.WithLogger(logger))
//
// Example with text output:
//
// logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
// sql, err := cel2sql.Convert(ast, cel2sql.WithSchemas(schemas), cel2sql.WithLogger(logger))
func WithLogger(logger *slog.Logger) ConvertOption {
return func(o *convertOptions) {
o.logger = logger
}
}
// WithMaxDepth sets the maximum recursion depth for expression traversal.
// If not provided, defaultMaxRecursionDepth (100) is used.
// This protects against stack overflow from deeply nested expressions (CWE-674).
//
// Example with custom depth:
//
// sql, err := cel2sql.Convert(ast, cel2sql.WithMaxDepth(150))
//
// Example with multiple options:
//
// sql, err := cel2sql.Convert(ast,
// cel2sql.WithMaxDepth(50),
// cel2sql.WithContext(ctx),
// cel2sql.WithSchemas(schemas))
func WithMaxDepth(maxDepth int) ConvertOption {
return func(o *convertOptions) {
o.maxDepth = maxDepth
}
}
// WithMaxOutputLength sets the maximum length of generated SQL output.
// If not provided, defaultMaxSQLOutputLength (50000) is used.
// This protects against resource exhaustion from extremely large SQL queries (CWE-400).
//
// Example with custom output length limit:
//
// sql, err := cel2sql.Convert(ast, cel2sql.WithMaxOutputLength(100000))
//
// Example with multiple options:
//
// sql, err := cel2sql.Convert(ast,
// cel2sql.WithMaxOutputLength(25000),
// cel2sql.WithMaxDepth(50),
// cel2sql.WithContext(ctx))
func WithMaxOutputLength(maxLength int) ConvertOption {
return func(o *convertOptions) {
o.maxOutputLen = maxLength
}
}
// WithParamStartIndex sets the first placeholder index for ConvertParameterized.
// Use this when embedding the CEL fragment into a larger parameterized query so placeholders
// don't clash with existing parameters. Default is 1 ($1, $2, ...).
// Example: WithParamStartIndex(5) produces $5, $6, ...; the caller appends result.Parameters
// to their args at the corresponding positions.
func WithParamStartIndex(index int) ConvertOption {
return func(o *convertOptions) {
o.paramStartIndex = index
}
}
// Result represents the output of a CEL to SQL conversion with parameterized queries.
// It contains the SQL string with placeholders ($1, $2, etc.) and the corresponding parameter values.
type Result struct {
SQL string // The generated SQL WHERE clause with placeholders
Parameters []any // Parameter values in order ($1, $2, etc.)
}
// Convert converts a CEL AST to a SQL WHERE clause condition.
// By default, PostgreSQL SQL is generated. Use WithDialect to select a different dialect.
//
// Example without options (PostgreSQL):
//
// sql, err := cel2sql.Convert(ast)
//
// Example with schema information for JSON/JSONB support:
//
// sql, err := cel2sql.Convert(ast, cel2sql.WithSchemas(schemas))
//
// Example with a different dialect:
//
// sql, err := cel2sql.Convert(ast, cel2sql.WithDialect(mysql.New()))
func Convert(ast *cel.Ast, opts ...ConvertOption) (string, error) {
start := time.Now()
options := &convertOptions{
logger: slog.New(slog.DiscardHandler), // Default: no-op logger with zero overhead
maxDepth: defaultMaxRecursionDepth, // Default: 100 recursion depth limit
maxOutputLen: defaultMaxSQLOutputLength, // Default: 50000 character output limit
}
for _, opt := range opts {
opt(options)
}
// Default to PostgreSQL dialect if none specified
if options.dialect == nil {
options.dialect = postgres.New()
}
options.logger.Debug("starting CEL to SQL conversion")
checkedExpr, err := cel.AstToCheckedExpr(ast)
if err != nil {
options.logger.Error("AST to CheckedExpr conversion failed", slog.Any("error", err))
return "", err
}
un := &converter{
typeMap: checkedExpr.TypeMap,
schemas: options.schemas,
jsonVars: options.jsonVars,
columnAlias: options.columnAlias,
ctx: options.ctx,
logger: options.logger,
dialect: options.dialect,
maxDepth: options.maxDepth,
maxOutputLen: options.maxOutputLen,
}
if err := un.visit(checkedExpr.Expr); err != nil {
options.logger.Error("conversion failed", slog.Any("error", err))
return "", err
}
result := un.str.String()
duration := time.Since(start)
options.logger.LogAttrs(context.Background(), slog.LevelDebug,
"conversion completed",
slog.String("sql", result),
slog.String("dialect", string(options.dialect.Name())),
slog.Duration("duration", duration),
)
return result, nil
}
// ConvertParameterized converts a CEL AST to a parameterized SQL WHERE clause.
// Returns both the SQL string with placeholders and the parameter values.
// By default uses PostgreSQL ($1, $2). Use WithDialect for other placeholder styles.
//
// Constants that are parameterized:
// - String literals: 'John' → $1
// - Numeric literals: 42, 3.14 → $1, $2
// - Byte literals: b"data" → $1
//
// Constants kept inline (for query plan optimization):
// - TRUE, FALSE (boolean constants)
// - NULL
//
// Example:
//
// result, err := cel2sql.ConvertParameterized(ast,
// cel2sql.WithSchemas(schemas),
// cel2sql.WithContext(ctx))
// // result.SQL: "user.age = $1 AND user.name = $2"
// // result.Parameters: []interface{}{18, "John"}
//
// // Execute with database/sql
// rows, err := db.Query("SELECT * FROM users WHERE "+result.SQL, result.Parameters...)
func ConvertParameterized(ast *cel.Ast, opts ...ConvertOption) (*Result, error) {
start := time.Now()
options := &convertOptions{
logger: slog.New(slog.DiscardHandler), // Default: no-op logger with zero overhead
maxDepth: defaultMaxRecursionDepth, // Default: 100 recursion depth limit
maxOutputLen: defaultMaxSQLOutputLength, // Default: 50000 character output limit
}
for _, opt := range opts {
opt(options)
}
// Default to PostgreSQL dialect if none specified
if options.dialect == nil {
options.dialect = postgres.New()
}
options.logger.Debug("starting parameterized CEL to SQL conversion")
checkedExpr, err := cel.AstToCheckedExpr(ast)
if err != nil {
options.logger.Error("AST to CheckedExpr conversion failed", slog.Any("error", err))
return nil, err
}
paramStart := options.paramStartIndex
if paramStart < 1 {
paramStart = 1
}
un := &converter{
typeMap: checkedExpr.TypeMap,
schemas: options.schemas,
jsonVars: options.jsonVars,
columnAlias: options.columnAlias,
ctx: options.ctx,
logger: options.logger,
dialect: options.dialect,
maxDepth: options.maxDepth,
maxOutputLen: options.maxOutputLen,
parameterize: true, // Enable parameterization
paramCount: paramStart - 1, // First placeholder will be paramStart after first increment
}
if err := un.visit(checkedExpr.Expr); err != nil {
options.logger.Error("conversion failed", slog.Any("error", err))
return nil, err
}
sql := un.str.String()
duration := time.Since(start)
options.logger.LogAttrs(context.Background(), slog.LevelDebug,
"parameterized conversion completed",
slog.String("sql", sql),
slog.Int("param_count", len(un.parameters)),
slog.Duration("duration", duration),
)
return &Result{
SQL: sql,
Parameters: un.parameters,
}, nil
}
type converter struct {
str strings.Builder
typeMap map[int64]*exprpb.Type
schemas map[string]schema.Schema
jsonVars map[string]bool // Variable names that are JSONB columns
columnAlias map[string]string // CEL variable name → SQL column name
ctx context.Context
logger *slog.Logger
dialect dialect.Dialect
depth int // Current recursion depth
maxDepth int // Maximum allowed recursion depth
maxOutputLen int // Maximum allowed SQL output length
comprehensionDepth int // Current comprehension nesting depth
jsonIterVars map[string]bool // Iteration variables from JSON array comprehensions
parameterize bool // Enable parameterized output
parameters []any // Collected parameters for parameterized queries
paramCount int // Parameter counter for placeholders
}
// checkContext checks if the context has been cancelled or expired.
// Returns nil if no context was provided or if the context is still active.
// Returns an error if the context has been cancelled or its deadline has exceeded.
func (con *converter) checkContext() error {
if con.ctx == nil {
return nil
}
if err := con.ctx.Err(); err != nil {
return fmt.Errorf("%w: %w", ErrContextCanceled, err)
}
return nil
}
func (con *converter) visit(expr *exprpb.Expr) error {
// Track recursion depth
con.depth++
defer func() { con.depth-- }()
// Check depth limit before context check (fail fast)
// Allow depths up to and including maxDepth
if con.depth > con.maxDepth {
return fmt.Errorf("%w: depth %d exceeds limit of %d", ErrMaxDepthExceeded, con.depth, con.maxDepth)
}
// Check for context cancellation at the main recursion entry point
if err := con.checkContext(); err != nil {
return err
}
// Check SQL output length limit to prevent resource exhaustion (CWE-400)
if con.str.Len() > con.maxOutputLen {
return fmt.Errorf("%w: %d bytes exceeds limit of %d", ErrMaxOutputLengthExceeded, con.str.Len(), con.maxOutputLen)
}
switch expr.ExprKind.(type) {
case *exprpb.Expr_CallExpr:
return con.visitCall(expr)
// Comprehensions are supported (all, exists, exists_one, filter, map).
case *exprpb.Expr_ComprehensionExpr:
return con.visitComprehension(expr)
case *exprpb.Expr_ConstExpr:
return con.visitConst(expr)
case *exprpb.Expr_IdentExpr:
return con.visitIdent(expr)
case *exprpb.Expr_ListExpr:
return con.visitList(expr)
case *exprpb.Expr_SelectExpr:
return con.visitSelect(expr)
case *exprpb.Expr_StructExpr:
return con.visitStruct(expr)
}
return newConversionErrorf(errMsgUnsupportedExpression, "expr type: %T, id: %d", expr.ExprKind, expr.Id)
}
// isFieldJSON checks if a field in a table is a JSON/JSONB type using schema information
func (con *converter) isFieldJSON(tableName, fieldName string) bool {
if con.schemas == nil {
con.logger.Debug("no schemas provided for JSON detection")
return false
}
schema, ok := con.schemas[tableName]
if !ok {
con.logger.Debug("schema not found for table", slog.String("table", tableName))
return false
}
for _, field := range schema.Fields() {
if field.Name == fieldName {
con.logger.LogAttrs(context.Background(), slog.LevelDebug,
"field type lookup",
slog.String("table", tableName),
slog.String("field", fieldName),
slog.Bool("is_json", field.IsJSON),
)
return field.IsJSON
}
}
con.logger.Debug("field not found in schema",
slog.String("table", tableName),
slog.String("field", fieldName))
return false
}
// getTableAndFieldFromSelectChain extracts the table name and field name from a select expression chain
// For obj.metadata, it returns ("obj", "metadata")
func (con *converter) getTableAndFieldFromSelectChain(expr *exprpb.Expr) (string, string, bool) {
selectExpr := expr.GetSelectExpr()
if selectExpr == nil {
return "", "", false
}
fieldName := selectExpr.GetField()
operand := selectExpr.GetOperand()
// Check if the operand is an identifier (table name)
if identExpr := operand.GetIdentExpr(); identExpr != nil {
tableName := identExpr.GetName()
return tableName, fieldName, true
}
return "", "", false
}
// isFieldJSONB checks if a field in a table is specifically JSONB (vs JSON) using schema information
func (con *converter) isFieldJSONB(tableName, fieldName string) bool {
if con.schemas == nil {
return false
}
schema, ok := con.schemas[tableName]
if !ok {
return false
}
for _, field := range schema.Fields() {
if field.Name == fieldName {
return field.IsJSONB
}
}
return false
}
// isFieldArray checks if a field in a table is an array using schema information
func (con *converter) isFieldArray(tableName, fieldName string) bool {
if con.schemas == nil {
return false
}
schema, ok := con.schemas[tableName]
if !ok {
return false
}
for _, field := range schema.Fields() {
if field.Name == fieldName {
return field.Repeated
}
}
return false
}
// getFieldElementType returns the element type of an array field using schema information
func (con *converter) getFieldElementType(tableName, fieldName string) string {
if con.schemas == nil {
return ""
}
schema, ok := con.schemas[tableName]
if !ok {
return ""
}
for _, field := range schema.Fields() {
if field.Name == fieldName && field.Repeated {
return field.ElementType
}
}
return ""
}
// getArrayDimension returns the number of array dimensions for a field expression.
// Returns 1 if no schema information is available (backward compatible default).
// For multi-dimensional arrays, returns the detected dimension count (2 for int[][], 3 for int[][][], etc.)
func (con *converter) getArrayDimension(expr *exprpb.Expr) int {
// Default to 1D arrays if we can't determine from schema
if con.schemas == nil {
return 1
}
// Try to extract field name from the select expression
selectExpr := expr.GetSelectExpr()
if selectExpr == nil {
return 1
}
fieldName := selectExpr.GetField()
operand := selectExpr.GetOperand()
// Get the type of the operand from the type map
operandType := con.typeMap[operand.GetId()]
if operandType == nil {
return 1
}
// Extract the type name (e.g., "TestTable" from the object type)
typeName := operandType.GetMessageType()
if typeName == "" {
return 1
}
// Look up the schema by type name
schema, ok := con.schemas[typeName]
if !ok {
return 1
}
// Find the field in the schema
field, found := schema.FindField(fieldName)
if !found || !field.Repeated {
return 1
}
// If dimensions is explicitly set and > 0, use it
if field.Dimensions > 0 {
return field.Dimensions
}
// Otherwise default to 1
return 1
}
func (con *converter) visitCall(expr *exprpb.Expr) error {
// Check for context cancellation before processing function calls
if err := con.checkContext(); err != nil {
return err
}
c := expr.GetCallExpr()
fun := c.GetFunction()
switch fun {
// ternary operator
case operators.Conditional:
return con.visitCallConditional(expr)
// index operator
case operators.Index:
return con.visitCallIndex(expr)
// unary operators
case operators.LogicalNot, operators.Negate:
return con.visitCallUnary(expr)
// binary operators
case operators.Add,
operators.Divide,
operators.Equals,
operators.Greater,
operators.GreaterEquals,
operators.In,
operators.Less,
operators.LessEquals,
operators.LogicalAnd,
operators.LogicalOr,
operators.Multiply,
operators.NotEquals,
operators.OldIn,
operators.Subtract:
return con.visitCallBinary(expr)
// standard function calls.
default:
return con.visitCallFunc(expr)
}
}
func (con *converter) visitCallBinary(expr *exprpb.Expr) error {
c := expr.GetCallExpr()
fun := c.GetFunction()
args := c.GetArgs()
lhs := args[0]
// add parens if the current operator is lower precedence than the lhs expr operator.
lhsParen := isComplexOperatorWithRespectTo(fun, lhs)
rhs := args[1]
// add parens if the current operator is lower precedence than the rhs expr operator,
// or the same precedence and the operator is left recursive.
rhsParen := isComplexOperatorWithRespectTo(fun, rhs)
lhsType := con.getType(lhs)
rhsType := con.getType(rhs)
if (isTimestampRelatedType(lhsType) && isDurationRelatedType(rhsType)) ||
(isTimestampRelatedType(rhsType) && isDurationRelatedType(lhsType)) {
return con.callTimestampOperation(fun, lhs, rhs)
}
if !rhsParen && isLeftRecursive(fun) {
rhsParen = isSamePrecedence(fun, rhs)
}
// Handle string concatenation via dialect before writing LHS.
// This allows MySQL to use CONCAT() instead of ||.
if fun == operators.Add &&
((lhsType.GetPrimitive() == exprpb.Type_STRING && rhsType.GetPrimitive() == exprpb.Type_STRING) ||
(isStringLiteral(lhs) || isStringLiteral(rhs))) {
return con.dialect.WriteStringConcat(&con.str,
func() error { return con.visitMaybeNested(lhs, lhsParen) },
func() error { return con.visitMaybeNested(rhs, rhsParen) },
)
}
// Handle array membership (IN operator with list) via dialect before writing LHS.
// This allows dialects like SQLite to use a fundamentally different pattern
// (e.g., "elem IN (SELECT value FROM json_each(array))") instead of "elem = ANY(array)".
if fun == operators.In && isListType(rhsType) {
// Non-JSON list membership
if !isFieldAccessExpression(rhs) || !con.isJSONArrayField(rhs) {
return con.dialect.WriteArrayMembership(&con.str,
func() error { return con.visitMaybeNested(lhs, lhsParen) },
func() error { return con.visitMaybeNested(rhs, rhsParen) },
)
}
}
// Check if we need numeric casting for JSON text extraction
needsNumericCasting := false
if con.isJSONTextExtraction(lhs) && isNumericComparison(fun) && isNumericType(rhsType) {
needsNumericCasting = true
con.str.WriteString("(")
}
if err := con.visitMaybeNested(lhs, lhsParen); err != nil {
return err
}
if needsNumericCasting {
con.str.WriteString(")")
con.dialect.WriteCastToNumeric(&con.str)
}
var operator string
if fun == operators.Add && (lhsType.GetPrimitive() == exprpb.Type_STRING && rhsType.GetPrimitive() == exprpb.Type_STRING) {
operator = "||"
} else if fun == operators.Add && (rhsType.GetPrimitive() == exprpb.Type_BYTES && lhsType.GetPrimitive() == exprpb.Type_BYTES) {
operator = "||"
} else if fun == operators.Add && (isListType(lhsType) && isListType(rhsType)) {
operator = "||"
} else if fun == operators.Add && (isStringLiteral(lhs) || isStringLiteral(rhs)) {
// If either operand is a string literal, assume string concatenation
operator = "||"
} else if fun == operators.Equals && (isNullLiteral(rhs) || isBoolLiteral(rhs)) {
operator = "IS"
} else if fun == operators.NotEquals && (isNullLiteral(rhs) || isBoolLiteral(rhs)) {
operator = "IS NOT"
} else if fun == operators.In && isListType(rhsType) {
operator = "="
} else if fun == operators.In && isFieldAccessExpression(rhs) {
// In PostgreSQL, field access expressions in IN clauses are likely array membership tests
// For both JSON arrays and regular arrays, we use the same operator
operator = "="
} else if fun == operators.In {
operator = "IN"
} else if op, found := standardSQLBinaryOperators[fun]; found {
operator = op
} else if op, found := operators.FindReverseBinaryOperator(fun); found {
operator = op
} else {
return newConversionErrorf(errMsgInvalidOperator, "binary operator: %s", fun)
}
con.logger.LogAttrs(context.Background(), slog.LevelDebug,
"binary operator conversion",
slog.String("cel_op", fun),
slog.String("sql_op", operator),
)
con.str.WriteString(" ")
con.str.WriteString(operator)
con.str.WriteString(" ")
if fun == operators.In && (isListType(rhsType) || isFieldAccessExpression(rhs)) {
// Check if we're dealing with a JSON array
if isFieldAccessExpression(rhs) && con.isJSONArrayField(rhs) {
// For JSON arrays, use dialect-specific JSON array membership
jsonFunc := con.getJSONArrayFunction(rhs)
// For nested JSON access like settings.permissions, we need to handle differently
if con.isNestedJSONAccess(rhs) {
// Use dialect-specific nested JSON array membership
if err := con.dialect.WriteNestedJSONArrayMembership(&con.str, func() error {
return con.visitNestedJSONForArray(rhs)
}); err != nil {
return err
}
return nil
}
// For direct JSON array access
if err := con.dialect.WriteJSONArrayMembership(&con.str, jsonFunc, func() error {
return con.visitMaybeNested(rhs, rhsParen)
}); err != nil {
return err
}
return nil
}
con.str.WriteString("ANY(")
}
if err := con.visitMaybeNested(rhs, rhsParen); err != nil {
return err
}
if fun == operators.In && (isListType(rhsType) || isFieldAccessExpression(rhs)) {
// Check if we're dealing with a JSON array - already handled above for JSON arrays
if !isFieldAccessExpression(rhs) || !con.isJSONArrayField(rhs) {
con.str.WriteString(")")
}
}
return nil
}
func (con *converter) visitCallConditional(expr *exprpb.Expr) error {
c := expr.GetCallExpr()
args := c.GetArgs()
con.str.WriteString("CASE WHEN ")
if err := con.visit(args[0]); err != nil {
return err
}
con.str.WriteString(" THEN ")
if err := con.visit(args[1]); err != nil {
return err
}
con.str.WriteString(" ELSE ")
if err := con.visit(args[2]); err != nil {
return err
}
con.str.WriteString(" END")
return nil
}
func (con *converter) callContains(target *exprpb.Expr, args []*exprpb.Expr) error {
// Check if the target is a JSON/JSONB field
if target != nil && con.isJSONArrayField(target) {
// For JSON/JSONB arrays, use the ? operator
if err := con.visit(target); err != nil {
return err
}
con.str.WriteString(" ? ")
if len(args) > 0 {
if err := con.visit(args[0]); err != nil {
return err
}
}
return nil
}
// For regular strings, use dialect-specific contains
return con.dialect.WriteContains(&con.str,
func() error {
if target != nil {
nested := isBinaryOrTernaryOperator(target)
return con.visitMaybeNested(target, nested)
}
return nil
},
func() error {
for i, arg := range args {
if err := con.visit(arg); err != nil {
return err
}
if i < len(args)-1 {
con.str.WriteString(", ")
}
}
return nil
},
)
}
func (con *converter) callStartsWith(target *exprpb.Expr, args []*exprpb.Expr) error {
// CEL startsWith function: string.startsWith(prefix)
// Convert to PostgreSQL: string LIKE 'prefix%'
// or for more robust handling: LEFT(string, LENGTH(prefix)) = prefix
if target == nil || len(args) == 0 {
return fmt.Errorf("%w: startsWith function requires both string and prefix arguments", ErrInvalidArguments)
}
// Visit the string expression
nested := isBinaryOrTernaryOperator(target)
if err := con.visitMaybeNested(target, nested); err != nil {
return err
}
con.str.WriteString(" LIKE ")
// Visit the prefix argument and append '%' for LIKE pattern
// If it's a constant string, we can append % directly
if constExpr := args[0].GetConstExpr(); constExpr != nil && constExpr.GetStringValue() != "" {
prefix := constExpr.GetStringValue()
// Reject patterns containing null bytes
if strings.Contains(prefix, "\x00") {
return fmt.Errorf("%w: LIKE patterns cannot contain null bytes", ErrInvalidArguments)
}
// Escape special LIKE characters: %, _, \
escaped := escapeLikePattern(prefix)
con.str.WriteString("'")
con.str.WriteString(escaped)
con.str.WriteString("%'")
con.dialect.WriteLikeEscape(&con.str)
} else {
// For non-literal patterns, escape special characters at runtime and concatenate with %
con.str.WriteString("REPLACE(REPLACE(REPLACE(")
if err := con.visit(args[0]); err != nil {
return err
}
con.str.WriteString(", '\\\\', '\\\\\\\\'), '%', '\\%'), '_', '\\_') || '%'")
con.dialect.WriteLikeEscape(&con.str)
}
return nil
}
func (con *converter) callEndsWith(target *exprpb.Expr, args []*exprpb.Expr) error {
// CEL endsWith function: string.endsWith(suffix)
// Convert to SQL: string LIKE '%suffix'
if target == nil || len(args) == 0 {
return fmt.Errorf("%w: endsWith function requires both string and suffix arguments", ErrInvalidArguments)
}
// Visit the string expression
nested := isBinaryOrTernaryOperator(target)
if err := con.visitMaybeNested(target, nested); err != nil {
return err
}
con.str.WriteString(" LIKE ")
// Visit the suffix argument and prepend '%' for LIKE pattern
// If it's a constant string, we can prepend % directly
if constExpr := args[0].GetConstExpr(); constExpr != nil && constExpr.GetStringValue() != "" {
suffix := constExpr.GetStringValue()
// Reject patterns containing null bytes
if strings.Contains(suffix, "\x00") {
return fmt.Errorf("%w: LIKE patterns cannot contain null bytes", ErrInvalidArguments)
}
// Escape special LIKE characters: %, _, \
escaped := escapeLikePattern(suffix)
con.str.WriteString("'%")
con.str.WriteString(escaped)
con.str.WriteString("'")
con.dialect.WriteLikeEscape(&con.str)
} else {
// For non-literal patterns, escape special characters at runtime and concatenate with %
con.str.WriteString("'%' || REPLACE(REPLACE(REPLACE(")
if err := con.visit(args[0]); err != nil {
return err
}
con.str.WriteString(", '\\\\', '\\\\\\\\'), '%', '\\%'), '_', '\\_')")
con.dialect.WriteLikeEscape(&con.str)
}
return nil
}
func (con *converter) callCasting(function string, _ *exprpb.Expr, args []*exprpb.Expr) error {
if len(args) == 0 {
return fmt.Errorf("%w: type conversion requires an argument", ErrInvalidArguments)
}
arg := args[0]
if function == overloads.TypeConvertInt && isTimestampType(con.getType(arg)) {
return con.dialect.WriteEpochExtract(&con.str, func() error {
return con.visit(arg)
})
}
con.str.WriteString("CAST(")
if err := con.visit(arg); err != nil {
return err
}
con.str.WriteString(" AS ")
// Map CEL type conversion function to dialect-specific type name
var celTypeName string
switch function {
case overloads.TypeConvertBool:
celTypeName = "bool"
case overloads.TypeConvertBytes:
celTypeName = "bytes"
case overloads.TypeConvertDouble:
celTypeName = "double"
case overloads.TypeConvertInt:
celTypeName = "int"
case overloads.TypeConvertString:
celTypeName = "string"
case overloads.TypeConvertUint:
celTypeName = "uint"
}
con.dialect.WriteTypeName(&con.str, celTypeName)
con.str.WriteString(")")
return nil
}
// callMatches handles CEL matches() function with regex conversion
func (con *converter) callMatches(target *exprpb.Expr, args []*exprpb.Expr) error {
// CEL matches function: string.matches(pattern) or matches(string, pattern)
// Check if the dialect supports regex
if !con.dialect.SupportsRegex() {
return fmt.Errorf("%w: regex matching is not supported by %s dialect", ErrUnsupportedDialectFeature, con.dialect.Name())
}