-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathdml.go
More file actions
711 lines (617 loc) · 19.1 KB
/
dml.go
File metadata and controls
711 lines (617 loc) · 19.1 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
// Package parser - dml.go
// DML statement parsing: INSERT, UPDATE, DELETE, MERGE (SQL:2003).
package parser
import (
"fmt"
"strings"
goerrors "github.com/ajitpratap0/GoSQLX/pkg/errors"
"github.com/ajitpratap0/GoSQLX/pkg/models"
"github.com/ajitpratap0/GoSQLX/pkg/sql/ast"
)
// parseInsertStatement parses an INSERT statement
func (p *Parser) parseInsertStatement() (ast.Statement, error) {
// We've already consumed the INSERT token in matchType
// Parse INTO
if !p.isType(models.TokenTypeInto) {
return nil, p.expectedError("INTO")
}
p.advance() // Consume INTO
// Parse table name (supports schema.table qualification and double-quoted identifiers)
tableName, err := p.parseQualifiedName()
if err != nil {
return nil, p.expectedError("table name")
}
// Parse column list if present
columns := make([]ast.Expression, 0)
if p.isType(models.TokenTypeLParen) {
p.advance() // Consume (
for {
// Parse column name (supports double-quoted identifiers)
if !p.isIdentifier() {
return nil, p.expectedError("column name")
}
columns = append(columns, &ast.Identifier{Name: p.currentToken.Literal})
p.advance()
// Check if there are more columns
if !p.isType(models.TokenTypeComma) {
break
}
p.advance() // Consume comma
}
if !p.isType(models.TokenTypeRParen) {
return nil, p.expectedError(")")
}
p.advance() // Consume )
}
// Parse VALUES or SELECT
var values [][]ast.Expression
var query ast.Statement
if p.isType(models.TokenTypeSelect) {
// INSERT ... SELECT syntax
p.advance() // Consume SELECT
stmt, err := p.parseSelectWithSetOperations()
if err != nil {
return nil, err
}
query = stmt
} else if p.isType(models.TokenTypeValues) {
p.advance() // Consume VALUES
// Parse value rows - supports multi-row INSERT: VALUES (a, b), (c, d), (e, f)
values = make([][]ast.Expression, 0)
for {
if !p.isType(models.TokenTypeLParen) {
if len(values) == 0 {
return nil, p.expectedError("(")
}
break
}
p.advance() // Consume (
// Parse one row of values
row := make([]ast.Expression, 0)
for {
// Parse value using parseExpression to support all expression types
// including function calls like NOW(), UUID(), etc.
expr, err := p.parseExpression()
if err != nil {
return nil, fmt.Errorf("failed to parse value at position %d in VALUES row %d: %w", len(row)+1, len(values)+1, err)
}
row = append(row, expr)
// Check if there are more values in this row
if !p.isType(models.TokenTypeComma) {
break
}
p.advance() // Consume comma
}
if !p.isType(models.TokenTypeRParen) {
return nil, p.expectedError(")")
}
p.advance() // Consume )
values = append(values, row)
// Check if there are more rows (comma after closing paren)
if !p.isType(models.TokenTypeComma) {
break
}
p.advance() // Consume comma between rows
}
} else {
return nil, p.expectedError("VALUES or SELECT")
}
// Parse ON CONFLICT clause if present (PostgreSQL UPSERT)
var onConflict *ast.OnConflict
if p.isType(models.TokenTypeOn) {
// Peek ahead to check for CONFLICT
if p.peekToken().Literal == "CONFLICT" {
p.advance() // Consume ON
p.advance() // Consume CONFLICT
var err error
onConflict, err = p.parseOnConflictClause()
if err != nil {
return nil, err
}
}
}
// Parse RETURNING clause if present (PostgreSQL)
var returning []ast.Expression
if p.isType(models.TokenTypeReturning) || p.currentToken.Literal == "RETURNING" {
p.advance() // Consume RETURNING
var err error
returning, err = p.parseReturningColumns()
if err != nil {
return nil, err
}
}
// Create INSERT statement
return &ast.InsertStatement{
TableName: tableName,
Columns: columns,
Values: values,
Query: query,
OnConflict: onConflict,
Returning: returning,
}, nil
}
// parseUpdateStatement parses an UPDATE statement
func (p *Parser) parseUpdateStatement() (ast.Statement, error) {
// We've already consumed the UPDATE token in matchType
// Parse table name (supports schema.table qualification and double-quoted identifiers)
tableName, err := p.parseQualifiedName()
if err != nil {
return nil, p.expectedError("table name")
}
// Parse SET
if !p.isType(models.TokenTypeSet) {
return nil, p.expectedError("SET")
}
p.advance() // Consume SET
// Parse assignments
updates := make([]ast.UpdateExpression, 0)
for {
// Parse column name (supports double-quoted identifiers)
if !p.isIdentifier() {
return nil, p.expectedError("column name")
}
columnName := p.currentToken.Literal
p.advance()
if !p.isType(models.TokenTypeEq) {
return nil, p.expectedError("=")
}
p.advance() // Consume =
// Parse value expression
var expr ast.Expression
if p.isStringLiteral() {
expr = &ast.LiteralValue{Value: p.currentToken.Literal, Type: "string"}
p.advance()
} else if p.isNumericLiteral() {
litType := "int"
if strings.ContainsAny(p.currentToken.Literal, ".eE") {
litType = "float"
}
expr = &ast.LiteralValue{Value: p.currentToken.Literal, Type: litType}
p.advance()
} else if p.isBooleanLiteral() {
expr = &ast.LiteralValue{Value: p.currentToken.Literal, Type: "bool"}
p.advance()
} else {
var err error
expr, err = p.parseExpression()
if err != nil {
return nil, err
}
}
// Create update expression
columnExpr := &ast.Identifier{Name: columnName}
updateExpr := ast.UpdateExpression{
Column: columnExpr,
Value: expr,
}
updates = append(updates, updateExpr)
// Check if there are more assignments
if !p.isType(models.TokenTypeComma) {
break
}
p.advance() // Consume comma
}
// Parse WHERE clause if present
var whereClause ast.Expression
if p.isType(models.TokenTypeWhere) {
p.advance() // Consume WHERE
var err error
whereClause, err = p.parseExpression()
if err != nil {
return nil, err
}
}
// Parse RETURNING clause if present (PostgreSQL)
var returning []ast.Expression
if p.isType(models.TokenTypeReturning) || p.currentToken.Literal == "RETURNING" {
p.advance() // Consume RETURNING
var err error
returning, err = p.parseReturningColumns()
if err != nil {
return nil, err
}
}
// Create UPDATE statement
return &ast.UpdateStatement{
TableName: tableName,
Assignments: updates,
Where: whereClause,
Returning: returning,
}, nil
}
// parseDeleteStatement parses a DELETE statement
func (p *Parser) parseDeleteStatement() (ast.Statement, error) {
// We've already consumed the DELETE token in matchType
// Parse FROM
if !p.isType(models.TokenTypeFrom) {
return nil, p.expectedError("FROM")
}
p.advance() // Consume FROM
// Parse table name (supports schema.table qualification and double-quoted identifiers)
tableName, err := p.parseQualifiedName()
if err != nil {
return nil, p.expectedError("table name")
}
// Parse WHERE clause if present
var whereClause ast.Expression
if p.isType(models.TokenTypeWhere) {
p.advance() // Consume WHERE
var err error
whereClause, err = p.parseExpression()
if err != nil {
return nil, err
}
}
// Parse RETURNING clause if present (PostgreSQL)
var returning []ast.Expression
if p.isType(models.TokenTypeReturning) || p.currentToken.Literal == "RETURNING" {
p.advance() // Consume RETURNING
var err error
returning, err = p.parseReturningColumns()
if err != nil {
return nil, err
}
}
// Create DELETE statement
return &ast.DeleteStatement{
TableName: tableName,
Where: whereClause,
Returning: returning,
}, nil
}
// parseMergeStatement parses a MERGE statement (SQL:2003 F312)
// Syntax: MERGE INTO target [AS alias] USING source [AS alias] ON condition
//
// WHEN MATCHED [AND condition] THEN UPDATE/DELETE
// WHEN NOT MATCHED [AND condition] THEN INSERT
// WHEN NOT MATCHED BY SOURCE [AND condition] THEN UPDATE/DELETE
func (p *Parser) parseMergeStatement() (ast.Statement, error) {
stmt := &ast.MergeStatement{}
// Parse INTO (optional)
if p.isType(models.TokenTypeInto) {
p.advance() // Consume INTO
}
// Parse target table
tableRef, err := p.parseTableReference()
if err != nil {
return nil, goerrors.WrapError(goerrors.ErrCodeInvalidSyntax, "error parsing MERGE target table", models.Location{}, "", err)
}
stmt.TargetTable = *tableRef
// Parse optional target alias (AS alias or just alias)
if p.isType(models.TokenTypeAs) {
p.advance() // Consume AS
if !p.isIdentifier() && !p.isNonReservedKeyword() {
return nil, p.expectedError("target alias after AS")
}
stmt.TargetAlias = p.currentToken.Literal
p.advance()
} else if p.canBeAlias() && !p.isType(models.TokenTypeUsing) && p.currentToken.Literal != "USING" {
stmt.TargetAlias = p.currentToken.Literal
p.advance()
}
// Parse USING
if !p.isType(models.TokenTypeUsing) && p.currentToken.Literal != "USING" {
return nil, p.expectedError("USING")
}
p.advance() // Consume USING
// Parse source table (could be a table or subquery)
sourceRef, err := p.parseTableReference()
if err != nil {
return nil, goerrors.WrapError(goerrors.ErrCodeInvalidSyntax, "error parsing MERGE source", models.Location{}, "", err)
}
stmt.SourceTable = *sourceRef
// Parse optional source alias
if p.isType(models.TokenTypeAs) {
p.advance() // Consume AS
if !p.isIdentifier() && !p.isNonReservedKeyword() {
return nil, p.expectedError("source alias after AS")
}
stmt.SourceAlias = p.currentToken.Literal
p.advance()
} else if p.canBeAlias() && !p.isType(models.TokenTypeOn) && p.currentToken.Literal != "ON" {
stmt.SourceAlias = p.currentToken.Literal
p.advance()
}
// Parse ON condition
if !p.isType(models.TokenTypeOn) {
return nil, p.expectedError("ON")
}
p.advance() // Consume ON
onCondition, err := p.parseExpression()
if err != nil {
return nil, goerrors.WrapError(goerrors.ErrCodeInvalidSyntax, "error parsing MERGE ON condition", models.Location{}, "", err)
}
stmt.OnCondition = onCondition
// Parse WHEN clauses
for p.isType(models.TokenTypeWhen) {
whenClause, err := p.parseMergeWhenClause()
if err != nil {
return nil, err
}
stmt.WhenClauses = append(stmt.WhenClauses, whenClause)
}
if len(stmt.WhenClauses) == 0 {
return nil, goerrors.MissingClauseError("WHEN", models.Location{}, "")
}
return stmt, nil
}
// parseMergeWhenClause parses a WHEN clause in a MERGE statement
func (p *Parser) parseMergeWhenClause() (*ast.MergeWhenClause, error) {
clause := &ast.MergeWhenClause{}
p.advance() // Consume WHEN
// Determine clause type: MATCHED, NOT MATCHED, NOT MATCHED BY SOURCE
if p.isType(models.TokenTypeMatched) || p.currentToken.Literal == "MATCHED" {
clause.Type = "MATCHED"
p.advance() // Consume MATCHED
} else if p.isType(models.TokenTypeNot) {
p.advance() // Consume NOT
if !p.isType(models.TokenTypeMatched) && p.currentToken.Literal != "MATCHED" {
return nil, p.expectedError("MATCHED after NOT")
}
p.advance() // Consume MATCHED
// Check for BY SOURCE
if p.isType(models.TokenTypeBy) {
p.advance() // Consume BY
if !p.isType(models.TokenTypeSource) && p.currentToken.Literal != "SOURCE" {
return nil, p.expectedError("SOURCE after BY")
}
p.advance() // Consume SOURCE
clause.Type = "NOT_MATCHED_BY_SOURCE"
} else {
clause.Type = "NOT_MATCHED"
}
} else {
return nil, p.expectedError("MATCHED or NOT MATCHED")
}
// Parse optional AND condition
if p.isType(models.TokenTypeAnd) {
p.advance() // Consume AND
condition, err := p.parseExpression()
if err != nil {
return nil, goerrors.WrapError(goerrors.ErrCodeInvalidSyntax, "error parsing WHEN condition", models.Location{}, "", err)
}
clause.Condition = condition
}
// Parse THEN
if !p.isType(models.TokenTypeThen) {
return nil, p.expectedError("THEN")
}
p.advance() // Consume THEN
// Parse action (UPDATE, INSERT, DELETE)
action, err := p.parseMergeAction(clause.Type)
if err != nil {
return nil, err
}
clause.Action = action
return clause, nil
}
// parseMergeAction parses the action in a WHEN clause
func (p *Parser) parseMergeAction(clauseType string) (*ast.MergeAction, error) {
action := &ast.MergeAction{}
if p.isType(models.TokenTypeUpdate) {
action.ActionType = "UPDATE"
p.advance() // Consume UPDATE
// Parse SET
if !p.isType(models.TokenTypeSet) {
return nil, p.expectedError("SET after UPDATE")
}
p.advance() // Consume SET
// Parse SET clauses
for {
if !p.isIdentifier() && !p.canBeAlias() {
return nil, p.expectedError("column name")
}
// Handle qualified column names (e.g., t.name)
columnName := p.currentToken.Literal
p.advance()
// Check for qualified name (table.column)
if p.isType(models.TokenTypePeriod) {
p.advance() // Consume .
if !p.isIdentifier() && !p.canBeAlias() {
return nil, p.expectedError("column name after .")
}
columnName = columnName + "." + p.currentToken.Literal
p.advance()
}
setClause := ast.SetClause{Column: columnName}
if !p.isType(models.TokenTypeEq) {
return nil, p.expectedError("=")
}
p.advance() // Consume =
value, err := p.parseExpression()
if err != nil {
return nil, goerrors.WrapError(goerrors.ErrCodeInvalidSyntax, "error parsing SET value", models.Location{}, "", err)
}
setClause.Value = value
action.SetClauses = append(action.SetClauses, setClause)
if !p.isType(models.TokenTypeComma) {
break
}
p.advance() // Consume comma
}
} else if p.isType(models.TokenTypeInsert) {
if clauseType == "MATCHED" || clauseType == "NOT_MATCHED_BY_SOURCE" {
return nil, goerrors.InvalidSyntaxError(fmt.Sprintf("INSERT not allowed in WHEN %s clause", clauseType), models.Location{}, "")
}
action.ActionType = "INSERT"
p.advance() // Consume INSERT
// Parse optional column list
if p.isType(models.TokenTypeLParen) {
p.advance() // Consume (
for {
if !p.isIdentifier() {
return nil, p.expectedError("column name")
}
action.Columns = append(action.Columns, p.currentToken.Literal)
p.advance()
if !p.isType(models.TokenTypeComma) {
break
}
p.advance() // Consume comma
}
if !p.isType(models.TokenTypeRParen) {
return nil, p.expectedError(")")
}
p.advance() // Consume )
}
// Parse VALUES or DEFAULT VALUES
if p.isType(models.TokenTypeDefault) {
p.advance() // Consume DEFAULT
if !p.isType(models.TokenTypeValues) {
return nil, p.expectedError("VALUES after DEFAULT")
}
p.advance() // Consume VALUES
action.DefaultValues = true
} else if p.isType(models.TokenTypeValues) {
p.advance() // Consume VALUES
if !p.isType(models.TokenTypeLParen) {
return nil, p.expectedError("(")
}
p.advance() // Consume (
for {
value, err := p.parseExpression()
if err != nil {
return nil, goerrors.WrapError(goerrors.ErrCodeInvalidSyntax, "error parsing INSERT value", models.Location{}, "", err)
}
action.Values = append(action.Values, value)
if !p.isType(models.TokenTypeComma) {
break
}
p.advance() // Consume comma
}
if !p.isType(models.TokenTypeRParen) {
return nil, p.expectedError(")")
}
p.advance() // Consume )
} else {
return nil, p.expectedError("VALUES or DEFAULT VALUES")
}
} else if p.isType(models.TokenTypeDelete) {
if clauseType == "NOT_MATCHED" {
return nil, goerrors.InvalidSyntaxError("DELETE not allowed in WHEN NOT MATCHED clause", models.Location{}, "")
}
action.ActionType = "DELETE"
p.advance() // Consume DELETE
} else {
return nil, p.expectedError("UPDATE, INSERT, or DELETE")
}
return action, nil
}
// parseReturningColumns parses the columns in a RETURNING clause
// Supports: column names, *, qualified names (table.column), expressions
func (p *Parser) parseReturningColumns() ([]ast.Expression, error) {
var columns []ast.Expression
for {
// Check for * (return all columns)
if p.isType(models.TokenTypeMul) {
columns = append(columns, &ast.Identifier{Name: "*"})
p.advance()
} else {
// Parse expression (can be column name, qualified name, or expression)
expr, err := p.parseExpression()
if err != nil {
return nil, fmt.Errorf("failed to parse RETURNING column: %w", err)
}
columns = append(columns, expr)
}
// Check for comma to continue parsing more columns
if !p.isType(models.TokenTypeComma) {
break
}
p.advance() // Consume comma
}
return columns, nil
}
// parseOnConflictClause parses the ON CONFLICT clause (PostgreSQL UPSERT)
// Syntax: ON CONFLICT [(columns)] | ON CONSTRAINT name DO NOTHING | DO UPDATE SET ...
func (p *Parser) parseOnConflictClause() (*ast.OnConflict, error) {
onConflict := &ast.OnConflict{}
// Parse optional conflict target: (column_list) or ON CONSTRAINT constraint_name
if p.isType(models.TokenTypeLParen) {
p.advance() // Consume (
var targets []ast.Expression
for {
if !p.isIdentifier() {
return nil, p.expectedError("column name in ON CONFLICT target")
}
targets = append(targets, &ast.Identifier{Name: p.currentToken.Literal})
p.advance()
if !p.isType(models.TokenTypeComma) {
break
}
p.advance() // Consume comma
}
if !p.isType(models.TokenTypeRParen) {
return nil, p.expectedError(")")
}
p.advance() // Consume )
onConflict.Target = targets
} else if p.isType(models.TokenTypeOn) && p.peekToken().Literal == "CONSTRAINT" {
// ON CONSTRAINT constraint_name
p.advance() // Consume ON
p.advance() // Consume CONSTRAINT
if !p.isIdentifier() {
return nil, p.expectedError("constraint name")
}
onConflict.Constraint = p.currentToken.Literal
p.advance()
}
// Parse DO keyword
if p.currentToken.Literal != "DO" {
return nil, p.expectedError("DO")
}
p.advance() // Consume DO
// Parse action: NOTHING or UPDATE
if p.currentToken.Literal == "NOTHING" {
onConflict.Action = ast.OnConflictAction{DoNothing: true}
p.advance() // Consume NOTHING
} else if p.isType(models.TokenTypeUpdate) {
p.advance() // Consume UPDATE
// Parse SET keyword
if !p.isType(models.TokenTypeSet) {
return nil, p.expectedError("SET")
}
p.advance() // Consume SET
// Parse update assignments
var updates []ast.UpdateExpression
for {
if !p.isIdentifier() {
return nil, p.expectedError("column name")
}
columnName := p.currentToken.Literal
p.advance()
if !p.isType(models.TokenTypeEq) {
return nil, p.expectedError("=")
}
p.advance() // Consume =
// Parse value expression (supports EXCLUDED.column references)
value, err := p.parseExpression()
if err != nil {
return nil, fmt.Errorf("failed to parse ON CONFLICT UPDATE value: %w", err)
}
updates = append(updates, ast.UpdateExpression{
Column: &ast.Identifier{Name: columnName},
Value: value,
})
if !p.isType(models.TokenTypeComma) {
break
}
p.advance() // Consume comma
}
onConflict.Action.DoUpdate = updates
// Parse optional WHERE clause
if p.isType(models.TokenTypeWhere) {
p.advance() // Consume WHERE
where, err := p.parseExpression()
if err != nil {
return nil, fmt.Errorf("failed to parse ON CONFLICT WHERE clause: %w", err)
}
onConflict.Action.Where = where
}
} else {
return nil, p.expectedError("NOTHING or UPDATE")
}
return onConflict, nil
}
// parseTableReference parses a simple table reference (table name)
// Returns a TableReference with the Name field populated