-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathddl.go
More file actions
796 lines (729 loc) · 22 KB
/
ddl.go
File metadata and controls
796 lines (729 loc) · 22 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
// 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 parser - ddl.go
// DDL statement parsing: CREATE TABLE core, DROP, TRUNCATE.
// Related modules:
// - ddl_columns.go - column definitions and table constraints
// - ddl_index.go - CREATE INDEX
// - ddl_view.go - CREATE VIEW, CREATE MATERIALIZED VIEW, REFRESH
package parser
import (
"strings"
"github.com/ajitpratap0/GoSQLX/pkg/models"
"github.com/ajitpratap0/GoSQLX/pkg/sql/ast"
"github.com/ajitpratap0/GoSQLX/pkg/sql/keywords"
)
// isTokenMatch checks if the current token matches the given keyword
// This handles both keyword tokens and identifier tokens with matching literal values
// (needed because some keywords like DATA, NO may be tokenized as identifiers)
func (p *Parser) isTokenMatch(keyword string) bool {
// Check if token literal matches the keyword (case-insensitive)
return strings.EqualFold(p.currentToken.Token.Value, keyword)
}
// parseCreateStatement parses CREATE statements (TABLE, VIEW, MATERIALIZED VIEW, INDEX)
func (p *Parser) parseCreateStatement() (ast.Statement, error) {
// Check for modifiers: OR REPLACE, TEMPORARY, TEMP
orReplace := false
temporary := false
for {
if p.isType(models.TokenTypeOr) {
p.advance() // Consume OR
if !p.isType(models.TokenTypeReplace) {
return nil, p.expectedError("REPLACE after OR")
}
p.advance() // Consume REPLACE
orReplace = true
} else if p.isTokenMatch("TEMPORARY") || p.isTokenMatch("TEMP") {
p.advance() // Consume TEMPORARY/TEMP
temporary = true
} else {
break
}
}
// Determine object type
if p.isType(models.TokenTypeMaterialized) {
p.advance() // Consume MATERIALIZED
if !p.isType(models.TokenTypeView) {
return nil, p.expectedError("VIEW after MATERIALIZED")
}
p.advance() // Consume VIEW
return p.parseCreateMaterializedView()
} else if p.isType(models.TokenTypeView) {
p.advance() // Consume VIEW
return p.parseCreateView(orReplace, temporary)
} else if p.isType(models.TokenTypeTable) {
p.advance() // Consume TABLE
return p.parseCreateTable(temporary)
} else if p.isType(models.TokenTypeIndex) {
p.advance() // Consume INDEX
return p.parseCreateIndex(false) // Not unique
} else if p.isType(models.TokenTypeUnique) {
p.advance() // Consume UNIQUE
if !p.isType(models.TokenTypeIndex) {
return nil, p.expectedError("INDEX after UNIQUE")
}
p.advance() // Consume INDEX
return p.parseCreateIndex(true) // Unique
} else if p.isMariaDB() && p.isTokenMatch("SEQUENCE") {
seqPos := p.currentLocation() // position of SEQUENCE token
p.advance() // Consume SEQUENCE
stmt, err := p.parseCreateSequenceStatement(orReplace)
if err != nil {
return nil, err
}
if stmt.Pos.IsZero() {
stmt.Pos = seqPos
}
return stmt, nil
}
// Snowflake object-type extensions: STAGE, STREAM, TASK, PIPE, FILE FORMAT,
// WAREHOUSE, DATABASE, SCHEMA, ROLE, FUNCTION, PROCEDURE, SEQUENCE.
// Parse-only: consumed permissively and returned as UnsupportedStatement
// until dedicated AST nodes are introduced.
if p.dialect == string(keywords.DialectSnowflake) {
kind := strings.ToUpper(p.currentToken.Token.Value)
if kind == "FILE" && strings.EqualFold(p.peekToken().Token.Value, "FORMAT") {
p.advance() // FILE
kind = "FILE FORMAT"
}
switch kind {
case "STAGE", "STREAM", "TASK", "PIPE", "FILE FORMAT",
"WAREHOUSE", "DATABASE", "SCHEMA", "ROLE", "SEQUENCE",
"FUNCTION", "PROCEDURE":
stmtKind := "CREATE " + kind
p.advance() // Consume object-kind keyword
var rawParts []string
rawParts = append(rawParts, "CREATE", kind)
// Optional IF NOT EXISTS
if p.isType(models.TokenTypeIf) {
rawParts = append(rawParts, "IF")
p.advance()
if p.isType(models.TokenTypeNot) {
rawParts = append(rawParts, "NOT")
p.advance()
}
if p.isType(models.TokenTypeExists) {
rawParts = append(rawParts, "EXISTS")
p.advance()
}
}
// Object name (qualified identifier)
name, _ := p.parseQualifiedName()
if name != "" {
rawParts = append(rawParts, name)
}
// Consume the rest of the statement body until ';' or EOF,
// tracking balanced parens.
depth := 0
for {
t := p.currentToken.Token.Type
if t == models.TokenTypeEOF {
break
}
if t == models.TokenTypeSemicolon && depth == 0 {
break
}
if p.currentToken.Token.Value != "" {
rawParts = append(rawParts, p.currentToken.Token.Value)
}
if t == models.TokenTypeLParen {
depth++
} else if t == models.TokenTypeRParen {
depth--
}
p.advance()
}
stub := ast.GetUnsupportedStatement()
stub.Kind = stmtKind
stub.RawSQL = strings.Join(rawParts, " ")
return stub, nil
}
}
return nil, p.expectedError("TABLE, VIEW, MATERIALIZED VIEW, or INDEX after CREATE")
}
// parseCreateTable parses CREATE TABLE statement with partitioning support
func (p *Parser) parseCreateTable(temporary bool) (*ast.CreateTableStatement, error) {
stmt := &ast.CreateTableStatement{
Temporary: temporary,
}
// Check for IF NOT EXISTS
if p.isType(models.TokenTypeIf) {
p.advance() // Consume IF
if !p.isType(models.TokenTypeNot) {
return nil, p.expectedError("NOT after IF")
}
p.advance() // Consume NOT
if !p.isType(models.TokenTypeExists) {
return nil, p.expectedError("EXISTS after NOT")
}
p.advance() // Consume EXISTS
stmt.IfNotExists = true
}
// Parse table name (supports schema.table qualification and double-quoted identifiers)
createTableName, err := p.parseQualifiedName()
if err != nil {
return nil, p.expectedError("table name")
}
stmt.Name = createTableName
// Snowflake: COPY GRANTS modifier before the column list or AS SELECT.
// Consumed but not modeled on the AST.
if strings.EqualFold(p.currentToken.Token.Value, "COPY") &&
strings.EqualFold(p.peekToken().Token.Value, "GRANTS") {
p.advance() // COPY
p.advance() // GRANTS
}
// CREATE TABLE ... AS SELECT — no column list, just a query.
// ClickHouse also: CREATE TABLE t AS source_table ENGINE = ...
if p.isType(models.TokenTypeAs) {
p.advance() // AS
if p.isType(models.TokenTypeSelect) || p.isType(models.TokenTypeWith) {
p.advance() // SELECT / WITH
query, err := p.parseSelectWithSetOperations()
if err != nil {
return nil, err
}
_ = query // CTAS query not modeled on CreateTableStatement yet
return stmt, nil
}
// ClickHouse: CREATE TABLE t AS <source_table> ENGINE = ...
// The identifier is the source table; consume remaining clauses.
if p.dialect == string(keywords.DialectClickHouse) && p.isIdentifier() {
p.advance() // Consume source table name
// Consume ENGINE and trailing clauses
for !p.isType(models.TokenTypeEOF) && !p.isType(models.TokenTypeSemicolon) {
p.advance()
}
return stmt, nil
}
return nil, p.expectedError("SELECT after AS")
}
// Expect opening parenthesis for column definitions
if !p.isType(models.TokenTypeLParen) {
return nil, p.expectedError("(")
}
p.advance() // Consume (
// Parse column definitions and constraints
for {
// MariaDB: PERIOD FOR name (start_col, end_col) — application-time or system-time period
if p.isMariaDB() && p.isTokenMatch("PERIOD") {
periodPos := p.currentLocation() // position of PERIOD keyword
pd, err := p.parsePeriodDefinition()
if err != nil {
return nil, err
}
pd.Pos = periodPos
stmt.PeriodDefinitions = append(stmt.PeriodDefinitions, pd)
} else if p.isAnyType(models.TokenTypePrimary, models.TokenTypeForeign,
models.TokenTypeUnique, models.TokenTypeCheck, models.TokenTypeConstraint) {
// Check for table-level constraints
constraint, err := p.parseTableConstraint()
if err != nil {
return nil, err
}
stmt.Constraints = append(stmt.Constraints, *constraint)
} else {
// Parse column definition
colDef, err := p.parseColumnDef()
if err != nil {
return nil, err
}
stmt.Columns = append(stmt.Columns, *colDef)
}
// Check for more definitions
if p.isType(models.TokenTypeComma) {
p.advance() // Consume comma
continue
}
break
}
// Expect closing parenthesis
if !p.isType(models.TokenTypeRParen) {
return nil, p.expectedError(")")
}
p.advance() // Consume )
// MariaDB: WITH SYSTEM VERSIONING — enables system-versioned temporal history
if p.isMariaDB() && p.isType(models.TokenTypeWith) {
// peek ahead to check for SYSTEM VERSIONING (not WITH TIES or WITH CHECK etc.)
next := p.peekToken()
if strings.EqualFold(next.Token.Value, "SYSTEM") {
p.advance() // Consume WITH
p.advance() // Consume SYSTEM
if !strings.EqualFold(p.currentToken.Token.Value, "VERSIONING") {
return nil, p.expectedError("VERSIONING after WITH SYSTEM")
}
p.advance() // Consume VERSIONING
stmt.WithSystemVersioning = true
}
}
// Parse optional PARTITION BY clause
if p.isType(models.TokenTypePartition) {
p.advance() // Consume PARTITION
if !p.isType(models.TokenTypeBy) {
return nil, p.expectedError("BY after PARTITION")
}
p.advance() // Consume BY
partitionBy, err := p.parsePartitionByClause()
if err != nil {
return nil, err
}
stmt.PartitionBy = partitionBy
// Parse partition definitions if present
if p.isType(models.TokenTypeLParen) {
p.advance() // Consume (
for {
partDef, err := p.parsePartitionDefinition()
if err != nil {
return nil, err
}
stmt.Partitions = append(stmt.Partitions, *partDef)
if p.isType(models.TokenTypeComma) {
p.advance() // Consume comma
continue
}
break
}
if !p.isType(models.TokenTypeRParen) {
return nil, p.expectedError(")")
}
p.advance() // Consume )
}
}
// Parse optional table options
for p.isTokenMatch("ENGINE") || p.isTokenMatch("CHARSET") ||
p.isType(models.TokenTypeCollate) || p.isTokenMatch("COMMENT") {
opt := ast.TableOption{Name: p.currentToken.Token.Value}
p.advance()
if p.isType(models.TokenTypeEq) {
p.advance() // Consume =
}
if p.isIdentifier() || p.isType(models.TokenTypeString) {
opt.Value = p.currentToken.Token.Value
p.advance()
}
// ClickHouse engine values may carry their own argument list:
// ENGINE = MergeTree()
// ENGINE = ReplicatedMergeTree('/path', '{replica}')
// ENGINE = Distributed('cluster', 'db', 'local_t', sharding_key)
// Consume them as a balanced block appended to the option value.
if p.isType(models.TokenTypeLParen) {
args, err := p.parseTypeArgsString()
if err != nil {
return nil, err
}
opt.Value += args
}
stmt.Options = append(stmt.Options, opt)
}
// ClickHouse CREATE TABLE trailing clauses: ORDER BY, PARTITION BY,
// PRIMARY KEY, SAMPLE BY, SETTINGS. These appear after ENGINE = ... and
// are required for MergeTree-family engines. Parse permissively:
// each consumes a parenthesised expression list or a single column ref.
for p.dialect == string(keywords.DialectClickHouse) {
if p.isType(models.TokenTypeOrder) {
p.advance() // ORDER
if p.isType(models.TokenTypeBy) {
p.advance()
}
if err := p.skipClickHouseClauseExpr(); err != nil {
return nil, err
}
continue
}
if p.isTokenMatch("PARTITION") {
p.advance()
if p.isType(models.TokenTypeBy) {
p.advance()
}
if err := p.skipClickHouseClauseExpr(); err != nil {
return nil, err
}
continue
}
if p.isType(models.TokenTypePrimary) {
p.advance()
if p.isType(models.TokenTypeKey) {
p.advance()
}
if err := p.skipClickHouseClauseExpr(); err != nil {
return nil, err
}
continue
}
if p.isTokenMatch("SAMPLE") {
p.advance()
if p.isType(models.TokenTypeBy) {
p.advance()
}
if err := p.skipClickHouseClauseExpr(); err != nil {
return nil, err
}
continue
}
if p.isTokenMatch("TTL") {
p.advance()
if err := p.skipClickHouseClauseExpr(); err != nil {
return nil, err
}
continue
}
if p.isTokenMatch("SETTINGS") {
p.advance()
// SETTINGS is a comma-separated list of name=value assignments.
// Consume each k=v pair until the next clause, EOF, or ';'.
for {
t := p.currentToken.Token.Type
val := strings.ToUpper(p.currentToken.Token.Value)
if t == models.TokenTypeEOF || t == models.TokenTypeSemicolon {
break
}
if val == "ORDER" || val == "PARTITION" || val == "PRIMARY" ||
val == "SAMPLE" || val == "TTL" {
break
}
p.advance()
}
continue
}
break
}
// Snowflake: CLUSTER BY (expr, ...) — defines the clustering key.
if strings.EqualFold(p.currentToken.Token.Value, "CLUSTER") {
p.advance() // CLUSTER
if p.isType(models.TokenTypeBy) {
p.advance() // BY
}
if p.isType(models.TokenTypeLParen) {
if err := p.skipClickHouseClauseExpr(); err != nil {
return nil, err
}
}
}
// SQLite: optional WITHOUT ROWID clause
if p.isTokenMatch("WITHOUT") {
p.advance() // Consume WITHOUT
if !p.isTokenMatch("ROWID") {
return nil, p.expectedError("ROWID after WITHOUT")
}
p.advance() // Consume ROWID
stmt.WithoutRowID = true
}
return stmt, nil
}
// parsePartitionByClause parses PARTITION BY RANGE/LIST/HASH (columns)
func (p *Parser) parsePartitionByClause() (*ast.PartitionBy, error) {
partitionBy := &ast.PartitionBy{}
// Parse partition type
if p.isType(models.TokenTypeRange) {
partitionBy.Type = "RANGE"
p.advance()
} else if p.isTokenMatch("LIST") {
partitionBy.Type = "LIST"
p.advance()
} else if p.isTokenMatch("HASH") {
partitionBy.Type = "HASH"
p.advance()
} else {
return nil, p.expectedError("RANGE, LIST, or HASH")
}
// Expect opening parenthesis
if !p.isType(models.TokenTypeLParen) {
return nil, p.expectedError("(")
}
p.advance() // Consume (
// Parse column list
for {
if !p.isIdentifier() {
return nil, p.expectedError("column name")
}
partitionBy.Columns = append(partitionBy.Columns, p.currentToken.Token.Value)
p.advance()
if p.isType(models.TokenTypeComma) {
p.advance() // Consume comma
continue
}
break
}
// Expect closing parenthesis
if !p.isType(models.TokenTypeRParen) {
return nil, p.expectedError(")")
}
p.advance() // Consume )
return partitionBy, nil
}
// parsePartitionDefinition parses a single partition definition
func (p *Parser) parsePartitionDefinition() (*ast.PartitionDefinition, error) {
partDef := &ast.PartitionDefinition{}
// Expect PARTITION keyword
if !p.isType(models.TokenTypePartition) {
return nil, p.expectedError("PARTITION")
}
p.advance() // Consume PARTITION
// Parse partition name (supports double-quoted identifiers)
if !p.isIdentifier() {
return nil, p.expectedError("partition name")
}
partDef.Name = p.currentToken.Token.Value
p.advance()
// Parse VALUES clause
if !p.isType(models.TokenTypeValues) {
return nil, p.expectedError("VALUES")
}
p.advance() // Consume VALUES
// Parse value specification
if p.isTokenMatch("LESS") {
p.advance() // Consume LESS
if !p.isTokenMatch("THAN") {
return nil, p.expectedError("THAN after LESS")
}
p.advance() // Consume THAN
partDef.Type = "LESS THAN"
// Parse value or MAXVALUE
if p.isType(models.TokenTypeLParen) {
p.advance() // Consume (
if p.isTokenMatch("MAXVALUE") {
partDef.LessThan = &ast.Identifier{Name: "MAXVALUE"}
p.advance()
} else {
expr, err := p.parseExpression()
if err != nil {
return nil, err
}
partDef.LessThan = expr
}
if !p.isType(models.TokenTypeRParen) {
return nil, p.expectedError(")")
}
p.advance() // Consume )
} else if p.isTokenMatch("MAXVALUE") {
partDef.LessThan = &ast.Identifier{Name: "MAXVALUE"}
p.advance()
}
} else if p.isType(models.TokenTypeIn) {
p.advance() // Consume IN
partDef.Type = "IN"
// Parse value list
if !p.isType(models.TokenTypeLParen) {
return nil, p.expectedError("(")
}
p.advance() // Consume (
for {
expr, err := p.parseExpression()
if err != nil {
return nil, err
}
partDef.InValues = append(partDef.InValues, expr)
if p.isType(models.TokenTypeComma) {
p.advance() // Consume comma
continue
}
break
}
if !p.isType(models.TokenTypeRParen) {
return nil, p.expectedError(")")
}
p.advance() // Consume )
} else if p.isType(models.TokenTypeFrom) {
p.advance() // Consume FROM
partDef.Type = "FROM TO"
// Parse FROM value
if !p.isType(models.TokenTypeLParen) {
return nil, p.expectedError("(")
}
p.advance() // Consume (
fromExpr, err := p.parseExpression()
if err != nil {
return nil, err
}
partDef.From = fromExpr
if !p.isType(models.TokenTypeRParen) {
return nil, p.expectedError(")")
}
p.advance() // Consume )
// Expect TO
if !p.isType(models.TokenTypeTo) {
return nil, p.expectedError("TO")
}
p.advance() // Consume TO
// Parse TO value
if !p.isType(models.TokenTypeLParen) {
return nil, p.expectedError("(")
}
p.advance() // Consume (
toExpr, err := p.parseExpression()
if err != nil {
return nil, err
}
partDef.To = toExpr
if !p.isType(models.TokenTypeRParen) {
return nil, p.expectedError(")")
}
p.advance() // Consume )
}
// Parse optional TABLESPACE
if p.isTokenMatch("TABLESPACE") {
p.advance() // Consume TABLESPACE
if !p.isIdentifier() {
return nil, p.expectedError("tablespace name")
}
partDef.Tablespace = p.currentToken.Token.Value
p.advance()
}
return partDef, nil
}
// parseDropStatement parses DROP statements (TABLE, VIEW, MATERIALIZED VIEW, INDEX)
func (p *Parser) parseDropStatement() (*ast.DropStatement, error) {
stmt := &ast.DropStatement{}
// Determine object type
if p.isType(models.TokenTypeMaterialized) {
p.advance() // Consume MATERIALIZED
if !p.isType(models.TokenTypeView) {
return nil, p.expectedError("VIEW after MATERIALIZED")
}
p.advance() // Consume VIEW
stmt.ObjectType = "MATERIALIZED VIEW"
} else if p.isType(models.TokenTypeView) {
p.advance() // Consume VIEW
stmt.ObjectType = "VIEW"
} else if p.isType(models.TokenTypeTable) {
p.advance() // Consume TABLE
stmt.ObjectType = "TABLE"
} else if p.isType(models.TokenTypeIndex) {
p.advance() // Consume INDEX
stmt.ObjectType = "INDEX"
} else {
return nil, p.expectedError("TABLE, VIEW, MATERIALIZED VIEW, or INDEX after DROP")
}
// Check for IF EXISTS
if p.isType(models.TokenTypeIf) {
p.advance() // Consume IF
if !p.isType(models.TokenTypeExists) {
return nil, p.expectedError("EXISTS after IF")
}
p.advance() // Consume EXISTS
stmt.IfExists = true
}
// Parse object names (can be comma-separated, supports schema.name qualification)
for {
dropName, err := p.parseQualifiedName()
if err != nil {
return nil, p.expectedError("object name")
}
stmt.Names = append(stmt.Names, dropName)
if p.isType(models.TokenTypeComma) {
p.advance() // Consume comma
continue
}
break
}
// Parse optional CASCADE/RESTRICT
if p.isType(models.TokenTypeCascade) {
stmt.CascadeType = "CASCADE"
p.advance()
} else if p.isType(models.TokenTypeRestrict) {
stmt.CascadeType = "RESTRICT"
p.advance()
}
return stmt, nil
}
// parseTruncateStatement parses TRUNCATE TABLE statement
// Syntax: TRUNCATE [TABLE] table_name [, table_name ...] [RESTART IDENTITY | CONTINUE IDENTITY] [CASCADE | RESTRICT]
func (p *Parser) parseTruncateStatement() (*ast.TruncateStatement, error) {
stmt := &ast.TruncateStatement{}
// Optional TABLE keyword
if p.isType(models.TokenTypeTable) {
p.advance() // Consume TABLE
}
// Parse table names (can be comma-separated, supports schema.table qualification)
for {
truncTableName, err := p.parseQualifiedName()
if err != nil {
return nil, p.expectedError("table name")
}
stmt.Tables = append(stmt.Tables, truncTableName)
if p.isType(models.TokenTypeComma) {
p.advance() // Consume comma
continue
}
break
}
// Parse optional RESTART IDENTITY / CONTINUE IDENTITY
if p.isTokenMatch("RESTART") {
p.advance() // Consume RESTART
if !p.isTokenMatch("IDENTITY") {
return nil, p.expectedError("IDENTITY after RESTART")
}
p.advance() // Consume IDENTITY
stmt.RestartIdentity = true
} else if p.isTokenMatch("CONTINUE") {
p.advance() // Consume CONTINUE
if !p.isTokenMatch("IDENTITY") {
return nil, p.expectedError("IDENTITY after CONTINUE")
}
p.advance() // Consume IDENTITY
stmt.ContinueIdentity = true
}
// Parse optional CASCADE/RESTRICT
if p.isType(models.TokenTypeCascade) {
stmt.CascadeType = "CASCADE"
p.advance()
} else if p.isType(models.TokenTypeRestrict) {
stmt.CascadeType = "RESTRICT"
p.advance()
}
return stmt, nil
}
// skipClickHouseClauseExpr consumes the expression following a ClickHouse
// CREATE TABLE trailing clause (ORDER BY, PARTITION BY, PRIMARY KEY, SAMPLE BY).
// We do not currently model these clauses on the AST; this just walks the
// tokens until the start of the next clause, EOF, or ';'. Supports both
// parenthesised lists and bare expressions.
func (p *Parser) skipClickHouseClauseExpr() error {
if p.isType(models.TokenTypeLParen) {
// Balanced paren block.
depth := 0
for {
switch p.currentToken.Token.Type {
case models.TokenTypeEOF:
return p.expectedError(") to close clause expression")
case models.TokenTypeLParen:
depth++
p.advance()
case models.TokenTypeRParen:
depth--
p.advance()
if depth == 0 {
return nil
}
default:
p.advance()
}
}
}
// Bare expression: consume until next clause/EOF/;.
for {
t := p.currentToken.Token.Type
if t == models.TokenTypeEOF || t == models.TokenTypeSemicolon {
return nil
}
// Stop at next CH trailing-clause keyword.
if t == models.TokenTypeOrder || t == models.TokenTypePrimary {
return nil
}
val := strings.ToUpper(p.currentToken.Token.Value)
if val == "PARTITION" || val == "SAMPLE" || val == "SETTINGS" || val == "TTL" {
return nil
}
p.advance()
}
}