-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathsql.go
More file actions
1853 lines (1707 loc) · 44.7 KB
/
sql.go
File metadata and controls
1853 lines (1707 loc) · 44.7 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.
// This file implements SQL() string methods on all AST node types,
// enabling AST→SQL roundtrip serialization.
package ast
import (
"fmt"
"strings"
"sync"
"unicode"
)
// builderPool reuses strings.Builder instances for SQL serialization,
// following the project's existing pooling patterns (sync.Pool for tokenizer
// buffers, token objects, etc.) to reduce allocations in hot paths.
var builderPool = sync.Pool{
New: func() interface{} {
return &strings.Builder{}
},
}
// getBuilder retrieves a strings.Builder from the pool, ready for use.
// Always pair with putBuilder to return it.
func getBuilder() *strings.Builder {
sb := builderPool.Get().(*strings.Builder)
sb.Reset()
return sb
}
// putBuilder returns a strings.Builder to the pool.
func putBuilder(sb *strings.Builder) {
if sb == nil {
return
}
// Don't pool very large builders to avoid holding excess memory.
if sb.Cap() > 64*1024 {
return
}
builderPool.Put(sb)
}
// SQL returns the SQL string representation of the AST.
func (a AST) SQL() string {
parts := make([]string, 0, len(a.Statements))
for _, stmt := range a.Statements {
if s, ok := stmt.(interface{ SQL() string }); ok {
parts = append(parts, s.SQL())
}
}
return strings.Join(parts, ";\n")
}
// ============================================================
// Expressions
// ============================================================
// SQL returns the SQL representation of the identifier.
// Identifiers are emitted unescaped because they have already been validated
// during parsing - the tokenizer and parser only accept syntactically valid
// identifiers (or quoted identifiers whose quotes are preserved in the AST).
// Re-escaping here would be redundant and could introduce double-quoting bugs.
func (i *Identifier) SQL() string {
if i == nil {
return ""
}
if i.Table != "" {
return safeIdentifier(i.Table) + "." + safeIdentifier(i.Name)
}
return safeIdentifier(i.Name)
}
// safeIdentifier returns the identifier unchanged if it contains only safe
// characters (letters, digits, underscores, dots, *). Otherwise it double-
// quotes it with proper escaping to prevent SQL identifier injection.
func safeIdentifier(name string) string {
if name == "" {
return `""`
}
for _, r := range name {
if r != '_' && r != '*' && r != '.' && !unicode.IsLetter(r) && !unicode.IsDigit(r) {
return `"` + strings.ReplaceAll(name, `"`, `""`) + `"`
}
}
return name
}
// escapeStringLiteral escapes a string for safe inclusion in a single-quoted
// SQL literal, handling characters that can lead to SQL injection.
func escapeStringLiteral(s string) string {
var b strings.Builder
b.Grow(len(s))
for _, r := range s {
switch r {
case '\'':
b.WriteString("''")
case '\\':
b.WriteString(`\\`)
case '\x00':
// Drop null bytes - invalid in SQL string literals.
case '\n':
b.WriteString(`\n`)
case '\r':
b.WriteString(`\r`)
case '\x1a': // Ctrl-Z (EOF on Windows)
b.WriteString(`\Z`)
default:
b.WriteRune(r)
}
}
return b.String()
}
// SQL returns the SQL literal representation of this value.
// Strings are single-quoted with proper escaping; NULLs are returned as "NULL";
// booleans are returned in uppercase (TRUE/FALSE); numbers are returned as-is.
func (l *LiteralValue) SQL() string {
if l == nil {
return ""
}
if l.Value == nil || strings.EqualFold(l.Type, "NULL") {
return "NULL"
}
switch strings.ToUpper(l.Type) {
case "STRING":
return "'" + escapeStringLiteral(fmt.Sprintf("%v", l.Value)) + "'"
case "BOOLEAN":
return strings.ToUpper(fmt.Sprintf("%v", l.Value))
default:
return fmt.Sprintf("%v", l.Value)
}
}
// SQL returns the unquoted identifier name. Used for round-trip serialization.
func (i *Ident) SQL() string {
if i == nil {
return ""
}
return i.Name
}
// SQL returns the SQL representation of this binary expression.
// The operator, left, and right sub-expressions are serialized in infix notation.
// NOT-qualified operators (LIKE, ILIKE, SIMILAR TO) are rendered as "x NOT OP y".
func (b *BinaryExpression) SQL() string {
if b == nil {
return ""
}
left := exprSQL(b.Left)
right := exprSQL(b.Right)
op := b.Operator
if b.CustomOp != nil {
op = b.CustomOp.String()
}
upperOp := strings.ToUpper(op)
// Handle IS NULL / IS NOT NULL (right side is NULL literal)
if upperOp == "IS NULL" || upperOp == "IS NOT NULL" {
return fmt.Sprintf("%s %s", left, upperOp)
}
// Handle special operators like LIKE, ILIKE, SIMILAR TO
if b.Not {
switch upperOp {
case "LIKE", "ILIKE", "SIMILAR TO":
return fmt.Sprintf("%s NOT %s %s", left, upperOp, right)
default:
return fmt.Sprintf("NOT (%s %s %s)", left, op, right)
}
}
return fmt.Sprintf("%s %s %s", left, op, right)
}
// SQL returns the SQL representation of this unary expression.
// Prefix operators (NOT, +, -, etc.) are prepended; the PostgreSQL
// postfix factorial operator (!) is appended.
func (u *UnaryExpression) SQL() string {
if u == nil {
return ""
}
inner := exprSQL(u.Expr)
switch u.Operator {
case Not:
return "NOT " + inner
case PGPostfixFactorial:
return inner + "!"
case Plus:
return "+" + inner
case Minus:
return "-" + inner
case Prior:
return "PRIOR " + inner
default:
return u.Operator.String() + inner
}
}
// SQL returns the SQL representation of this aliased expression in the form
// "expr AS alias".
func (a *AliasedExpression) SQL() string {
if a == nil {
return ""
}
return exprSQL(a.Expr) + " AS " + a.Alias
}
// SQL returns the SQL representation of this CAST expression in the form
// "CAST(expr AS type)".
func (c *CastExpression) SQL() string {
if c == nil {
return ""
}
return fmt.Sprintf("CAST(%s AS %s)", exprSQL(c.Expr), c.Type)
}
// SQL returns the SQL representation of this CASE expression including all
// WHEN/THEN clauses and an optional ELSE clause.
func (c *CaseExpression) SQL() string {
if c == nil {
return ""
}
sb := getBuilder()
defer putBuilder(sb)
sb.WriteString("CASE")
if c.Value != nil {
sb.WriteString(" ")
sb.WriteString(exprSQL(c.Value))
}
for _, w := range c.WhenClauses {
sb.WriteString(" WHEN ")
sb.WriteString(exprSQL(w.Condition))
sb.WriteString(" THEN ")
sb.WriteString(exprSQL(w.Result))
}
if c.ElseClause != nil {
sb.WriteString(" ELSE ")
sb.WriteString(exprSQL(c.ElseClause))
}
sb.WriteString(" END")
return sb.String()
}
// SQL returns the SQL representation of this WHEN clause in the form
// "WHEN condition THEN result".
func (w *WhenClause) SQL() string {
if w == nil {
return ""
}
return fmt.Sprintf("WHEN %s THEN %s", exprSQL(w.Condition), exprSQL(w.Result))
}
// SQL returns the SQL representation of this BETWEEN expression.
// The NOT modifier is included when BetweenExpression.Not is true.
func (b *BetweenExpression) SQL() string {
if b == nil {
return ""
}
not := ""
if b.Not {
not = "NOT "
}
return fmt.Sprintf("%s %sBETWEEN %s AND %s", exprSQL(b.Expr), not, exprSQL(b.Lower), exprSQL(b.Upper))
}
// SQL returns the SQL representation of this IN expression.
// The NOT modifier is included when InExpression.Not is true.
// Supports both value lists "x IN (1, 2, 3)" and subqueries "x IN (SELECT ...)".
func (i *InExpression) SQL() string {
if i == nil {
return ""
}
not := ""
if i.Not {
not = "NOT "
}
if i.Subquery != nil {
return fmt.Sprintf("%s %sIN (%s)", exprSQL(i.Expr), not, stmtSQL(i.Subquery))
}
vals := make([]string, len(i.List))
for idx, v := range i.List {
vals[idx] = exprSQL(v)
}
return fmt.Sprintf("%s %sIN (%s)", exprSQL(i.Expr), not, strings.Join(vals, ", "))
}
// SQL returns the SQL representation of this EXISTS expression as "EXISTS (subquery)".
func (e *ExistsExpression) SQL() string {
if e == nil {
return ""
}
return fmt.Sprintf("EXISTS (%s)", stmtSQL(e.Subquery))
}
// SQL returns the SQL representation of this scalar subquery as "(SELECT ...)".
func (s *SubqueryExpression) SQL() string {
if s == nil {
return ""
}
return fmt.Sprintf("(%s)", stmtSQL(s.Subquery))
}
// SQL returns the SQL representation of this ANY expression as "expr op ANY (subquery)".
func (a *AnyExpression) SQL() string {
if a == nil {
return ""
}
return fmt.Sprintf("%s %s ANY (%s)", exprSQL(a.Expr), a.Operator, stmtSQL(a.Subquery))
}
// SQL returns the SQL representation of this ALL expression as "expr op ALL (subquery)".
func (a *AllExpression) SQL() string {
if a == nil {
return ""
}
return fmt.Sprintf("%s %s ALL (%s)", exprSQL(a.Expr), a.Operator, stmtSQL(a.Subquery))
}
// SQL returns the SQL representation of this function call including arguments,
// optional DISTINCT modifier, ORDER BY clause (for aggregates like STRING_AGG),
// WITHIN GROUP (for ordered-set aggregates), FILTER (WHERE ...) clause, and
// OVER (...) window specification.
func (f *FunctionCall) SQL() string {
if f == nil {
return ""
}
sb := getBuilder()
defer putBuilder(sb)
sb.WriteString(f.Name)
sb.WriteString("(")
if f.Distinct {
sb.WriteString("DISTINCT ")
}
args := make([]string, len(f.Arguments))
for i, arg := range f.Arguments {
args[i] = exprSQL(arg)
}
sb.WriteString(strings.Join(args, ", "))
if len(f.OrderBy) > 0 {
sb.WriteString(" ORDER BY ")
sb.WriteString(orderBySQL(f.OrderBy))
}
sb.WriteString(")")
if len(f.WithinGroup) > 0 {
sb.WriteString(" WITHIN GROUP (ORDER BY ")
sb.WriteString(orderBySQL(f.WithinGroup))
sb.WriteString(")")
}
if f.Filter != nil {
sb.WriteString(" FILTER (WHERE ")
sb.WriteString(exprSQL(f.Filter))
sb.WriteString(")")
}
if f.Over != nil {
sb.WriteString(" OVER (")
sb.WriteString(windowSpecSQL(f.Over))
sb.WriteString(")")
}
return sb.String()
}
// SQL returns "EXTRACT(field FROM source)" as a SQL string.
func (e *ExtractExpression) SQL() string {
if e == nil {
return ""
}
return fmt.Sprintf("EXTRACT(%s FROM %s)", e.Field, exprSQL(e.Source))
}
// SQL returns "POSITION(substr IN str)" as a SQL string.
func (p *PositionExpression) SQL() string {
if p == nil {
return ""
}
return fmt.Sprintf("POSITION(%s IN %s)", exprSQL(p.Substr), exprSQL(p.Str))
}
// SQL returns the SQL representation of this SUBSTRING expression.
// With a length: "SUBSTRING(str FROM start FOR length)".
// Without a length: "SUBSTRING(str FROM start)".
func (s *SubstringExpression) SQL() string {
if s == nil {
return ""
}
if s.Length != nil {
return fmt.Sprintf("SUBSTRING(%s FROM %s FOR %s)", exprSQL(s.Str), exprSQL(s.Start), exprSQL(s.Length))
}
return fmt.Sprintf("SUBSTRING(%s FROM %s)", exprSQL(s.Str), exprSQL(s.Start))
}
// SQL returns the SQL representation of this interval as "INTERVAL 'value'".
func (i *IntervalExpression) SQL() string {
if i == nil {
return ""
}
return fmt.Sprintf("INTERVAL '%s'", i.Value)
}
// SQL returns the SQL representation of this list expression as a
// comma-separated parenthesized list: "(v1, v2, v3)".
func (l *ListExpression) SQL() string {
if l == nil {
return ""
}
vals := make([]string, len(l.Values))
for i, v := range l.Values {
vals[i] = exprSQL(v)
}
return strings.Join(vals, ", ")
}
// SQL returns the SQL representation of this tuple expression as a
// parenthesized comma-separated list: "(v1, v2, v3)".
func (t *TupleExpression) SQL() string {
if t == nil {
return ""
}
vals := make([]string, len(t.Expressions))
for i, e := range t.Expressions {
vals[i] = exprSQL(e)
}
return "(" + strings.Join(vals, ", ") + ")"
}
// SQL returns the SQL representation of this ARRAY constructor.
// From a subquery: "ARRAY(SELECT ...)".
// From an element list: "ARRAY[e1, e2, e3]".
func (a *ArrayConstructorExpression) SQL() string {
if a == nil {
return ""
}
if a.Subquery != nil {
return fmt.Sprintf("ARRAY(%s)", stmtSQL(a.Subquery))
}
vals := make([]string, len(a.Elements))
for i, e := range a.Elements {
vals[i] = exprSQL(e)
}
return "ARRAY[" + strings.Join(vals, ", ") + "]"
}
// SQL returns the SQL representation of this array subscript expression,
// e.g. "arr[1]" or "matrix[i][j]" for multi-dimensional subscripts.
func (a *ArraySubscriptExpression) SQL() string {
if a == nil {
return ""
}
s := exprSQL(a.Array)
for _, idx := range a.Indices {
s += "[" + exprSQL(idx) + "]"
}
return s
}
// SQL returns the SQL representation of this array slice expression,
// e.g. "arr[1:3]", "arr[2:]", "arr[:5]", or "arr[:]".
func (a *ArraySliceExpression) SQL() string {
if a == nil {
return ""
}
start := ""
end := ""
if a.Start != nil {
start = exprSQL(a.Start)
}
if a.End != nil {
end = exprSQL(a.End)
}
return fmt.Sprintf("%s[%s:%s]", exprSQL(a.Array), start, end)
}
// GROUP BY advanced expressions
// SQL returns the SQL representation of this ROLLUP expression as
// "ROLLUP(col1, col2, ...)".
func (r *RollupExpression) SQL() string {
if r == nil {
return ""
}
return "ROLLUP(" + exprListSQL(r.Expressions) + ")"
}
// SQL returns the SQL representation of this CUBE expression as
// "CUBE(col1, col2, ...)".
func (c *CubeExpression) SQL() string {
if c == nil {
return ""
}
return "CUBE(" + exprListSQL(c.Expressions) + ")"
}
// SQL returns the SQL representation of this GROUPING SETS expression as
// "GROUPING SETS((a, b), (a), ())".
func (g *GroupingSetsExpression) SQL() string {
if g == nil {
return ""
}
sets := make([]string, len(g.Sets))
for i, set := range g.Sets {
sets[i] = "(" + exprListSQL(set) + ")"
}
return "GROUPING SETS(" + strings.Join(sets, ", ") + ")"
}
// ============================================================
// Statements
// ============================================================
// SQL returns the full SQL string for this SELECT statement, including all
// clauses: WITH, DISTINCT ON/DISTINCT, SELECT list, FROM, JOIN, WHERE,
// GROUP BY, HAVING, WINDOW, ORDER BY, LIMIT, OFFSET, FETCH, and FOR.
// This enables round-trip serialization of parsed queries.
func (s *SelectStatement) SQL() string {
if s == nil {
return ""
}
sb := getBuilder()
defer putBuilder(sb)
if s.With != nil {
sb.WriteString(s.With.SQL())
sb.WriteString(" ")
}
sb.WriteString("SELECT ")
if len(s.DistinctOnColumns) > 0 {
sb.WriteString("DISTINCT ON (")
sb.WriteString(exprListSQL(s.DistinctOnColumns))
sb.WriteString(") ")
} else if s.Distinct {
sb.WriteString("DISTINCT ")
}
sb.WriteString(exprListSQL(s.Columns))
if len(s.From) > 0 {
sb.WriteString(" FROM ")
froms := make([]string, len(s.From))
for i := range s.From {
froms[i] = tableRefSQL(&s.From[i])
}
sb.WriteString(strings.Join(froms, ", "))
}
for _, j := range s.Joins {
j := j // G601: Create local copy to avoid memory aliasing
sb.WriteString(" ")
sb.WriteString(joinSQL(&j))
}
if s.ArrayJoin != nil {
if s.ArrayJoin.Left {
sb.WriteString(" LEFT ARRAY JOIN ")
} else {
sb.WriteString(" ARRAY JOIN ")
}
elems := make([]string, len(s.ArrayJoin.Elements))
for i, e := range s.ArrayJoin.Elements {
elemStr := exprSQL(e.Expr)
if e.Alias != "" {
elemStr += " AS " + e.Alias
}
elems[i] = elemStr
}
sb.WriteString(strings.Join(elems, ", "))
}
if s.PrewhereClause != nil {
sb.WriteString(" PREWHERE ")
sb.WriteString(exprSQL(s.PrewhereClause))
}
if s.Where != nil {
sb.WriteString(" WHERE ")
sb.WriteString(exprSQL(s.Where))
}
if len(s.GroupBy) > 0 {
sb.WriteString(" GROUP BY ")
sb.WriteString(exprListSQL(s.GroupBy))
}
if s.Having != nil {
sb.WriteString(" HAVING ")
sb.WriteString(exprSQL(s.Having))
}
// MariaDB hierarchical query clauses (10.2+): START WITH ... CONNECT BY ...
// These must appear after HAVING and before ORDER BY per MariaDB grammar.
if s.StartWith != nil {
sb.WriteString(" START WITH ")
sb.WriteString(exprSQL(s.StartWith))
}
if s.ConnectBy != nil {
sb.WriteString(" ")
sb.WriteString(s.ConnectBy.ToSQL())
}
if len(s.Windows) > 0 {
sb.WriteString(" WINDOW ")
wins := make([]string, len(s.Windows))
for i := range s.Windows {
wins[i] = s.Windows[i].Name + " AS (" + windowSpecSQL(&s.Windows[i]) + ")"
}
sb.WriteString(strings.Join(wins, ", "))
}
if len(s.OrderBy) > 0 {
sb.WriteString(" ORDER BY ")
sb.WriteString(orderBySQL(s.OrderBy))
}
if s.Limit != nil {
fmt.Fprintf(sb, " LIMIT %d", *s.Limit)
}
if s.Offset != nil {
fmt.Fprintf(sb, " OFFSET %d", *s.Offset)
}
if s.Fetch != nil {
sb.WriteString(fetchSQL(s.Fetch))
}
if s.For != nil {
sb.WriteString(forSQL(s.For))
}
return sb.String()
}
// SQL returns the full SQL string for this INSERT statement, including the
// optional WITH clause, column list, VALUES rows or SELECT subquery, ON CONFLICT
// clause, and RETURNING clause.
func (i *InsertStatement) SQL() string {
if i == nil {
return ""
}
sb := getBuilder()
defer putBuilder(sb)
if i.With != nil {
sb.WriteString(i.With.SQL())
sb.WriteString(" ")
}
sb.WriteString("INSERT INTO ")
sb.WriteString(i.TableName)
if len(i.Columns) > 0 {
sb.WriteString(" (")
sb.WriteString(exprListSQL(i.Columns))
sb.WriteString(")")
}
if i.Query != nil {
sb.WriteString(" ")
sb.WriteString(stmtSQL(i.Query))
} else if len(i.Values) > 0 {
sb.WriteString(" VALUES ")
rows := make([]string, len(i.Values))
for idx, row := range i.Values {
vals := make([]string, len(row))
for j, v := range row {
vals[j] = exprSQL(v)
}
rows[idx] = "(" + strings.Join(vals, ", ") + ")"
}
sb.WriteString(strings.Join(rows, ", "))
}
if i.OnConflict != nil {
sb.WriteString(onConflictSQL(i.OnConflict))
}
if len(i.Returning) > 0 {
sb.WriteString(" RETURNING ")
sb.WriteString(exprListSQL(i.Returning))
}
return sb.String()
}
// SQL returns the full SQL string for this UPDATE statement, including the
// optional WITH clause, SET assignments, FROM clause, WHERE condition, and
// RETURNING clause.
func (u *UpdateStatement) SQL() string {
if u == nil {
return ""
}
sb := getBuilder()
defer putBuilder(sb)
if u.With != nil {
sb.WriteString(u.With.SQL())
sb.WriteString(" ")
}
sb.WriteString("UPDATE ")
sb.WriteString(u.TableName)
if u.Alias != "" {
sb.WriteString(" ")
sb.WriteString(u.Alias)
}
sb.WriteString(" SET ")
updates := u.Assignments
upds := make([]string, len(updates))
for i, upd := range updates {
upds[i] = exprSQL(upd.Column) + " = " + exprSQL(upd.Value)
}
sb.WriteString(strings.Join(upds, ", "))
if len(u.From) > 0 {
sb.WriteString(" FROM ")
froms := make([]string, len(u.From))
for i := range u.From {
froms[i] = tableRefSQL(&u.From[i])
}
sb.WriteString(strings.Join(froms, ", "))
}
if u.Where != nil {
sb.WriteString(" WHERE ")
sb.WriteString(exprSQL(u.Where))
}
if len(u.Returning) > 0 {
sb.WriteString(" RETURNING ")
sb.WriteString(exprListSQL(u.Returning))
}
return sb.String()
}
// SQL returns the full SQL string for this DELETE statement, including the
// optional WITH clause, USING clause, WHERE condition, and RETURNING clause.
func (d *DeleteStatement) SQL() string {
if d == nil {
return ""
}
sb := getBuilder()
defer putBuilder(sb)
if d.With != nil {
sb.WriteString(d.With.SQL())
sb.WriteString(" ")
}
sb.WriteString("DELETE FROM ")
sb.WriteString(d.TableName)
if d.Alias != "" {
sb.WriteString(" ")
sb.WriteString(d.Alias)
}
if len(d.Using) > 0 {
sb.WriteString(" USING ")
usings := make([]string, len(d.Using))
for i := range d.Using {
usings[i] = tableRefSQL(&d.Using[i])
}
sb.WriteString(strings.Join(usings, ", "))
}
if d.Where != nil {
sb.WriteString(" WHERE ")
sb.WriteString(exprSQL(d.Where))
}
if len(d.Returning) > 0 {
sb.WriteString(" RETURNING ")
sb.WriteString(exprListSQL(d.Returning))
}
return sb.String()
}
// SQL returns the full SQL string for this CREATE TABLE statement including
// column definitions, table constraints, INHERITS, PARTITION BY, and table options.
func (c *CreateTableStatement) SQL() string {
if c == nil {
return ""
}
sb := getBuilder()
defer putBuilder(sb)
sb.WriteString("CREATE ")
if c.Temporary {
sb.WriteString("TEMPORARY ")
}
sb.WriteString("TABLE ")
if c.IfNotExists {
sb.WriteString("IF NOT EXISTS ")
}
sb.WriteString(c.Name)
sb.WriteString(" (")
parts := make([]string, 0, len(c.Columns)+len(c.Constraints))
for _, col := range c.Columns {
col := col // G601: Create local copy to avoid memory aliasing
parts = append(parts, columnDefSQL(&col))
}
for _, con := range c.Constraints {
con := con // G601: Create local copy to avoid memory aliasing
parts = append(parts, tableConstraintSQL(&con))
}
sb.WriteString(strings.Join(parts, ", "))
sb.WriteString(")")
if len(c.Inherits) > 0 {
sb.WriteString(" INHERITS (")
sb.WriteString(strings.Join(c.Inherits, ", "))
sb.WriteString(")")
}
if c.PartitionBy != nil {
fmt.Fprintf(sb, " PARTITION BY %s (%s)", c.PartitionBy.Type, strings.Join(c.PartitionBy.Columns, ", "))
}
for _, opt := range c.Options {
fmt.Fprintf(sb, " %s=%s", opt.Name, opt.Value)
}
return sb.String()
}
// SQL returns the full SQL string for this CREATE INDEX statement including
// the UNIQUE modifier, IF NOT EXISTS, USING method, column list, and WHERE predicate.
func (c *CreateIndexStatement) SQL() string {
if c == nil {
return ""
}
sb := getBuilder()
defer putBuilder(sb)
sb.WriteString("CREATE ")
if c.Unique {
sb.WriteString("UNIQUE ")
}
sb.WriteString("INDEX ")
if c.IfNotExists {
sb.WriteString("IF NOT EXISTS ")
}
sb.WriteString(c.Name)
sb.WriteString(" ON ")
sb.WriteString(c.Table)
if c.Using != "" {
sb.WriteString(" USING ")
sb.WriteString(c.Using)
}
sb.WriteString(" (")
cols := make([]string, len(c.Columns))
for i, col := range c.Columns {
s := col.Column
if col.Direction != "" {
s += " " + col.Direction
}
cols[i] = s
}
sb.WriteString(strings.Join(cols, ", "))
sb.WriteString(")")
if c.Where != nil {
sb.WriteString(" WHERE ")
sb.WriteString(exprSQL(c.Where))
}
return sb.String()
}
// SQL returns the SQL representation of this ALTER TABLE statement.
// Note: the parser returns AlterStatement (in alter.go); this method
// is for manually-constructed AlterTableStatement values.
func (a *AlterTableStatement) SQL() string {
if a == nil {
return ""
}
sb := getBuilder()
defer putBuilder(sb)
sb.WriteString("ALTER TABLE ")
sb.WriteString(a.Table)
for _, action := range a.Actions {
action := action // G601: Create local copy to avoid memory aliasing
sb.WriteString(" ")
sb.WriteString(alterActionSQL(&action))
}
return sb.String()
}
// SQL returns the SQL representation of this DROP statement, including the
// object type, optional IF EXISTS, object names, and CASCADE/RESTRICT behavior.
func (d *DropStatement) SQL() string {
if d == nil {
return ""
}
sb := getBuilder()
defer putBuilder(sb)
sb.WriteString("DROP ")
sb.WriteString(d.ObjectType)
sb.WriteString(" ")
if d.IfExists {
sb.WriteString("IF EXISTS ")
}
sb.WriteString(strings.Join(d.Names, ", "))
if d.CascadeType != "" {
sb.WriteString(" ")
sb.WriteString(d.CascadeType)
}
return sb.String()
}
// SQL returns the SQL representation of this TRUNCATE statement, including
// table names, RESTART/CONTINUE IDENTITY options, and CASCADE/RESTRICT behavior.
func (t *TruncateStatement) SQL() string {
if t == nil {
return ""
}
sb := getBuilder()
defer putBuilder(sb)
sb.WriteString("TRUNCATE TABLE ")
sb.WriteString(strings.Join(t.Tables, ", "))
if t.RestartIdentity {
sb.WriteString(" RESTART IDENTITY")
} else if t.ContinueIdentity {
sb.WriteString(" CONTINUE IDENTITY")
}
if t.CascadeType != "" {
sb.WriteString(" ")
sb.WriteString(t.CascadeType)
}
return sb.String()
}
// SQL returns the SQL representation of this WITH clause including any RECURSIVE
// modifier and all CTE definitions.
func (w *WithClause) SQL() string {
if w == nil {
return ""
}
sb := getBuilder()
defer putBuilder(sb)
sb.WriteString("WITH ")
if w.Recursive {
sb.WriteString("RECURSIVE ")
}
ctes := make([]string, len(w.CTEs))
for i, cte := range w.CTEs {
ctes[i] = cteSQL(cte)
}
sb.WriteString(strings.Join(ctes, ", "))
return sb.String()
}
// SQL returns the SQL representation of this set operation as
// "left UNION|EXCEPT|INTERSECT [ALL] right".
func (s *SetOperation) SQL() string {
if s == nil {
return ""
}
left := stmtSQL(s.Left)
right := stmtSQL(s.Right)
op := s.Operator
if s.All {
op += " ALL"
}
return fmt.Sprintf("%s %s %s", left, op, right)
}
// SQL returns the SQL representation of this VALUES clause as
// "VALUES (v1, v2), (v3, v4), ...".
func (v *Values) SQL() string {
if v == nil {
return ""
}
rows := make([]string, len(v.Rows))
for i, row := range v.Rows {
vals := make([]string, len(row))
for j, val := range row {
vals[j] = exprSQL(val)
}
rows[i] = "(" + strings.Join(vals, ", ") + ")"
}
return "VALUES " + strings.Join(rows, ", ")
}