4c11dbea69b0a235882046e0776c5b50157761f9
[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)
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         ;;; KMR: The TYPE field is used by CommonSQL for type conversion -- it
153       ;;; should not be output in SQL statements
154       #+ignore
155       (format *sql-stream* "~@[~A.~]~A~@[ ~A~]"
156               (when qualifier
157                 (convert-to-db-default-case (sql-escape qualifier) database))
158               (sql-escape (convert-to-db-default-case name database))
159               (when type
160                 (convert-to-db-default-case (symbol-name type) database)))
161       (format *sql-stream* "~@[~A.~]~A"
162               (when qualifier
163                 (convert-to-db-default-case (sql-escape qualifier) database))
164               (sql-escape (convert-to-db-default-case name database))))
165     t))
166
167 (defmethod output-sql-hash-key ((expr sql-ident-attribute) database)
168   (declare (ignore database))
169   (with-slots (qualifier name type params)
170     expr
171     (list 'sql-ident-attribute qualifier name type params)))
172
173 ;; For SQL Identifiers for tables
174 (defclass sql-ident-table (sql-ident)
175   ((alias
176     :initarg :table-alias :initform nil))
177   (:documentation "An SQL table identifier."))
178
179 (defmethod make-load-form ((sql sql-ident-table) &optional environment)
180   (declare (ignore environment))
181   (with-slots (alias name)
182     sql
183     `(make-instance 'sql-ident-table :name ',name :table-alias ',alias)))
184
185 (defun generate-sql (expr database)
186   (let ((*sql-stream* (make-string-output-stream)))
187     (output-sql expr database)
188     (get-output-stream-string *sql-stream*)))
189
190 (defmethod output-sql ((expr sql-ident-table) database)
191   (with-slots (name alias)
192     expr
193     (if (null alias)
194         (write-string (sql-escape (convert-to-db-default-case (symbol-name name) database)) *sql-stream*)
195         (progn
196           (write-string (sql-escape (convert-to-db-default-case (symbol-name name) database)) *sql-stream*)
197           (write-char #\Space *sql-stream*)
198           (format *sql-stream* "~s" alias))))
199   t)
200
201 #|
202 (defmethod database-output-sql ((self duration) database)
203   (declare (ignore database))
204   (format nil "'~a'" (duration-timestring self)))
205
206 (defmethod database-output-sql ((self money) database)
207   (database-output-sql (slot-value self 'odcl::units) database))
208 |#
209
210
211 (defmethod output-sql-hash-key ((expr sql-ident-table) database)
212   (declare (ignore database))
213   (with-slots (name alias)
214     expr
215     (list 'sql-ident-table name alias)))
216
217 (defclass sql-relational-exp (%sql-expression)
218   ((operator
219     :initarg :operator
220     :initform nil)
221    (sub-expressions
222     :initarg :sub-expressions
223     :initform nil))
224   (:documentation "An SQL relational expression."))
225
226 (defmethod collect-table-refs ((sql sql-relational-exp))
227   (let ((tabs nil))
228     (dolist (exp (slot-value sql 'sub-expressions))
229       (let ((refs (collect-table-refs exp)))
230         (if refs (setf tabs (append refs tabs)))))
231     (remove-duplicates tabs
232                        :test (lambda (tab1 tab2)
233                                (equal (slot-value tab1 'name)
234                                       (slot-value tab2 'name))))))
235
236
237
238
239 ;; Write SQL for relational operators (like 'AND' and 'OR').
240 ;; should do arity checking of subexpressions
241
242 (defmethod output-sql ((expr sql-relational-exp) database)
243   (with-slots (operator sub-expressions)
244     expr
245     (let ((subs (if (consp (car sub-expressions))
246                     (car sub-expressions)
247                     sub-expressions)))
248       (write-char #\( *sql-stream*)
249       (do ((sub subs (cdr sub)))
250           ((null (cdr sub)) (output-sql (car sub) database))
251         (output-sql (car sub) database)
252         (write-char #\Space *sql-stream*)
253         (output-sql operator database)
254         (write-char #\Space *sql-stream*))
255       (write-char #\) *sql-stream*)))
256   t)
257
258 (defclass sql-upcase-like (sql-relational-exp)
259   ()
260   (:documentation "An SQL 'like' that upcases its arguments."))
261   
262 ;; Write SQL for relational operators (like 'AND' and 'OR').
263 ;; should do arity checking of subexpressions
264   
265 (defmethod output-sql ((expr sql-upcase-like) database)
266   (flet ((write-term (term)
267            (write-string "upper(" *sql-stream*)
268            (output-sql term database)
269            (write-char #\) *sql-stream*)))
270     (with-slots (sub-expressions)
271       expr
272       (let ((subs (if (consp (car sub-expressions))
273                       (car sub-expressions)
274                       sub-expressions)))
275         (write-char #\( *sql-stream*)
276         (do ((sub subs (cdr sub)))
277             ((null (cdr sub)) (write-term (car sub)))
278           (write-term (car sub))
279           (write-string " LIKE " *sql-stream*))
280         (write-char #\) *sql-stream*))))
281   t)
282
283 (defclass sql-assignment-exp (sql-relational-exp)
284   ()
285   (:documentation "An SQL Assignment expression."))
286
287
288 (defmethod output-sql ((expr sql-assignment-exp) database)
289   (with-slots (operator sub-expressions)
290     expr
291     (do ((sub sub-expressions (cdr sub)))
292         ((null (cdr sub)) (output-sql (car sub) database))
293       (output-sql (car sub) database)
294       (write-char #\Space *sql-stream*)
295       (output-sql operator database)
296       (write-char #\Space *sql-stream*)))
297   t)
298
299 (defclass sql-value-exp (%sql-expression)
300   ((modifier
301     :initarg :modifier
302     :initform nil)
303    (components
304     :initarg :components
305     :initform nil))
306   (:documentation
307    "An SQL value expression.")
308   )
309
310 (defmethod collect-table-refs ((sql sql-value-exp))
311   (let ((tabs nil))
312     (if (listp (slot-value sql 'components))
313         (progn
314           (dolist (exp (slot-value sql 'components))
315             (let ((refs (collect-table-refs exp)))
316               (if refs (setf tabs (append refs tabs)))))
317           (remove-duplicates tabs
318                              :test (lambda (tab1 tab2)
319                                      (equal (slot-value tab1 'name)
320                                             (slot-value tab2 'name)))))
321         nil)))
322
323
324
325 (defmethod output-sql ((expr sql-value-exp) database)
326   (with-slots (modifier components)
327     expr
328     (if modifier
329         (progn
330           (write-char #\( *sql-stream*)
331           (output-sql modifier database)
332           (write-char #\Space *sql-stream*)
333           (output-sql components database)
334           (write-char #\) *sql-stream*))
335         (output-sql components database))))
336
337 (defclass sql-typecast-exp (sql-value-exp)
338   ()
339   (:documentation "An SQL typecast expression."))
340
341 (defmethod output-sql ((expr sql-typecast-exp) 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) database)
375   (with-slots (name args)
376     expr
377     (output-sql name database)
378     (when args (output-sql args database)))
379   t)
380
381 (defclass sql-query (%sql-expression)
382   ((selections
383     :initarg :selections
384     :initform nil)
385    (all
386     :initarg :all
387     :initform nil)
388    (flatp
389     :initarg :flatp
390     :initform nil)
391    (set-operation
392     :initarg :set-operation
393     :initform nil)
394    (distinct
395     :initarg :distinct
396     :initform nil)
397    (from
398     :initarg :from
399     :initform nil)
400    (where
401     :initarg :where
402     :initform nil)
403    (group-by
404     :initarg :group-by
405     :initform nil)
406    (having
407     :initarg :having
408     :initform nil)
409    (limit
410     :initarg :limit
411     :initform nil)
412    (offset
413     :initarg :offset
414     :initform nil)
415    (order-by
416     :initarg :order-by
417     :initform nil)
418    (order-by-descending
419     :initarg :order-by-descending
420     :initform nil))
421   (:documentation "An SQL SELECT query."))
422
423 (defmethod collect-table-refs ((sql sql-query))
424   (remove-duplicates (collect-table-refs (slot-value sql 'where))
425                      :test (lambda (tab1 tab2)
426                              (equal (slot-value tab1 'name)
427                                     (slot-value tab2 'name)))))
428
429 (defvar *select-arguments*
430   '(:all :database :distinct :flatp :from :group-by :having :order-by
431     :order-by-descending :set-operation :where :offset :limit))
432
433 (defun query-arg-p (sym)
434   (member sym *select-arguments*))
435
436 (defun query-get-selections (select-args)
437   "Return two values: the list of select-args up to the first keyword,
438 uninclusive, and the args from that keyword to the end."
439   (let ((first-key-arg (position-if #'query-arg-p select-args)))
440     (if first-key-arg
441         (values (subseq select-args 0 first-key-arg)
442                 (subseq select-args first-key-arg))
443         select-args)))
444
445 (defun make-query (&rest args)
446   (flet ((select-objects (target-args)
447            (and target-args
448                 (every #'(lambda (arg)
449                            (and (symbolp arg)
450                                 (find-class arg nil)))
451                        target-args))))
452     (multiple-value-bind (selections arglist)
453         (query-get-selections args)
454       (if (select-objects selections) 
455           (apply #'select args)
456           (destructuring-bind (&key all flatp set-operation distinct from where
457                                     group-by having order-by order-by-descending
458                                     offset limit &allow-other-keys)
459               arglist
460             (if (null selections)
461                 (error "No target columns supplied to select statement."))
462             (if (null from)
463                 (error "No source tables supplied to select statement."))
464             (make-instance 'sql-query :selections selections
465                            :all all :flatp flatp :set-operation set-operation
466                            :distinct distinct :from from :where where
467                            :limit limit :offset offset
468                            :group-by group-by :having having :order-by order-by
469                            :order-by-descending order-by-descending))))))
470
471 (defvar *in-subselect* nil)
472
473 (defmethod output-sql ((query sql-query) database)
474   (with-slots (distinct selections from where group-by having order-by
475                         order-by-descending limit offset)
476       query
477     (when *in-subselect*
478       (write-string "(" *sql-stream*))
479     (write-string "SELECT " *sql-stream*)
480     (when distinct
481       (write-string "DISTINCT " *sql-stream*)
482       (unless (eql t distinct)
483         (write-string "ON " *sql-stream*)
484         (output-sql distinct database)
485         (write-char #\Space *sql-stream*)))
486     (output-sql (apply #'vector selections) database)
487     (write-string " FROM " *sql-stream*)
488     (if (listp from)
489         (output-sql (apply #'vector from) database)
490         (output-sql from database))
491     (when where
492       (write-string " WHERE " *sql-stream*)
493       (let ((*in-subselect* t))
494         (output-sql where database)))
495     (when group-by
496       (write-string " GROUP BY " *sql-stream*)
497       (output-sql group-by database))
498     (when having
499       (write-string " HAVING " *sql-stream*)
500       (output-sql having database))
501     (when order-by
502       (write-string " ORDER BY " *sql-stream*)
503       (if (listp order-by)
504           (do ((order order-by (cdr order)))
505               ((null order))
506             (output-sql (car order) database)
507             (when (cdr order)
508               (write-char #\, *sql-stream*)))
509           (output-sql order-by database)))
510     (when order-by-descending
511       (write-string " ORDER BY " *sql-stream*)
512       (if (listp order-by-descending)
513           (do ((order order-by-descending (cdr order)))
514               ((null order))
515             (output-sql (car order) database)
516             (when (cdr order)
517               (write-char #\, *sql-stream*)))
518           (output-sql order-by-descending database))
519       (write-string " DESC " *sql-stream*))
520     (when limit
521       (write-string " LIMIT " *sql-stream*)
522       (output-sql limit database))
523     (when offset
524       (write-string " OFFSET " *sql-stream*)
525       (output-sql offset database))
526     (when *in-subselect*
527       (write-string ")" *sql-stream*)))
528   t)
529
530 ;; INSERT
531
532 (defclass sql-insert (%sql-expression)
533   ((into
534     :initarg :into
535     :initform nil)
536    (attributes
537     :initarg :attributes
538     :initform nil)
539    (values
540     :initarg :values
541     :initform nil)
542    (query
543     :initarg :query
544     :initform nil))
545   (:documentation
546    "An SQL INSERT statement."))
547
548 (defmethod output-sql ((ins sql-insert) database)
549   (with-slots (into attributes values query)
550     ins
551     (write-string "INSERT INTO " *sql-stream*)
552     (output-sql into database)
553     (when attributes
554       (write-char #\Space *sql-stream*)
555       (output-sql attributes database))
556     (when values
557       (write-string " VALUES " *sql-stream*)
558       (output-sql values database))
559     (when query
560       (write-char #\Space *sql-stream*)
561       (output-sql query database)))
562   t)
563
564 ;; DELETE
565
566 (defclass sql-delete (%sql-expression)
567   ((from
568     :initarg :from
569     :initform nil)
570    (where
571     :initarg :where
572     :initform nil))
573   (:documentation
574    "An SQL DELETE statement."))
575
576 (defmethod output-sql ((stmt sql-delete) database)
577   (with-slots (from where)
578     stmt
579     (write-string "DELETE FROM " *sql-stream*)
580     (typecase from
581       (symbol (write-string (sql-escape from) *sql-stream*))
582       (t  (output-sql from database)))
583     (when where
584       (write-string " WHERE " *sql-stream*)
585       (output-sql where database)))
586   t)
587
588 ;; UPDATE
589
590 (defclass sql-update (%sql-expression)
591   ((table
592     :initarg :table
593     :initform nil)
594    (attributes
595     :initarg :attributes
596     :initform nil)
597    (values
598     :initarg :values
599     :initform nil)
600    (where
601     :initarg :where
602     :initform nil))
603   (:documentation "An SQL UPDATE statement."))
604
605 (defmethod output-sql ((expr sql-update) database)
606   (with-slots (table where attributes values)
607     expr
608     (flet ((update-assignments ()
609              (mapcar #'(lambda (a b)
610                          (make-instance 'sql-assignment-exp
611                                         :operator '=
612                                         :sub-expressions (list a b)))
613                      attributes values)))
614       (write-string "UPDATE " *sql-stream*)
615       (output-sql table database)
616       (write-string " SET " *sql-stream*)
617       (output-sql (apply #'vector (update-assignments)) database)
618       (when where
619         (write-string " WHERE " *sql-stream*)
620         (output-sql where database))))
621   t)
622
623 ;; CREATE TABLE
624
625 (defclass sql-create-table (%sql-expression)
626   ((name
627     :initarg :name
628     :initform nil)
629    (columns
630     :initarg :columns
631     :initform nil)
632    (modifiers
633     :initarg :modifiers
634     :initform nil)
635    (transactions
636     :initarg :transactions
637     :initform nil))
638   (:documentation
639    "An SQL CREATE TABLE statement."))
640
641 ;; Here's a real warhorse of a function!
642
643 (defun listify (x)
644   (if (atom x)
645       (list x)
646       x))
647
648 (defmethod output-sql ((stmt sql-create-table) database)
649   (flet ((output-column (column-spec)
650            (destructuring-bind (name type &optional db-type &rest constraints)
651                column-spec
652              (let ((type (listify type)))
653                (output-sql name database)
654                (write-char #\Space *sql-stream*)
655                (write-string
656                 (if (stringp db-type) db-type ; override definition
657                     (database-get-type-specifier (car type) (cdr type) database))
658                 *sql-stream*)
659                (let ((constraints
660                       (database-constraint-statement constraints database)))
661                  (when constraints
662                    (write-string " " *sql-stream*)
663                    (write-string constraints *sql-stream*)))))))
664     (with-slots (name columns modifiers transactions)
665       stmt
666       (write-string "CREATE TABLE " *sql-stream*)
667       (output-sql name database)
668       (write-string " (" *sql-stream*)
669       (do ((column columns (cdr column)))
670           ((null (cdr column))
671            (output-column (car column)))
672         (output-column (car column))
673         (write-string ", " *sql-stream*))
674       (when modifiers
675         (do ((modifier (listify modifiers) (cdr modifier)))
676             ((null modifier))
677           (write-string ", " *sql-stream*)
678           (write-string (car modifier) *sql-stream*)))
679       (write-char #\) *sql-stream*)
680       (when (and (eq :mysql (database-underlying-type database))
681                  transactions
682                  (db-type-transaction-capable? :mysql database))
683         (write-string " Type=InnoDB" *sql-stream*)))) 
684   t)
685
686
687 ;; CREATE VIEW
688
689 (defclass sql-create-view (%sql-expression)
690   ((name :initarg :name :initform nil)
691    (column-list :initarg :column-list :initform nil)
692    (query :initarg :query :initform nil)
693    (with-check-option :initarg :with-check-option :initform nil))
694   (:documentation "An SQL CREATE VIEW statement."))
695
696 (defmethod output-sql ((stmt sql-create-view) database)
697   (with-slots (name column-list query with-check-option) stmt
698     (write-string "CREATE VIEW " *sql-stream*)
699     (output-sql name database)
700     (when column-list (write-string " " *sql-stream*)
701           (output-sql (listify column-list) database))
702     (write-string " AS " *sql-stream*)
703     (output-sql query database)
704     (when with-check-option (write-string " WITH CHECK OPTION" *sql-stream*))))
705
706
707 ;;
708 ;; Column constraint types
709 ;;
710 (defparameter *constraint-types*
711   (list 
712    (cons (symbol-name-default-case "NOT-NULL") "NOT NULL") 
713    (cons (symbol-name-default-case "PRIMARY-KEY") "PRIMARY KEY")))
714
715 ;;
716 ;; Convert type spec to sql syntax
717 ;;
718
719 (defmethod database-constraint-description (constraint database)
720   (declare (ignore database))
721   (let ((output (assoc (symbol-name constraint) *constraint-types*
722                        :test #'equal)))
723     (if (null output)
724         (error 'clsql-sql-syntax-error
725                :reason (format nil "unsupported column constraint '~a'"
726                                constraint))
727         (cdr output))))
728
729 (defmethod database-constraint-statement (constraint-list database)
730   (declare (ignore database))
731   (make-constraints-description constraint-list))
732   
733 (defun make-constraints-description (constraint-list)
734   (if constraint-list
735       (let ((string ""))
736         (do ((constraint constraint-list (cdr constraint)))
737             ((null constraint) string)
738           (let ((output (assoc (symbol-name (car constraint))
739                                *constraint-types*
740                                :test #'equal)))
741             (if (null output)
742                 (error 'clsql-sql-syntax-error
743                        :reason (format nil "unsupported column constraint '~a'"
744                                        constraint))
745                 (setq string (concatenate 'string string (cdr output))))
746             (if (< 1 (length constraint))
747                 (setq string (concatenate 'string string " "))))))))
748