Repository navigation
Expand file tree
/
Copy pathcompiler.lisp
More file actions
2199 lines (2058 loc) · 124 KB
/
Copy pathcompiler.lisp
File metadata and controls
2199 lines (2058 loc) · 124 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(defpackage :endb/sql/compiler
(:use :cl)
(:export #:compile-sql)
(:import-from :endb/sql/db)
(:import-from :endb/sql/expr)
(:import-from :endb/lib/cst)
(:import-from :endb/lib)
(:import-from :endb/arrow)
(:import-from :endb/bloom)
(:import-from :alexandria)
(:import-from :fset)
(:import-from :trivia))
(in-package :endb/sql/compiler)
(defgeneric sql->cl (ctx type &rest args))
(defun %anonymous-column-name (idx)
(concatenate 'string "column" (princ-to-string idx)))
(defun %unqualified-column-name (column)
(let* ((idx (position #\. column)))
(if idx
(subseq column (1+ idx))
column)))
(defun %qualified-column-name (table-alias column)
(concatenate 'string table-alias "." column))
(defun %qualified-asterisk-p (x)
(and (listp x)
(= 2 (length x))
(eq :* (first x))
(symbolp (second x))))
(defun %select-projection (ctx select-list select-star-projection table-projections)
(loop for idx from 1
for (expr alias) in select-list
append (cond
((eq :* expr) select-star-projection)
(alias (list (symbol-name alias)))
((symbolp expr) (list (%unqualified-column-name (symbol-name expr))))
((%qualified-asterisk-p expr)
(let ((projection (fset:lookup table-projections (symbol-name (second expr)))))
(if projection
(mapcar #'%unqualified-column-name projection)
(%annotated-error (fset:lookup ctx :sql) (second expr) (format nil "Unknown table: ~A" (second expr)) "Unknown table"))))
((and (listp expr)
(eq :parameter (first expr))
(symbolp (second expr)))
(list (%unqualified-column-name (symbol-name (second expr)))))
((and (listp expr)
(eq :object (first expr))
(= 1 (length (second expr)))
(eq :* (first (first (second expr)))))
(list (%unqualified-column-name (symbol-name (second (first (second expr)))))))
((and (listp expr)
(eq :access (first expr))
(not (member (nth 2 expr) '(:* :#)))
(or (stringp (nth 2 expr))
(symbolp (nth 2 expr)))) (list (format nil "~A" (nth 2 expr))))
(t (list (%anonymous-column-name idx))))))
(defun %annotated-error-with-span (input message label-message start end)
(let* ((filename endb/lib/cst:*default-filename*)
(report (fset:map ("kind" "Error")
("msg" message)
("location" (fset:seq filename start))
("source" input)
("labels" (fset:seq (fset:map ("span" (fset:seq filename (fset:map ("start" start) ("end" end))))
("msg" label-message)
("color" "Red")
("order" 0)
("priority" 0)))))))
(error 'endb/sql/expr:sql-runtime-error
:message (endb/lib/cst:render-error-report report))))
(defun %annotated-error (input s message &optional (label-message message))
(%annotated-error-with-span input message label-message (get s :start) (get s :end)))
(defun %base-table-or-view->cl (ctx table-name &key temporal (errorp t))
(let* ((db (fset:lookup ctx :db))
(ctes (or (fset:lookup ctx :ctes) (fset:empty-map)))
(cte (fset:lookup ctes (symbol-name table-name)))
(table-type (endb/sql/db:table-type db (symbol-name table-name))))
(cond
(cte
(progn
(dolist (cb (fset:lookup ctx :on-cte-access))
(funcall cb (symbol-name table-name)))
(values `(,(intern (symbol-name table-name))) (cte-projection cte) (cte-free-vars cte))))
((equal "BASE TABLE" table-type)
(values (make-base-table :name (symbol-name table-name)
:temporal temporal
:size (endb/sql/db:base-table-size db (symbol-name table-name)))
(endb/sql/db:table-columns db (symbol-name table-name))))
((equal "VIEW" table-type)
(let ((view-sql (endb/sql/db:view-definition db (symbol-name table-name))))
(multiple-value-bind (src projection free-vars)
(%ast->cl-with-free-vars ctx (endb/lib/cst:parse-sql-ast view-sql))
(declare (ignore projection))
(values src (endb/sql/db:table-columns db (symbol-name table-name)) free-vars))))
(errorp (%annotated-error (fset:lookup ctx :sql) table-name (format nil "Unknown table: ~A" table-name) "Unknown table")))))
(defun %wrap-with-order-by-and-limit (src order-by limit offset)
(let* ((src (if order-by
`(endb/sql/expr:ra-order-by ,src ',order-by)
src))
(src (if (and order-by limit)
`(endb/sql/expr:ra-limit ,src ',limit ',offset)
src)))
src))
(defun %resolve-order-by (ctx order-by projection &key allow-expr-p)
(loop with expr-idx = (length projection)
for ordering-term in order-by
for span = (nthcdr 2 ordering-term)
for start = (getf span :start)
for end = (getf span :end)
for (expr direction) = ordering-term
for projected-idx = (when (symbolp expr)
(position (symbol-name expr) projection :test 'equal))
collect (list (cond
((numberp expr)
(if (<= 1 expr (length projection))
expr
(%annotated-error-with-span (fset:lookup ctx :sql)
(format nil "ORDER BY index not in range: ~A" expr)
"ORDER BY index not in range"
start
end)))
(projected-idx (1+ projected-idx))
(allow-expr-p (incf expr-idx))
(t (if (symbolp expr)
(%annotated-error (fset:lookup ctx :sql) expr (format nil "Cannot resolve ORDER BY column: ~A" expr) "Cannot resolve ORDER BY column")
(%annotated-error-with-span (fset:lookup ctx :sql)
"Invalid ORDER BY expression"
"Invalid ORDER BY expression"
start
end))))
(or direction :asc))))
(defun %and-clauses (expr)
(if (listp expr)
(case (first expr)
(:and (append (%and-clauses (second expr))
(%and-clauses (third expr))))
(:or (append (list expr)
(intersection (%and-clauses (second expr))
(%and-clauses (third expr))
:key #'prin1-to-string
:test 'equal)))
(t (list expr)))
(list expr)))
(defstruct base-table name temporal size)
(defstruct from-table src vars free-vars size projection alias)
(defstruct where-clause src free-vars ast)
(defstruct aggregate src init-src var where-src)
(defstruct cte src free-vars projection ast)
(defun %binary-predicate-p (x)
(and (listp x)
(= 3 (length x))))
(defun %equi-join-predicate-p (vars clause-src)
(when (%binary-predicate-p clause-src)
(destructuring-bind (op lhs rhs)
clause-src
(and (equal 'endb/sql/expr:sql-= op)
(member lhs vars)
(member rhs vars)))))
(defun %equi-join-participant-p (vars clause-src)
(when (%binary-predicate-p clause-src)
(destructuring-bind (op lhs rhs)
clause-src
(and (equal 'endb/sql/expr:sql-= op)
(or (and (member lhs vars) (symbolp rhs))
(and (member rhs vars) (symbolp lhs)))))))
(defun %maybe-equi-join-p (clause-src)
(when (%binary-predicate-p clause-src)
(destructuring-bind (op lhs rhs)
clause-src
(and (equal 'endb/sql/expr:sql-= op)
(and (symbolp rhs)
(symbolp lhs))))))
(defun %unique-vars (vars)
(let ((seen ()))
(loop for x in (reverse vars)
if (not (member x seen))
do (push x seen)
else
do (push nil seen)
finally (return seen))))
(defun %table-alias (table-ast)
(if (= 1 (length table-ast))
(first table-ast)
(second table-ast)))
(defun %using-to-on (table-1 table-2 using)
(labels ((make-column-reference (table-name column-name)
(let ((col-ref (make-symbol (concatenate 'string (symbol-name table-name) "." (symbol-name column-name)))))
(setf (get col-ref :start) (get column-name :start) (get col-ref :end) (get column-name :end))
col-ref)))
(let* ((table-1-alias (%table-alias table-1))
(table-2-alias (%table-alias table-2)))
(reduce
(lambda (acc column)
(let ((expr (list := (make-column-reference table-1-alias column) (make-column-reference table-2-alias column))))
(if acc
(list :and acc expr)
expr)))
using
:initial-value nil))))
(defun %flatten-from (from)
(let ((from-element (first from)))
(when from-element
(append (if (eq :join (first from-element))
(destructuring-bind (table-1 table-2 &key on using type)
(rest from-element)
(if (eq :left type)
(append (%flatten-from (list table-1))
(list (list (list :left-join
table-2
(if using
(%using-to-on table-1 table-2 using)
on))
(%table-alias table-2))))
(%flatten-from (list table-1 table-2))))
(list from-element))
(%flatten-from (rest from))))))
(defun %from-where-clauses (from)
(let ((from-element (first from)))
(when from-element
(append
(when (eq :join (first from-element))
(destructuring-bind (table-1 table-2 &key on using type)
(rest from-element)
(if (eq :left type)
(%from-where-clauses (list table-1))
(append (if using
(%and-clauses (%using-to-on table-1 table-2 using))
(%and-clauses on))
(%from-where-clauses (list table-1 table-2))))))
(%from-where-clauses (rest from))))))
(defun %replace-all (smap x)
(cond
((symbolp x) (or (cdr (assoc x smap)) x))
((listp x) (cons (%replace-all smap (car x))
(%replace-all smap (cdr x))))
(t x)))
(defun %numeric-bloom-check-src (x y stats-md-sym)
(let* ((hashes (endb/sql/expr:ra-bloom-hashes y)))
(if (= 1 (length hashes))
`(endb/bloom:sbbf-check-p
(fset:lookup
(fset:lookup ,stats-md-sym ,(get x :column))
"bloom")
,(first hashes))
(alexandria:with-gensyms (bloom-sym lambda-sym)
`(let ((,bloom-sym (fset:lookup
(fset:lookup ,stats-md-sym ,(get x :column))
"bloom")))
(some (lambda (,lambda-sym)
(endb/bloom:sbbf-check-p ,bloom-sym ,lambda-sym))
',hashes))))))
(defun %parameter-lookup-p (src param-sym)
(and (listp src)
(eq 'fset:lookup (first src))
(eq param-sym (second src))))
(defun %hash-index-column-and-src (clause vars param-sym)
(labels ((free-var-or-constant-p (y)
(or (and (symbolp y)
(not (member y vars)))
(constantp y)
(%parameter-lookup-p y param-sym))))
(trivia:match (where-clause-src clause)
((trivia:guard
(list (or 'endb/sql/expr:sql-=
'endb/sql/expr:sql-is)
x y)
(and (member x vars) (free-var-or-constant-p y)))
(values (get x :column) y))
((trivia:guard
(list (or 'endb/sql/expr:sql-=
'endb/sql/expr:sql-is)
y x)
(and (member x vars) (free-var-or-constant-p y)))
(values (get x :column) y)))))
(defun %where-clause-stats-src (clause vars stats-md-sym param-sym)
(labels ((free-var-or-constant-p (y)
(or (and (symbolp y)
(not (member y vars)))
(constantp y)
(%parameter-lookup-p y param-sym))))
(trivia:match (where-clause-src clause)
((trivia:guard
(list 'endb/sql/expr:sql-= x y)
(and (member x vars) (numberp y)))
(%numeric-bloom-check-src x y stats-md-sym))
((trivia:guard
(list 'endb/sql/expr:sql-= y x)
(and (member x vars) (numberp y)))
(%numeric-bloom-check-src x y stats-md-sym))
((trivia:guard
(list (or 'endb/sql/expr:sql-=
'endb/sql/expr:sql-is)
x y)
(and (member x vars) (free-var-or-constant-p y)))
(alexandria:with-gensyms (bloom-sym lambda-sym)
`(let ((,bloom-sym (fset:lookup
(fset:lookup ,stats-md-sym ,(get x :column))
"bloom")))
(some (lambda (,lambda-sym)
(endb/bloom:sbbf-check-p ,bloom-sym ,lambda-sym))
,(if (constantp y)
`',(endb/sql/expr:ra-bloom-hashes y)
`(endb/sql/expr:ra-bloom-hashes ,y))))))
((trivia:guard
(list (or 'endb/sql/expr:sql-=
'endb/sql/expr:sql-is)
y x)
(and (member x vars) (free-var-or-constant-p y)))
(alexandria:with-gensyms (bloom-sym lambda-sym)
`(let ((,bloom-sym (fset:lookup
(fset:lookup ,stats-md-sym ,(get x :column))
"bloom")))
(some (lambda (,lambda-sym)
(endb/bloom:sbbf-check-p ,bloom-sym ,lambda-sym))
,(if (constantp y)
`',(endb/sql/expr:ra-bloom-hashes y)
`(endb/sql/expr:ra-bloom-hashes ,y))))))
((trivia:guard
(list 'endb/sql/expr:ra-in x y)
(and (member x vars) (listp y) (every #'free-var-or-constant-p y)))
(alexandria:with-gensyms (bloom-sym lambda-sym)
`(let ((,bloom-sym (fset:lookup
(fset:lookup ,stats-md-sym ,(get x :column))
"bloom")))
(some (lambda (,lambda-sym)
(endb/bloom:sbbf-check-p ,bloom-sym ,lambda-sym))
(append ,@(loop for v in (if (eq 'list (first y))
(rest y)
y)
collect (if (constantp v)
`',(endb/sql/expr:ra-bloom-hashes v)
`(endb/sql/expr:ra-bloom-hashes ,v))))))))
((trivia:guard
(list 'endb/sql/expr:sql-between x y z)
(and (member x vars) (free-var-or-constant-p y) (free-var-or-constant-p z)))
`(and (eq t (endb/sql/expr:sql->=
(fset:lookup
(fset:lookup ,stats-md-sym ,(get x :column))
"max")
,y))
(eq t (endb/sql/expr:sql-<=
(fset:lookup
(fset:lookup ,stats-md-sym ,(get x :column))
"min")
,z))))
((trivia:guard
(list 'endb/sql/expr:sql-like y x)
(and (member x vars) (stringp y)))
(let ((idx (position-if (lambda (z)
(member z '(#\% #\_)))
y)))
(when (and idx (plusp idx))
`(and (eq t (endb/sql/expr:sql->=
(fset:lookup
(fset:lookup ,stats-md-sym ,(get x :column))
"max")
,(subseq y 0 idx)))
(eq t (endb/sql/expr:sql-<=
(fset:lookup
(fset:lookup ,stats-md-sym ,(get x :column))
"min")
,(concatenate 'string (subseq y 0 idx) (string #\UFFFF))))))))
((trivia:guard
(list 'endb/sql/expr:sql-< x y)
(and (member x vars) (free-var-or-constant-p y)))
`(eq t (endb/sql/expr:sql-<
(fset:lookup
(fset:lookup ,stats-md-sym ,(get x :column))
"min")
,y)))
((trivia:guard
(list 'endb/sql/expr:sql-<= x y)
(and (member x vars) (free-var-or-constant-p y)))
`(eq t (endb/sql/expr:sql-<=
(fset:lookup
(fset:lookup ,stats-md-sym ,(get x :column))
"min")
,y)))
((trivia:guard
(list 'endb/sql/expr:sql-< y x)
(and (member x vars) (free-var-or-constant-p y)))
`(eq t (endb/sql/expr:sql-<
,y
(fset:lookup
(fset:lookup ,stats-md-sym ,(get x :column))
"max"))))
((trivia:guard
(list 'endb/sql/expr:sql-<= y x)
(and (member x vars) (free-var-or-constant-p y)))
`(eq t (endb/sql/expr:sql-<=
,y
(fset:lookup
(fset:lookup ,stats-md-sym ,(get x :column))
"max"))))
((trivia:guard
(list 'endb/sql/expr:sql-> x y)
(and (member x vars) (free-var-or-constant-p y)))
`(eq t (endb/sql/expr:sql->
(fset:lookup
(fset:lookup ,stats-md-sym ,(get x :column))
"max")
,y)))
((trivia:guard
(list 'endb/sql/expr:sql->= x y)
(and (member x vars) (free-var-or-constant-p y)))
`(eq t (endb/sql/expr:sql->=
(fset:lookup
(fset:lookup ,stats-md-sym ,(get x :column))
"max")
,y)))
((trivia:guard
(list 'endb/sql/expr:sql-> y x)
(and (member x vars) (free-var-or-constant-p y)))
`(eq t (endb/sql/expr:sql->
,y
(fset:lookup
(fset:lookup ,stats-md-sym ,(get x :column))
"min"))))
((trivia:guard
(list 'endb/sql/expr:sql->= y x)
(and (member x vars) (free-var-or-constant-p y)))
`(eq t (endb/sql/expr:sql->=
,y
(fset:lookup
(fset:lookup ,stats-md-sym ,(get x :column))
"min")))))))
(defun %table-scan->cl (ctx vars projection from-src where-clauses nested-src &optional extra-stats-src)
(let* ((where-src (loop for clause in where-clauses
collect `(eq t ,(where-clause-src clause)))))
(if (base-table-p from-src)
(alexandria:with-gensyms (table-md-sym
arrow-file-md-sym
deleted-md-sym
erased-md-sym
stats-md-sym
sha1-md-sym
batch-row-sym
system-time-start-sym
system-time-end-sym
temporal-sym
raw-deleted-row-ids-sym
deleted-row-ids-sym
erased-row-ids-sym
lambda-sym
batch-sym
scan-row-id-sym
scan-batch-idx-sym
scan-batch-idx-string-sym
scan-arrow-file-sym
uncommitted-p-sym
hash-index-rows-sym
row-idx-sym)
(let* ((table-name (base-table-name from-src))
(batch-sym (or (fset:lookup ctx :batch-sym) batch-sym))
(stats-md-sym (or (fset:lookup ctx :stats-md-sym) stats-md-sym))
(scan-row-id-sym (or (fset:lookup ctx :scan-row-id-sym) scan-row-id-sym))
(scan-batch-idx-sym (or (fset:lookup ctx :scan-batch-idx-sym) scan-batch-idx-sym))
(scan-arrow-file-sym (or (fset:lookup ctx :scan-arrow-file-sym) scan-arrow-file-sym))
(db-sym (fset:lookup ctx :db-sym))
(param-sym (fset:lookup ctx :param-sym))
(kw-projection (remove :|system_time| (loop for c in projection
collect (intern c :keyword))))
(array-vars (loop repeat (length kw-projection)
collect (gensym)))
(stats-src (loop for clause in where-clauses
for stats-src = (%where-clause-stats-src clause vars stats-md-sym param-sym)
when stats-src
collect stats-src))
(stats-src (append stats-src extra-stats-src)))
(multiple-value-bind (hash-index-column hash-index-src)
(loop for clause in where-clauses
for pair = (%hash-index-column-and-src clause vars param-sym)
when pair
do (return-from nil pair))
(destructuring-bind (&optional (temporal-type :as-of temporal-type-p) (temporal-start :current_timestamp) (temporal-end temporal-start))
(base-table-temporal from-src)
(let ((loop-body-src `(when (and ,@(when temporal-type-p
`((eq t (,(case temporal-type
((:as-of :between :all) 'endb/sql/expr:sql-<=)
(:from 'endb/sql/expr:sql-<))
(endb/arrow:arrow-get ,temporal-sym ,scan-row-id-sym)
,system-time-end-sym))))
(endb/sql/expr:ra-visible-row-p ,deleted-row-ids-sym ,erased-row-ids-sym ,scan-row-id-sym)
,@where-src)
,nested-src)))
`(symbol-macrolet (,@(loop for v in vars
for p in (append
(loop for p in kw-projection
for v in array-vars
collect `(if ,v
(endb/arrow:arrow-get ,v ,scan-row-id-sym)
(endb/arrow:arrow-struct-column-value ,batch-sym ,scan-row-id-sym ,p)))
(unless endb/sql/expr:*sqlite-mode*
(list `(let ((,scan-row-id-sym ,scan-row-id-sym))
(lambda ()
(endb/arrow:arrow-get ,batch-sym ,scan-row-id-sym)))
`(let ((,scan-row-id-sym ,scan-row-id-sym))
(lambda ()
(fset:map ("start" (endb/arrow:arrow-get ,temporal-sym ,scan-row-id-sym))
("end" (endb/sql/db:batch-row-system-time-end ,raw-deleted-row-ids-sym ,scan-row-id-sym))))))))
collect `(,v ,p)))
(let ((,table-md-sym (endb/sql/db:base-table-meta ,db-sym ,table-name))
,@(when temporal-type-p
`((,system-time-start-sym ,(ast->cl ctx (if (eq temporal-type :all)
endb/sql/expr:+unix-epoch-time+
temporal-start)))
(,system-time-end-sym ,(ast->cl ctx (if (eq temporal-type :all)
endb/sql/expr:+end-of-time+
temporal-end))))))
,(when temporal-type-p
`(endb/sql/expr:ra-check-system-time-type "start" ,system-time-start-sym))
,(when temporal-type-p
`(endb/sql/expr:ra-check-system-time-type "end" ,system-time-end-sym))
(fset:do-map (,scan-arrow-file-sym ,arrow-file-md-sym ,table-md-sym)
(let ((,deleted-md-sym (fset:lookup ,arrow-file-md-sym "deleted"))
(,erased-md-sym (fset:lookup ,arrow-file-md-sym "erased"))
(,stats-md-sym (fset:lookup ,arrow-file-md-sym "stats"))
(,sha1-md-sym (fset:lookup ,arrow-file-md-sym "sha1"))
(,scan-batch-idx-sym -1))
(declare (ignorable ,stats-md-sym))
(when (and ,@stats-src)
(multiple-value-bind (,batch-row-sym ,uncommitted-p-sym)
(endb/sql/db:base-table-arrow-batches ,db-sym ,table-name ,scan-arrow-file-sym :sha1 ,sha1-md-sym)
(declare (ignorable ,uncommitted-p-sym))
(dolist (,batch-row-sym ,batch-row-sym)
(incf ,scan-batch-idx-sym)
(let* ((,batch-sym (endb/arrow:arrow-struct-column-array ,batch-row-sym ,(intern table-name :keyword)))
(,temporal-sym (endb/arrow:arrow-struct-column-array ,batch-row-sym :|system_time_start|))
(,scan-batch-idx-string-sym (prin1-to-string ,scan-batch-idx-sym))
(,raw-deleted-row-ids-sym (fset:lookup ,deleted-md-sym ,scan-batch-idx-string-sym))
(,deleted-row-ids-sym ,(if temporal-type-p
`(fset:filter
(lambda (,lambda-sym)
(eq t (endb/sql/expr:sql-<= (fset:lookup ,lambda-sym "system_time_end") ,system-time-start-sym)))
,raw-deleted-row-ids-sym)
raw-deleted-row-ids-sym))
(,erased-row-ids-sym (fset:lookup ,erased-md-sym ,scan-batch-idx-string-sym))
,@(loop for p in kw-projection
for v in array-vars
collect `(,v (endb/arrow:arrow-struct-column-array ,batch-sym ,p))))
(declare (ignorable ,temporal-sym ,@array-vars))
,(if hash-index-column
`(let ((,hash-index-rows-sym (unless ,uncommitted-p-sym
(endb/sql/expr:ra-hash-index
(endb/sql/db:db-hash-index-cache ,db-sym)
(endb/sql/db:db-indexer-queue ,db-sym)
(format nil "~A/~A/~A/~A" ,table-name ,scan-arrow-file-sym ,scan-batch-idx-sym ,hash-index-column)
,batch-sym
,(intern hash-index-column :keyword)
,hash-index-src))))
(dotimes (,row-idx-sym (if ,hash-index-rows-sym
(length ,hash-index-rows-sym)
(endb/arrow:arrow-length ,batch-sym)))
(let ((,scan-row-id-sym (if ,hash-index-rows-sym
(aref ,hash-index-rows-sym ,row-idx-sym)
,row-idx-sym)))
,loop-body-src)))
`(dotimes (,scan-row-id-sym (endb/arrow:arrow-length ,batch-sym))
,loop-body-src)))))))))))))))
(alexandria:with-gensyms (row-sym)
`(symbol-macrolet (,@(loop for v in (%unique-vars vars)
for idx from 0
when v
collect `(,v (aref ,row-sym ,idx))))
(dolist (,row-sym ,from-src)
,(if where-src
`(when (and ,@where-src)
,nested-src)
nested-src)))))))
(defparameter +sip-hashes-limit+ 1024)
(defun %uncorrelated-index-key-form (index-key-form)
(and (vectorp index-key-form)
(= 1 (length index-key-form))))
(defun %join->cl (ctx from-table scan-where-clauses equi-join-clauses var-groups)
(with-slots (src vars free-vars)
from-table
(multiple-value-bind (in-vars out-vars)
(loop for (nil lhs rhs) in (mapcar #'where-clause-src equi-join-clauses)
if (member lhs vars)
collect lhs into out-vars
else
collect lhs into in-vars
if (member rhs vars)
collect rhs into out-vars
else
collect rhs into in-vars
finally
(return (values in-vars out-vars)))
(alexandria:with-gensyms (row-sym lambda-sym stats-md-sym)
(let* ((index-sym (fset:lookup ctx :index-sym))
(sip-init-src)
(sip-probe-src)
(sip-stats-src)
(ctx (fset:with ctx :stats-md-sym stats-md-sym)))
(fset:do-map (sip-index-key-form sip (or (fset:lookup ctx :index-sip) (fset:empty-map)))
(let* ((source-from-table (fset:lookup sip :from-table))
(source-out-vars (fset:lookup sip :out-vars))
(source-vars (from-table-vars source-from-table))
(out-var-groups (remove nil (loop for v in source-out-vars
collect (find-if (lambda (xs)
(member v xs))
var-groups))))
(sip-in-vars (intersection in-vars source-vars))
(sip-can-reuse-index-p (and out-var-groups
(loop for out-var-group in out-var-groups
always (intersection out-vars out-var-group))))
(sip-out-vars (if sip-can-reuse-index-p
(loop for out-var-group in out-var-groups
collect (first (intersection out-vars out-var-group)))
(loop for v in sip-in-vars
collect (nth (position v in-vars) out-vars)))))
(when (and sip-out-vars (%uncorrelated-index-key-form sip-index-key-form))
(alexandria:with-gensyms (sip-table-sym sip-hashes-sym)
(when (and (base-table-p (from-table-src from-table))
(= 1 (length sip-out-vars)))
(alexandria:with-gensyms (bloom-sym)
(push `(,sip-hashes-sym (when (< (hash-table-count ,sip-table-sym) +sip-hashes-limit+)
(let ((,sip-hashes-sym (make-array 0
:element-type '(unsigned-byte 64)
:fill-pointer 0
:adjustable t)))
(alexandria:maphash-keys
(lambda (,lambda-sym)
(dolist (,lambda-sym (endb/sql/expr:ra-bloom-hashes ,lambda-sym))
(vector-push-extend ,lambda-sym ,sip-hashes-sym)))
,sip-table-sym)
,sip-hashes-sym)))
sip-init-src)
(push `(or (null ,sip-hashes-sym)
(let ((,bloom-sym (fset:lookup
(fset:lookup ,stats-md-sym ,(get (first sip-out-vars) :column))
"bloom")))
(some (lambda (,lambda-sym)
(endb/bloom:sbbf-check-p ,bloom-sym ,lambda-sym))
,sip-hashes-sym)))
sip-stats-src)))
(if sip-can-reuse-index-p
(push `(,sip-table-sym (let ((,sip-table-sym (gethash ,sip-index-key-form ,index-sym)))
(endb/lib:log-trace "reuse sip: ~A ~A~%" ,(from-table-alias source-from-table) (hash-table-count ,sip-table-sym))
,sip-table-sym))
sip-init-src)
(let ((sip-in-key-form (if (= 1 (length sip-in-vars))
`(aref ,row-sym ,(position (first sip-in-vars) source-vars))
`(vector ,@(loop for v in sip-in-vars
collect `(aref ,row-sym ,(position v source-vars)))))))
(push `(,sip-table-sym (let ((,sip-table-sym (endb/sql/expr:make-sql-no-nulls-hash-table)))
(alexandria:maphash-values
(lambda (,lambda-sym)
(dolist (,row-sym ,lambda-sym)
(setf (gethash ,sip-in-key-form ,sip-table-sym) t)))
(gethash ,sip-index-key-form ,index-sym))
(endb/lib:log-trace "sip: ~A ~A~%" ,(from-table-alias source-from-table) (hash-table-count ,sip-table-sym))
,sip-table-sym))
sip-init-src)))
(let ((sip-out-key-form (if (= 1 (length sip-out-vars))
(first sip-out-vars)
`(vector ,@sip-out-vars))))
(push `(gethash ,sip-out-key-form ,sip-table-sym) sip-probe-src))))))
(alexandria:with-gensyms (index-table-sym index-key-form-sym)
(let* ((new-free-vars (set-difference free-vars in-vars))
(index-key-form (if new-free-vars
`(vector ',index-key-form-sym ,@new-free-vars)
(vector index-key-form-sym))))
(values
`(gethash ,(if (= 1 (length in-vars))
(first in-vars)
`(vector ,@in-vars))
(endb/sql/expr:ra-compute-index-if-absent
,index-sym
,index-key-form
(lambda ()
(let* ((,index-table-sym (endb/sql/expr:make-sql-no-nulls-hash-table))
,@sip-init-src)
,(%table-scan->cl ctx
vars
(mapcar #'%unqualified-column-name (from-table-projection from-table))
src
scan-where-clauses
`(when (and ,@sip-probe-src)
(push (vector ,@vars)
(gethash ,(if (= 1 (length out-vars))
(first out-vars)
`(vector ,@out-vars))
,index-table-sym)))
sip-stats-src)
(endb/lib:log-trace "join table: ~A ~A~%"
,(from-table-alias from-table)
(reduce #'+ (mapcar #'length
(alexandria:hash-table-values ,index-table-sym))))
(maphash
(lambda (,lambda-sym ,row-sym)
(setf (gethash ,lambda-sym ,index-table-sym) (reverse ,row-sym)))
,index-table-sym)
,index-table-sym))))
(fset:with ctx :index-sip (fset:with (or (fset:lookup ctx :index-sip) (fset:empty-map))
index-key-form (fset:map (:from-table from-table) (:out-vars out-vars))))))))))))
(defun %selection-with-limit-offset->cl (ctx selected-src &optional limit offset)
(let ((acc-sym (fset:lookup ctx :acc-sym)))
(if (or limit offset)
(let* ((rows-sym (fset:lookup ctx :rows-sym))
(block-sym (fset:lookup ctx :block-sym))
(limit (if offset
(+ offset limit)
limit))
(offset (or offset 0)))
`(progn
(when (and (>= ,rows-sym ,offset)
(not (eql ,rows-sym ,limit)))
(incf ,rows-sym)
(push (vector ,@selected-src) ,acc-sym))
(when (eql ,rows-sym ,limit)
(return-from ,block-sym ,acc-sym))))
`(push (vector ,@selected-src) ,acc-sym))))
(defun %scan-where-clause-p (ast)
(if (listp ast)
(if (eq :not (first ast))
(%scan-where-clause-p (second ast))
(not (eq :exists (first ast))))
t))
(defun %build-var-groups (groups)
(let ((new-groups (delete-duplicates
(loop for g1 in groups
collect (delete-duplicates
(loop for g2 in groups
when (intersection g1 g2)
append g2)))
:test 'equal)))
(if (equal new-groups groups)
groups
(%build-var-groups new-groups))))
(defun %from->cl (ctx from-tables where-clauses selected-src &optional vars (var-groups nil var-groups-p))
(let* ((var-groups (if var-groups-p
var-groups
(let ((var-pairs (loop for clause in where-clauses
when (%maybe-equi-join-p (where-clause-src clause))
collect (rest (where-clause-src clause)))))
(%build-var-groups var-pairs))))
(candidate-tables (remove-if-not (lambda (x)
(subsetp (from-table-free-vars x) vars))
from-tables))
(from-table (or (find-if (lambda (x)
(loop with vars = (append (from-table-vars x) vars)
for c in where-clauses
thereis (%equi-join-predicate-p vars (where-clause-src c))))
candidate-tables)
(first candidate-tables)))
(from-tables (remove from-table from-tables))
(equi-join-participant-p (loop for c in where-clauses
thereis (%equi-join-participant-p (from-table-vars from-table)
(where-clause-src c))))
(new-vars (from-table-vars from-table))
(vars (append new-vars vars)))
(multiple-value-bind (scan-clauses equi-join-clauses pushdown-clauses)
(loop for c in where-clauses
if (and (subsetp (where-clause-free-vars c) new-vars)
(%scan-where-clause-p (where-clause-ast c)))
collect c into scan-clauses
else if (%equi-join-predicate-p vars (where-clause-src c))
collect c into equi-join-clauses
else if (subsetp (where-clause-free-vars c) vars)
collect c into pushdown-clauses
finally
(return (values scan-clauses equi-join-clauses pushdown-clauses)))
(multiple-value-bind (join-src join-ctx)
(when equi-join-participant-p
(%join->cl ctx from-table scan-clauses equi-join-clauses var-groups))
(let* ((new-where-clauses (append scan-clauses equi-join-clauses pushdown-clauses))
(where-clauses (set-difference where-clauses new-where-clauses))
(nested-src (cond
(from-tables
(%from->cl (or join-ctx ctx) from-tables where-clauses selected-src vars var-groups))
(where-clauses
`(when (and ,@(loop for clause in where-clauses collect `(eq t ,(where-clause-src clause))))
,selected-src))
(t selected-src)))
(projection (mapcar #'%unqualified-column-name (from-table-projection from-table))))
(if equi-join-participant-p
(%table-scan->cl join-ctx
new-vars
projection
join-src
pushdown-clauses
nested-src)
(progn
(endb/lib:log-trace "table scan: ~A~%" (from-table-alias from-table))
(%table-scan->cl ctx
new-vars
projection
(from-table-src from-table)
(append scan-clauses pushdown-clauses)
nested-src))))))))
(defun %group-by->cl (ctx from-tables where-clauses selected-src limit offset group-by having-src correlated-vars selected-non-aggregate-columns)
(alexandria:with-gensyms (group-acc-sym group-key-sym group-sym)
(let* ((aggregate-table (fset:lookup ctx :aggregate-table))
(group-by-projection (loop for g in group-by
collect (ast->cl ctx g)))
(group-by-exprs-projection (loop for k being the hash-key of aggregate-table
collect k))
(group-key-form `(vector ,@group-by-projection))
(init-srcs (loop for v being the hash-value of aggregate-table
collect (aggregate-init-src v)))
(group-by-selected-src `(symbol-macrolet (,@(loop for v in group-by-exprs-projection
for idx from 0
collect `(,v (aref ,group-sym ,idx))))
(let* ((,group-key-sym ,group-key-form)
(,group-sym (gethash ,group-key-sym ,group-acc-sym)))
(unless ,group-sym
(setf ,group-sym (vector ,@init-srcs))
(setf (gethash ,group-key-sym ,group-acc-sym) ,group-sym))
,@(loop for v being the hash-value of aggregate-table
collect `(when (eq t ,(aggregate-where-src v))
(endb/sql/expr:agg-accumulate ,(aggregate-var v) ,@(aggregate-src v)))))))
(empty-group-key-form (make-array (length group-by-projection) :initial-element :null))
(group-by-src `(let ((,group-acc-sym (endb/sql/expr:make-sql-hash-table)))
,(%from->cl ctx from-tables where-clauses group-by-selected-src correlated-vars)
,(unless group-by
`(when (zerop (hash-table-count ,group-acc-sym))
(setf (gethash ,empty-group-key-form ,group-acc-sym)
(vector ,@init-srcs))))
,group-acc-sym))
(non-group-selected-vars (loop for v in selected-non-aggregate-columns
unless (find (fset:lookup ctx v) group-by-projection)
collect v)))
(when non-group-selected-vars
(%annotated-error-with-span (fset:lookup ctx :sql)
(format nil "Selecting columns: ~A that does not match group by: ~A"
non-group-selected-vars
(or group-by "()"))
(format nil "Selecting columns: ~A that does not match group by"
non-group-selected-vars)
(get (first group-by) :start)
(get (first (last group-by)) :end)))
(alexandria:with-gensyms (key-sym val-sym)
`(symbol-macrolet (,@(loop for v in (%unique-vars group-by-projection)
for idx from 0
when v
collect `(,v (aref ,key-sym ,idx)))
,@(loop for v in group-by-exprs-projection
for idx from 0
collect `(,v (aref ,val-sym ,idx))))
(maphash
(lambda (,key-sym ,val-sym)
(declare (ignorable ,key-sym ,val-sym))
(when (eq t ,having-src)
,(%selection-with-limit-offset->cl ctx selected-src limit offset)))
,group-by-src))))))
(defun %env-extension (table-alias projection &optional functions)
(reduce
(lambda (acc column)
(let* ((qualified-column (%qualified-column-name table-alias column))
(column-sym (gensym (concatenate 'string qualified-column "__")))
(acc (fset:with acc column column-sym)))
(setf (get column-sym :column) column)
(when (member column functions :test 'equal)
(setf (get column-sym :functionp) t))
(fset:with acc qualified-column column-sym)))
projection
:initial-value (fset:empty-map)))
(defun %recursive-select-p (ctx table-or-subquery)
(and (symbolp table-or-subquery)
(equal (fset:lookup ctx :current-cte)
(symbol-name table-or-subquery))))
(defun %pick-initial-join-order (from-tables where-clauses)
(loop for from-table in from-tables
if (loop for c in where-clauses
thereis (and (subsetp (where-clause-free-vars c) (from-table-vars from-table))
(%scan-where-clause-p (where-clause-ast c))))
collect from-table into filtered-tables
else
collect from-table into unfiltered-tables
finally (return (append (stable-sort filtered-tables #'< :key #'from-table-size)
(stable-sort unfiltered-tables #'< :key #'from-table-size)))))
(defmethod sql->cl (ctx (type (eql :select)) &rest args)
(destructuring-bind (select-list &key distinct (from '(((:values ((:null))) #:dual))) (where :true)
(group-by () group-by-p) (having :true havingp)
order-by limit offset)
args
(labels ((select->cl (ctx from-ast from-tables-acc)
(destructuring-bind (table-or-subquery &optional (table-alias table-or-subquery) column-names temporal)
(first from-ast)
(multiple-value-bind (table-src projection free-vars)
(cond
((symbolp table-or-subquery)
(%base-table-or-view->cl ctx table-or-subquery :temporal temporal))
((and (listp table-or-subquery)
(eq :objects (first table-or-subquery)))
(%ast->cl-with-free-vars (fset:with ctx :inside-from-p t) table-or-subquery))
(t (%ast->cl-with-free-vars ctx table-or-subquery)))
(when (and column-names (not (= (length projection) (length column-names))))
(%annotated-error (fset:lookup ctx :sql) table-alias "Number of column names does not match projection"))
(let* ((projection (or (mapcar #'symbol-name column-names) projection))
(table-alias (%unqualified-column-name (symbol-name table-alias)))
(qualified-projection (loop for column in projection
collect (%qualified-column-name table-alias column)))
(extra-projection (unless endb/sql/expr:*sqlite-mode*
(cond
((base-table-p table-src)
(list "!doc" "system_time"))
((and (listp table-or-subquery)
(eq :objects (first table-or-subquery)))
(list "!doc")))))
(projection (append projection extra-projection))
(env-extension (%env-extension table-alias projection (when (base-table-p table-src)
extra-projection)))
(ctx (fset:map-union ctx env-extension))
(ctx (if (%recursive-select-p ctx table-or-subquery)
(fset:with ctx :recursive-select t)
ctx))
(ctx (fset:with ctx
:table-projections
(fset:with (or (fset:lookup ctx :table-projections) (fset:empty-map))
table-alias
qualified-projection)))
(from-table (make-from-table :src table-src
:vars (loop for p in projection
collect (fset:lookup env-extension p))
:free-vars free-vars
:size (if (base-table-p table-src)
(base-table-size table-src)
most-positive-fixnum)
:projection qualified-projection
:alias table-alias))
(from-tables-acc (append from-tables-acc (list from-table))))
(if (rest from-ast)
(select->cl ctx (rest from-ast) from-tables-acc)
(let* ((aggregate-table (make-hash-table))
(ctx (fset:with ctx :aggregate-table aggregate-table))
(ctx (fset:less ctx :on-cte-access))
(full-projection (loop for from-table in from-tables-acc
append (from-table-projection from-table)))
(table-projections (fset:lookup ctx :table-projections))
(selected-non-aggregate-columns ())
(selected-ctx (fset:with
ctx
:on-var-access
(cons (lambda (inner-ctx k v)