changelog shortlog graph tags branches changeset files revisions annotate raw help

Mercurial > core / lisp/lib/obj/query.lisp

changeset 575: efb4a19ff530
parent: 9e7d4393eac6
child: 60c7b1c83c47
author: Richard Westhaver <ellis@rwest.io>
date: Sun, 04 Aug 2024 00:18:52 -0400
permissions: -rw-r--r--
description: color palettes, obj/query upgrades and q/sql parsing - successfully parsing SQL-SELECT
1 ;;; obj/query/pkg.lisp --- Query Objects
2 
3 ;; Lisp primitive Query objects for DIY query engines.
4 
5 ;;; Commentary:
6 
7 ;; This package provides the base set of classes and methods for implementing
8 ;; query engines.
9 
10 ;; The intention is to use these objects in several high-level packages where
11 ;; we need the ability to ask complex questions about some arbitrary data
12 ;; source.
13 
14 ;; The type of high-level packages can loosely be categorized as:
15 
16 ;; - Frontends :: The interface exposed to the user - SQL, Prolog, etc.
17 
18 ;; - Middleware :: interfaces which are used internally and exposed publicly -
19 ;; query planners/optimizers/ast
20 
21 ;; - Backends :: The interface exposed to the underlying data sources -
22 ;; RocksDB, SQLite, etc.
23 
24 ;;;; Refs
25 
26 ;; https://gist.github.com/twitu/221c8349887cec0a83b395e4cbb492a7
27 
28 ;; https://www1.columbia.edu/sec/acis/db2/db2d0/db2d0103.htm
29 
30 ;; https://howqueryengineswork.com/
31 
32 ;;; Code:
33 (in-package :obj/query)
34 
35 ;;; Types
36 (eval-always
37  (defvar *literal-value-types* '(boolean fixnum signed-byte unsigned-byte float double-float string)))
38 
39 (deftype literal-value-type () `(or ,@*literal-value-types*))
40 
41 ;;; Field
42 (defstruct field
43  (name (symbol-name (gensym "#")) :type simple-string)
44  (type t :type (or symbol list)))
45 
46 (defmethod make-load-form ((self field) &optional env)
47  (declare (ignore env))
48  `(make-field :name ,(field-name self) :type ,(field-type self)))
49 
50 ;;; Field Vectors
51 (deftype field-vector () '(vector field))
52 
53 ;; convenience interface for FIELD-VECTOR
54 (defclass column-vector () ((data :type simple-vector :accessor column-data)))
55 
56 (defclass literal-value-vector (column-vector)
57  ((type :type literal-value-type :initarg :type :accessor column-type)
58  (data :initarg :data :accessor column-data)
59  (size :type fixnum :initarg :size :accessor column-size)))
60 
61 (defgeneric column-literal-value (self)
62  (:method ((self literal-value-vector))
63  (column-data self)))
64 
65 (defgeneric column-type (self)
66  (:method ((self column-vector))
67  (array-element-type (column-data self))))
68 
69 (defgeneric column-value (self i)
70  (:method ((self column-vector) (i fixnum))
71  (aref (column-data self) i))
72  (:method ((self literal-value-vector) (i fixnum))
73  (if (or (< i 0) (>= i (column-size self)))
74  (error 'simple-error :format-control "index out of bounds: ~A" :format-arguments i)
75  (column-literal-value self))))
76 
77 ;;; Schema
78 (defclass schema ()
79  ((fields :type field-vector :initarg :fields :accessor fields)))
80 
81 (defun make-schema (&rest fields)
82  (make-instance 'schema :fields (coerce fields 'field-vector)))
83 
84 (defgeneric load-schema (self &optional schema))
85 
86 (defmethod make-load-form ((self schema) &optional env)
87  (declare (ignore env))
88  `(make-instance ,(class-of self) :fields ,(fields self)))
89 
90 (defclass schema-metadata ()
91  ((metadata :initarg :metadata :accessor schema-metadata)))
92 
93 (defmethod make-load-form ((self schema-metadata) &optional env)
94  (declare (ignore env))
95  `(make-instance ,(class-of self) :metadata ,(schema-metadata self)))
96 
97 (defgeneric column-size (self)
98  (:method ((self column-vector))
99  (length (column-data self))))
100 
101 ;;; Record Batch
102 (defstruct record-batch
103  (schema (make-schema) :type schema)
104  (fields #() :type field-vector))
105 
106 (defmethod make-load-form ((self record-batch) &optional env)
107  (declare (ignore env))
108  `(make-record-batch :schema ,(record-batch-schema self) :fields ,(record-batch-fields self)))
109 
110 ;;; Proto
111 (defgeneric field (self n)
112  (:method ((self record-batch) (n fixnum))
113  (aref (record-batch-fields self) n)))
114 
115 (defgeneric fields (self)
116  (:method ((self record-batch))
117  (record-batch-fields self)))
118 
119 (defgeneric schema (self)
120  (:method ((self record-batch))
121  (record-batch-schema self)))
122 
123 (defgeneric derive-schema (self))
124 
125 (defgeneric select (self names)
126  (:method ((self schema) (names list))
127  (let* ((fields (fields self))
128  (ret (make-array (length fields) :element-type 'field :fill-pointer 0
129  :initial-element (make-field))))
130  (make-instance 'schema
131  :fields (dolist (n names ret)
132  (if-let ((found (find n fields :test 'equal :key 'field-name)))
133  (vector-push found ret)
134  (error 'invalid-argument :item n :reason "Invalid column name"))))))
135  (:method ((self schema) (names vector))
136  (let* ((fields (fields self))
137  (ret (make-array (length fields) :element-type 'field :fill-pointer 0
138  :initial-element (make-field))))
139  (make-instance 'schema
140  :fields (loop for n across names
141  do (if-let ((found (find n fields :test 'equal :key 'field-name)))
142  (vector-push found ret)
143  (error 'invalid-argument :item n :reason "Invalid column name"))
144  finally (return ret))))))
145 
146 (defgeneric project (self indices)
147  (:method ((self schema) (indices list))
148  (make-instance 'schema
149  :fields (coerce (mapcar (lambda (i) (aref (fields self) i)) indices) 'field-vector)))
150  (:method ((self schema) (indices vector))
151  (make-instance 'schema
152  :fields (coerce
153  (loop for i across indices
154  collect (aref (fields self) i))
155  'field-vector))))
156 
157 (defgeneric row-count (self)
158  (:method ((self record-batch))
159  (sequence:length (aref (record-batch-fields self) 0))))
160 
161 (defgeneric column-count (self)
162  (:method ((self record-batch))
163  (length (record-batch-fields self))))
164 
165 ;;; Execution Context
166 (defclass execution-context () ())
167 
168 (defclass data-source ()
169  ((schema :type schema :accessor schema)))
170 
171 (defgeneric scan-data-source (self projection)
172  (:documentation "Scan the data source, selecting the specified columns."))
173 
174 ;;; Dataframes
175 ;; minimal data-frame abstraction. methods are prefixed with 'DF-'.
176 (defclass data-frame ()
177  ((fields :initform #() :initarg :fields :accessor df-fields)
178  (data :initform #() :initarg :data :accessor df-data)))
179 
180 (defgeneric df-col (self))
181 
182 (defgeneric df-project (&rest expr &key &allow-other-keys))
183 (defgeneric df-filter (expr))
184 (defgeneric df-aggregate (group-by agg-expr))
185 
186 ;;; Expressions
187 (defclass query-expression () ())
188 
189 (defclass query-plan ()
190  ((schema :type schema :accessor schema :initarg :schema)
191  (children :type (vector query-plan))))
192 
193 (defclass logical-plan (query-plan)
194  ((children :type (vector logical-plan) :accessor children :initarg :children)))
195 
196 (defclass physical-plan (query-plan)
197  ((children :type (vector physical-plan))))
198 
199 ;;; Logical Expressions
200 (defclass logical-expression (query-expression) ())
201 
202 (defgeneric to-field (self input)
203  (:method ((self string) (input logical-plan))
204  (declare (ignore input))
205  (make-field :name self :type 'string))
206  (:method ((self number) (input logical-plan))
207  (declare (ignore input))
208  (make-field :name (princ-to-string self) :type 'number)))
209 
210 (defclass column-expression (logical-expression)
211  ((name :type string :initarg :name :accessor column-name)))
212 
213 (defmethod to-field ((self column-expression) (input logical-plan))
214  (or (find (column-name self) (fields (schema input)) :test 'equal :key 'field-name)
215  (error 'invalid-argument :item (column-name self) :reason "Invalid column name")))
216 
217 (defmethod df-col ((self string))
218  (make-instance 'column-expression :name self))
219 
220 (defclass literal-expression (logical-expression) ())
221 
222 ;;;;; Alias
223 (defclass alias-expression (logical-expression)
224  ((expr :type logical-expression :initarg :expr)
225  (alias :type string :initarg :alias)))
226 
227 ;;;;; Unary
228 (defclass unary-expression (logical-expression)
229  ((expr :type logical-expression)))
230 
231 ;;;;; Binary
232 (defclass binary-expression (logical-expression)
233  ((lhs :type logical-expression :initarg :lhs :accessor lhs)
234  (rhs :type logical-expression :initarg :rhs :accessor rhs)))
235 
236 (defgeneric binary-expression-name (self))
237 (defgeneric binary-expression-op (self))
238 
239 (defclass boolean-binary-expression (binary-expression)
240  ((name :initarg :name :type string :accessor binary-expression-name)
241  (op :initarg :op :type symbol :accessor binary-expression-op)))
242 
243 (defmethod to-field ((self boolean-binary-expression) (input logical-plan))
244  (declare (ignore input))
245  (make-field :name (binary-expression-name self) :type 'boolean))
246 
247 ;; Equiv Expr
248 (defclass eq-expression (boolean-binary-expression) ()
249  (:default-initargs
250  :name "eq"
251  :op 'eq))
252 
253 (defclass neq-expression (boolean-binary-expression) ()
254  (:default-initargs
255  :name "neq"
256  :op 'neq))
257 
258 (defclass gt-expression (boolean-binary-expression) ()
259  (:default-initargs
260  :name "gt"
261  :op '>))
262 
263 (defclass lt-expression (boolean-binary-expression) ()
264  (:default-initargs
265  :name "lt"
266  :op '<))
267 
268 (defclass gteq-expression (boolean-binary-expression) ()
269  (:default-initargs
270  :name "gteq"
271  :op '>=))
272 
273 (defclass lteq-expression (boolean-binary-expression) ()
274  (:default-initargs
275  :name "lteq"
276  :op '<=))
277 
278 ;; Bool Expr
279 (defclass and-expression (boolean-binary-expression) ()
280  (:default-initargs
281  :name "and"
282  :op 'and))
283 
284 (defclass or-expression (boolean-binary-expression) ()
285  (:default-initargs
286  :name "or"
287  :op 'or))
288 
289 ;; Math Expr
290 (defclass math-expression (binary-expression)
291  ((name :initarg :name :type string :accessor binary-expression-name)
292  (op :initarg :op :type symbol :accessor binary-expression-op)))
293 
294 ;; TODO 2024-08-03: ???
295 (defmethod to-field ((self math-expression) (input logical-plan))
296  (declare (ignorable input))
297  (make-field :name "mult" :type (field-type (to-field (lhs self) input))))
298 
299 (defclass add-expression (math-expression) ()
300  (:default-initargs
301  :name "add"
302  :op '+))
303 
304 (defclass sub-expression (math-expression) ()
305  (:default-initargs
306  :name "sub"
307  :op '-))
308 
309 (defclass mult-expression (math-expression) ()
310  (:default-initargs
311  :name "mult"
312  :op '*))
313 
314 (defclass div-expression (math-expression) ()
315  (:default-initargs
316  :name "div"
317  :op '/))
318 
319 (defclass mod-expression (math-expression) ()
320  (:default-initargs
321  :name "mod"
322  :op 'mod))
323 
324 ;;;;; Agg Expr
325 (deftype aggregate-function () `(function ((input logical-expression)) query-expression))
326 
327 (deftype aggregate-function-designator () `(or aggregate-function symbol))
328 
329 (defclass aggregate-expression (logical-expression)
330  ((name :type string)
331  (expr :type logical-expression)))
332 
333 (defmethod to-field ((self aggregate-expression) (input logical-plan))
334  (declare (ignorable input))
335  (make-field :name (slot-value self 'name) :type (field-type (to-field (slot-value self 'expr) input))))
336 
337 (defclass sum-expression (aggregate-expression) ()
338  (:default-initargs
339  :name "SUM"))
340 
341 (defclass min-expression (aggregate-expression) ()
342  (:default-initargs
343  :name "MIN"))
344 
345 (defclass max-expression (aggregate-expression) ()
346  (:default-initargs
347  :name "MAX"))
348 
349 (defclass avg-expression (aggregate-expression) ()
350  (:default-initargs
351  :name "AVG"))
352 
353 (defclass count-expression (aggregate-expression) ()
354  (:default-initargs
355  :name "COUNT"))
356 
357 (defmethod to-field ((self count-expression) (input logical-plan))
358  (declare (ignore input))
359  (make-field :name "COUNT" :type 'number))
360 
361 ;;; Logical Plan
362 
363 ;;;;; Scan
364 (defclass scan-data (logical-plan)
365  ((path :type string :initarg :path)
366  (data-source :type data-source :initarg :data-source)
367  (projection :type (vector string) :initarg :projection)))
368 
369 (defmethod derive-schema ((self scan-data))
370  (let ((proj (slot-value self 'projection)))
371  (if (= 0 (length proj))
372  (slot-value self 'schema)
373  (select (slot-value self 'schema) proj))))
374 
375 (defmethod schema ((self scan-data))
376  (derive-schema self))
377 
378 ;;;;; Projection
379 (defclass projection (logical-plan)
380  ((input :type logical-plan :initarg :input)
381  (expr :type (vector logical-expression) :initarg :expr)))
382 
383 (defmethod schema ((self projection))
384  (schema (slot-value self 'input)))
385 
386 ;;;;; Selection
387 (defclass selection (logical-plan)
388  ((input :type logical-plan :initarg :input)
389  (expr :type logical-expression :initarg :expr)))
390 
391 (defmethod schema ((self selection))
392  (schema (slot-value self 'input)))
393 
394 ;;;;; Aggregate
395 (defclass aggregate (logical-plan)
396  ((input :type logical-plan :initarg :input)
397  (group-expr :type (vector logical-expression) :initarg :group-expr)
398  (agg-expr :type (vector aggregate-expression) :initarg :agg-expr)))
399 
400 (defmethod schema ((self aggregate))
401  (let ((input (slot-value self 'input))
402  (ret))
403  (loop for g across (slot-value self 'group-expr)
404  do (push (to-field g input) ret))
405  (loop for a across (slot-value self 'agg-expr)
406  do (push (to-field a input) ret))
407  (make-schema :fields (coerce ret 'field-vector))))
408 
409 ;;; Physical Expression
410 (defclass physical-expression (query-expression) ())
411 
412 (defclass literal-physical-expression (physical-expression) ())
413 
414 (defgeneric evaluate (self input)
415  (:documentation "Evaluate the expression SELF with INPUT and return a COLUMN-VECTOR result.")
416  (:method ((self string) (input record-batch))
417  (make-instance 'literal-value-vector
418  :size (row-count input)
419  :type 'string
420  :data (sb-ext:string-to-octets self)))
421  (:method ((self number) (input record-batch))
422  (make-instance 'literal-value-vector :size (row-count input) :type 'number :data self)))
423 
424 (defclass column-physical-expression (physical-expression)
425  ((val :type array-index :initarg :val)))
426 
427 (defmethod evaluate ((self column-physical-expression) (input record-batch))
428  (field input (slot-value self 'val)))
429 
430 (defclass binary-physical-expression (physical-expression)
431  ((lhs :type physical-expression :accessor lhs :initarg :lhs)
432  (rhs :type physical-expression :accessor rhs :initarg :rhs)))
433 
434 (defgeneric evaluate2 (self lhs rhs))
435 
436 (defmethod evaluate ((self binary-physical-expression) (input record-batch))
437  (let ((ll (evaluate (lhs self) input))
438  (rr (evaluate (rhs self) input)))
439  (assert (= (length ll) (length rr)))
440  (if (eql (column-type ll) (column-type rr))
441  (evaluate2 self ll rr)
442  (error "invalid state! lhs != rhs"))))
443 
444 (defclass eq-physical-expression (binary-physical-expression) ())
445 
446 (defmethod evaluate2 ((self eq-physical-expression) lhs rhs)
447  (declare (ignore self))
448  (equal lhs rhs))
449 
450 (defclass neq-physical-expression (binary-physical-expression) ())
451 
452 (defmethod evaluate2 ((self neq-physical-expression) lhs rhs)
453  (declare (ignore self))
454  (equal lhs rhs))
455 
456 (defclass lt-physical-expression (binary-physical-expression) ())
457 
458 (defclass gt-physical-expression (binary-physical-expression) ())
459 
460 (defclass lteq-physical-expression (binary-physical-expression) ())
461 
462 (defclass gteq-physical-expression (binary-physical-expression) ())
463 
464 (defclass and-physical-expression (binary-physical-expression) ())
465 
466 (defclass or-physical-expression (binary-physical-expression) ())
467 
468 (defclass math-physical-expression (binary-physical-expression) ())
469 
470 (defmethod evaluate2 ((self math-physical-expression) (lhs column-vector) (rhs column-vector))
471  (coerce (loop for i below (column-size lhs)
472  collect (evaluate2 self (column-value lhs i) (column-value rhs i)))
473  'field-vector))
474 
475 (defclass add-physical-expresion (math-expression) ())
476 
477 (defmethod evaluate2 ((self add-physical-expresion) lhs rhs)
478  (declare (ignore self))
479  (+ lhs rhs))
480 
481 (defclass sub-physical-expression (math-expression) ())
482 
483 (defmethod evaluate2 ((self sub-physical-expression) lhs rhs)
484  (declare (ignore self))
485  (- lhs rhs))
486 
487 (defclass mult-physical-expression (math-expression) ())
488 
489 (defmethod evaluate2 ((self mult-physical-expression) lhs rhs)
490  (declare (ignore self))
491  (* lhs rhs))
492 
493 (defclass div-physical-expression (math-expression) ())
494 
495 (defmethod evaluate2 ((self div-physical-expression) lhs rhs)
496  (declare (ignore self))
497  (/ lhs rhs))
498 
499 (defclass accumulator ()
500  ((value :initarg :value :accessor accumulator-value)))
501 
502 (defgeneric accumulate (self val)
503  (:method ((self accumulator) val)
504  (when val
505  (setf (accumulator-value self) (+ val (accumulator-value self))))))
506 
507 (defgeneric make-accumulator (self))
508 
509 ;; max-accumulator
510 (defclass max-accumulator (accumulator) ())
511 
512 (defmethod accumulate ((self max-accumulator) (val number))
513  (when (> val (accumulator-value self))
514  (setf (accumulator-value self) val)))
515 
516 (defclass aggregate-physical-expression (physical-expression)
517  ((input :type physical-expression)))
518 
519 (defclass max-physical-expression (aggregate-physical-expression) ())
520 
521 (defmethod make-accumulator ((self max-physical-expression))
522  (make-instance 'max-accumulator))
523 
524 ;;; Physical Plan
525 (defgeneric execute (self))
526 
527 (defclass scan-exec (physical-plan)
528  ((data-source :type data-source :initarg :data-source)
529  (projection :type (vector string) :initarg :projection)))
530 
531 (defmethod schema ((self scan-exec))
532  (select (schema (slot-value self 'data-source)) (slot-value self 'projection)))
533 
534 (defmethod execute ((self scan-exec))
535  (scan-data-source (slot-value self 'data-source) (slot-value self 'projection)))
536 
537 (defclass projection-exec (physical-plan)
538  ((input :type physical-plan :initarg :input)
539  (expr :type (vector physical-expression) :initarg :expr)))
540 
541 (defmethod execute ((self projection-exec))
542  (coerce
543  (loop for batch across (fields (execute (slot-value self 'input)))
544  collect (make-record-batch :schema (slot-value self 'schema)
545  :fields (coerce
546  (loop for e across (slot-value self 'expr)
547  collect (evaluate e batch))
548  'field-vector)))
549  '(vector record-batch)))
550 
551 
552 (defclass selection-exec (physical-plan)
553  ((input :type physical-plan :initarg :input)
554  (expr :type physical-expression :initarg :expr)))
555 
556 (defmethod schema ((self selection-exec))
557  (schema (slot-value self 'input)))
558 
559 (defmethod execute ((self selection-exec))
560  (coerce
561  (loop for batch across (execute (slot-value self 'input))
562  with res = (coerce (evaluate (slot-value self 'expr) batch) 'bit-vector)
563  with schema = (schema batch)
564  with count = (column-count (fields (schema batch)))
565  with filtered = (loop for i from 0 below count
566  collect (filter self (field batch i) res))
567  collect (make-record-batch :schema schema :fields (coerce filtered 'field-vector)))
568  '(vector record-batch)))
569 
570 (defgeneric filter (self columns selection)
571  (:method ((self selection-exec) (columns column-vector) (selection simple-bit-vector))
572  (coerce
573  (loop for i from 0 below (length selection)
574  unless (zerop (bit selection i))
575  collect (column-value columns i))
576  'field-vector)))
577 
578 (defclass hash-aggregate-exec (physical-plan)
579  ((input :type physical-plan :initarg :input)
580  (group-expr :type (vector physical-plan) :initarg :group-expr)
581  (agg-expr :type (vector aggregate-physical-expression) :initarg :agg-expr)))
582 
583 (defmethod execute ((self hash-aggregate-exec))
584  (coerce
585  (loop for batch across (execute (slot-value self 'input))
586  with map = (make-hash-table :test 'equal)
587  with groupkeys = (map 'vector (lambda (x) (evaluate x batch)) (slot-value self 'group-expr))
588  with aggr-inputs = (map 'vector (lambda (x) (evaluate (slot-value x 'input) batch))
589  (slot-value self 'agg-expr))
590  do (loop for row-idx from 0 below (row-count batch)
591  with row-key = (map 'vector
592  (lambda (x)
593  (when-let ((val (column-value x row-idx)))
594  (typecase val
595  (octet-vector (sb-ext:octets-to-string val))
596  (t val))))
597  groupkeys)
598  with accs = (if-let ((val (gethash row-key map)))
599  val
600  (setf
601  (gethash row-key map)
602  (map 'vector
603  #'make-accumulator
604  (slot-value self 'agg-expr))))
605  ;; start accumulating
606  do (loop for i from 0 below (length accs)
607  for accum across accs
608  with val = (column-value (aref aggr-inputs i) row-idx)
609  return (accumulate accum val))
610  ;; collect results in array
611  with ret = (make-record-batch :schema (slot-value self 'schema)
612  :fields (make-array (hash-table-size map)
613  :element-type 'field
614  :initial-element (make-field)))
615  do (loop for row-idx from 0 below (hash-table-size map)
616  for gkey being the hash-keys of map
617  using (hash-value accums)
618  with glen = (length (slot-value self 'group-expr))
619  do (loop for i from 0 below glen
620  do (setf (aref (aref (fields ret) i) row-idx)
621  (aref gkey i)))
622  do (loop for i from 0 below (length (slot-value self 'agg-expr))
623  do (setf (aref (aref (fields ret) (+ i glen)) row-idx)
624  (accumulator-value (aref accums i)))))
625  collect ret))
626  '(vector record-batch)))
627 
628 ;;; Planner
629 
630 ;; The Query Planner is effectively a compiler which translates logical
631 ;; expressions and plans into their physical counterparts.
632 
633 (defclass query-planner () ())
634 
635 (defgeneric make-physical-expression (expr input)
636  (:documentation "Translate logical expression EXPR and logical plan INPUT
637  into a physical expression.")
638  (:method ((expr string) (input logical-plan))
639  (declare (ignore input))
640  expr)
641  (:method ((expr number) (input logical-plan))
642  (declare (ignore input))
643  expr)
644  (:method ((expr column-expression) (input logical-plan))
645  (let ((i (position (column-name expr) (fields (schema input)) :key 'field-name :test 'equal)))
646  (make-instance 'column-physical-expression :val i)))
647  (:method ((expr binary-expression) (input logical-plan))
648  (let ((l (make-physical-expression (lhs expr) input))
649  (r (make-physical-expression (rhs expr) input)))
650  (etypecase expr
651  (eq-expression (make-instance 'eq-physical-expression :lhs l :rhs r))
652  (neq-expression (make-instance 'neq-physical-expression :lhs l :rhs r))
653  (gt-expression (make-instance 'gt-physical-expression :lhs l :rhs r))
654  (gteq-expression (make-instance 'gteq-physical-expression :lhs l :rhs r))
655  (lt-expression (make-instance 'lt-physical-expression :lhs l :rhs r))
656  (lteq-expression (make-instance 'lteq-physical-expression :lhs l :rhs r))
657  (and-expression (make-instance 'and-physical-expression :lhs l :rhs r))
658  (or-expression (make-instance 'or-physical-expression :lhs l :rhs r))
659  (add-expression (make-instance 'add-physical-expresion :lhs l :rhs r))
660  (sub-expression (make-instance 'sub-physical-expression :lhs l :rhs r))
661  (mult-expression (make-instance 'mult-physical-expression :lhs l :rhs r))
662  (div-expression (make-instance 'div-physical-expression :lhs l :rhs r))))))
663 
664 (defgeneric make-physical-plan (plan)
665  (:documentation "Create a physical plan from logical PLAN.")
666  (:method ((plan logical-plan))
667  (etypecase plan
668  (scan-data (make-instance 'scan-exec
669  :data-source (slot-value plan 'data-source)
670  :projection (slot-value plan 'projection)))
671  (projection (make-instance 'projection-exec
672  :schema (make-instance 'schema
673  :fields
674  (map 'field-vector
675  (lambda (x) (to-field x (slot-value plan 'input)))
676  (slot-value plan 'expr)))
677  :input (make-physical-plan (slot-value plan 'input))
678  :expr (map 'vector (lambda (x) (make-physical-expression x (slot-value plan 'input)))
679  (slot-value plan 'expr))))
680  (selection (make-instance 'selection-exec
681  :input (make-physical-plan (slot-value plan 'input))
682  :expr (make-physical-expression (slot-value plan 'expr) (slot-value plan 'input))))
683  (aggregate (make-instance 'hash-aggregate-exec
684  :input (make-physical-plan (slot-value plan 'input))
685  :group-expr (make-physical-expression (slot-value plan 'group-expr) (slot-value plan 'input))
686  :agg-expr (make-physical-expression (slot-value plan 'agg-expr) (slot-value plan 'input)))))))
687 
688 ;;; Joins
689 
690 ;; TODO 2024-08-02:
691 
692 ;; inner-join
693 
694 ;; outer-join left-outer-join right-outer-join
695 
696 ;; semi-join
697 
698 ;; anti-join
699 
700 ;; cross-join
701 
702 ;;; Subqueries
703 
704 ;; TODO 2024-08-02:
705 
706 ;; subquery
707 
708 ;; correlated-subquery
709 
710 ;; SELECT id, name, (SELECT count(*) FROM orders WHERE customer_id = customer.id) AS num_orders FROM customers
711 
712 ;; uncorrelated-subquery
713 
714 ;; scalar-subquery
715 
716 ;; SELECT * FROM orders WHERE total > (SELECT avg(total) FROM sales WHERE customer_state = 'CA')
717 
718 ;; NOTE 2024-08-02: EXISTS, IN, NOT EXISTS, and NOT IN are also subqueries
719 
720 ;;; Optimizer
721 
722 ;; The Query Optimizer is responsible for walking a QUERY-PLAN and returning a
723 ;; modified version of the same object. Usually we want to run optimization on
724 ;; LOGICAL-PLANs but we also support specializing on PHYSICAL-PLAN.
725 
726 ;; Rule-based Optimizers: projection/predicate push-down, sub-expr elim
727 
728 ;; TBD: Cost-based optimizers
729 ;; TODO 2024-07-10:
730 (defclass query-optimizer () ())
731 
732 (defstruct (query-vop (:constructor make-query-vop (info)))
733  (info nil))
734 
735 (defgeneric optimize-query (self plan))
736 
737 ;; Projection Pushdown
738 (defun extract-columns (expr input &optional accum)
739  (etypecase expr
740  (array-index (accumulate accum (field (fields (schema input)) expr)))
741  (column-expression (accumulate accum (column-name expr)))
742  (binary-expression
743  (extract-columns (lhs expr) input accum)
744  (extract-columns (rhs expr) input accum))
745  (alias-expression (extract-columns (slot-value expr 'expr) input accum))
746  ;; cast-expression
747  (literal-expression nil)))
748 
749 (defun extract-columns* (exprs input &optional accum)
750  (mapcar (lambda (x) (extract-columns x input accum)) exprs))
751 
752 (defclass projection-pushdown-optimizer (query-optimizer) ())
753 
754 (defun %pushdown (plan &optional column-names)
755  (declare (logical-plan plan))
756  (etypecase plan
757  (projection
758  (extract-columns (slot-value plan 'expr) column-names)
759  (let ((input (%pushdown (slot-value plan 'input) column-names)))
760  (make-instance 'projection :input input :expr (slot-value plan 'expr))))
761  (selection
762  (extract-columns (slot-value plan 'expr) column-names)
763  (let ((input (%pushdown (slot-value plan 'input) column-names)))
764  (make-instance 'selection :input input :expr (slot-value plan 'expr))))
765  (aggregate
766  (extract-columns (slot-value plan 'group-expr) column-names)
767  (extract-columns*
768  (loop for x across (slot-value plan 'agg-expr) collect (slot-value x 'input))
769  column-names)
770  (let ((input (%pushdown (slot-value plan 'input) column-names)))
771  (make-instance 'aggregate
772  :input input
773  :group-expr (slot-value plan 'group-expr)
774  :agg-expr (slot-value plan 'agg-expr))))
775  (scan-data (make-instance 'scan-data
776  :path (slot-value plan 'name)
777  :data-source (slot-value plan 'data-source)
778  :projection column-names)))) ;; maybe sort here?
779 
780 (defmethod optimize-query ((self projection-pushdown-optimizer) (plan logical-plan))
781  (%pushdown plan))
782 
783 ;;; Query
784 (defclass query () ())
785 
786 (defgeneric make-query (self &rest initargs &key &allow-other-keys)
787  (:method ((self t) &rest initargs)
788  (declare (ignore initargs))
789  (make-instance 'query)))