alopex-sql 0.6.0

SQL parser components for the Alopex DB dialect
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
## SQL Parser for Alopex DB
##
## Recursive-descent parser that converts token stream into the Nim AST.

import std/strutils
import lexer, ast

type
  Parser* = object
    lex: Lexer
    current: Token
    errors*: seq[string]

  ParseError* = object of CatchableError

const
  ClauseTerminators = {tkWhere, tkOrder, tkGroup, tkHaving, tkLimit, tkOffset,
                       tkJoin, tkInner, tkLeft, tkRight, tkFull, tkCross,
                       tkNatural, tkUsing, tkOn}
  TypeTokens = {tkInt, tkBigint, tkSmallint, tkFloatType, tkDouble, tkDecimal,
                tkVarchar, tkChar, tkText, tkBlob, tkBoolean, tkBool,
                tkTimestamp, tkDate, tkTime, tkVector}
  OptionValueTokens = {tkIdent, tkString, tkInteger, tkFloat, tkHnsw, tkBtree,
                       tkCosine, tkL2, tkInner, tkText, tkBoolean, tkBool}

proc initParser*(input: string): Parser =
  result.lex = initLexer(input)
  result.current = result.lex.nextToken()

proc tokenSpan(tok: Token): Span =
  let width = max(tok.value.len, 1)
  newSpan(tok.line, tok.col, tok.col + width - 1)

proc currentSpan(p: Parser): Span =
  tokenSpan(p.current)

proc error(p: var Parser, msg: string) =
  let errMsg = "Parse error at line " & $p.current.line & ", col " & $p.current.col &
    ": " & msg & " (got " & $p.current.kind & " '" & p.current.value & "')"
  p.errors.add(errMsg)
  raise newException(ParseError, errMsg)

proc advance(p: var Parser): Token =
  result = p.current
  p.current = p.lex.nextToken()

proc expect(p: var Parser, kind: TokenKind): Token =
  if p.current.kind != kind:
    p.error("expected " & $kind)
  result = p.advance()

proc check(p: Parser, kind: TokenKind): bool =
  p.current.kind == kind

proc expectIdent(p: var Parser; context = "identifier"): Token =
  if p.current.kind != tkIdent:
    p.error("expected " & context)
  result = p.advance()

proc expectOptionValue(p: var Parser): Token =
  if p.current.kind notin OptionValueTokens:
    p.error("expected option value")
  result = p.advance()

proc makeAlias(expr: SqlNode, alias: string; span: Span = emptySpan()): SqlNode =
  SqlNode(kind: nkAlias, aliasExpr: expr, aliasName: alias, span: span,
          orderAsc: -1, nullsFirst: -1)

# Forward declarations
proc parseExpr(p: var Parser): SqlNode
proc parseSelectStmt(p: var Parser): SqlNode
proc parseInsertStmt(p: var Parser): SqlNode
proc parseUpdateStmt(p: var Parser): SqlNode
proc parseDeleteStmt(p: var Parser): SqlNode
proc parseCreateStmt(p: var Parser): SqlNode
proc parseDropStmt(p: var Parser): SqlNode
proc parseTypeName(p: var Parser): SqlNode

# --- Expression parsing (precedence climbing) ---

proc parseVectorLiteral(p: var Parser): SqlNode =
  let start = p.expect(tkLBracket)
  result = newNode(nkVectorLiteral, tokenSpan(start))
  var sawValue = false
  while not p.check(tkRBracket):
    var sign = 1.0
    if p.check(tkMinus):
      discard p.advance()
      sign = -1.0
    if p.current.kind notin {tkInteger, tkFloat}:
      p.error("expected vector numeric literal")
    let tok = p.advance()
    let value = if tok.kind == tkFloat: parseFloat(tok.value) else: parseFloat(tok.value)
    result.children.add(newFloatLit(value * sign, tokenSpan(tok)))
    sawValue = true
    if p.check(tkComma):
      discard p.advance()
    elif not p.check(tkRBracket):
      p.error("expected ',' or ']' in vector literal")
  if not sawValue:
    p.error("vector literal cannot be empty")
  discard p.expect(tkRBracket)

proc parseSubqueryInParens(p: var Parser): SqlNode =
  discard p.expect(tkLParen)
  if not p.check(tkSelect):
    p.error("expected SELECT subquery")
  result = p.parseSelectStmt()
  discard p.expect(tkRParen)

proc parseExistsExpr(p: var Parser; negated: bool): SqlNode =
  let tok = p.expect(tkExists)
  result = newNode(nkExists, tokenSpan(tok))
  result.negated = negated
  result.children.add(p.parseSubqueryInParens())

proc parseFunctionCall(p: var Parser; nameTok: Token): SqlNode =
  result = newNode(nkFunctionCall, tokenSpan(nameTok))
  result.children.add(newIdent(nameTok.value, tokenSpan(nameTok)))
  discard p.expect(tkLParen)
  if not p.check(tkRParen):
    if p.check(tkStar):
      result.funcStar = true
      result.children.add(newStar(tokenSpan(p.advance())))
    else:
      if p.check(tkDistinct):
        result.funcDistinct = true
        discard p.advance()
      result.children.add(p.parseExpr())
      while p.check(tkComma):
        discard p.advance()
        result.children.add(p.parseExpr())
  discard p.expect(tkRParen)

proc parseCastExpr(p: var Parser): SqlNode =
  let tok = p.expect(tkCast)
  result = newNode(nkFunctionCall, tokenSpan(tok))
  result.children.add(newIdent("CAST", tokenSpan(tok)))
  discard p.expect(tkLParen)
  result.children.add(p.parseExpr())
  discard p.expect(tkAs)
  result.children.add(p.parseTypeName())
  discard p.expect(tkRParen)

proc parsePrimary(p: var Parser): SqlNode =
  case p.current.kind
  of tkInteger:
    let tok = p.advance()
    result = newIntLit(parseBiggestInt(tok.value), tokenSpan(tok))
  of tkFloat:
    let tok = p.advance()
    result = newFloatLit(parseFloat(tok.value), tokenSpan(tok))
  of tkString:
    let tok = p.advance()
    result = newStringLit(tok.value, tokenSpan(tok))
  of tkTrue:
    let tok = p.advance()
    result = newBoolLit(true, tokenSpan(tok))
  of tkFalse:
    let tok = p.advance()
    result = newBoolLit(false, tokenSpan(tok))
  of tkNull:
    let tok = p.advance()
    result = newNull(tokenSpan(tok))
  of tkStar:
    let tok = p.advance()
    result = newStar(tokenSpan(tok))
  of tkLBracket:
    result = p.parseVectorLiteral()
  of tkLParen:
    let start = p.advance()
    if p.check(tkSelect):
      let subquery = p.parseSelectStmt()
      discard p.expect(tkRParen)
      result = newNode(nkScalarSubquery, tokenSpan(start))
      result.children.add(subquery)
    else:
      result = p.parseExpr()
      discard p.expect(tkRParen)
  of tkExists:
    result = p.parseExistsExpr(false)
  of tkCast:
    result = p.parseCastExpr()
  of tkNot:
    discard p.advance()
    if p.check(tkExists):
      result = p.parseExistsExpr(true)
    else:
      result = newUnaryOp(opNot, p.parsePrimary())
  of tkMinus:
    let tok = p.advance()
    result = newUnaryOp(opNeg, p.parsePrimary(), tokenSpan(tok))
  of tkIdent:
    let tok = p.advance()
    if p.check(tkLParen):
      result = p.parseFunctionCall(tok)
    elif p.check(tkDot):
      discard p.advance()
      let col = p.expectIdent("column name")
      result = newNode(nkColumnRef, tokenSpan(tok))
      result.children.add(newIdent(tok.value, tokenSpan(tok)))
      result.children.add(newIdent(col.value, tokenSpan(col)))
    else:
      result = newIdent(tok.value, tokenSpan(tok))
  of tkNow, tkVector:
    let tok = p.advance()
    if p.check(tkLParen):
      result = p.parseFunctionCall(tok)
    else:
      p.error("expected function call")
  else:
    p.error("unexpected token in expression")

proc parseMulDiv(p: var Parser): SqlNode =
  result = p.parsePrimary()
  while p.current.kind in {tkStar, tkSlash, tkPercent}:
    let op = case p.current.kind
      of tkStar: opMul
      of tkSlash: opDiv
      of tkPercent: opMod
      else: opMul
    discard p.advance()
    result = newBinaryOp(op, result, p.parsePrimary())

proc parseAddSub(p: var Parser): SqlNode =
  result = p.parseMulDiv()
  while p.current.kind in {tkPlus, tkMinus}:
    let op = if p.current.kind == tkPlus: opAdd else: opSub
    discard p.advance()
    result = newBinaryOp(op, result, p.parseMulDiv())

proc parseConcat(p: var Parser): SqlNode =
  result = p.parseAddSub()
  while p.check(tkPipePipe):
    discard p.advance()
    result = newBinaryOp(opStringConcat, result, p.parseAddSub())

proc comparisonOp(kind: TokenKind): BinaryOpKind =
  case kind
  of tkEq: opEq
  of tkNeq: opNeq
  of tkLt: opLt
  of tkLe: opLe
  of tkGt: opGt
  of tkGe: opGe
  else: opEq

proc parseQuantified(p: var Parser; left: SqlNode; op: BinaryOpKind): SqlNode =
  let quantTok = p.advance()
  result = newNode(nkQuantified, tokenSpan(quantTok))
  result.quantifier = if quantTok.kind == tkAll: qkAll else: qkAny
  result.children.add(left)
  result.children.add(newIdent($op, tokenSpan(quantTok)))
  result.children.add(p.parseSubqueryInParens())

proc parseInExpr(p: var Parser; left: SqlNode; negated: bool): SqlNode =
  discard p.expect(tkIn)
  discard p.expect(tkLParen)
  if p.check(tkSelect):
    result = newNode(nkInSubquery)
    result.negated = negated
    result.children.add(left)
    result.children.add(p.parseSelectStmt())
    discard p.expect(tkRParen)
  else:
    let list = newNode(nkExprList)
    if not p.check(tkRParen):
      list.children.add(p.parseExpr())
      while p.check(tkComma):
        discard p.advance()
        list.children.add(p.parseExpr())
    discard p.expect(tkRParen)
    result = newBinaryOp(if negated: opNotIn else: opIn, left, list)

proc parseComparison(p: var Parser): SqlNode =
  result = p.parseConcat()

  if p.check(tkNot):
    discard p.advance()
    if p.check(tkBetween):
      discard p.advance()
      let low = p.parseConcat()
      discard p.expect(tkAnd)
      let high = p.parseConcat()
      let range = newNode(nkExprList)
      range.children.add(low)
      range.children.add(high)
      result = newBinaryOp(opNotBetween, result, range)
    elif p.check(tkLike):
      discard p.advance()
      let pattern = p.parseConcat()
      if p.check(tkEscape):
        discard p.advance()
        let esc = p.parseConcat()
        let pair = newNode(nkExprList)
        pair.children.add(pattern)
        pair.children.add(esc)
        result = newBinaryOp(opNotLike, result, pair)
      else:
        result = newBinaryOp(opNotLike, result, pattern)
    elif p.check(tkIn):
      result = p.parseInExpr(result, true)
    else:
      result = newUnaryOp(opNot, result)
    return

  if p.check(tkIs):
    discard p.advance()
    if p.check(tkNot):
      discard p.advance()
      discard p.expect(tkNull)
      result = newUnaryOp(opIsNotNull, result)
    else:
      discard p.expect(tkNull)
      result = newUnaryOp(opIsNull, result)
    return

  if p.current.kind in {tkEq, tkNeq, tkLt, tkLe, tkGt, tkGe}:
    let op = comparisonOp(p.current.kind)
    discard p.advance()
    if p.current.kind in {tkAny, tkSome, tkAll}:
      result = p.parseQuantified(result, op)
    else:
      result = newBinaryOp(op, result, p.parseConcat())
  elif p.check(tkLike):
    discard p.advance()
    let pattern = p.parseConcat()
    if p.check(tkEscape):
      discard p.advance()
      let esc = p.parseConcat()
      let pair = newNode(nkExprList)
      pair.children.add(pattern)
      pair.children.add(esc)
      result = newBinaryOp(opLike, result, pair)
    else:
      result = newBinaryOp(opLike, result, pattern)
  elif p.check(tkIn):
    result = p.parseInExpr(result, false)
  elif p.check(tkBetween):
    discard p.advance()
    let low = p.parseConcat()
    discard p.expect(tkAnd)
    let high = p.parseConcat()
    let range = newNode(nkExprList)
    range.children.add(low)
    range.children.add(high)
    result = newBinaryOp(opBetween, result, range)

proc parseAndExpr(p: var Parser): SqlNode =
  result = p.parseComparison()
  while p.check(tkAnd):
    discard p.advance()
    result = newBinaryOp(opAnd, result, p.parseComparison())

proc parseExpr(p: var Parser): SqlNode =
  result = p.parseAndExpr()
  while p.check(tkOr):
    discard p.advance()
    result = newBinaryOp(opOr, result, p.parseAndExpr())

# --- SELECT / FROM parsing ---

proc parseSelectItem(p: var Parser): SqlNode =
  result = p.parseExpr()
  if p.check(tkAs):
    discard p.advance()
    let alias = p.expectIdent("alias")
    result = makeAlias(result, alias.value, tokenSpan(alias))
  elif p.check(tkIdent):
    let alias = p.advance()
    result = makeAlias(result, alias.value, tokenSpan(alias))

proc parseSelectList(p: var Parser): seq[SqlNode] =
  result.add(p.parseSelectItem())
  while p.check(tkComma):
    discard p.advance()
    result.add(p.parseSelectItem())

proc parseOptionalAlias(p: var Parser; item: SqlNode): SqlNode =
  result = item
  if p.check(tkAs):
    discard p.advance()
    let alias = p.expectIdent("alias")
    result = makeAlias(item, alias.value, tokenSpan(alias))
  elif p.check(tkIdent) and p.current.kind notin ClauseTerminators:
    let alias = p.advance()
    result = makeAlias(item, alias.value, tokenSpan(alias))

proc parseFromItem(p: var Parser): SqlNode =
  if p.check(tkLParen):
    let start = p.advance()
    if p.check(tkSelect):
      let subquery = p.parseSelectStmt()
      discard p.expect(tkRParen)
      result = newNode(nkFromDerived, tokenSpan(start))
      result.children.add(subquery)
      result = p.parseOptionalAlias(result)
    else:
      p.error("expected SELECT in FROM derived table")
  else:
    let name = p.expectIdent("table name")
    result = newIdent(name.value, tokenSpan(name))
    result = p.parseOptionalAlias(result)

proc parseUsingClause(p: var Parser): seq[string] =
  discard p.expect(tkUsing)
  discard p.expect(tkLParen)
  result.add(p.expectIdent("USING column").value)
  while p.check(tkComma):
    discard p.advance()
    result.add(p.expectIdent("USING column").value)
  discard p.expect(tkRParen)

proc parseFromClause(p: var Parser): SqlNode =
  result = newNode(nkFromClause, p.currentSpan())
  var item = p.parseFromItem()

  while p.current.kind in {tkNatural, tkJoin, tkInner, tkLeft, tkRight, tkFull, tkCross}:
    var natural = false
    if p.check(tkNatural):
      natural = true
      discard p.advance()

    var jk = jkInner
    case p.current.kind
    of tkInner:
      jk = jkInner
      discard p.advance()
      discard p.expect(tkJoin)
    of tkLeft:
      jk = jkLeft
      discard p.advance()
      if p.check(tkOuter): discard p.advance()
      discard p.expect(tkJoin)
    of tkRight:
      jk = jkRight
      discard p.advance()
      if p.check(tkOuter): discard p.advance()
      discard p.expect(tkJoin)
    of tkFull:
      jk = jkFull
      discard p.advance()
      if p.check(tkOuter): discard p.advance()
      discard p.expect(tkJoin)
    of tkCross:
      jk = jkCross
      discard p.advance()
      discard p.expect(tkJoin)
    of tkJoin:
      jk = jkInner
      discard p.advance()
    else:
      p.error("expected JOIN")

    let right = p.parseFromItem()
    var cond: SqlNode = nil
    var usingCols: seq[string] = @[]
    if p.check(tkOn):
      discard p.advance()
      cond = p.parseExpr()
    elif p.check(tkUsing):
      usingCols = p.parseUsingClause()
    item = newJoin(jk, item, right, cond, usingCols, natural)

  while p.check(tkComma):
    discard p.advance()
    let right = p.parseFromItem()
    item = newJoin(jkCross, item, right)

  result.children.add(item)

proc parseOrderByItem(p: var Parser): SqlNode =
  result = p.parseExpr()
  if p.check(tkAsc):
    let tok = p.advance()
    result = makeAlias(result, "ASC", tokenSpan(tok))
    result.orderAsc = 1
  elif p.check(tkDesc):
    let tok = p.advance()
    result = makeAlias(result, "DESC", tokenSpan(tok))
    result.orderAsc = 0
  if p.check(tkNulls):
    discard p.advance()
    if p.check(tkFirst):
      discard p.advance()
      result.nullsFirst = 1
    elif p.check(tkLast):
      discard p.advance()
      result.nullsFirst = 0
    else:
      p.error("expected FIRST or LAST after NULLS")

proc parseSelectStmt(p: var Parser): SqlNode =
  let start = p.expect(tkSelect)
  result = newNode(nkSelect, tokenSpan(start))

  if p.check(tkDistinct):
    discard p.advance()
    result.children.add(newIdent("DISTINCT"))

  let selectList = newNode(nkExprList)
  selectList.children = p.parseSelectList()
  result.children.add(selectList)

  if p.check(tkFrom):
    discard p.advance()
    result.children.add(p.parseFromClause())

  if p.check(tkWhere):
    discard p.advance()
    let whereNode = newNode(nkWhereClause)
    whereNode.children.add(p.parseExpr())
    result.children.add(whereNode)

  if p.check(tkGroup):
    discard p.advance()
    discard p.expect(tkBy)
    let groupBy = newNode(nkGroupByClause)
    groupBy.children.add(p.parseExpr())
    while p.check(tkComma):
      discard p.advance()
      groupBy.children.add(p.parseExpr())
    result.children.add(groupBy)

  if p.check(tkHaving):
    discard p.advance()
    let having = newNode(nkHavingClause)
    having.children.add(p.parseExpr())
    result.children.add(having)

  if p.check(tkOrder):
    discard p.advance()
    discard p.expect(tkBy)
    let orderBy = newNode(nkOrderByClause)
    orderBy.children.add(p.parseOrderByItem())
    while p.check(tkComma):
      discard p.advance()
      orderBy.children.add(p.parseOrderByItem())
    result.children.add(orderBy)

  if p.check(tkLimit):
    discard p.advance()
    let limitNode = newNode(nkLimitClause)
    limitNode.children.add(p.parseExpr())
    if p.check(tkOffset):
      discard p.advance()
      limitNode.children.add(p.parseExpr())
    result.children.add(limitNode)

# --- DML parsing ---

proc parseInsertStmt(p: var Parser): SqlNode =
  let start = p.expect(tkInsert)
  discard p.expect(tkInto)
  result = newNode(nkInsert, tokenSpan(start))
  let table = p.expectIdent("table name")
  result.children.add(newIdent(table.value, tokenSpan(table)))

  if p.check(tkLParen):
    discard p.advance()
    let cols = newNode(nkExprList)
    cols.children.add(newIdent(p.expectIdent("column name").value))
    while p.check(tkComma):
      discard p.advance()
      cols.children.add(newIdent(p.expectIdent("column name").value))
    discard p.expect(tkRParen)
    result.children.add(cols)

  discard p.expect(tkValues)
  while true:
    discard p.expect(tkLParen)
    let row = newNode(nkExprList)
    row.children.add(p.parseExpr())
    while p.check(tkComma):
      discard p.advance()
      row.children.add(p.parseExpr())
    discard p.expect(tkRParen)
    result.children.add(row)
    if p.check(tkComma):
      discard p.advance()
    else:
      break

proc parseUpdateStmt(p: var Parser): SqlNode =
  let start = p.expect(tkUpdate)
  result = newNode(nkUpdate, tokenSpan(start))
  let table = p.expectIdent("table name")
  result.children.add(newIdent(table.value, tokenSpan(table)))
  discard p.expect(tkSet)
  let setList = newNode(nkExprList)
  while true:
    let col = p.expectIdent("column name")
    discard p.expect(tkEq)
    setList.children.add(newBinaryOp(opEq, newIdent(col.value, tokenSpan(col)), p.parseExpr()))
    if p.check(tkComma):
      discard p.advance()
    else:
      break
  result.children.add(setList)
  if p.check(tkWhere):
    discard p.advance()
    let whereNode = newNode(nkWhereClause)
    whereNode.children.add(p.parseExpr())
    result.children.add(whereNode)

proc parseDeleteStmt(p: var Parser): SqlNode =
  let start = p.expect(tkDelete)
  discard p.expect(tkFrom)
  result = newNode(nkDelete, tokenSpan(start))
  let table = p.expectIdent("table name")
  result.children.add(newIdent(table.value, tokenSpan(table)))
  if p.check(tkWhere):
    discard p.advance()
    let whereNode = newNode(nkWhereClause)
    whereNode.children.add(p.parseExpr())
    result.children.add(whereNode)

# --- DDL parsing ---

proc parseTypeName(p: var Parser): SqlNode =
  if p.current.kind notin TypeTokens and p.current.kind != tkIdent:
    p.error("expected type name")
  let typeTok = p.advance()
  result = newNode(nkTypeName, tokenSpan(typeTok))
  result.children.add(newIdent(typeTok.value, tokenSpan(typeTok)))
  if p.check(tkLParen):
    discard p.advance()
    result.children.add(p.parseExpr())
    if p.check(tkComma):
      discard p.advance()
      if p.current.kind in {tkCosine, tkL2, tkInner, tkIdent}:
        let metric = p.advance()
        result.children.add(newIdent(metric.value, tokenSpan(metric)))
      else:
        result.children.add(p.parseExpr())
    discard p.expect(tkRParen)

proc parseColumnDef(p: var Parser): SqlNode =
  let name = p.expectIdent("column name")
  let typeName = p.parseTypeName()
  result = SqlNode(kind: nkColumnDef, colName: name.value, colType: typeName,
                   colConstraints: @[], span: tokenSpan(name),
                   orderAsc: -1, nullsFirst: -1)

  while true:
    if p.check(tkPrimary):
      discard p.advance()
      discard p.expect(tkKey)
      let c = newNode(nkConstraint)
      c.children.add(newIdent("PRIMARY KEY"))
      result.colConstraints.add(c)
    elif p.check(tkNot):
      discard p.advance()
      discard p.expect(tkNull)
      let c = newNode(nkConstraint)
      c.children.add(newIdent("NOT NULL"))
      result.colConstraints.add(c)
    elif p.check(tkUnique):
      discard p.advance()
      let c = newNode(nkConstraint)
      c.children.add(newIdent("UNIQUE"))
      result.colConstraints.add(c)
    elif p.check(tkDefault):
      discard p.advance()
      let c = newNode(nkConstraint)
      c.children.add(newIdent("DEFAULT"))
      c.children.add(p.parseExpr())
      result.colConstraints.add(c)
    else:
      break

proc parseWithOptions(p: var Parser): SqlNode =
  result = newNode(nkWithOptions)
  discard p.expect(tkWith)
  discard p.expect(tkLParen)
  while true:
    let key = p.expectIdent("option key")
    discard p.expect(tkEq)
    let value = p.expectOptionValue()
    let opt = newNode(nkIndexOption, tokenSpan(key))
    opt.children.add(newIdent(key.value, tokenSpan(key)))
    opt.children.add(newStringLit(value.value, tokenSpan(value)))
    result.children.add(opt)
    if p.check(tkComma):
      discard p.advance()
    else:
      break
  discard p.expect(tkRParen)

proc parseCreateTableAfterCreate(p: var Parser; start: Token): SqlNode =
  discard p.expect(tkTable)
  result = newNode(nkCreateTable, tokenSpan(start))
  if p.check(tkIf):
    discard p.advance()
    discard p.expect(tkNot)
    discard p.expect(tkExists)
    result.children.add(newIdent("IF NOT EXISTS"))
  let table = p.expectIdent("table name")
  result.children.add(newIdent(table.value, tokenSpan(table)))
  discard p.expect(tkLParen)
  result.children.add(p.parseColumnDef())
  while p.check(tkComma):
    discard p.advance()
    if p.check(tkPrimary) or p.check(tkUnique) or p.check(tkForeign) or p.check(tkConstraint):
      let c = newNode(nkConstraint)
      c.children.add(newIdent(p.advance().value))
      if p.check(tkKey): discard p.advance()
      if p.check(tkLParen):
        discard p.advance()
        c.children.add(newIdent(p.expectIdent("constraint column").value))
        while p.check(tkComma):
          discard p.advance()
          c.children.add(newIdent(p.expectIdent("constraint column").value))
        discard p.expect(tkRParen)
      result.children.add(c)
    else:
      result.children.add(p.parseColumnDef())
  discard p.expect(tkRParen)
  if p.check(tkWith):
    result.children.add(p.parseWithOptions())

proc parseCreateIndexAfterCreate(p: var Parser; start: Token): SqlNode =
  discard p.expect(tkIndex)
  result = newNode(nkCreateIndex, tokenSpan(start))
  if p.check(tkIf):
    discard p.advance()
    discard p.expect(tkNot)
    discard p.expect(tkExists)
    result.children.add(newIdent("IF NOT EXISTS"))
  let name = p.expectIdent("index name")
  discard p.expect(tkOn)
  let table = p.expectIdent("table name")
  discard p.expect(tkLParen)
  let column = p.expectIdent("index column")
  discard p.expect(tkRParen)
  result.children.add(newIdent(name.value, tokenSpan(name)))
  result.children.add(newIdent(table.value, tokenSpan(table)))
  result.children.add(newIdent(column.value, tokenSpan(column)))
  if p.check(tkUsing):
    discard p.advance()
    if p.current.kind notin {tkHnsw, tkBtree}:
      p.error("expected HNSW or BTREE index method")
    let idxMethod = p.advance()
    result.children.add(newIdent(idxMethod.value, tokenSpan(idxMethod)))
  if p.check(tkWith):
    result.children.add(p.parseWithOptions())

proc parseCreateStmt(p: var Parser): SqlNode =
  let start = p.expect(tkCreate)
  if p.check(tkTable):
    result = p.parseCreateTableAfterCreate(start)
  elif p.check(tkIndex):
    result = p.parseCreateIndexAfterCreate(start)
  else:
    p.error("expected TABLE or INDEX after CREATE")

proc parseDropTableAfterDrop(p: var Parser; start: Token): SqlNode =
  discard p.expect(tkTable)
  result = newNode(nkDropTable, tokenSpan(start))
  if p.check(tkIf):
    discard p.advance()
    discard p.expect(tkExists)
    result.children.add(newIdent("IF EXISTS"))
  let table = p.expectIdent("table name")
  result.children.add(newIdent(table.value, tokenSpan(table)))

proc parseDropIndexAfterDrop(p: var Parser; start: Token): SqlNode =
  discard p.expect(tkIndex)
  result = newNode(nkDropIndex, tokenSpan(start))
  if p.check(tkIf):
    discard p.advance()
    discard p.expect(tkExists)
    result.children.add(newIdent("IF EXISTS"))
  let name = p.expectIdent("index name")
  result.children.add(newIdent(name.value, tokenSpan(name)))

proc parseDropStmt(p: var Parser): SqlNode =
  let start = p.expect(tkDrop)
  if p.check(tkTable):
    result = p.parseDropTableAfterDrop(start)
  elif p.check(tkIndex):
    result = p.parseDropIndexAfterDrop(start)
  else:
    p.error("expected TABLE or INDEX after DROP")

proc parseStatement*(p: var Parser): SqlNode =
  case p.current.kind
  of tkSelect:
    result = p.parseSelectStmt()
  of tkInsert:
    result = p.parseInsertStmt()
  of tkUpdate:
    result = p.parseUpdateStmt()
  of tkDelete:
    result = p.parseDeleteStmt()
  of tkCreate:
    result = p.parseCreateStmt()
  of tkDrop:
    result = p.parseDropStmt()
  else:
    p.error("expected SQL statement (SELECT, INSERT, UPDATE, DELETE, CREATE, DROP)")

  if p.check(tkSemicolon):
    discard p.advance()

proc parseSqlStatements*(input: string): seq[SqlNode] =
  ## Parse one or more SQL statements separated by semicolons.
  var p = initParser(input)
  while p.check(tkSemicolon):
    discard p.advance()
  while not p.check(tkEof):
    let stmt = p.parseStatement()
    stmt.fillMissingSpans(stmt.span)
    result.add(stmt)
    while p.check(tkSemicolon):
      discard p.advance()

proc parseSql*(input: string): SqlNode =
  ## Parse SQL from string. A single statement returns that statement; multiple
  ## statements return nkStatementList.
  let statements = parseSqlStatements(input)
  if statements.len == 0:
    raise newException(ParseError, "empty SQL input")
  if statements.len == 1:
    result = statements[0]
  else:
    result = newNode(nkStatementList, statements[0].span)
    result.children = statements
    result.fillMissingSpans(result.span)