r10742: 17 Sep 2005 Kevin Rosenberg <kevin@rosenberg.net>
[clsql.git] / sql / expressions.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   "Top-level call for generating SQL strings. Returns an SQL
27   string appropriate for DATABASE which corresponds to the
28   supplied lisp expression SQL-EXPR."
29   (progv '(*sql-stream*)
30       `(,(make-string-output-stream))
31     (output-sql sql-expr database)
32     (get-output-stream-string *sql-stream*)))
33
34 (defmethod output-sql (expr database)
35   (write-string (database-output-sql expr database) *sql-stream*)
36   (values))
37
38 (defvar *output-hash* (make-hash-table :test #'equal)
39   "For caching generated SQL strings.")
40
41 (defmethod output-sql :around ((sql t) database)
42   (let* ((hash-key (output-sql-hash-key sql database))
43          (hash-value (when hash-key (gethash hash-key *output-hash*))))
44     (cond ((and hash-key hash-value)
45            (write-string hash-value *sql-stream*))
46           (hash-key
47            (let ((*sql-stream* (make-string-output-stream)))
48              (call-next-method)
49              (setf hash-value (get-output-stream-string *sql-stream*))
50              (setf (gethash hash-key *output-hash*) hash-value))
51            (write-string hash-value *sql-stream*))
52           (t
53            (call-next-method)))))
54
55 (defmethod output-sql-hash-key (expr database)
56   (declare (ignore expr database))
57   nil)
58
59
60 (defclass %sql-expression ()
61   ())
62
63 (defmethod output-sql ((expr %sql-expression) database)
64   (declare (ignore database))
65   (write-string +null-string+ *sql-stream*))
66
67 (defmethod print-object ((self %sql-expression) stream)
68   (print-unreadable-object
69    (self stream :type t)
70    (write-string (sql-output self) stream))
71   self)
72
73 ;; For straight up strings
74
75 (defclass sql (%sql-expression)
76   ((text
77     :initarg :string
78     :initform ""))
79   (:documentation "A literal SQL expression."))
80
81 (defmethod make-load-form ((sql sql) &optional environment)
82   (declare (ignore environment))
83   (with-slots (text)
84     sql
85     `(make-instance 'sql :string ',text)))
86
87 (defmethod output-sql ((expr sql) database)
88   (declare (ignore database))
89   (write-string (slot-value expr 'text) *sql-stream*)
90   t)
91
92 (defmethod print-object ((ident sql) stream)
93   (format stream "#<~S \"~A\">"
94           (type-of ident)
95           (sql-output ident nil))
96   ident)
97
98 ;; For SQL Identifiers of generic type
99
100 (defclass sql-ident (%sql-expression)
101   ((name
102     :initarg :name
103     :initform +null-string+))
104   (:documentation "An SQL identifer."))
105
106 (defmethod make-load-form ((sql sql-ident) &optional environment)
107   (declare (ignore environment))
108   (with-slots (name)
109     sql
110     `(make-instance 'sql-ident :name ',name)))
111
112 (defmethod output-sql ((expr sql-ident) database)
113   (with-slots (name) expr
114     (write-string
115      (convert-to-db-default-case 
116       (etypecase name
117         (string name)
118         (symbol (symbol-name name)))
119       database)
120      *sql-stream*))
121   t)
122
123 ;; For SQL Identifiers for attributes
124
125 (defclass sql-ident-attribute (sql-ident)
126   ((qualifier
127     :initarg :qualifier
128     :initform +null-string+)
129    (type
130     :initarg :type
131     :initform +null-string+))
132   (:documentation "An SQL Attribute identifier."))
133
134 (defmethod collect-table-refs (sql)
135   (declare (ignore sql))
136   nil)
137
138 (defmethod collect-table-refs ((sql sql-ident-attribute))
139   (let ((qual (slot-value sql 'qualifier)))
140     (if (and qual (symbolp (slot-value sql 'qualifier)))
141         (list (make-instance 'sql-ident-table :name
142                              (slot-value sql 'qualifier))))))
143
144 (defmethod make-load-form ((sql sql-ident-attribute) &optional environment)
145   (declare (ignore environment))
146   (with-slots (qualifier type name)
147     sql
148     `(make-instance 'sql-ident-attribute :name ',name
149       :qualifier ',qualifier
150       :type ',type)))
151
152 (defmethod output-sql ((expr sql-ident-attribute) database)
153   (with-slots (qualifier name type) expr
154     (if (and (not qualifier) (not type))
155         (etypecase name
156           ;; Honor care of name
157           (string
158            (write-string name *sql-stream*))
159           (symbol
160            (write-string (sql-escape (convert-to-db-default-case 
161                                       (symbol-name name) database)) *sql-stream*)))
162       
163         ;;; KMR: The TYPE field is used by CommonSQL for type conversion -- it
164       ;;; should not be output in SQL statements
165       #+ignore
166       (format *sql-stream* "~@[~A.~]~A~@[ ~A~]"
167               (when qualifier
168                 (convert-to-db-default-case (sql-escape qualifier) database))
169               (sql-escape (convert-to-db-default-case name database))
170               (when type
171                 (convert-to-db-default-case (symbol-name type) database)))
172       (format *sql-stream* "~@[~A.~]~A"
173               (when qualifier
174                 (typecase qualifier 
175                   (string (format nil "~s" qualifier))
176                   (t (convert-to-db-default-case (sql-escape qualifier) 
177                                                  database))))
178               (sql-escape (convert-to-db-default-case name database))))
179     t))
180
181 (defmethod output-sql-hash-key ((expr sql-ident-attribute) database)
182   (with-slots (qualifier name type)
183       expr
184     (list (and database (database-underlying-type database))
185           'sql-ident-attribute qualifier name type)))
186
187 ;; For SQL Identifiers for tables
188
189 (defclass sql-ident-table (sql-ident)
190   ((alias
191     :initarg :table-alias :initform nil))
192   (:documentation "An SQL table identifier."))
193
194 (defmethod make-load-form ((sql sql-ident-table) &optional environment)
195   (declare (ignore environment))
196   (with-slots (alias name)
197     sql
198     `(make-instance 'sql-ident-table :name ',name :table-alias ',alias)))
199
200 (defmethod output-sql ((expr sql-ident-table) database)
201   (with-slots (name alias) expr
202      (let ((namestr (if (symbolp name)
203                         (symbol-name name)
204                       name)))
205        (if (null alias)
206            (write-string
207             (sql-escape (convert-to-db-default-case namestr database))
208             *sql-stream*)
209          (progn
210            (write-string
211             (sql-escape (convert-to-db-default-case namestr database))
212             *sql-stream*)
213            (write-char #\Space *sql-stream*)
214            (format *sql-stream* "~s" alias)))))
215   t)
216
217 (defmethod output-sql-hash-key ((expr sql-ident-table) database)
218   (with-slots (name alias)
219       expr
220     (list (and database (database-underlying-type database))
221           'sql-ident-table name alias)))
222
223 (defclass sql-relational-exp (%sql-expression)
224   ((operator
225     :initarg :operator
226     :initform nil)
227    (sub-expressions
228     :initarg :sub-expressions
229     :initform nil))
230   (:documentation "An SQL relational expression."))
231
232 (defmethod collect-table-refs ((sql sql-relational-exp))
233   (let ((tabs nil))
234     (dolist (exp (slot-value sql 'sub-expressions))
235       (let ((refs (collect-table-refs exp)))
236         (if refs (setf tabs (append refs tabs)))))
237     (remove-duplicates tabs
238                        :test (lambda (tab1 tab2)
239                                (equal (slot-value tab1 'name)
240                                       (slot-value tab2 'name))))))
241
242
243
244
245 ;; Write SQL for relational operators (like 'AND' and 'OR').
246 ;; should do arity checking of subexpressions
247
248 (defmethod output-sql ((expr sql-relational-exp) database)
249   (with-slots (operator sub-expressions)
250     expr
251     (let ((subs (if (consp (car sub-expressions))
252                     (car sub-expressions)
253                     sub-expressions)))
254       (write-char #\( *sql-stream*)
255       (do ((sub subs (cdr sub)))
256           ((null (cdr sub)) (output-sql (car sub) database))
257         (output-sql (car sub) database)
258         (write-char #\Space *sql-stream*)
259         (output-sql operator database)
260         (write-char #\Space *sql-stream*))
261       (write-char #\) *sql-stream*)))
262   t)
263
264 (defclass sql-upcase-like (sql-relational-exp)
265   ()
266   (:documentation "An SQL 'like' that upcases its arguments."))
267   
268 (defmethod output-sql ((expr sql-upcase-like) database)
269   (flet ((write-term (term)
270            (write-string "upper(" *sql-stream*)
271            (output-sql term database)
272            (write-char #\) *sql-stream*)))
273     (with-slots (sub-expressions)
274       expr
275       (let ((subs (if (consp (car sub-expressions))
276                       (car sub-expressions)
277                       sub-expressions)))
278         (write-char #\( *sql-stream*)
279         (do ((sub subs (cdr sub)))
280             ((null (cdr sub)) (write-term (car sub)))
281           (write-term (car sub))
282           (write-string " LIKE " *sql-stream*))
283         (write-char #\) *sql-stream*))))
284   t)
285
286 (defclass sql-assignment-exp (sql-relational-exp)
287   ()
288   (:documentation "An SQL Assignment expression."))
289
290
291 (defmethod output-sql ((expr sql-assignment-exp) database)
292   (with-slots (operator sub-expressions)
293     expr
294     (do ((sub sub-expressions (cdr sub)))
295         ((null (cdr sub)) (output-sql (car sub) database))
296       (output-sql (car sub) database)
297       (write-char #\Space *sql-stream*)
298       (output-sql operator database)
299       (write-char #\Space *sql-stream*)))
300   t)
301
302 (defclass sql-value-exp (%sql-expression)
303   ((modifier
304     :initarg :modifier
305     :initform nil)
306    (components
307     :initarg :components
308     :initform nil))
309   (:documentation
310    "An SQL value expression.")
311   )
312
313 (defmethod collect-table-refs ((sql sql-value-exp))
314   (let ((tabs nil))
315     (if (listp (slot-value sql 'components))
316         (progn
317           (dolist (exp (slot-value sql 'components))
318             (let ((refs (collect-table-refs exp)))
319               (if refs (setf tabs (append refs tabs)))))
320           (remove-duplicates tabs
321                              :test (lambda (tab1 tab2)
322                                      (equal (slot-value tab1 'name)
323                                             (slot-value tab2 'name)))))
324         nil)))
325
326
327
328 (defmethod output-sql ((expr sql-value-exp) database)
329   (with-slots (modifier components)
330     expr
331     (if modifier
332         (progn
333           (write-char #\( *sql-stream*)
334           (output-sql modifier database)
335           (write-char #\Space *sql-stream*)
336           (output-sql components database)
337           (write-char #\) *sql-stream*))
338         (output-sql components database))))
339
340 (defclass sql-typecast-exp (sql-value-exp)
341   ()
342   (:documentation "An SQL typecast expression."))
343
344 (defmethod output-sql ((expr sql-typecast-exp) database)
345   (with-slots (components)
346     expr
347     (output-sql components database)))
348
349 (defmethod collect-table-refs ((sql sql-typecast-exp))
350   (when (slot-value sql 'components)
351     (collect-table-refs (slot-value sql 'components))))
352
353 (defclass sql-function-exp (%sql-expression)
354   ((name
355     :initarg :name
356     :initform nil)
357    (args
358     :initarg :args
359     :initform nil))
360   (:documentation
361    "An SQL function expression."))
362
363 (defmethod collect-table-refs ((sql sql-function-exp))
364   (let ((tabs nil))
365     (dolist (exp (slot-value sql 'args))
366       (let ((refs (collect-table-refs exp)))
367         (if refs (setf tabs (append refs tabs)))))
368     (remove-duplicates tabs
369                        :test (lambda (tab1 tab2)
370                                (equal (slot-value tab1 'name)
371                                       (slot-value tab2 'name))))))
372 (defvar *in-subselect* nil)
373
374 (defmethod output-sql ((expr sql-function-exp) database)
375   (with-slots (name args)
376     expr
377     (output-sql name database)
378     (let ((*in-subselect* nil)) ;; aboid double parens
379       (when args (output-sql args database))))
380   t)
381
382
383 (defclass sql-between-exp (sql-function-exp)
384   () 
385   (:documentation "An SQL between expression."))
386
387 (defmethod output-sql ((expr sql-between-exp) database)
388   (with-slots (name args)
389       expr 
390     (output-sql (first args) database)
391     (write-string " BETWEEN " *sql-stream*)
392     (output-sql (second args) database)
393     (write-string " AND " *sql-stream*)
394     (output-sql (third args) database))
395   t)
396
397 (defclass sql-query-modifier-exp (%sql-expression) 
398   ((modifier :initarg :modifier :initform nil)
399    (components :initarg :components :initform nil))
400   (:documentation "An SQL query modifier expression."))
401
402 (defmethod output-sql ((expr sql-query-modifier-exp) database)
403   (with-slots (modifier components)
404       expr
405     (output-sql modifier database)
406     (write-string " " *sql-stream*)
407     (output-sql (car components) database)
408     (when components 
409       (mapc #'(lambda (comp) 
410                 (write-string ", " *sql-stream*)
411                 (output-sql comp database))
412             (cdr components))))
413   t)
414
415 (defclass sql-set-exp (%sql-expression)
416   ((operator
417     :initarg :operator
418     :initform nil)
419    (sub-expressions
420     :initarg :sub-expressions
421     :initform nil))
422   (:documentation "An SQL set expression."))
423
424 (defmethod collect-table-refs ((sql sql-set-exp))
425   (let ((tabs nil))
426     (dolist (exp (slot-value sql 'sub-expressions))
427       (let ((refs (collect-table-refs exp)))
428         (if refs (setf tabs (append refs tabs)))))
429     (remove-duplicates tabs
430                        :test (lambda (tab1 tab2)
431                                (equal (slot-value tab1 'name)
432                                       (slot-value tab2 'name))))))
433
434 (defmethod output-sql ((expr sql-set-exp) database)
435   (with-slots (operator sub-expressions)
436       expr
437     (let ((subs (if (consp (car sub-expressions))
438                     (car sub-expressions)
439                     sub-expressions)))
440       (when (= (length subs) 1)
441         (output-sql operator database)
442         (write-char #\Space *sql-stream*))
443       (do ((sub subs (cdr sub)))
444           ((null (cdr sub)) (output-sql (car sub) database))
445         (output-sql (car sub) database)
446         (write-char #\Space *sql-stream*)
447         (output-sql operator database)
448         (write-char #\Space *sql-stream*))))
449   t)
450
451 (defclass sql-query (%sql-expression)
452   ((selections
453     :initarg :selections
454     :initform nil)
455    (all
456     :initarg :all
457     :initform nil)
458    (flatp
459     :initarg :flatp
460     :initform nil)
461    (set-operation
462     :initarg :set-operation
463     :initform nil)
464    (distinct
465     :initarg :distinct
466     :initform nil)
467    (from
468     :initarg :from
469     :initform nil)
470    (where
471     :initarg :where
472     :initform nil)
473    (group-by
474     :initarg :group-by
475     :initform nil)
476    (having
477     :initarg :having
478     :initform nil)
479    (limit
480     :initarg :limit
481     :initform nil)
482    (offset
483     :initarg :offset
484     :initform nil)
485    (order-by
486     :initarg :order-by
487     :initform nil)
488    (inner-join
489     :initarg :inner-join
490     :initform nil)
491    (on
492     :initarg :on
493     :initform nil))
494   (:documentation "An SQL SELECT query."))
495
496 (defclass sql-object-query (%sql-expression)
497   ((objects
498     :initarg :objects
499     :initform nil)
500    (flatp
501     :initarg :flatp
502     :initform nil)
503    (exp
504     :initarg :exp
505     :initform nil)
506    (refresh
507     :initarg :refresh
508     :initform nil)))
509
510 (defmethod collect-table-refs ((sql sql-query))
511   (remove-duplicates (collect-table-refs (slot-value sql 'where))
512                      :test (lambda (tab1 tab2)
513                              (equal (slot-value tab1 'name)
514                                     (slot-value tab2 'name)))))
515
516 (defvar *select-arguments*
517   '(:all :database :distinct :flatp :from :group-by :having :order-by
518     :set-operation :where :offset :limit :inner-join :on
519     ;; below keywords are not a SQL argument, but these keywords may terminate select
520     :caching :refresh))
521
522 (defun query-arg-p (sym)
523   (member sym *select-arguments*))
524
525 (defun query-get-selections (select-args)
526   "Return two values: the list of select-args up to the first keyword,
527 uninclusive, and the args from that keyword to the end."
528   (let ((first-key-arg (position-if #'query-arg-p select-args)))
529     (if first-key-arg
530         (values (subseq select-args 0 first-key-arg)
531                 (subseq select-args first-key-arg))
532         select-args)))
533
534 (defun make-query (&rest args)
535   (flet ((select-objects (target-args)
536            (and target-args
537                 (every #'(lambda (arg)
538                            (and (symbolp arg)
539                                 (find-class arg nil)))
540                        target-args))))
541     (multiple-value-bind (selections arglist)
542         (query-get-selections args)
543       (if (select-objects selections) 
544           (destructuring-bind (&key flatp refresh &allow-other-keys) arglist
545             (make-instance 'sql-object-query :objects selections
546                            :flatp flatp :refresh refresh
547                            :exp arglist))
548           (destructuring-bind (&key all flatp set-operation distinct from where
549                                     group-by having order-by 
550                                     offset limit inner-join on &allow-other-keys)
551               arglist
552             (if (null selections)
553                 (error "No target columns supplied to select statement."))
554             (if (null from)
555                 (error "No source tables supplied to select statement."))
556             (make-instance 'sql-query :selections selections
557                            :all all :flatp flatp :set-operation set-operation
558                            :distinct distinct :from from :where where
559                            :limit limit :offset offset
560                            :group-by group-by :having having :order-by order-by
561                            :inner-join inner-join :on on))))))
562
563 (defmethod output-sql ((query sql-query) database)
564   (with-slots (distinct selections from where group-by having order-by
565                         limit offset inner-join on all set-operation) 
566       query
567     (when *in-subselect*
568       (write-string "(" *sql-stream*))
569     (write-string "SELECT " *sql-stream*)
570     (when all 
571       (write-string "ALL " *sql-stream*))
572     (when (and distinct (not all))
573       (write-string "DISTINCT " *sql-stream*)
574       (unless (eql t distinct)
575         (write-string "ON " *sql-stream*)
576         (output-sql distinct database)
577         (write-char #\Space *sql-stream*)))
578     (output-sql (apply #'vector selections) database)
579     (when from
580       (write-string " FROM " *sql-stream*)
581       (flet ((ident-table-equal (a b) 
582                (and (if (and (eql (type-of a) 'sql-ident-table)
583                              (eql (type-of b) 'sql-ident-table))
584                         (string-equal (slot-value a 'alias)
585                                       (slot-value b 'alias))
586                         t)
587                     (string-equal (symbol-name (slot-value a 'name))
588                                   (symbol-name (slot-value b 'name))))))
589         (typecase from 
590           (list (output-sql (apply #'vector 
591                                    (remove-duplicates from 
592                                                       :test #'ident-table-equal))
593                             database))
594           (string (write-string from *sql-stream*))
595           (t (output-sql from database)))))
596     (when inner-join
597       (write-string " INNER JOIN " *sql-stream*)
598       (output-sql inner-join database))
599     (when on
600       (write-string " ON " *sql-stream*)
601       (output-sql on database))
602     (when where
603       (write-string " WHERE " *sql-stream*)
604       (let ((*in-subselect* t))
605         (output-sql where database)))
606     (when group-by
607       (write-string " GROUP BY " *sql-stream*)
608       (output-sql group-by database))
609     (when having
610       (write-string " HAVING " *sql-stream*)
611       (output-sql having database))
612     (when order-by
613       (write-string " ORDER BY " *sql-stream*)
614       (if (listp order-by)
615           (do ((order order-by (cdr order)))
616               ((null order))
617             (let ((item (car order)))
618               (typecase item 
619                 (cons 
620                  (output-sql (car item) database)
621                  (format *sql-stream* " ~A" (cadr item)))
622                 (t 
623                  (output-sql item database)))
624               (when (cdr order)
625                 (write-char #\, *sql-stream*))))
626           (output-sql order-by database)))
627     (when limit
628       (write-string " LIMIT " *sql-stream*)
629       (output-sql limit database))
630     (when offset
631       (write-string " OFFSET " *sql-stream*)
632       (output-sql offset database))
633     (when *in-subselect*
634       (write-string ")" *sql-stream*))
635     (when set-operation 
636       (write-char #\Space *sql-stream*)
637       (output-sql set-operation database)))
638   t)
639
640 (defmethod output-sql ((query sql-object-query) database)
641   (declare (ignore database))
642   (with-slots (objects)
643       query
644     (when objects
645       (format *sql-stream* "(~{~A~^ ~})" objects))))
646
647
648 ;; INSERT
649
650 (defclass sql-insert (%sql-expression)
651   ((into
652     :initarg :into
653     :initform nil)
654    (attributes
655     :initarg :attributes
656     :initform nil)
657    (values
658     :initarg :values
659     :initform nil)
660    (query
661     :initarg :query
662     :initform nil))
663   (:documentation
664    "An SQL INSERT statement."))
665
666 (defmethod output-sql ((ins sql-insert) database)
667   (with-slots (into attributes values query)
668     ins
669     (write-string "INSERT INTO " *sql-stream*)
670     (output-sql 
671      (typecase into
672        (string (sql-expression :attribute into))
673        (t into)) 
674      database)
675     (when attributes
676       (write-char #\Space *sql-stream*)
677       (output-sql attributes database))
678     (when values
679       (write-string " VALUES " *sql-stream*)
680       (output-sql values database))
681     (when query
682       (write-char #\Space *sql-stream*)
683       (output-sql query database)))
684   t)
685
686 ;; DELETE
687
688 (defclass sql-delete (%sql-expression)
689   ((from
690     :initarg :from
691     :initform nil)
692    (where
693     :initarg :where
694     :initform nil))
695   (:documentation
696    "An SQL DELETE statement."))
697
698 (defmethod output-sql ((stmt sql-delete) database)
699   (with-slots (from where)
700     stmt
701     (write-string "DELETE FROM " *sql-stream*)
702     (typecase from
703       ((or symbol string) (write-string (sql-escape from) *sql-stream*))
704       (t  (output-sql from database)))
705     (when where
706       (write-string " WHERE " *sql-stream*)
707       (output-sql where database)))
708   t)
709
710 ;; UPDATE
711
712 (defclass sql-update (%sql-expression)
713   ((table
714     :initarg :table
715     :initform nil)
716    (attributes
717     :initarg :attributes
718     :initform nil)
719    (values
720     :initarg :values
721     :initform nil)
722    (where
723     :initarg :where
724     :initform nil))
725   (:documentation "An SQL UPDATE statement."))
726
727 (defmethod output-sql ((expr sql-update) database)
728   (with-slots (table where attributes values)
729     expr
730     (flet ((update-assignments ()
731              (mapcar #'(lambda (a b)
732                          (make-instance 'sql-assignment-exp
733                                         :operator '=
734                                         :sub-expressions (list a b)))
735                      attributes values)))
736       (write-string "UPDATE " *sql-stream*)
737       (output-sql table database)
738       (write-string " SET " *sql-stream*)
739       (output-sql (apply #'vector (update-assignments)) database)
740       (when where
741         (write-string " WHERE " *sql-stream*)
742         (output-sql where database))))
743   t)
744
745 ;; CREATE TABLE
746
747 (defclass sql-create-table (%sql-expression)
748   ((name
749     :initarg :name
750     :initform nil)
751    (columns
752     :initarg :columns
753     :initform nil)
754    (modifiers
755     :initarg :modifiers
756     :initform nil)
757    (transactions
758     :initarg :transactions
759     :initform nil))
760   (:documentation
761    "An SQL CREATE TABLE statement."))
762
763 ;; Here's a real warhorse of a function!
764
765 (declaim (inline listify))
766 (defun listify (x)
767   (if (atom x)
768       (list x)
769       x))
770
771 (defmethod output-sql ((stmt sql-create-table) database)
772   (flet ((output-column (column-spec)
773            (destructuring-bind (name type &optional db-type &rest constraints)
774                column-spec
775              (let ((type (listify type)))
776                (output-sql name database)
777                (write-char #\Space *sql-stream*)
778                (write-string
779                 (if (stringp db-type) db-type ; override definition
780                   (database-get-type-specifier (car type) (cdr type) database
781                                                (database-underlying-type database)))
782                 *sql-stream*)
783                (let ((constraints (database-constraint-statement  
784                                    (if (and db-type (symbolp db-type))
785                                        (cons db-type constraints)
786                                        constraints)
787                                    database)))
788                  (when constraints
789                    (write-string " " *sql-stream*)
790                    (write-string constraints *sql-stream*)))))))
791     (with-slots (name columns modifiers transactions)
792       stmt
793       (write-string "CREATE TABLE " *sql-stream*)
794       (output-sql name database)
795       (write-string " (" *sql-stream*)
796       (do ((column columns (cdr column)))
797           ((null (cdr column))
798            (output-column (car column)))
799         (output-column (car column))
800         (write-string ", " *sql-stream*))
801       (when modifiers
802         (do ((modifier (listify modifiers) (cdr modifier)))
803             ((null modifier))
804           (write-string ", " *sql-stream*)
805           (write-string (car modifier) *sql-stream*)))
806       (write-char #\) *sql-stream*)
807       (when (and (eq :mysql (database-underlying-type database))
808                  transactions
809                  (db-type-transaction-capable? :mysql database))
810         (write-string " Type=InnoDB" *sql-stream*)))) 
811   t)
812
813
814 ;; CREATE VIEW
815
816 (defclass sql-create-view (%sql-expression)
817   ((name :initarg :name :initform nil)
818    (column-list :initarg :column-list :initform nil)
819    (query :initarg :query :initform nil)
820    (with-check-option :initarg :with-check-option :initform nil))
821   (:documentation "An SQL CREATE VIEW statement."))
822
823 (defmethod output-sql ((stmt sql-create-view) database)
824   (with-slots (name column-list query with-check-option) stmt
825     (write-string "CREATE VIEW " *sql-stream*)
826     (output-sql name database)
827     (when column-list (write-string " " *sql-stream*)
828           (output-sql (listify column-list) database))
829     (write-string " AS " *sql-stream*)
830     (output-sql query database)
831     (when with-check-option (write-string " WITH CHECK OPTION" *sql-stream*))))
832
833
834 ;;
835 ;; DATABASE-OUTPUT-SQL 
836 ;; 
837
838 (defmethod database-output-sql ((str string) database)
839   (declare (optimize (speed 3) (safety 1)
840                      #+cmu (extensions:inhibit-warnings 3)))
841   (let ((len (length str)))
842     (declare (type fixnum len))
843     (cond ((zerop len)
844            +empty-string+)
845           ((and (null (position #\' str))
846                 (null (position #\\ str)))
847            (concatenate 'string "'" str "'"))
848           (t
849            (let ((buf (make-string (+ (* len 2) 2) :initial-element #\')))
850              (declare (simple-string buf))
851              (do* ((i 0 (incf i))
852                    (j 1 (incf j)))
853                   ((= i len) (subseq buf 0 (1+ j)))
854                (declare (type fixnum i j))
855                (let ((char (aref str i)))
856                  (declare (character char))
857                  (cond ((char= char #\')
858                         (setf (aref buf j) #\')
859                         (incf j)
860                         (setf (aref buf j) #\'))
861                        ((and (char= char #\\)
862                              ;; MTP: only escape backslash with pgsql/mysql 
863                              (member (database-underlying-type database) 
864                                      '(:postgresql :mysql)
865                                      :test #'eq))
866                         (setf (aref buf j) #\\)
867                         (incf j)
868                         (setf (aref buf j) #\\))
869                        (t
870                         (setf (aref buf j) char))))))))))
871
872 (let ((keyword-package (symbol-package :foo)))
873   (defmethod database-output-sql ((sym symbol) database)
874   (if (null sym) 
875       +null-string+ 
876       (convert-to-db-default-case
877        (if (equal (symbol-package sym) keyword-package)
878            (concatenate 'string "'" (string sym) "'")
879            (symbol-name sym))
880        database))))
881
882 (defmethod database-output-sql ((tee (eql t)) database)
883   (declare (ignore database))
884   "'Y'")
885
886 (defmethod database-output-sql ((num number) database)
887   (declare (ignore database))
888   (princ-to-string num))
889
890 (defmethod database-output-sql ((arg list) database)
891   (if (null arg) 
892       +null-string+ 
893       (format nil "(~{~A~^,~})" (mapcar #'(lambda (val)
894                                             (sql-output val database))
895                                         arg))))
896
897 (defmethod database-output-sql ((arg vector) database)
898   (format nil "~{~A~^,~}" (map 'list #'(lambda (val)
899                                          (sql-output val database))
900                                arg)))
901
902 (defmethod output-sql-hash-key ((arg vector) database)
903   (list 'vector (map 'list (lambda (arg)
904                              (or (output-sql-hash-key arg database)
905                                  (return-from output-sql-hash-key nil)))
906                      arg)))
907
908 (defmethod database-output-sql ((self wall-time) database)
909   (declare (ignore database))
910   (db-timestring self))
911
912 (defmethod database-output-sql ((self date) database)
913   (declare (ignore database))
914   (db-datestring self))
915
916 (defmethod database-output-sql ((self duration) database)
917   (declare (ignore database))
918   (format nil "'~a'" (duration-timestring self)))
919
920 #+ignore 
921 (defmethod database-output-sql ((self money) database)
922   (database-output-sql (slot-value self 'odcl::units) database))
923
924 (defmethod database-output-sql (thing database)
925   (if (or (null thing)
926           (eq 'null thing))
927       +null-string+
928     (error 'sql-user-error
929            :message
930            (format nil
931                    "No type conversion to SQL for ~A is defined for DB ~A."
932                    (type-of thing) (type-of database)))))
933
934
935 ;;
936 ;; Column constraint types and conversion to SQL 
937 ;;
938
939 (defparameter *constraint-types*
940   (list 
941    (cons (symbol-name-default-case "NOT-NULL") "NOT NULL") 
942    (cons (symbol-name-default-case "PRIMARY-KEY") "PRIMARY KEY")
943    (cons (symbol-name-default-case "NOT") "NOT") 
944    (cons (symbol-name-default-case "NULL") "NULL") 
945    (cons (symbol-name-default-case "PRIMARY") "PRIMARY") 
946    (cons (symbol-name-default-case "KEY") "KEY")
947    (cons (symbol-name-default-case "UNSIGNED") "UNSIGNED") 
948    (cons (symbol-name-default-case "ZEROFILL") "ZEROFILL") 
949    (cons (symbol-name-default-case "AUTO-INCREMENT") "AUTO_INCREMENT")
950    (cons (symbol-name-default-case "UNIQUE") "UNIQUE")))
951
952 (defmethod database-constraint-statement (constraint-list database)
953   (declare (ignore database))
954   (make-constraints-description constraint-list))
955   
956 (defun make-constraints-description (constraint-list)
957   (if constraint-list
958       (let ((string ""))
959         (do ((constraint constraint-list (cdr constraint)))
960             ((null constraint) string)
961           (let ((output (assoc (symbol-name (car constraint))
962                                *constraint-types*
963                                :test #'equal)))
964             (if (null output)
965                 (error 'sql-user-error
966                        :message (format nil "unsupported column constraint '~A'"
967                                         constraint))
968                 (setq string (concatenate 'string string (cdr output))))
969             (if (< 1 (length constraint))
970                 (setq string (concatenate 'string string " "))))))))
971