-
Notifications
You must be signed in to change notification settings - Fork 12
/
antlr.go
2270 lines (1863 loc) · 57.2 KB
/
antlr.go
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 parse
import (
"encoding/hex"
"math"
"math/big"
"strconv"
"strings"
"github.com/antlr4-go/antlr/v4"
"github.com/kwilteam/kwil-db/core/types"
"github.com/kwilteam/kwil-db/core/types/decimal"
"github.com/kwilteam/kwil-db/core/types/validation"
"github.com/kwilteam/kwil-db/parse/gen"
)
// schemaVisitor is a visitor for converting Kuneiform's ANTLR
// generated parse tree into our native schema type. It will perform
// syntax validation on actions and procedures.
type schemaVisitor struct {
antlr.BaseParseTreeVisitor
// schema is the schema that was parsed.
// If no schema was parsed, it will be nil.
schema *types.Schema
// schemaInfo holds information on the position
// of certain blocks in the schema.
schemaInfo *SchemaInfo
// errs is used for passing errors back to the caller.
errs *errorListener
// stream is the input stream
stream *antlr.InputStream
// both procedures and actions are only needed if parsing
// an entire top-level schema, and will not be called if
// parsing only an action or procedure body, or SQL.
// procedures maps the asts of all parsed procedures
procedures map[string][]ProcedureStmt
// actions maps the asts of all parsed actions
actions map[string][]ActionStmt
}
// getTextFromStream gets the text from the input stream for a given range.
// This is a hack over a bug in the generated antlr code, where it will try
// to access index out of bounds.
func (s *schemaVisitor) getTextFromStream(start, stop int) (str string) {
defer func() {
if r := recover(); r != nil {
str = ""
}
}()
return s.stream.GetText(start, stop)
}
// newSchemaVisitor creates a new schema visitor.
func newSchemaVisitor(stream *antlr.InputStream, errLis *errorListener) *schemaVisitor {
return &schemaVisitor{
schemaInfo: &SchemaInfo{
Blocks: make(map[string]*Block),
},
errs: errLis,
stream: stream,
}
}
var _ gen.KuneiformParserVisitor = (*schemaVisitor)(nil)
// below are the 4 top-level entry points for the visitor.
func (s *schemaVisitor) VisitSchema_entry(ctx *gen.Schema_entryContext) any {
return ctx.Schema().Accept(s)
}
func (s *schemaVisitor) VisitAction_entry(ctx *gen.Action_entryContext) any {
return ctx.Action_block().Accept(s)
}
func (s *schemaVisitor) VisitProcedure_entry(ctx *gen.Procedure_entryContext) any {
return ctx.Procedure_block().Accept(s)
}
func (s *schemaVisitor) VisitSql_entry(ctx *gen.Sql_entryContext) any {
return ctx.Sql().Accept(s)
}
// unknownExpression creates a new literal with an unknown type and null value.
// It should be used when we have to return early from a visitor method that
// returns an expression.
func unknownExpression(ctx antlr.ParserRuleContext) *ExpressionLiteral {
e := &ExpressionLiteral{
Type: types.UnknownType,
Value: nil,
}
e.Set(ctx)
return e
}
func (s *schemaVisitor) VisitString_literal(ctx *gen.String_literalContext) any {
str := ctx.STRING_().GetText()
if !strings.HasPrefix(str, "'") || !strings.HasSuffix(str, "'") || len(str) < 2 {
panic("invalid string literal")
}
str = str[1 : len(str)-1]
n := &ExpressionLiteral{
Type: types.TextType,
Value: str,
}
n.Set(ctx)
return n
}
var (
maxInt64 = big.NewInt(math.MaxInt64)
minInt64 = big.NewInt(math.MinInt64)
)
func (s *schemaVisitor) VisitInteger_literal(ctx *gen.Integer_literalContext) any {
i := ctx.DIGITS_().GetText()
if ctx.MINUS() != nil {
i = "-" + i
}
// integer literal can be either a uint256 or int64
bigNum := new(big.Int)
_, ok := bigNum.SetString(i, 10)
if !ok {
s.errs.RuleErr(ctx, ErrSyntax, "invalid integer literal: %s", i)
return unknownExpression(ctx)
}
if bigNum.Cmp(maxInt64) > 0 {
// it is a uint256
u256, err := types.Uint256FromBig(bigNum)
if err != nil {
s.errs.RuleErr(ctx, ErrSyntax, "invalid integer literal: %s", i)
return unknownExpression(ctx)
}
e := &ExpressionLiteral{
Type: types.Uint256Type,
Value: u256,
}
e.Set(ctx)
return e
}
if bigNum.Cmp(minInt64) < 0 {
s.errs.RuleErr(ctx, ErrType, "integer literal out of range: %s", i)
return unknownExpression(ctx)
}
e := &ExpressionLiteral{
Type: types.IntType,
Value: bigNum.Int64(),
}
e.Set(ctx)
return e
}
func (s *schemaVisitor) VisitDecimal_literal(ctx *gen.Decimal_literalContext) any {
// our decimal library can parse the decimal, so we simply pass it there
txt := ctx.GetText()
dec, err := decimal.NewFromString(txt)
if err != nil {
s.errs.RuleErr(ctx, err, "invalid decimal literal: %s", txt)
return unknownExpression(ctx)
}
typ, err := types.NewDecimalType(dec.Precision(), dec.Scale())
if err != nil {
s.errs.RuleErr(ctx, err, "invalid decimal literal: %s", txt)
return unknownExpression(ctx)
}
e := &ExpressionLiteral{
Type: typ,
Value: dec,
}
e.Set(ctx)
return e
}
func (s *schemaVisitor) VisitBoolean_literal(ctx *gen.Boolean_literalContext) any {
var b bool
switch {
case ctx.TRUE() != nil:
b = true
case ctx.FALSE() != nil:
b = false
default:
panic("unknown boolean literal")
}
e := &ExpressionLiteral{
Type: types.BoolType,
Value: b,
}
e.Set(ctx)
return e
}
func (s *schemaVisitor) VisitNull_literal(ctx *gen.Null_literalContext) any {
e := &ExpressionLiteral{
Type: types.NullType,
Value: nil,
}
e.Set(ctx)
return e
}
func (s *schemaVisitor) VisitBinary_literal(ctx *gen.Binary_literalContext) any {
b := ctx.GetText()
// trim off beginning 0x
if b[:2] != "0x" {
// this should get caught by the parser
s.errs.RuleErr(ctx, ErrSyntax, "invalid blob literal: %s", b)
}
b = b[2:]
decoded, err := hex.DecodeString(b)
if err != nil {
// this should get caught by the parser
s.errs.RuleErr(ctx, ErrSyntax, "invalid blob literal: %s", b)
}
e := &ExpressionLiteral{
Type: types.BlobType,
Value: decoded,
}
e.Set(ctx)
return e
}
func (s *schemaVisitor) VisitIdentifier_list(ctx *gen.Identifier_listContext) any {
var ident []string
for _, i := range ctx.AllIdentifier() {
ident = append(ident, i.Accept(s).(string))
}
return ident
}
func (s *schemaVisitor) VisitIdentifier(ctx *gen.IdentifierContext) any {
return s.getIdent(ctx.IDENTIFIER())
}
func (s *schemaVisitor) VisitType(ctx *gen.TypeContext) any {
dt := &types.DataType{
Name: s.getIdent(ctx.IDENTIFIER()),
}
if ctx.LPAREN() != nil {
// there should be 2 digits
prec, err := strconv.ParseInt(ctx.DIGITS_(0).GetText(), 10, 64)
if err != nil {
s.errs.RuleErr(ctx, ErrSyntax, "invalid precision: %s", ctx.DIGITS_(0).GetText())
return types.UnknownType
}
scale, err := strconv.ParseInt(ctx.DIGITS_(1).GetText(), 10, 64)
if err != nil {
s.errs.RuleErr(ctx, ErrSyntax, "invalid scale: %s", ctx.DIGITS_(1).GetText())
return types.UnknownType
}
dt.Metadata = [2]uint16{uint16(prec), uint16(scale)}
}
if ctx.LBRACKET() != nil {
dt.IsArray = true
}
err := dt.Clean()
if err != nil {
s.errs.RuleErr(ctx, err, "invalid type: %s", dt.String())
return types.UnknownType
}
return dt
}
func (s *schemaVisitor) VisitType_cast(ctx *gen.Type_castContext) any {
return s.Visit(ctx.Type_()).(*types.DataType)
}
func (s *schemaVisitor) VisitVariable(ctx *gen.VariableContext) any {
var e *ExpressionVariable
var tok antlr.Token
switch {
case ctx.VARIABLE() != nil:
e = &ExpressionVariable{
Name: strings.ToLower(strings.TrimLeft(ctx.GetText(), "$")),
Prefix: VariablePrefixDollar,
}
tok = ctx.VARIABLE().GetSymbol()
case ctx.CONTEXTUAL_VARIABLE() != nil:
e = &ExpressionVariable{
Name: strings.ToLower(strings.TrimLeft(ctx.GetText(), "@")),
Prefix: VariablePrefixAt,
}
tok = ctx.CONTEXTUAL_VARIABLE().GetSymbol()
_, ok := SessionVars[e.Name]
if !ok {
s.errs.RuleErr(ctx, ErrUnknownContextualVariable, e.Name)
}
default:
panic("unknown variable")
}
s.validateVariableIdentifier(tok, e.Name)
e.Set(ctx)
return e
}
func (s *schemaVisitor) VisitVariable_list(ctx *gen.Variable_listContext) any {
var vars []*ExpressionVariable
for _, v := range ctx.AllVariable() {
vars = append(vars, v.Accept(s).(*ExpressionVariable))
}
return vars
}
func (s *schemaVisitor) VisitSchema(ctx *gen.SchemaContext) any {
s.schema = &types.Schema{
Name: ctx.Database_declaration().Accept(s).(string),
Tables: arr[*types.Table](len(ctx.AllTable_declaration())),
Extensions: arr[*types.Extension](len(ctx.AllUse_declaration())),
Actions: arr[*types.Action](len(ctx.AllAction_declaration())),
Procedures: arr[*types.Procedure](len(ctx.AllProcedure_declaration())),
ForeignProcedures: arr[*types.ForeignProcedure](len(ctx.AllForeign_procedure_declaration())),
}
for i, t := range ctx.AllTable_declaration() {
s.schema.Tables[i] = t.Accept(s).(*types.Table)
s.registerBlock(t, s.schema.Tables[i].Name)
}
// only now that we have visited all tables can we validate
// foreign keys
for _, t := range s.schema.Tables {
for _, fk := range t.ForeignKeys {
// the best we can do is get the position of the full
// table.
pos, ok := s.schemaInfo.Blocks[strings.ToLower(fk.ParentTable)]
if !ok {
pos2, ok2 := s.schemaInfo.Blocks[t.Name]
if ok2 {
s.errs.AddErr(pos2, ErrUnknownTable, fk.ParentTable)
} else {
s.errs.RuleErr(ctx, ErrUnknownTable, fk.ParentTable)
}
continue
}
// check that all ParentKeys exist
parentTable, ok := s.schema.FindTable(fk.ParentTable)
if !ok {
s.errs.AddErr(pos, ErrUnknownTable, fk.ParentTable)
continue
}
for _, col := range fk.ParentKeys {
if _, ok := parentTable.FindColumn(col); !ok {
s.errs.AddErr(pos, ErrUnknownColumn, col)
}
}
}
}
for i, e := range ctx.AllUse_declaration() {
s.schema.Extensions[i] = e.Accept(s).(*types.Extension)
s.registerBlock(e, s.schema.Extensions[i].Alias)
}
for i, a := range ctx.AllAction_declaration() {
s.schema.Actions[i] = a.Accept(s).(*types.Action)
s.registerBlock(a, s.schema.Actions[i].Name)
}
for i, p := range ctx.AllProcedure_declaration() {
s.schema.Procedures[i] = p.Accept(s).(*types.Procedure)
s.registerBlock(p, s.schema.Procedures[i].Name)
}
for i, p := range ctx.AllForeign_procedure_declaration() {
s.schema.ForeignProcedures[i] = p.Accept(s).(*types.ForeignProcedure)
s.registerBlock(p, s.schema.ForeignProcedures[i].Name)
}
return s.schema
}
// registerBlock registers a top-level block (table, action, procedure, etc.),
// ensuring uniqueness
func (s *schemaVisitor) registerBlock(ctx antlr.ParserRuleContext, name string) {
lower := strings.ToLower(name)
if _, ok := s.schemaInfo.Blocks[lower]; ok {
s.errs.RuleErr(ctx, ErrDuplicateBlock, lower)
return
}
if _, ok := Functions[lower]; ok {
s.errs.RuleErr(ctx, ErrReservedKeyword, lower)
return
}
if validation.IsKeyword(lower) {
s.errs.RuleErr(ctx, ErrReservedKeyword, lower)
return
}
node := &Position{}
node.Set(ctx)
s.schemaInfo.Blocks[lower] = &Block{
Position: *node,
AbsStart: ctx.GetStart().GetStart(),
AbsEnd: ctx.GetStop().GetStop(),
}
}
// arr will make an array of type A if the input is greater than 0
func arr[A any](b int) []A {
if b > 0 {
return make([]A, b)
}
return nil
}
func (s *schemaVisitor) VisitAnnotation(ctx *gen.AnnotationContext) any {
// we will parse but reconstruct annotations, so they can later be consumed by the gateway
str := strings.Builder{}
str.WriteString(s.getIdent(ctx.CONTEXTUAL_VARIABLE()))
str.WriteString("(")
for i, l := range ctx.AllLiteral() {
if i > 0 {
str.WriteString(", ")
}
str.WriteString(s.getIdent(ctx.IDENTIFIER(i)))
str.WriteString("=")
// we do not touch the literal, since case should be preserved
str.WriteString(l.GetText())
}
str.WriteString(")")
return str.String()
}
// isErrNode is true if an antlr terminal node is an error node.
func isErrNode(node antlr.TerminalNode) bool {
_, ok := node.(antlr.ErrorNode)
return ok
}
func (s *schemaVisitor) VisitDatabase_declaration(ctx *gen.Database_declarationContext) any {
// needed to avoid https://github.com/kwilteam/kwil-db/issues/752
if isErrNode(ctx.DATABASE()) {
return ""
}
return s.getIdent(ctx.IDENTIFIER())
}
func (s *schemaVisitor) VisitUse_declaration(ctx *gen.Use_declarationContext) any {
// the first identifier is the extension name, the last is the alias,
// and all in between are keys in the initialization.
e := &types.Extension{
Name: s.getIdent(ctx.IDENTIFIER(0)),
Initialization: arr[*types.ExtensionConfig](len(ctx.AllIDENTIFIER()) - 2),
Alias: s.getIdent(ctx.IDENTIFIER(len(ctx.AllIDENTIFIER()) - 1)),
}
for i, id := range ctx.AllIDENTIFIER()[1 : len(ctx.AllIDENTIFIER())-1] {
val := ctx.Literal(i).Accept(s).(*ExpressionLiteral)
e.Initialization[i] = &types.ExtensionConfig{
Key: s.getIdent(id),
Value: val.String(),
}
}
return e
}
func (s *schemaVisitor) VisitTable_declaration(ctx *gen.Table_declarationContext) any {
t := &types.Table{
Name: s.getIdent(ctx.IDENTIFIER()),
Columns: arr[*types.Column](len(ctx.AllColumn_def())),
Indexes: arr[*types.Index](len(ctx.AllIndex_def())),
ForeignKeys: arr[*types.ForeignKey](len(ctx.AllForeign_key_def())),
}
for i, c := range ctx.AllColumn_def() {
t.Columns[i] = c.Accept(s).(*types.Column)
}
for i, idx := range ctx.AllIndex_def() {
t.Indexes[i] = idx.Accept(s).(*types.Index)
// check that all columns in indexes and foreign key children exist
for _, col := range t.Indexes[i].Columns {
if _, ok := t.FindColumn(col); !ok {
s.errs.RuleErr(idx, ErrUnknownColumn, col)
}
}
}
for i, fk := range ctx.AllForeign_key_def() {
t.ForeignKeys[i] = fk.Accept(s).(*types.ForeignKey)
// check that all ChildKeys exist.
// we will have to check for parent keys in a later stage,
// since not all tables are parsed yet.
for _, col := range t.ForeignKeys[i].ChildKeys {
if _, ok := t.FindColumn(col); !ok {
s.errs.RuleErr(fk, ErrUnknownColumn, col)
}
}
}
_, err := t.GetPrimaryKey()
if err != nil {
s.errs.RuleErr(ctx, ErrNoPrimaryKey, err.Error())
}
return t
}
func (s *schemaVisitor) VisitColumn_def(ctx *gen.Column_defContext) any {
col := &types.Column{
Name: s.getIdent(ctx.IDENTIFIER()),
Type: ctx.Type_().Accept(s).(*types.DataType),
}
// due to unfortunate lexing edge cases to support min/max, we
// have to parse the constraints here. Each constraint is a text, and should be
// one of:
// MIN/MAX/MINLEN/MAXLEN/MIN_LENGTH/MAX_LENGTH/NOTNULL/NOT/NULL/PRIMARY/KEY/PRIMARY_KEY/PK/DEFAULT/UNIQUE
// If NOT is present, it needs to be followed by NULL; similarly, if NULL is present, it needs to be preceded by NOT.
// If PRIMARY is present, it can be followed by key, but does not have to be. key must be preceded by primary.
// MIN, MAX, MINLEN, MAXLEN, MIN_LENGTH, MAX_LENGTH, and DEFAULT must also have a literal following them.
type constraint struct {
ident string
lit *string
}
constraints := make([]constraint, len(ctx.AllConstraint()))
for i, c := range ctx.AllConstraint() {
con := constraint{}
switch {
case c.IDENTIFIER() != nil:
con.ident = c.IDENTIFIER().GetText()
case c.PRIMARY() != nil:
con.ident = "primary_key"
case c.NOT() != nil:
con.ident = "notnull"
case c.DEFAULT() != nil:
con.ident = "default"
case c.UNIQUE() != nil:
con.ident = "unique"
default:
panic("unknown constraint")
}
if c.Literal() != nil {
l := strings.ToLower(c.Literal().Accept(s).(*ExpressionLiteral).String())
con.lit = &l
}
constraints[i] = con
}
for i := range constraints {
switch constraints[i].ident {
case "min":
if constraints[i].lit == nil {
s.errs.RuleErr(ctx, ErrSyntax, "missing literal for min constraint")
return col
}
col.Attributes = append(col.Attributes, &types.Attribute{
Type: types.MIN,
Value: *constraints[i].lit,
})
case "max":
if constraints[i].lit == nil {
s.errs.RuleErr(ctx, ErrSyntax, "missing literal for max constraint")
return col
}
col.Attributes = append(col.Attributes, &types.Attribute{
Type: types.MAX,
Value: *constraints[i].lit,
})
case "minlen", "min_length":
if constraints[i].lit == nil {
s.errs.RuleErr(ctx, ErrSyntax, "missing literal for min length constraint")
return col
}
col.Attributes = append(col.Attributes, &types.Attribute{
Type: types.MIN_LENGTH,
Value: *constraints[i].lit,
})
case "maxlen", "max_length":
if constraints[i].lit == nil {
s.errs.RuleErr(ctx, ErrSyntax, "missing literal for max length constraint")
return col
}
col.Attributes = append(col.Attributes, &types.Attribute{
Type: types.MAX_LENGTH,
Value: *constraints[i].lit,
})
case "notnull":
if constraints[i].lit != nil {
s.errs.RuleErr(ctx, ErrSyntax, "unexpected literal for not null constraint")
return col
}
col.Attributes = append(col.Attributes, &types.Attribute{
Type: types.NOT_NULL,
})
case "primary_key", "pk":
if constraints[i].lit != nil {
s.errs.RuleErr(ctx, ErrSyntax, "unexpected literal for primary key constraint")
return col
}
col.Attributes = append(col.Attributes, &types.Attribute{
Type: types.PRIMARY_KEY,
})
case "default":
if constraints[i].lit == nil {
s.errs.RuleErr(ctx, ErrSyntax, "missing literal for default constraint")
return col
}
col.Attributes = append(col.Attributes, &types.Attribute{
Type: types.DEFAULT,
Value: *constraints[i].lit,
})
case "unique":
if constraints[i].lit != nil {
s.errs.RuleErr(ctx, ErrSyntax, "unexpected literal for unique constraint")
return col
}
col.Attributes = append(col.Attributes, &types.Attribute{
Type: types.UNIQUE,
})
default:
s.errs.RuleErr(ctx, ErrSyntax, "unknown constraint: %s", constraints[i].ident)
return col
}
}
for _, con := range col.Attributes {
err := con.Clean(col)
if err != nil {
s.errs.RuleErr(ctx, ErrColumnConstraint, err.Error())
return col
}
}
return col
}
func (s *schemaVisitor) VisitConstraint(ctx *gen.ConstraintContext) any {
panic("VisitConstraint should not be called, as the logic should be implemented in VisitColumn_def")
}
func (s *schemaVisitor) VisitIndex_def(ctx *gen.Index_defContext) any {
name := ctx.HASH_IDENTIFIER().GetText()
name = strings.TrimLeft(name, "#")
idx := &types.Index{
Name: strings.ToLower(name),
Columns: ctx.Identifier_list().Accept(s).([]string),
}
s.validateVariableIdentifier(ctx.HASH_IDENTIFIER().GetSymbol(), idx.Name)
switch {
case ctx.INDEX() != nil:
idx.Type = types.BTREE
case ctx.UNIQUE() != nil:
idx.Type = types.UNIQUE_BTREE
case ctx.PRIMARY() != nil:
idx.Type = types.PRIMARY
default:
panic("unknown index type")
}
return idx
}
func (s *schemaVisitor) VisitForeign_key_def(ctx *gen.Foreign_key_defContext) any {
fk := &types.ForeignKey{
ChildKeys: ctx.GetChild_keys().Accept(s).([]string),
ParentKeys: ctx.GetParent_keys().Accept(s).([]string),
ParentTable: strings.ToLower(ctx.GetParent_table().GetText()),
Actions: arr[*types.ForeignKeyAction](len(ctx.AllForeign_key_action())),
}
for i, a := range ctx.AllForeign_key_action() {
fk.Actions[i] = a.Accept(s).(*types.ForeignKeyAction)
}
return fk
}
func (s *schemaVisitor) VisitForeign_key_action(ctx *gen.Foreign_key_actionContext) any {
ac := &types.ForeignKeyAction{}
switch {
case ctx.UPDATE() != nil, ctx.LEGACY_ON_UPDATE() != nil:
ac.On = types.ON_UPDATE
case ctx.DELETE() != nil, ctx.LEGACY_ON_DELETE() != nil:
ac.On = types.ON_DELETE
default:
panic("unknown foreign key action")
}
switch {
case ctx.ACTION() != nil, ctx.LEGACY_NO_ACTION() != nil:
ac.Do = types.DO_NO_ACTION
case ctx.NULL() != nil, ctx.LEGACY_SET_NULL() != nil:
ac.Do = types.DO_SET_NULL
case ctx.DEFAULT() != nil, ctx.LEGACY_SET_DEFAULT() != nil:
ac.Do = types.DO_SET_DEFAULT
// cascade and restrict do not have legacys
case ctx.CASCADE() != nil:
ac.Do = types.DO_CASCADE
case ctx.RESTRICT() != nil:
ac.Do = types.DO_RESTRICT
default:
panic("unknown foreign key action")
}
return ac
}
func (s *schemaVisitor) VisitType_list(ctx *gen.Type_listContext) any {
var ts []*types.DataType
for _, t := range ctx.AllType_() {
ts = append(ts, t.Accept(s).(*types.DataType))
}
return ts
}
func (s *schemaVisitor) VisitNamed_type_list(ctx *gen.Named_type_listContext) any {
var ts []*types.NamedType
for i, t := range ctx.AllIDENTIFIER() {
ts = append(ts, &types.NamedType{
Name: s.getIdent(t),
Type: ctx.Type_(i).Accept(s).(*types.DataType),
})
}
return ts
}
func (s *schemaVisitor) VisitTyped_variable_list(ctx *gen.Typed_variable_listContext) any {
var vars []*types.ProcedureParameter
for i, v := range ctx.AllVariable() {
vars = append(vars, &types.ProcedureParameter{
Name: v.Accept(s).(*ExpressionVariable).String(),
Type: ctx.Type_(i).Accept(s).(*types.DataType),
})
}
return vars
}
func (s *schemaVisitor) VisitAccess_modifier(ctx *gen.Access_modifierContext) any {
// we will have to parse this at a later stage, since this is either public/private,
// or a types.Modifier
panic("VisitAccess_modifier should not be called")
}
// getModifiersAndPublicity parses access modifiers and returns. it should be used when
// parsing procedures and actions
func getModifiersAndPublicity(ctxs []gen.IAccess_modifierContext) (public bool, mods []types.Modifier) {
for _, ctx := range ctxs {
switch {
case ctx.PUBLIC() != nil:
public = true
case ctx.PRIVATE() != nil:
public = false
case ctx.VIEW() != nil:
mods = append(mods, types.ModifierView)
case ctx.OWNER() != nil:
mods = append(mods, types.ModifierOwner)
default:
// should not happen, as this would suggest a bug in the parser
panic("unknown access modifier")
}
}
return
}
func (s *schemaVisitor) VisitAction_declaration(ctx *gen.Action_declarationContext) any {
act := &types.Action{
Name: s.getIdent(ctx.IDENTIFIER()),
Annotations: arr[string](len(ctx.AllAnnotation())),
}
for i, a := range ctx.AllAnnotation() {
act.Annotations[i] = a.Accept(s).(string)
}
public, mods := getModifiersAndPublicity(ctx.AllAccess_modifier())
act.Public = public
act.Modifiers = mods
if ctx.Variable_list() != nil {
params := ctx.Variable_list().Accept(s).([]*ExpressionVariable)
paramStrs := make([]string, len(params))
for i, p := range params {
paramStrs[i] = p.String()
}
act.Parameters = paramStrs
}
act.Body = s.getTextFromStream(ctx.Action_block().GetStart().GetStart(), ctx.Action_block().GetStop().GetStop())
ast := ctx.Action_block().Accept(s).([]ActionStmt)
s.actions[act.Name] = ast
return act
}
func (s *schemaVisitor) VisitProcedure_declaration(ctx *gen.Procedure_declarationContext) any {
proc := &types.Procedure{
Name: s.getIdent(ctx.IDENTIFIER()),
Annotations: arr[string](len(ctx.AllAnnotation())),
}
if ctx.Typed_variable_list() != nil {
proc.Parameters = ctx.Typed_variable_list().Accept(s).([]*types.ProcedureParameter)
}
if ctx.Procedure_return() != nil {
proc.Returns = ctx.Procedure_return().Accept(s).(*types.ProcedureReturn)
}
for i, a := range ctx.AllAnnotation() {
proc.Annotations[i] = a.Accept(s).(string)
}
public, mods := getModifiersAndPublicity(ctx.AllAccess_modifier())
proc.Public = public
proc.Modifiers = mods
ast := ctx.Procedure_block().Accept(s).([]ProcedureStmt)
s.procedures[proc.Name] = ast
proc.Body = s.getTextFromStream(ctx.Procedure_block().GetStart().GetStart(), ctx.Procedure_block().GetStop().GetStop())
return proc
}
func (s *schemaVisitor) VisitForeign_procedure_declaration(ctx *gen.Foreign_procedure_declarationContext) any {
// similar to https://github.com/kwilteam/kwil-db/issues/752, the parser will recognize
// `foreign proced`` as a foreign procedure named `proced`. it will throw an error, but we
// don't want to return this to the client either.
fp := &types.ForeignProcedure{}
if isErrNode(ctx.FOREIGN()) {
return fp
}
if isErrNode(ctx.PROCEDURE()) {
return fp
}
fp.Name = s.getIdent(ctx.IDENTIFIER())
if ctx.Procedure_return() != nil {
fp.Returns = ctx.Procedure_return().Accept(s).(*types.ProcedureReturn)
}
// no default, since foreign procedures can take no inputs optionally
switch {
case ctx.GetUnnamed_params() != nil:
fp.Parameters = ctx.GetUnnamed_params().Accept(s).([]*types.DataType)
case ctx.GetNamed_params() != nil:
ps := ctx.GetNamed_params().Accept(s).([]*types.ProcedureParameter)
var dataTypes []*types.DataType
for _, p := range ps {
dataTypes = append(dataTypes, p.Type)
}
fp.Parameters = dataTypes
}
return fp
}
func (s *schemaVisitor) VisitProcedure_return(ctx *gen.Procedure_returnContext) any {
ret := &types.ProcedureReturn{}
switch {
case ctx.GetReturn_columns() != nil:
ret.Fields = ctx.GetReturn_columns().Accept(s).([]*types.NamedType)
case ctx.GetUnnamed_return_types() != nil:
ret.Fields = make([]*types.NamedType, len(ctx.GetUnnamed_return_types().AllType_()))
for i, t := range ctx.GetUnnamed_return_types().AllType_() {
ret.Fields[i] = &types.NamedType{
Name: "col" + strconv.Itoa(i),
Type: t.Accept(s).(*types.DataType),
}
}
default:
panic("unknown return type")
}
if ctx.TABLE() != nil {
ret.IsTable = true
}
return ret
}
// VisitSQL visits a SQL statement. It is the top-level SQL visitor.
func (s *schemaVisitor) VisitSql(ctx *gen.SqlContext) any {
return ctx.Sql_statement().Accept(s)
}
// VisitSql_statement visits a SQL statement. It is called by all nested
// sql statements (e.g. in procedures and actions)
func (s *schemaVisitor) VisitSql_statement(ctx *gen.Sql_statementContext) any {
stmt := &SQLStatement{
CTEs: arr[*CommonTableExpression](len(ctx.AllCommon_table_expression())),
}
for i, cte := range ctx.AllCommon_table_expression() {
stmt.CTEs[i] = cte.Accept(s).(*CommonTableExpression)
}
switch {
case ctx.Select_statement() != nil:
stmt.SQL = ctx.Select_statement().Accept(s).(*SelectStatement)
case ctx.Update_statement() != nil:
stmt.SQL = ctx.Update_statement().Accept(s).(*UpdateStatement)
case ctx.Insert_statement() != nil:
stmt.SQL = ctx.Insert_statement().Accept(s).(*InsertStatement)
case ctx.Delete_statement() != nil:
stmt.SQL = ctx.Delete_statement().Accept(s).(*DeleteStatement)
default:
panic("unknown sql statement")
}
stmt.Set(ctx)
return stmt
}
func (s *schemaVisitor) VisitCommon_table_expression(ctx *gen.Common_table_expressionContext) any {
// first identifier is the table name, the rest are the columns
cte := &CommonTableExpression{
Name: ctx.Identifier(0).Accept(s).(string),
Query: ctx.Select_statement().Accept(s).(*SelectStatement),
}
for _, id := range ctx.AllIdentifier()[1:] {
cte.Columns = append(cte.Columns, id.Accept(s).(string))
}
cte.Set(ctx)
return cte
}
func (s *schemaVisitor) VisitSelect_statement(ctx *gen.Select_statementContext) any {
stmt := &SelectStatement{
SelectCores: arr[*SelectCore](len(ctx.AllSelect_core())),
CompoundOperators: arr[CompoundOperator](len(ctx.AllCompound_operator())),
Ordering: arr[*OrderingTerm](len(ctx.AllOrdering_term())),
}
for i, core := range ctx.AllSelect_core() {
stmt.SelectCores[i] = core.Accept(s).(*SelectCore)
}
for i, op := range ctx.AllCompound_operator() {
stmt.CompoundOperators[i] = op.Accept(s).(CompoundOperator)
}
for i, ord := range ctx.AllOrdering_term() {
stmt.Ordering[i] = ord.Accept(s).(*OrderingTerm)
}
if ctx.GetLimit() != nil {
stmt.Limit = ctx.GetLimit().Accept(s).(Expression)
}
if ctx.GetOffset() != nil {
stmt.Offset = ctx.GetOffset().Accept(s).(Expression)
}