-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathast.go
More file actions
2327 lines (2118 loc) · 79 KB
/
ast.go
File metadata and controls
2327 lines (2118 loc) · 79 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
// Copyright 2026 GoSQLX Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ast
import (
"fmt"
"github.com/ajitpratap0/GoSQLX/pkg/models"
)
// Node represents any node in the Abstract Syntax Tree.
//
// Node is the base interface that all AST nodes must implement. It provides
// two core methods for tree inspection and traversal:
//
// - TokenLiteral(): Returns the literal token value that starts this node
// - Children(): Returns all child nodes for tree traversal
//
// The Node interface enables the visitor pattern for AST traversal. Use the
// Walk() and Inspect() functions from visitor.go to traverse the tree.
//
// Example - Checking node type:
//
// switch node := astNode.(type) {
// case *SelectStatement:
// fmt.Println("Found SELECT statement")
// case *BinaryExpression:
// fmt.Printf("Binary operator: %s\n", node.Operator)
// }
type Node interface {
TokenLiteral() string
Children() []Node
}
// Statement represents a SQL statement node in the AST.
//
// Statement extends the Node interface and represents top-level SQL statements
// such as SELECT, INSERT, UPDATE, DELETE, CREATE TABLE, etc. Statements form
// the root nodes of the syntax tree.
//
// All statement types implement both Node and Statement interfaces. The
// statementNode() method is a marker method to distinguish statements from
// expressions at compile time.
//
// Supported Statement Types:
// - DML: SelectStatement, InsertStatement, UpdateStatement, DeleteStatement
// - DDL: CreateTableStatement, AlterTableStatement, DropStatement
// - Advanced: MergeStatement, TruncateStatement, WithClause, SetOperation
// - Views: CreateViewStatement, CreateMaterializedViewStatement
//
// Example - Type assertion:
//
// if stmt, ok := node.(Statement); ok {
// fmt.Printf("Statement type: %s\n", stmt.TokenLiteral())
// }
type Statement interface {
Node
statementNode()
}
// Expression represents a SQL expression node in the AST.
//
// Expression extends the Node interface and represents SQL expressions that
// can appear within statements, such as literals, identifiers, binary operations,
// function calls, subqueries, etc.
//
// All expression types implement both Node and Expression interfaces. The
// expressionNode() method is a marker method to distinguish expressions from
// statements at compile time.
//
// Supported Expression Types:
// - Basic: Identifier, LiteralValue, AliasedExpression
// - Operators: BinaryExpression, UnaryExpression, BetweenExpression, InExpression
// - Functions: FunctionCall (with window function support)
// - Subqueries: SubqueryExpression, ExistsExpression, AnyExpression, AllExpression
// - Conditional: CaseExpression, CastExpression
// - Grouping: RollupExpression, CubeExpression, GroupingSetsExpression
//
// Example - Building an expression:
//
// // Build: column = 'value'
// expr := &BinaryExpression{
// Left: &Identifier{Name: "column"},
// Operator: "=",
// Right: &LiteralValue{Value: "value", Type: "STRING"},
// }
type Expression interface {
Node
expressionNode()
}
// WithClause represents a WITH clause in a SQL statement.
// It supports both simple and recursive Common Table Expressions (CTEs).
// Phase 2 Complete: Full parser integration with all statement types.
type WithClause struct {
Recursive bool
CTEs []*CommonTableExpr
Pos models.Location // Source position of the WITH keyword (1-based line and column)
}
func (w *WithClause) statementNode() {}
func (w WithClause) TokenLiteral() string { return "WITH" }
func (w WithClause) Children() []Node {
children := make([]Node, len(w.CTEs))
for i, cte := range w.CTEs {
children[i] = cte
}
return children
}
// CommonTableExpr represents a single Common Table Expression in a WITH clause.
// It supports optional column specifications and any statement type as the CTE query.
// Phase 2 Complete: Full parser support with column specifications.
// Phase 2.6: Added MATERIALIZED/NOT MATERIALIZED support for query optimization hints.
type CommonTableExpr struct {
Name string
Columns []string
Statement Statement
ScalarExpr Expression // ClickHouse: WITH <expr> AS <name> (scalar CTE, no subquery)
Materialized *bool // nil = default, true = MATERIALIZED, false = NOT MATERIALIZED
Pos models.Location // Source position of the CTE name (1-based line and column)
}
func (c *CommonTableExpr) statementNode() {}
func (c CommonTableExpr) TokenLiteral() string { return c.Name }
func (c CommonTableExpr) Children() []Node {
return []Node{c.Statement}
}
// QueryExpression is a Statement that can appear as the source of INSERT ... SELECT.
// Only *SelectStatement and *SetOperation satisfy this interface.
type QueryExpression interface {
Statement
queryExpressionNode()
}
// SetOperation represents set operations (UNION, EXCEPT, INTERSECT) between two statements.
// It supports the ALL modifier (e.g., UNION ALL) and proper left-associative parsing.
// Phase 2 Complete: Full parser support with left-associative precedence.
type SetOperation struct {
Left Statement
Operator string // UNION, EXCEPT, INTERSECT
Right Statement
All bool // UNION ALL vs UNION
}
func (s *SetOperation) statementNode() {}
func (s *SetOperation) queryExpressionNode() {}
func (s SetOperation) TokenLiteral() string { return s.Operator }
func (s SetOperation) Children() []Node {
return []Node{s.Left, s.Right}
}
// JoinClause represents a JOIN clause in SQL
type JoinClause struct {
Type string // INNER, LEFT, RIGHT, FULL
Left TableReference
Right TableReference
Condition Expression
Pos models.Location // Source position of the JOIN keyword (1-based line and column)
}
func (j *JoinClause) expressionNode() {}
func (j JoinClause) TokenLiteral() string { return j.Type + " JOIN" }
func (j JoinClause) Children() []Node {
children := []Node{&j.Left, &j.Right}
if j.Condition != nil {
children = append(children, j.Condition)
}
return children
}
// TableReference represents a table reference in a FROM clause.
//
// TableReference can represent either a simple table name or a derived table
// (subquery). It supports PostgreSQL's LATERAL keyword for correlated subqueries.
//
// Fields:
// - Name: Table name (empty if this is a derived table/subquery)
// - Alias: Optional table alias (AS alias)
// - Subquery: Subquery for derived tables: (SELECT ...) AS alias
// - Lateral: LATERAL keyword for correlated subqueries (PostgreSQL v1.6.0)
//
// The Lateral field enables PostgreSQL's LATERAL JOIN feature, which allows
// subqueries in the FROM clause to reference columns from preceding tables.
//
// Example - Simple table reference:
//
// TableReference{
// Name: "users",
// Alias: "u",
// }
// // SQL: FROM users u
//
// Example - Derived table (subquery):
//
// TableReference{
// Alias: "recent_orders",
// Subquery: selectStmt,
// }
// // SQL: FROM (SELECT ...) AS recent_orders
//
// Example - LATERAL JOIN (PostgreSQL v1.6.0):
//
// TableReference{
// Lateral: true,
// Alias: "r",
// Subquery: correlatedSelectStmt,
// }
// // SQL: FROM users u, LATERAL (SELECT * FROM orders WHERE user_id = u.id) r
//
// New in v1.6.0: Lateral field for PostgreSQL LATERAL JOIN support.
type TableReference struct {
Name string // Table name (empty if this is a derived table)
Alias string // Optional alias
Subquery *SelectStatement // For derived tables: (SELECT ...) AS alias
Lateral bool // LATERAL keyword for correlated subqueries (PostgreSQL)
TableHints []string // SQL Server table hints: WITH (NOLOCK), WITH (ROWLOCK, UPDLOCK), etc.
Final bool // ClickHouse FINAL modifier: forces MergeTree part merge
// TableFunc is a function-call table reference such as
// Snowflake LATERAL FLATTEN(input => col), TABLE(my_func(1,2)),
// IDENTIFIER('t'), or PostgreSQL unnest(array_col). When set, Name
// holds the function name and TableFunc carries the call itself.
TableFunc *FunctionCall
// TimeTravel is the Snowflake time-travel clause applied to this table
// reference: AT / BEFORE (TIMESTAMP|OFFSET|STATEMENT => expr) or
// CHANGES (INFORMATION => DEFAULT|APPEND_ONLY).
TimeTravel *TimeTravelClause
// ForSystemTime is the MariaDB temporal table clause (10.3.4+).
// Example: SELECT * FROM t FOR SYSTEM_TIME AS OF '2024-01-01'
ForSystemTime *ForSystemTimeClause // MariaDB temporal query
// Pivot is the SQL Server / Oracle PIVOT clause for row-to-column transformation.
// Example: SELECT * FROM t PIVOT (SUM(sales) FOR region IN ([North], [South])) AS pvt
Pivot *PivotClause
// Unpivot is the SQL Server / Oracle UNPIVOT clause for column-to-row transformation.
// Example: SELECT * FROM t UNPIVOT (sales FOR region IN (north_sales, south_sales)) AS unpvt
Unpivot *UnpivotClause
// MatchRecognize is the SQL:2016 row-pattern recognition clause (Snowflake, Oracle).
MatchRecognize *MatchRecognizeClause
}
func (t *TableReference) statementNode() {}
func (t TableReference) TokenLiteral() string {
if t.Name != "" {
return t.Name
}
if t.Alias != "" {
return t.Alias
}
return "subquery"
}
func (t TableReference) Children() []Node {
var nodes []Node
if t.Subquery != nil {
nodes = append(nodes, t.Subquery)
}
if t.TableFunc != nil {
nodes = append(nodes, t.TableFunc)
}
if t.TimeTravel != nil {
nodes = append(nodes, t.TimeTravel)
}
if t.Pivot != nil {
nodes = append(nodes, t.Pivot)
}
if t.Unpivot != nil {
nodes = append(nodes, t.Unpivot)
}
if t.MatchRecognize != nil {
nodes = append(nodes, t.MatchRecognize)
}
return nodes
}
// OrderByExpression represents an ORDER BY clause element with direction and NULL ordering
type OrderByExpression struct {
Expression Expression // The expression to order by
Ascending bool // true for ASC (default), false for DESC
NullsFirst *bool // nil = default behavior, true = NULLS FIRST, false = NULLS LAST
}
func (*OrderByExpression) expressionNode() {}
func (o *OrderByExpression) TokenLiteral() string { return "ORDER BY" }
func (o *OrderByExpression) Children() []Node {
if o.Expression != nil {
return []Node{o.Expression}
}
return nil
}
// WindowSpec represents a window specification
type WindowSpec struct {
Name string
PartitionBy []Expression
OrderBy []OrderByExpression
FrameClause *WindowFrame
}
func (w *WindowSpec) statementNode() {}
func (w WindowSpec) TokenLiteral() string { return "WINDOW" }
func (w WindowSpec) Children() []Node {
children := make([]Node, 0)
children = append(children, nodifyExpressions(w.PartitionBy)...)
for _, orderBy := range w.OrderBy {
orderBy := orderBy // G601: Create local copy to avoid memory aliasing
children = append(children, &orderBy)
}
if w.FrameClause != nil {
children = append(children, w.FrameClause)
}
return children
}
// WindowFrame represents window frame clause
type WindowFrame struct {
Type string // ROWS, RANGE
Start WindowFrameBound
End *WindowFrameBound
}
func (w *WindowFrame) statementNode() {}
func (w WindowFrame) TokenLiteral() string { return w.Type }
func (w WindowFrame) Children() []Node { return nil }
// WindowFrameBound represents window frame bound
type WindowFrameBound struct {
Type string // CURRENT ROW, UNBOUNDED PRECEDING, etc.
Value Expression
}
func (w *WindowFrameBound) expressionNode() {}
func (w WindowFrameBound) TokenLiteral() string {
if w.Type != "" {
return w.Type
}
return "BOUND"
}
func (w WindowFrameBound) Children() []Node {
if w.Value != nil {
return []Node{w.Value}
}
return nil
}
// SelectStatement represents a SELECT SQL statement with full SQL-99/SQL:2003 support.
//
// SelectStatement is the primary query statement type supporting:
// - CTEs (WITH clause)
// - DISTINCT and DISTINCT ON (PostgreSQL)
// - Multiple FROM tables and subqueries
// - All JOIN types with LATERAL support
// - WHERE, GROUP BY, HAVING, ORDER BY clauses
// - Window functions with PARTITION BY and frame specifications
// - LIMIT/OFFSET and SQL-99 FETCH clause
//
// Fields:
// - With: WITH clause for Common Table Expressions (CTEs)
// - Distinct: DISTINCT keyword for duplicate elimination
// - DistinctOnColumns: DISTINCT ON (expr, ...) for PostgreSQL (v1.6.0)
// - Columns: SELECT list expressions (columns, *, functions, etc.)
// - From: FROM clause table references (tables, subqueries, LATERAL)
// - TableName: Table name for simple queries (pool optimization)
// - Joins: JOIN clauses (INNER, LEFT, RIGHT, FULL, CROSS, NATURAL)
// - Where: WHERE clause filter condition
// - GroupBy: GROUP BY expressions (including ROLLUP, CUBE, GROUPING SETS)
// - Having: HAVING clause filter condition
// - Windows: Window specifications (WINDOW clause)
// - OrderBy: ORDER BY expressions with NULLS FIRST/LAST
// - Limit: LIMIT clause (number of rows)
// - Offset: OFFSET clause (skip rows)
// - Fetch: SQL-99 FETCH FIRST/NEXT clause (v1.6.0)
//
// Example - Basic SELECT:
//
// SelectStatement{
// Columns: []Expression{&Identifier{Name: "id"}, &Identifier{Name: "name"}},
// From: []TableReference{{Name: "users"}},
// Where: &BinaryExpression{...},
// }
// // SQL: SELECT id, name FROM users WHERE ...
//
// Example - DISTINCT ON (PostgreSQL v1.6.0):
//
// SelectStatement{
// DistinctOnColumns: []Expression{&Identifier{Name: "dept_id"}},
// Columns: []Expression{&Identifier{Name: "dept_id"}, &Identifier{Name: "name"}},
// From: []TableReference{{Name: "employees"}},
// }
// // SQL: SELECT DISTINCT ON (dept_id) dept_id, name FROM employees
//
// Example - Window function with FETCH (v1.6.0):
//
// SelectStatement{
// Columns: []Expression{
// &FunctionCall{
// Name: "ROW_NUMBER",
// Over: &WindowSpec{
// OrderBy: []OrderByExpression{{Expression: &Identifier{Name: "salary"}, Ascending: false}},
// },
// },
// },
// From: []TableReference{{Name: "employees"}},
// Fetch: &FetchClause{FetchValue: ptrInt64(10), FetchType: "FIRST"},
// }
// // SQL: SELECT ROW_NUMBER() OVER (ORDER BY salary DESC) FROM employees FETCH FIRST 10 ROWS ONLY
//
// New in v1.6.0:
// - DistinctOnColumns for PostgreSQL DISTINCT ON
// - Fetch for SQL-99 FETCH FIRST/NEXT clause
// - Enhanced LATERAL JOIN support via TableReference.Lateral
// - FILTER clause support via FunctionCall.Filter
type SelectStatement struct {
With *WithClause
Distinct bool
DistinctOnColumns []Expression // PostgreSQL DISTINCT ON (expr, ...) clause
Top *TopClause // SQL Server TOP N [PERCENT] clause
Columns []Expression
From []TableReference
TableName string // Added for pool operations
Joins []JoinClause
ArrayJoin *ArrayJoinClause // ClickHouse ARRAY JOIN / LEFT ARRAY JOIN clause
PrewhereClause Expression // ClickHouse PREWHERE clause (applied before WHERE, before reading data)
Sample *SampleClause // ClickHouse SAMPLE clause (comes after FROM/FINAL, before PREWHERE)
Where Expression
GroupBy []Expression
Having Expression
Qualify Expression // Snowflake / BigQuery QUALIFY clause (filters after window functions)
// StartWith is the optional seed condition for CONNECT BY (MariaDB 10.2+).
// Example: START WITH parent_id IS NULL
StartWith Expression // MariaDB hierarchical query seed
// ConnectBy holds the hierarchy traversal condition (MariaDB 10.2+).
// Example: CONNECT BY PRIOR id = parent_id
ConnectBy *ConnectByClause // MariaDB hierarchical query
Windows []WindowSpec
OrderBy []OrderByExpression
Limit *int
Offset *int
Fetch *FetchClause // SQL-99 FETCH FIRST/NEXT clause (F861, F862)
For *ForClause // Row-level locking clause (SQL:2003, PostgreSQL, MySQL)
Pos models.Location // Source position of the SELECT keyword (1-based line and column)
}
// TopClause represents SQL Server's TOP N [PERCENT] clause
// Syntax: SELECT TOP n [PERCENT] columns...
// Count is an Expression to support TOP (10), TOP (@var), TOP (subquery)
type TopClause struct {
Count Expression // Number of rows (or percentage) as an expression
IsPercent bool // Whether PERCENT keyword was specified
WithTies bool // Whether WITH TIES was specified (SQL Server)
}
func (t *TopClause) expressionNode() {}
func (t TopClause) TokenLiteral() string { return "TOP" }
func (t TopClause) Children() []Node {
if t.Count != nil {
return []Node{t.Count}
}
return nil
}
// FetchClause represents the SQL-99 FETCH FIRST/NEXT clause (F861, F862)
// Syntax: [OFFSET n {ROW | ROWS}] FETCH {FIRST | NEXT} n [{ROW | ROWS}] {ONLY | WITH TIES}
// Examples:
// - OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY
// - FETCH FIRST 5 ROWS ONLY
// - FETCH FIRST 10 PERCENT ROWS WITH TIES
type FetchClause struct {
// OffsetValue is the number of rows to skip (OFFSET n ROWS)
OffsetValue *int64
// FetchValue is the number of rows to fetch (FETCH n ROWS)
FetchValue *int64
// FetchType is either "FIRST" or "NEXT"
FetchType string
// IsPercent indicates FETCH ... PERCENT ROWS
IsPercent bool
// WithTies indicates FETCH ... WITH TIES (includes tied rows)
WithTies bool
}
func (f *FetchClause) expressionNode() {}
func (f FetchClause) TokenLiteral() string { return "FETCH" }
func (f FetchClause) Children() []Node { return nil }
// ForClause represents row-level locking clauses in SELECT statements (SQL:2003, PostgreSQL, MySQL)
// Syntax: FOR {UPDATE | SHARE | NO KEY UPDATE | KEY SHARE} [OF table_name [, ...]] [NOWAIT | SKIP LOCKED]
// Examples:
// - FOR UPDATE
// - FOR SHARE NOWAIT
// - FOR UPDATE OF orders SKIP LOCKED
// - FOR NO KEY UPDATE
// - FOR KEY SHARE
type ForClause struct {
// LockType specifies the type of lock:
// "UPDATE" - exclusive lock for UPDATE operations
// "SHARE" - shared lock for read operations
// "NO KEY UPDATE" - PostgreSQL: exclusive lock that doesn't block SHARE locks on same row
// "KEY SHARE" - PostgreSQL: shared lock that doesn't block UPDATE locks
LockType string
// Tables specifies which tables to lock (FOR UPDATE OF table_name)
// Empty slice means lock all tables in the query
Tables []string
// NoWait indicates NOWAIT option (fail immediately if lock cannot be acquired)
NoWait bool
// SkipLocked indicates SKIP LOCKED option (skip rows that can't be locked)
SkipLocked bool
}
func (f *ForClause) expressionNode() {}
func (f ForClause) TokenLiteral() string { return "FOR" }
func (f ForClause) Children() []Node { return nil }
func (s *SelectStatement) statementNode() {}
func (s *SelectStatement) queryExpressionNode() {}
func (s SelectStatement) TokenLiteral() string { return "SELECT" }
func (s SelectStatement) Children() []Node {
children := make([]Node, 0)
if s.With != nil {
children = append(children, s.With)
}
children = append(children, nodifyExpressions(s.DistinctOnColumns)...)
children = append(children, nodifyExpressions(s.Columns)...)
for _, from := range s.From {
from := from // G601: Create local copy to avoid memory aliasing
children = append(children, &from)
}
for _, join := range s.Joins {
join := join // G601: Create local copy to avoid memory aliasing
children = append(children, &join)
}
if s.PrewhereClause != nil {
children = append(children, s.PrewhereClause)
}
if s.Where != nil {
children = append(children, s.Where)
}
children = append(children, nodifyExpressions(s.GroupBy)...)
if s.Having != nil {
children = append(children, s.Having)
}
if s.Qualify != nil {
children = append(children, s.Qualify)
}
for _, window := range s.Windows {
window := window // G601: Create local copy to avoid memory aliasing
children = append(children, &window)
}
for _, orderBy := range s.OrderBy {
orderBy := orderBy // G601: Create local copy to avoid memory aliasing
children = append(children, &orderBy)
}
if s.Fetch != nil {
children = append(children, s.Fetch)
}
if s.For != nil {
children = append(children, s.For)
}
if s.StartWith != nil {
children = append(children, s.StartWith)
}
if s.ConnectBy != nil {
children = append(children, s.ConnectBy)
}
return children
}
// Helper function to convert []Expression to []Node
func nodifyExpressions(exprs []Expression) []Node {
nodes := make([]Node, len(exprs))
for i, expr := range exprs {
nodes[i] = expr
}
return nodes
}
// RollupExpression represents ROLLUP(col1, col2, ...) in GROUP BY clause
// ROLLUP generates hierarchical grouping sets from right to left
// Example: ROLLUP(a, b, c) generates grouping sets:
//
// (a, b, c), (a, b), (a), ()
type RollupExpression struct {
Expressions []Expression
}
func (r *RollupExpression) expressionNode() {}
func (r RollupExpression) TokenLiteral() string { return "ROLLUP" }
func (r RollupExpression) Children() []Node { return nodifyExpressions(r.Expressions) }
// CubeExpression represents CUBE(col1, col2, ...) in GROUP BY clause
// CUBE generates all possible combinations of grouping sets
// Example: CUBE(a, b) generates grouping sets:
//
// (a, b), (a), (b), ()
type CubeExpression struct {
Expressions []Expression
}
func (c *CubeExpression) expressionNode() {}
func (c CubeExpression) TokenLiteral() string { return "CUBE" }
func (c CubeExpression) Children() []Node { return nodifyExpressions(c.Expressions) }
// GroupingSetsExpression represents GROUPING SETS(...) in GROUP BY clause
// Allows explicit specification of grouping sets
// Example: GROUPING SETS((a, b), (a), ())
type GroupingSetsExpression struct {
Sets [][]Expression // Each inner slice is one grouping set
}
func (g *GroupingSetsExpression) expressionNode() {}
func (g GroupingSetsExpression) TokenLiteral() string { return "GROUPING SETS" }
func (g GroupingSetsExpression) Children() []Node {
children := make([]Node, 0)
for _, set := range g.Sets {
children = append(children, nodifyExpressions(set)...)
}
return children
}
// Identifier represents a column or table name
type Identifier struct {
Name string
Table string // Optional table qualifier
Pos models.Location // Source position of this identifier (1-based line and column)
}
func (i *Identifier) expressionNode() {}
func (i Identifier) TokenLiteral() string { return i.Name }
func (i Identifier) Children() []Node { return nil }
// FunctionCall represents a function call expression with full SQL-99/PostgreSQL support.
//
// FunctionCall supports:
// - Scalar functions: UPPER(), LOWER(), COALESCE(), etc.
// - Aggregate functions: COUNT(), SUM(), AVG(), MAX(), MIN(), etc.
// - Window functions: ROW_NUMBER(), RANK(), DENSE_RANK(), LAG(), LEAD(), etc.
// - DISTINCT modifier: COUNT(DISTINCT column)
// - FILTER clause: Conditional aggregation (PostgreSQL v1.6.0)
// - ORDER BY clause: For order-sensitive aggregates like STRING_AGG, ARRAY_AGG (v1.6.0)
// - OVER clause: Window specifications for window functions
//
// Fields:
// - Name: Function name (e.g., "COUNT", "SUM", "ROW_NUMBER")
// - Arguments: Function arguments (expressions)
// - Over: Window specification for window functions (OVER clause)
// - Distinct: DISTINCT modifier for aggregates (COUNT(DISTINCT col))
// - Filter: FILTER clause for conditional aggregation (PostgreSQL v1.6.0)
// - OrderBy: ORDER BY clause for order-sensitive aggregates (v1.6.0)
//
// Example - Basic aggregate:
//
// FunctionCall{
// Name: "COUNT",
// Arguments: []Expression{&Identifier{Name: "id"}},
// }
// // SQL: COUNT(id)
//
// Example - Window function:
//
// FunctionCall{
// Name: "ROW_NUMBER",
// Over: &WindowSpec{
// PartitionBy: []Expression{&Identifier{Name: "dept_id"}},
// OrderBy: []OrderByExpression{{Expression: &Identifier{Name: "salary"}, Ascending: false}},
// },
// }
// // SQL: ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY salary DESC)
//
// Example - FILTER clause (PostgreSQL v1.6.0):
//
// FunctionCall{
// Name: "COUNT",
// Arguments: []Expression{&Identifier{Name: "id"}},
// Filter: &BinaryExpression{Left: &Identifier{Name: "status"}, Operator: "=", Right: &LiteralValue{Value: "active"}},
// }
// // SQL: COUNT(id) FILTER (WHERE status = 'active')
//
// Example - ORDER BY in aggregate (PostgreSQL v1.6.0):
//
// FunctionCall{
// Name: "STRING_AGG",
// Arguments: []Expression{&Identifier{Name: "name"}, &LiteralValue{Value: ", "}},
// OrderBy: []OrderByExpression{{Expression: &Identifier{Name: "name"}, Ascending: true}},
// }
// // SQL: STRING_AGG(name, ', ' ORDER BY name)
//
// Example - Window function with frame:
//
// FunctionCall{
// Name: "AVG",
// Arguments: []Expression{&Identifier{Name: "amount"}},
// Over: &WindowSpec{
// OrderBy: []OrderByExpression{{Expression: &Identifier{Name: "date"}, Ascending: true}},
// FrameClause: &WindowFrame{
// Type: "ROWS",
// Start: WindowFrameBound{Type: "2 PRECEDING"},
// End: &WindowFrameBound{Type: "CURRENT ROW"},
// },
// },
// }
// // SQL: AVG(amount) OVER (ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
//
// New in v1.6.0:
// - Filter: FILTER clause for conditional aggregation
// - OrderBy: ORDER BY clause for order-sensitive aggregates (STRING_AGG, ARRAY_AGG, etc.)
// - WithinGroup: ORDER BY clause for ordered-set aggregates (PERCENTILE_CONT, PERCENTILE_DISC, MODE, etc.)
type FunctionCall struct {
Name string
Arguments []Expression // Renamed from Args for consistency
Parameters []Expression // ClickHouse parametric aggregates: quantile(0.5)(x) — params before args
Over *WindowSpec // For window functions
Distinct bool
Filter Expression // WHERE clause for aggregate functions
OrderBy []OrderByExpression // ORDER BY clause for aggregate functions (STRING_AGG, ARRAY_AGG, etc.)
WithinGroup []OrderByExpression // ORDER BY clause for ordered-set aggregates (PERCENTILE_CONT, etc.)
NullTreatment string // "IGNORE NULLS" or "RESPECT NULLS" on window functions (Snowflake, Oracle, BigQuery, SQL:2016)
Pos models.Location // Source position of the function name (1-based line and column)
}
func (f *FunctionCall) expressionNode() {}
func (f FunctionCall) TokenLiteral() string { return f.Name }
func (f FunctionCall) Children() []Node {
children := nodifyExpressions(f.Arguments)
if len(f.Parameters) > 0 {
children = append(children, nodifyExpressions(f.Parameters)...)
}
if f.Over != nil {
children = append(children, f.Over)
}
if f.Filter != nil {
children = append(children, f.Filter)
}
for _, orderBy := range f.OrderBy {
orderBy := orderBy // G601: Create local copy to avoid memory aliasing
children = append(children, &orderBy)
}
for _, orderBy := range f.WithinGroup {
orderBy := orderBy // G601: Create local copy to avoid memory aliasing
children = append(children, &orderBy)
}
return children
}
// CaseExpression represents a CASE expression
type CaseExpression struct {
Value Expression // Optional CASE value
WhenClauses []WhenClause
ElseClause Expression
Pos models.Location // Source position of the CASE keyword (1-based line and column)
}
func (c *CaseExpression) expressionNode() {}
func (c CaseExpression) TokenLiteral() string { return "CASE" }
func (c CaseExpression) Children() []Node {
children := make([]Node, 0)
if c.Value != nil {
children = append(children, c.Value)
}
for _, when := range c.WhenClauses {
when := when // G601: Create local copy to avoid memory aliasing
children = append(children, &when)
}
if c.ElseClause != nil {
children = append(children, c.ElseClause)
}
return children
}
// WhenClause represents WHEN ... THEN ... in CASE expression
type WhenClause struct {
Condition Expression
Result Expression
Pos models.Location // Source position of the WHEN keyword (1-based line and column)
}
func (w *WhenClause) expressionNode() {}
func (w WhenClause) TokenLiteral() string { return "WHEN" }
func (w WhenClause) Children() []Node {
return []Node{w.Condition, w.Result}
}
// ExistsExpression represents EXISTS (subquery)
type ExistsExpression struct {
Subquery Statement
}
func (e *ExistsExpression) expressionNode() {}
func (e ExistsExpression) TokenLiteral() string { return "EXISTS" }
func (e ExistsExpression) Children() []Node {
return []Node{e.Subquery}
}
// InExpression represents expr IN (values) or expr IN (subquery)
type InExpression struct {
Expr Expression
List []Expression // For value list: IN (1, 2, 3)
Subquery Statement // For subquery: IN (SELECT ...)
Not bool
Pos models.Location // Source position of the IN keyword (1-based line and column)
}
func (i *InExpression) expressionNode() {}
func (i InExpression) TokenLiteral() string { return "IN" }
func (i InExpression) Children() []Node {
children := []Node{i.Expr}
if i.Subquery != nil {
children = append(children, i.Subquery)
} else {
children = append(children, nodifyExpressions(i.List)...)
}
return children
}
// SubqueryExpression represents a scalar subquery (SELECT ...)
type SubqueryExpression struct {
Subquery Statement
Pos models.Location // Source position of the opening parenthesis (1-based line and column)
}
func (s *SubqueryExpression) expressionNode() {}
func (s SubqueryExpression) TokenLiteral() string { return "SUBQUERY" }
func (s SubqueryExpression) Children() []Node { return []Node{s.Subquery} }
// AnyExpression represents expr op ANY (subquery)
type AnyExpression struct {
Expr Expression
Operator string
Subquery Statement
}
func (a *AnyExpression) expressionNode() {}
func (a AnyExpression) TokenLiteral() string { return "ANY" }
func (a AnyExpression) Children() []Node { return []Node{a.Expr, a.Subquery} }
// AllExpression represents expr op ALL (subquery)
type AllExpression struct {
Expr Expression
Operator string
Subquery Statement
}
func (al *AllExpression) expressionNode() {}
func (al AllExpression) TokenLiteral() string { return "ALL" }
func (al AllExpression) Children() []Node { return []Node{al.Expr, al.Subquery} }
// BetweenExpression represents expr BETWEEN lower AND upper
type BetweenExpression struct {
Expr Expression
Lower Expression
Upper Expression
Not bool
Pos models.Location // Source position of the BETWEEN keyword (1-based line and column)
}
func (b *BetweenExpression) expressionNode() {}
func (b BetweenExpression) TokenLiteral() string { return "BETWEEN" }
func (b BetweenExpression) Children() []Node {
return []Node{b.Expr, b.Lower, b.Upper}
}
// BinaryExpression represents binary operations between two expressions.
//
// BinaryExpression supports all standard SQL binary operators plus PostgreSQL-specific
// operators including JSON/JSONB operators added in v1.6.0.
//
// Fields:
// - Left: Left-hand side expression
// - Operator: Binary operator (=, <, >, +, -, *, /, AND, OR, ->, #>, etc.)
// - Right: Right-hand side expression
// - Not: NOT modifier for negation (NOT expr)
// - CustomOp: PostgreSQL custom operators (OPERATOR(schema.name))
//
// Supported Operator Categories:
// - Comparison: =, <>, <, >, <=, >=, <=> (spaceship)
// - Arithmetic: +, -, *, /, %, DIV, // (integer division)
// - Logical: AND, OR, XOR
// - String: || (concatenation)
// - Bitwise: &, |, ^, <<, >> (shifts)
// - Pattern: LIKE, ILIKE, SIMILAR TO
// - Range: OVERLAPS
// - PostgreSQL JSON/JSONB (v1.6.0): ->, ->>, #>, #>>, @>, <@, ?, ?|, ?&, #-
//
// Example - Basic comparison:
//
// BinaryExpression{
// Left: &Identifier{Name: "age"},
// Operator: ">",
// Right: &LiteralValue{Value: 18, Type: "INTEGER"},
// }
// // SQL: age > 18
//
// Example - Logical AND:
//
// BinaryExpression{
// Left: &BinaryExpression{
// Left: &Identifier{Name: "active"},
// Operator: "=",
// Right: &LiteralValue{Value: true, Type: "BOOLEAN"},
// },
// Operator: "AND",
// Right: &BinaryExpression{
// Left: &Identifier{Name: "status"},
// Operator: "=",
// Right: &LiteralValue{Value: "pending", Type: "STRING"},
// },
// }
// // SQL: active = true AND status = 'pending'
//
// Example - PostgreSQL JSON operator -> (v1.6.0):
//
// BinaryExpression{
// Left: &Identifier{Name: "data"},
// Operator: "->",
// Right: &LiteralValue{Value: "name", Type: "STRING"},
// }
// // SQL: data->'name'
//
// Example - PostgreSQL JSON operator ->> (v1.6.0):
//
// BinaryExpression{
// Left: &Identifier{Name: "data"},
// Operator: "->>",
// Right: &LiteralValue{Value: "email", Type: "STRING"},
// }
// // SQL: data->>'email' (returns text)
//
// Example - PostgreSQL JSON contains @> (v1.6.0):
//
// BinaryExpression{
// Left: &Identifier{Name: "attributes"},
// Operator: "@>",
// Right: &LiteralValue{Value: `{"color": "red"}`, Type: "STRING"},
// }
// // SQL: attributes @> '{"color": "red"}'
//
// Example - PostgreSQL JSON key exists ? (v1.6.0):
//
// BinaryExpression{
// Left: &Identifier{Name: "profile"},
// Operator: "?",
// Right: &LiteralValue{Value: "email", Type: "STRING"},
// }
// // SQL: profile ? 'email'
//
// Example - Custom PostgreSQL operator:
//
// BinaryExpression{
// Left: &Identifier{Name: "point1"},
// Operator: "",
// Right: &Identifier{Name: "point2"},
// CustomOp: &CustomBinaryOperator{Parts: []string{"pg_catalog", "<->"}},
// }
// // SQL: point1 OPERATOR(pg_catalog.<->) point2
//
// New in v1.6.0:
// - JSON/JSONB operators: ->, ->>, #>, #>>, @>, <@, ?, ?|, ?&, #-
// - CustomOp field for PostgreSQL custom operators
//
// PostgreSQL JSON/JSONB Operator Reference:
// - -> (Arrow): Extract JSON field or array element (returns JSON)
// - ->> (LongArrow): Extract JSON field or array element as text
// - #> (HashArrow): Extract JSON at path (returns JSON)
// - #>> (HashLongArrow): Extract JSON at path as text
// - @> (AtArrow): JSON contains (does left JSON contain right?)
// - <@ (ArrowAt): JSON is contained by (is left JSON contained in right?)
// - ? (Question): JSON key exists
// - ?| (QuestionPipe): Any of the keys exist
// - ?& (QuestionAnd): All of the keys exist
// - #- (HashMinus): Delete key from JSON
type BinaryExpression struct {
Left Expression
Operator string
Right Expression
Not bool // For NOT (expr)
CustomOp *CustomBinaryOperator // For PostgreSQL custom operators
Pos models.Location // Source position of the operator (1-based line and column)
}
func (b *BinaryExpression) expressionNode() {}
func (b *BinaryExpression) TokenLiteral() string {
if b.CustomOp != nil {
return b.CustomOp.String()
}
return b.Operator
}
func (b BinaryExpression) Children() []Node { return []Node{b.Left, b.Right} }