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