c390c5f03e18feb77bdc3ba11459b8c149f0f59f
[clsql.git] / sql / classes.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; ======================================================================
3 ;;;; File:    classes.lisp
4 ;;;; Updated: <04/04/2004 12:08:49 marcusp>
5 ;;;; ======================================================================
6 ;;;;
7 ;;;; Description ==========================================================
8 ;;;; ======================================================================
9 ;;;;
10 ;;;; Classes defining SQL expressions and methods for formatting the
11 ;;;; appropriate SQL commands.
12 ;;;;
13 ;;;; ======================================================================
14
15 (in-package #:clsql-usql-sys)
16
17
18 (defvar +empty-string+ "''")
19
20 (defvar +null-string+ "NULL")
21
22 (defvar *sql-stream* nil
23   "stream which accumulates SQL output")
24
25 (defvar *default-schema* "UNCOMMONSQL")
26
27 (defvar *object-schemas* (make-hash-table :test #'equal)
28   "Hash of schema name to class constituent lists.")
29
30 (defun in-schema (schemaname)
31   (setf *default-schema* schemaname))
32
33 (defun sql-output (sql-expr &optional database)
34   (progv '(*sql-stream*)
35       `(,(make-string-output-stream))
36     (output-sql sql-expr database)
37     (get-output-stream-string *sql-stream*)))
38
39
40 (defclass %sql-expression ()
41   ())
42
43 (defmethod output-sql ((expr %sql-expression) &optional
44                        (database *default-database*))
45   (declare (ignore database))
46   (write-string +null-string+ *sql-stream*))
47
48 (defmethod print-object ((self %sql-expression) stream)
49   (print-unreadable-object
50    (self stream :type t)
51    (write-string (sql-output self) stream)))
52
53 ;; For straight up strings
54
55 (defclass sql (%sql-expression)
56   ((text
57     :initarg :string
58     :initform ""))
59   (:documentation "A literal SQL expression."))
60
61 (defmethod make-load-form ((sql sql) &optional environment)
62   (declare (ignore environment))
63   (with-slots (text)
64     sql
65     `(make-instance 'sql :string ',text)))
66
67 (defmethod output-sql ((expr sql) &optional (database *default-database*))
68   (declare (ignore database))
69   (write-string (slot-value expr 'text) *sql-stream*)
70   t)
71
72 (defmethod print-object ((ident sql) stream)
73   (format stream "#<~S \"~A\">"
74           (type-of ident)
75           (sql-output ident)))
76
77 ;; For SQL Identifiers of generic type
78 (defclass sql-ident (%sql-expression)
79   ((name
80     :initarg :name
81     :initform "NULL"))
82   (:documentation "An SQL identifer."))
83
84 (defmethod make-load-form ((sql sql-ident) &optional environment)
85   (declare (ignore environment))
86   (with-slots (name)
87     sql
88     `(make-instance 'sql-ident :name ',name)))
89
90 (defvar *output-hash* (make-hash-table :test #'equal))
91
92 (defmethod output-sql-hash-key (expr &optional (database *default-database*))
93   (declare (ignore expr database))
94   nil)
95
96 (defmethod output-sql :around ((sql t) &optional (database *default-database*))
97   (declare (ignore database))
98   (let* ((hash-key (output-sql-hash-key sql))
99          (hash-value (when hash-key (gethash hash-key *output-hash*))))
100     (cond ((and hash-key hash-value)
101            (write-string hash-value *sql-stream*))
102           (hash-key
103            (let ((*sql-stream* (make-string-output-stream)))
104              (call-next-method)
105              (setf hash-value (get-output-stream-string *sql-stream*))
106              (setf (gethash hash-key *output-hash*) hash-value))
107            (write-string hash-value *sql-stream*))
108           (t
109            (call-next-method)))))
110
111 (defmethod output-sql ((expr sql-ident) &optional
112                        (database *default-database*))
113   (declare (ignore database))
114   (with-slots (name)
115     expr
116     (etypecase name
117       (string
118        (write-string name *sql-stream*))
119       (symbol
120        (write-string (symbol-name name) *sql-stream*)))
121     t))
122
123 ;; For SQL Identifiers for attributes
124
125 (defclass sql-ident-attribute (sql-ident)
126   ((qualifier
127     :initarg :qualifier
128     :initform "NULL")
129    (type
130     :initarg :type
131     :initform "NULL")
132    (params
133     :initarg :params
134     :initform nil))
135   (:documentation "An SQL Attribute identifier."))
136
137 (defmethod collect-table-refs (sql)
138   (declare (ignore sql))
139   nil)
140
141 (defmethod collect-table-refs ((sql sql-ident-attribute))
142   (let ((qual (slot-value sql 'qualifier)))
143     (if (and qual (symbolp (slot-value sql 'qualifier)))
144         (list (make-instance 'sql-ident-table :name
145                              (slot-value sql 'qualifier))))))
146
147 (defmethod make-load-form ((sql sql-ident-attribute) &optional environment)
148   (declare (ignore environment))
149   (with-slots (qualifier type name)
150     sql
151     `(make-instance 'sql-ident-attribute :name ',name
152       :qualifier ',qualifier
153       :type ',type)))
154
155 (defmethod output-sql ((expr sql-ident-attribute) &optional
156                        (database *default-database*))
157   (declare (ignore database))
158   (with-slots (qualifier name type params)
159     expr
160     (if (and name (not qualifier) (not type))
161         (write-string (sql-escape (symbol-name name)) *sql-stream*)
162         (format *sql-stream* "~@[~A.~]~A~@[ ~A~]"
163                 (if qualifier (sql-escape qualifier) qualifier)
164                 (sql-escape name)
165                 type))
166     t))
167
168 (defmethod output-sql-hash-key ((expr sql-ident-attribute) &optional
169                                 (database *default-database*))
170   (declare (ignore database))
171   (with-slots (qualifier name type params)
172     expr
173     (list 'sql-ident-attribute qualifier name type params)))
174
175 ;; For SQL Identifiers for tables
176 (defclass sql-ident-table (sql-ident)
177   ((alias
178     :initarg :table-alias :initform nil))
179   (:documentation "An SQL table identifier."))
180
181 (defmethod make-load-form ((sql sql-ident-table) &optional environment)
182   (declare (ignore environment))
183   (with-slots (alias name)
184     sql
185     `(make-instance 'sql-ident-table :name name :alias ',alias)))
186
187 (defun generate-sql (expr)
188   (let ((*sql-stream* (make-string-output-stream)))
189     (output-sql expr)
190     (get-output-stream-string *sql-stream*)))
191
192 (defmethod output-sql ((expr sql-ident-table) &optional
193                        (database *default-database*))
194   (declare (ignore database))
195   (with-slots (name alias)
196     expr
197     (if (null alias)
198         (write-string (sql-escape (symbol-name name)) *sql-stream*)
199         (progn
200           (write-string (sql-escape (symbol-name name)) *sql-stream*)
201           (write-char #\Space *sql-stream*)
202           (format *sql-stream* "~s" alias))))
203   t)
204
205 (defmethod output-sql-hash-key ((expr sql-ident-table) &optional
206                                 (database *default-database*))
207   (declare (ignore database))
208   (with-slots (name alias)
209     expr
210     (list 'sql-ident-table name alias)))
211
212 (defclass sql-relational-exp (%sql-expression)
213   ((operator
214     :initarg :operator
215     :initform nil)
216    (sub-expressions
217     :initarg :sub-expressions
218     :initform nil))
219   (:documentation "An SQL relational expression."))
220
221 (defmethod collect-table-refs ((sql sql-relational-exp))
222   (let ((tabs nil))
223     (dolist (exp (slot-value sql 'sub-expressions))
224       (let ((refs (collect-table-refs exp)))
225         (if refs (setf tabs (append refs tabs)))))
226     (remove-duplicates tabs
227                        :test (lambda (tab1 tab2)
228                                (equal (slot-value tab1 'name)
229                                       (slot-value tab2 'name))))))
230
231
232
233
234 ;; Write SQL for relational operators (like 'AND' and 'OR').
235 ;; should do arity checking of subexpressions
236
237 (defmethod output-sql ((expr sql-relational-exp) &optional
238                        (database *default-database*))
239   (with-slots (operator sub-expressions)
240     expr
241     (let ((subs (if (consp (car sub-expressions))
242                     (car sub-expressions)
243                     sub-expressions)))
244       (write-char #\( *sql-stream*)
245       (do ((sub subs (cdr sub)))
246           ((null (cdr sub)) (output-sql (car sub) database))
247         (output-sql (car sub) database)
248         (write-char #\Space *sql-stream*)
249         (output-sql operator database)
250         (write-char #\Space *sql-stream*))
251       (write-char #\) *sql-stream*)))
252   t)
253
254 (defclass sql-upcase-like (sql-relational-exp)
255   ()
256   (:documentation "An SQL 'like' that upcases its arguments."))
257   
258 ;; Write SQL for relational operators (like 'AND' and 'OR').
259 ;; should do arity checking of subexpressions
260   
261 (defmethod output-sql ((expr sql-upcase-like) &optional
262                        (database *default-database*))
263   (flet ((write-term (term)
264            (write-string "upper(" *sql-stream*)
265            (output-sql term database)
266            (write-char #\) *sql-stream*)))
267     (with-slots (sub-expressions)
268       expr
269       (let ((subs (if (consp (car sub-expressions))
270                       (car sub-expressions)
271                       sub-expressions)))
272         (write-char #\( *sql-stream*)
273         (do ((sub subs (cdr sub)))
274             ((null (cdr sub)) (write-term (car sub)))
275           (write-term (car sub))
276           (write-string " LIKE " *sql-stream*))
277         (write-char #\) *sql-stream*))))
278   t)
279
280 (defclass sql-assignment-exp (sql-relational-exp)
281   ()
282   (:documentation "An SQL Assignment expression."))
283
284
285 (defmethod output-sql ((expr sql-assignment-exp) &optional
286                        (database *default-database*))
287   (with-slots (operator sub-expressions)
288     expr
289     (do ((sub sub-expressions (cdr sub)))
290         ((null (cdr sub)) (output-sql (car sub) database))
291       (output-sql (car sub) database)
292       (write-char #\Space *sql-stream*)
293       (output-sql operator database)
294       (write-char #\Space *sql-stream*)))
295   t)
296
297 (defclass sql-value-exp (%sql-expression)
298   ((modifier
299     :initarg :modifier
300     :initform nil)
301    (components
302     :initarg :components
303     :initform nil))
304   (:documentation
305    "An SQL value expression.")
306   )
307
308 (defmethod collect-table-refs ((sql sql-value-exp))
309   (let ((tabs nil))
310     (if (listp (slot-value sql 'components))
311         (progn
312           (dolist (exp (slot-value sql 'components))
313             (let ((refs (collect-table-refs exp)))
314               (if refs (setf tabs (append refs tabs)))))
315           (remove-duplicates tabs
316                              :test (lambda (tab1 tab2)
317                                      (equal (slot-value tab1 'name)
318                                             (slot-value tab2 'name)))))
319         nil)))
320
321
322
323 (defmethod output-sql ((expr sql-value-exp) &optional
324                        (database *default-database*))
325   (with-slots (modifier components)
326     expr
327     (if modifier
328         (progn
329           (write-char #\( *sql-stream*)
330           (output-sql modifier database)
331           (write-char #\Space *sql-stream*)
332           (output-sql components database)
333           (write-char #\) *sql-stream*))
334         (output-sql components database))))
335
336 (defclass sql-typecast-exp (sql-value-exp)
337   ()
338   (:documentation "An SQL typecast expression."))
339
340 (defmethod output-sql ((expr sql-typecast-exp) &optional
341                        (database *default-database*))
342   (database-output-sql expr database))
343
344 (defmethod database-output-sql ((expr sql-typecast-exp) database)
345   (with-slots (components)
346     expr
347     (output-sql components database)))
348
349
350 (defmethod collect-table-refs ((sql sql-typecast-exp))
351   (when (slot-value sql 'components)
352     (collect-table-refs (slot-value sql 'components))))
353
354 (defclass sql-function-exp (%sql-expression)
355   ((name
356     :initarg :name
357     :initform nil)
358    (args
359     :initarg :args
360     :initform nil))
361   (:documentation
362    "An SQL function expression."))
363
364 (defmethod collect-table-refs ((sql sql-function-exp))
365   (let ((tabs nil))
366     (dolist (exp (slot-value sql 'components))
367       (let ((refs (collect-table-refs exp)))
368         (if refs (setf tabs (append refs tabs)))))
369     (remove-duplicates tabs
370                        :test (lambda (tab1 tab2)
371                                (equal (slot-value tab1 'name)
372                                       (slot-value tab2 'name))))))
373
374 (defmethod output-sql ((expr sql-function-exp) &optional
375                        (database *default-database*))
376   (with-slots (name args)
377     expr
378     (output-sql name database)
379     (when args (output-sql args database)))
380   t)
381
382 (defclass sql-query (%sql-expression)
383   ((selections
384     :initarg :selections
385     :initform nil)
386    (all
387     :initarg :all
388     :initform nil)
389    (flatp
390     :initarg :flatp
391     :initform nil)
392    (set-operation
393     :initarg :set-operation
394     :initform nil)
395    (distinct
396     :initarg :distinct
397     :initform nil)
398    (from
399     :initarg :from
400     :initform nil)
401    (where
402     :initarg :where
403     :initform nil)
404    (group-by
405     :initarg :group-by
406     :initform nil)
407    (having
408     :initarg :having
409     :initform nil)
410    (limit
411     :initarg :limit
412     :initform nil)
413    (offset
414     :initarg :offset
415     :initform nil)
416    (order-by
417     :initarg :order-by
418     :initform nil)
419    (order-by-descending
420     :initarg :order-by-descending
421     :initform nil))
422   (:documentation "An SQL SELECT query."))
423
424 (defmethod collect-table-refs ((sql sql-query))
425   (remove-duplicates (collect-table-refs (slot-value sql 'where))
426                      :test (lambda (tab1 tab2)
427                              (equal (slot-value tab1 'name)
428                                     (slot-value tab2 'name)))))
429
430 (defvar *select-arguments*
431   '(:all :database :distinct :flatp :from :group-by :having :order-by
432     :order-by-descending :set-operation :where :offset :limit))
433
434 (defun query-arg-p (sym)
435   (member sym *select-arguments*))
436
437 (defun query-get-selections (select-args)
438   "Return two values: the list of select-args up to the first keyword,
439 uninclusive, and the args from that keyword to the end."
440   (let ((first-key-arg (position-if #'query-arg-p select-args)))
441     (if first-key-arg
442         (values (subseq select-args 0 first-key-arg)
443                 (subseq select-args first-key-arg))
444         select-args)))
445
446 (defmethod make-query (&rest args)
447   (multiple-value-bind (selections arglist)
448       (query-get-selections args)
449     (destructuring-bind (&key all flatp set-operation distinct from where
450                               group-by having order-by order-by-descending
451                               offset limit &allow-other-keys)
452         arglist
453       (if (null selections)
454           (error "No target columns supplied to select statement."))
455       (if (null from)
456           (error "No source tables supplied to select statement."))
457       (make-instance 'sql-query :selections selections
458                      :all all :flatp flatp :set-operation set-operation
459                      :distinct distinct :from from :where where
460                      :limit limit :offset offset
461                      :group-by group-by :having having :order-by order-by
462                      :order-by-descending order-by-descending))))
463
464 (defvar *in-subselect* nil)
465
466 (defmethod output-sql ((query sql-query) &optional
467                        (database *default-database*))
468   (with-slots (distinct selections from where group-by having order-by
469                         order-by-descending limit offset)
470       query
471     (when *in-subselect*
472       (write-string "(" *sql-stream*))
473     (write-string "SELECT " *sql-stream*)
474     (when distinct
475       (write-string "DISTINCT " *sql-stream*)
476       (unless (eql t distinct)
477         (write-string "ON " *sql-stream*)
478         (output-sql distinct database)
479         (write-char #\Space *sql-stream*)))
480     (output-sql (apply #'vector selections) database)
481     (write-string " FROM " *sql-stream*)
482     (if (listp from)
483         (output-sql (apply #'vector from) database)
484         (output-sql from database))
485     (when where
486       (write-string " WHERE " *sql-stream*)
487       (let ((*in-subselect* t))
488         (output-sql where database)))
489     (when group-by
490       (write-string " GROUP BY " *sql-stream*)
491       (output-sql group-by database))
492     (when having
493       (write-string " HAVING " *sql-stream*)
494       (output-sql having database))
495     (when order-by
496       (write-string " ORDER BY " *sql-stream*)
497       (if (listp order-by)
498           (do ((order order-by (cdr order)))
499               ((null order))
500             (output-sql (car order) database)
501             (when (cdr order)
502               (write-char #\, *sql-stream*)))
503           (output-sql order-by database)))
504     (when order-by-descending
505       (write-string " ORDER BY " *sql-stream*)
506       (if (listp order-by-descending)
507           (do ((order order-by-descending (cdr order)))
508               ((null order))
509             (output-sql (car order) database)
510             (when (cdr order)
511               (write-char #\, *sql-stream*)))
512           (output-sql order-by-descending database))
513       (write-string " DESC " *sql-stream*))
514     (when limit
515       (write-string " LIMIT " *sql-stream*)
516       (output-sql limit database))
517     (when offset
518       (write-string " OFFSET " *sql-stream*)
519       (output-sql offset database))
520     (when *in-subselect*
521       (write-string ")" *sql-stream*)))
522   t)
523
524 ;; INSERT
525
526 (defclass sql-insert (%sql-expression)
527   ((into
528     :initarg :into
529     :initform nil)
530    (attributes
531     :initarg :attributes
532     :initform nil)
533    (values
534     :initarg :values
535     :initform nil)
536    (query
537     :initarg :query
538     :initform nil))
539   (:documentation
540    "An SQL INSERT statement."))
541
542 (defmethod output-sql ((ins sql-insert) &optional
543                        (database *default-database*))
544   (with-slots (into attributes values query)
545     ins
546     (write-string "INSERT INTO " *sql-stream*)
547     (output-sql into database)
548     (when attributes
549       (write-char #\Space *sql-stream*)
550       (output-sql attributes database))
551     (when values
552       (write-string " VALUES " *sql-stream*)
553       (output-sql values database))
554     (when query
555       (write-char #\Space *sql-stream*)
556       (output-sql query database)))
557   t)
558
559 ;; DELETE
560
561 (defclass sql-delete (%sql-expression)
562   ((from
563     :initarg :from
564     :initform nil)
565    (where
566     :initarg :where
567     :initform nil))
568   (:documentation
569    "An SQL DELETE statement."))
570
571 (defmethod output-sql ((stmt sql-delete) &optional
572                        (database *default-database*))
573   (with-slots (from where)
574     stmt
575     (write-string "DELETE FROM " *sql-stream*)
576     (typecase from
577       (symbol (write-string (sql-escape from) *sql-stream*))
578       (t  (output-sql from database)))
579     (when where
580       (write-string " WHERE " *sql-stream*)
581       (output-sql where database)))
582   t)
583
584 ;; UPDATE
585
586 (defclass sql-update (%sql-expression)
587   ((table
588     :initarg :table
589     :initform nil)
590    (attributes
591     :initarg :attributes
592     :initform nil)
593    (values
594     :initarg :values
595     :initform nil)
596    (where
597     :initarg :where
598     :initform nil))
599   (:documentation "An SQL UPDATE statement."))
600
601 (defmethod output-sql ((expr sql-update) &optional
602                        (database *default-database*))
603   (with-slots (table where attributes values)
604     expr
605     (flet ((update-assignments ()
606              (mapcar #'(lambda (a b)
607                          (make-instance 'sql-assignment-exp
608                                         :operator '=
609                                         :sub-expressions (list a b)))
610                      attributes values)))
611       (write-string "UPDATE " *sql-stream*)
612       (output-sql table database)
613       (write-string " SET " *sql-stream*)
614       (output-sql (apply #'vector (update-assignments)) database)
615       (when where
616         (write-string " WHERE " *sql-stream*)
617         (output-sql where database))))
618   t)
619
620 ;; CREATE TABLE
621
622 (defclass sql-create-table (%sql-expression)
623   ((name
624     :initarg :name
625     :initform nil)
626    (columns
627     :initarg :columns
628     :initform nil)
629    (modifiers
630     :initarg :modifiers
631     :initform nil))
632   (:documentation
633    "An SQL CREATE TABLE statement."))
634
635 ;; Here's a real warhorse of a function!
636
637 (defun listify (x)
638   (if (atom x)
639       (list x)
640       x))
641
642 (defmethod output-sql ((stmt sql-create-table) &optional
643                        (database *default-database*))
644   (flet ((output-column (column-spec)
645            (destructuring-bind (name type &rest constraints)
646                column-spec
647              (let ((type (listify type)))
648                (output-sql name database)
649                (write-char #\Space *sql-stream*)
650                (write-string
651                 (database-get-type-specifier (car type) (cdr type) database)
652                 *sql-stream*)
653                (let ((constraints
654                       (database-constraint-statement constraints database)))
655                  (when constraints
656                    (write-string " " *sql-stream*)
657                    (write-string constraints *sql-stream*)))))))
658     (with-slots (name columns modifiers)
659       stmt
660       (write-string "CREATE TABLE " *sql-stream*)
661       (output-sql name database)
662       (write-string " (" *sql-stream*)
663       (do ((column columns (cdr column)))
664           ((null (cdr column))
665            (output-column (car column)))
666         (output-column (car column))
667         (write-string ", " *sql-stream*))
668       (when modifiers
669         (do ((modifier (listify modifiers) (cdr modifier)))
670             ((null modifier))
671           (write-string ", " *sql-stream*)
672           (write-string (car modifier) *sql-stream*)))
673       (write-char #\) *sql-stream*)))
674   t)
675
676
677 ;; CREATE VIEW
678
679 (defclass sql-create-view (%sql-expression)
680   ((name :initarg :name :initform nil)
681    (column-list :initarg :column-list :initform nil)
682    (query :initarg :query :initform nil)
683    (with-check-option :initarg :with-check-option :initform nil))
684   (:documentation "An SQL CREATE VIEW statement."))
685
686 (defmethod output-sql ((stmt sql-create-view) &optional database)
687   (with-slots (name column-list query with-check-option) stmt
688     (write-string "CREATE VIEW " *sql-stream*)
689     (output-sql name database)
690     (when column-list (write-string " " *sql-stream*)
691           (output-sql (listify column-list) database))
692     (write-string " AS " *sql-stream*)
693     (output-sql query database)
694     (when with-check-option (write-string " WITH CHECK OPTION" *sql-stream*))))
695
696
697 ;;
698 ;; Column constraint types
699 ;;
700 (defparameter *constraint-types*
701   '(("NOT-NULL" . "NOT NULL")
702     ("PRIMARY-KEY" . "PRIMARY KEY")))
703
704 ;;
705 ;; Convert type spec to sql syntax
706 ;;
707
708 (defmethod database-constraint-description (constraint database)
709   (declare (ignore database))
710   (let ((output (assoc (symbol-name constraint) *constraint-types*
711                        :test #'equal)))
712     (if (null output)
713         (error 'clsql-sql-syntax-error
714                :reason (format nil "unsupported column constraint '~a'"
715                                constraint))
716         (cdr output))))
717
718 (defmethod database-constraint-statement (constraint-list database)
719   (declare (ignore database))
720   (make-constraints-description constraint-list))
721   
722 (defun make-constraints-description (constraint-list)
723   (if constraint-list
724       (let ((string ""))
725         (do ((constraint constraint-list (cdr constraint)))
726             ((null constraint) string)
727           (let ((output (assoc (symbol-name (car constraint))
728                                *constraint-types*
729                                :test #'equal)))
730             (if (null output)
731                 (error 'clsql-sql-syntax-error
732                        :reason (format nil "unsupported column constraint '~a'"
733                                        constraint))
734                 (setq string (concatenate 'string string (cdr output))))
735             (if (< 1 (length constraint))
736                 (setq string (concatenate 'string string " "))))))))
737