r9220: Added type specifier for universal-time.
[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   (flet ((select-objects (target-args)
440            (and target-args
441                 (every #'(lambda (arg)
442                            (and (symbolp arg)
443                                 (find-class arg nil)))
444                        target-args))))
445     (multiple-value-bind (selections arglist)
446         (query-get-selections args)
447       (if (select-objects selections) 
448           (apply #'select 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) database)
467   (with-slots (distinct selections from where group-by having order-by
468                         order-by-descending limit offset)
469       query
470     (when *in-subselect*
471       (write-string "(" *sql-stream*))
472     (write-string "SELECT " *sql-stream*)
473     (when distinct
474       (write-string "DISTINCT " *sql-stream*)
475       (unless (eql t distinct)
476         (write-string "ON " *sql-stream*)
477         (output-sql distinct database)
478         (write-char #\Space *sql-stream*)))
479     (output-sql (apply #'vector selections) database)
480     (write-string " FROM " *sql-stream*)
481     (if (listp from)
482         (output-sql (apply #'vector from) database)
483         (output-sql from database))
484     (when where
485       (write-string " WHERE " *sql-stream*)
486       (let ((*in-subselect* t))
487         (output-sql where database)))
488     (when group-by
489       (write-string " GROUP BY " *sql-stream*)
490       (output-sql group-by database))
491     (when having
492       (write-string " HAVING " *sql-stream*)
493       (output-sql having database))
494     (when order-by
495       (write-string " ORDER BY " *sql-stream*)
496       (if (listp order-by)
497           (do ((order order-by (cdr order)))
498               ((null order))
499             (output-sql (car order) database)
500             (when (cdr order)
501               (write-char #\, *sql-stream*)))
502           (output-sql order-by database)))
503     (when order-by-descending
504       (write-string " ORDER BY " *sql-stream*)
505       (if (listp order-by-descending)
506           (do ((order order-by-descending (cdr order)))
507               ((null order))
508             (output-sql (car order) database)
509             (when (cdr order)
510               (write-char #\, *sql-stream*)))
511           (output-sql order-by-descending database))
512       (write-string " DESC " *sql-stream*))
513     (when limit
514       (write-string " LIMIT " *sql-stream*)
515       (output-sql limit database))
516     (when offset
517       (write-string " OFFSET " *sql-stream*)
518       (output-sql offset database))
519     (when *in-subselect*
520       (write-string ")" *sql-stream*)))
521   t)
522
523 ;; INSERT
524
525 (defclass sql-insert (%sql-expression)
526   ((into
527     :initarg :into
528     :initform nil)
529    (attributes
530     :initarg :attributes
531     :initform nil)
532    (values
533     :initarg :values
534     :initform nil)
535    (query
536     :initarg :query
537     :initform nil))
538   (:documentation
539    "An SQL INSERT statement."))
540
541 (defmethod output-sql ((ins sql-insert) database)
542   (with-slots (into attributes values query)
543     ins
544     (write-string "INSERT INTO " *sql-stream*)
545     (output-sql into database)
546     (when attributes
547       (write-char #\Space *sql-stream*)
548       (output-sql attributes database))
549     (when values
550       (write-string " VALUES " *sql-stream*)
551       (output-sql values database))
552     (when query
553       (write-char #\Space *sql-stream*)
554       (output-sql query database)))
555   t)
556
557 ;; DELETE
558
559 (defclass sql-delete (%sql-expression)
560   ((from
561     :initarg :from
562     :initform nil)
563    (where
564     :initarg :where
565     :initform nil))
566   (:documentation
567    "An SQL DELETE statement."))
568
569 (defmethod output-sql ((stmt sql-delete) database)
570   (with-slots (from where)
571     stmt
572     (write-string "DELETE FROM " *sql-stream*)
573     (typecase from
574       (symbol (write-string (sql-escape from) *sql-stream*))
575       (t  (output-sql from database)))
576     (when where
577       (write-string " WHERE " *sql-stream*)
578       (output-sql where database)))
579   t)
580
581 ;; UPDATE
582
583 (defclass sql-update (%sql-expression)
584   ((table
585     :initarg :table
586     :initform nil)
587    (attributes
588     :initarg :attributes
589     :initform nil)
590    (values
591     :initarg :values
592     :initform nil)
593    (where
594     :initarg :where
595     :initform nil))
596   (:documentation "An SQL UPDATE statement."))
597
598 (defmethod output-sql ((expr sql-update) database)
599   (with-slots (table where attributes values)
600     expr
601     (flet ((update-assignments ()
602              (mapcar #'(lambda (a b)
603                          (make-instance 'sql-assignment-exp
604                                         :operator '=
605                                         :sub-expressions (list a b)))
606                      attributes values)))
607       (write-string "UPDATE " *sql-stream*)
608       (output-sql table database)
609       (write-string " SET " *sql-stream*)
610       (output-sql (apply #'vector (update-assignments)) database)
611       (when where
612         (write-string " WHERE " *sql-stream*)
613         (output-sql where database))))
614   t)
615
616 ;; CREATE TABLE
617
618 (defclass sql-create-table (%sql-expression)
619   ((name
620     :initarg :name
621     :initform nil)
622    (columns
623     :initarg :columns
624     :initform nil)
625    (modifiers
626     :initarg :modifiers
627     :initform nil)
628    (transactions
629     :initarg :transactions
630     :initform nil))
631   (:documentation
632    "An SQL CREATE TABLE statement."))
633
634 ;; Here's a real warhorse of a function!
635
636 (defun listify (x)
637   (if (atom x)
638       (list x)
639       x))
640
641 (defmethod output-sql ((stmt sql-create-table) database)
642   (flet ((output-column (column-spec)
643            (destructuring-bind (name type &optional db-type &rest constraints)
644                column-spec
645              (let ((type (listify type)))
646                (output-sql name database)
647                (write-char #\Space *sql-stream*)
648                (write-string
649                 (if (stringp db-type) db-type ; override definition
650                     (database-get-type-specifier (car type) (cdr type) database))
651                 *sql-stream*)
652                (let ((constraints
653                       (database-constraint-statement constraints database)))
654                  (when constraints
655                    (write-string " " *sql-stream*)
656                    (write-string constraints *sql-stream*)))))))
657     (with-slots (name columns modifiers transactions)
658       stmt
659       (write-string "CREATE TABLE " *sql-stream*)
660       (output-sql name database)
661       (write-string " (" *sql-stream*)
662       (do ((column columns (cdr column)))
663           ((null (cdr column))
664            (output-column (car column)))
665         (output-column (car column))
666         (write-string ", " *sql-stream*))
667       (when modifiers
668         (do ((modifier (listify modifiers) (cdr modifier)))
669             ((null modifier))
670           (write-string ", " *sql-stream*)
671           (write-string (car modifier) *sql-stream*)))
672       (write-char #\) *sql-stream*)
673       (when (and (eq :mysql (database-underlying-type database))
674                  transactions
675                  (db-type-transaction-capable? :mysql database))
676         (write-string " Type=InnoDB" *sql-stream*)))) 
677   t)
678
679
680 ;; CREATE VIEW
681
682 (defclass sql-create-view (%sql-expression)
683   ((name :initarg :name :initform nil)
684    (column-list :initarg :column-list :initform nil)
685    (query :initarg :query :initform nil)
686    (with-check-option :initarg :with-check-option :initform nil))
687   (:documentation "An SQL CREATE VIEW statement."))
688
689 (defmethod output-sql ((stmt sql-create-view) database)
690   (with-slots (name column-list query with-check-option) stmt
691     (write-string "CREATE VIEW " *sql-stream*)
692     (output-sql name database)
693     (when column-list (write-string " " *sql-stream*)
694           (output-sql (listify column-list) database))
695     (write-string " AS " *sql-stream*)
696     (output-sql query database)
697     (when with-check-option (write-string " WITH CHECK OPTION" *sql-stream*))))
698
699
700 ;;
701 ;; Column constraint types
702 ;;
703 (defparameter *constraint-types*
704   (list 
705    (cons (symbol-name-default-case "NOT-NULL") "NOT NULL") 
706    (cons (symbol-name-default-case "PRIMARY-KEY") "PRIMARY KEY")))
707
708 ;;
709 ;; Convert type spec to sql syntax
710 ;;
711
712 (defmethod database-constraint-description (constraint database)
713   (declare (ignore database))
714   (let ((output (assoc (symbol-name constraint) *constraint-types*
715                        :test #'equal)))
716     (if (null output)
717         (error 'clsql-sql-syntax-error
718                :reason (format nil "unsupported column constraint '~a'"
719                                constraint))
720         (cdr output))))
721
722 (defmethod database-constraint-statement (constraint-list database)
723   (declare (ignore database))
724   (make-constraints-description constraint-list))
725   
726 (defun make-constraints-description (constraint-list)
727   (if constraint-list
728       (let ((string ""))
729         (do ((constraint constraint-list (cdr constraint)))
730             ((null constraint) string)
731           (let ((output (assoc (symbol-name (car constraint))
732                                *constraint-types*
733                                :test #'equal)))
734             (if (null output)
735                 (error 'clsql-sql-syntax-error
736                        :reason (format nil "unsupported column constraint '~a'"
737                                        constraint))
738                 (setq string (concatenate 'string string (cdr output))))
739             (if (< 1 (length constraint))
740                 (setq string (concatenate 'string string " "))))))))
741