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