3a2532aafbb18e8c8e8d7ef502583deb42ab50a9
[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)
202     expr
203     (if (null alias)
204         (write-string (sql-escape (convert-to-db-default-case (symbol-name name) database)) *sql-stream*)
205         (progn
206           (write-string (sql-escape (convert-to-db-default-case (symbol-name name) database)) *sql-stream*)
207           (write-char #\Space *sql-stream*)
208           (format *sql-stream* "~s" alias))))
209   t)
210
211 (defmethod output-sql-hash-key ((expr sql-ident-table) database)
212   (with-slots (name alias)
213       expr
214     (list (and database (database-underlying-type database))
215           '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 (defmethod output-sql ((expr sql-upcase-like) database)
263   (flet ((write-term (term)
264            (write-string "upper(" *sql-stream*)
265            (output-sql term database)
266            (write-char #\) *sql-stream*)))
267     (with-slots (sub-expressions)
268       expr
269       (let ((subs (if (consp (car sub-expressions))
270                       (car sub-expressions)
271                       sub-expressions)))
272         (write-char #\( *sql-stream*)
273         (do ((sub subs (cdr sub)))
274             ((null (cdr sub)) (write-term (car sub)))
275           (write-term (car sub))
276           (write-string " LIKE " *sql-stream*))
277         (write-char #\) *sql-stream*))))
278   t)
279
280 (defclass sql-assignment-exp (sql-relational-exp)
281   ()
282   (:documentation "An SQL Assignment expression."))
283
284
285 (defmethod output-sql ((expr sql-assignment-exp) database)
286   (with-slots (operator sub-expressions)
287     expr
288     (do ((sub sub-expressions (cdr sub)))
289         ((null (cdr sub)) (output-sql (car sub) database))
290       (output-sql (car sub) database)
291       (write-char #\Space *sql-stream*)
292       (output-sql operator database)
293       (write-char #\Space *sql-stream*)))
294   t)
295
296 (defclass sql-value-exp (%sql-expression)
297   ((modifier
298     :initarg :modifier
299     :initform nil)
300    (components
301     :initarg :components
302     :initform nil))
303   (:documentation
304    "An SQL value expression.")
305   )
306
307 (defmethod collect-table-refs ((sql sql-value-exp))
308   (let ((tabs nil))
309     (if (listp (slot-value sql 'components))
310         (progn
311           (dolist (exp (slot-value sql 'components))
312             (let ((refs (collect-table-refs exp)))
313               (if refs (setf tabs (append refs tabs)))))
314           (remove-duplicates tabs
315                              :test (lambda (tab1 tab2)
316                                      (equal (slot-value tab1 'name)
317                                             (slot-value tab2 'name)))))
318         nil)))
319
320
321
322 (defmethod output-sql ((expr sql-value-exp) database)
323   (with-slots (modifier components)
324     expr
325     (if modifier
326         (progn
327           (write-char #\( *sql-stream*)
328           (output-sql modifier database)
329           (write-char #\Space *sql-stream*)
330           (output-sql components database)
331           (write-char #\) *sql-stream*))
332         (output-sql components database))))
333
334 (defclass sql-typecast-exp (sql-value-exp)
335   ()
336   (:documentation "An SQL typecast expression."))
337
338 (defmethod output-sql ((expr sql-typecast-exp) database)
339   (with-slots (components)
340     expr
341     (output-sql components database)))
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 (defvar *in-subselect* nil)
367
368 (defmethod output-sql ((expr sql-function-exp) database)
369   (with-slots (name args)
370     expr
371     (output-sql name database)
372     (let ((*in-subselect* nil)) ;; aboid double parens
373       (when args (output-sql args database))))
374   t)
375
376
377 (defclass sql-between-exp (sql-function-exp)
378   () 
379   (:documentation "An SQL between expression."))
380
381 (defmethod output-sql ((expr sql-between-exp) database)
382   (with-slots (name args)
383       expr 
384     (output-sql (first args) database)
385     (write-string " BETWEEN " *sql-stream*)
386     (output-sql (second args) database)
387     (write-string " AND " *sql-stream*)
388     (output-sql (third args) database))
389   t)
390
391 (defclass sql-query-modifier-exp (%sql-expression) 
392   ((modifier :initarg :modifier :initform nil)
393    (components :initarg :components :initform nil))
394   (:documentation "An SQL query modifier expression."))
395
396 (defmethod output-sql ((expr sql-query-modifier-exp) database)
397   (with-slots (modifier components)
398       expr
399     (output-sql modifier database)
400     (write-string " " *sql-stream*)
401     (output-sql (car components) database)
402     (when components 
403       (mapc #'(lambda (comp) 
404                 (write-string ", " *sql-stream*)
405                 (output-sql comp database))
406             (cdr components))))
407   t)
408
409 (defclass sql-set-exp (%sql-expression)
410   ((operator
411     :initarg :operator
412     :initform nil)
413    (sub-expressions
414     :initarg :sub-expressions
415     :initform nil))
416   (:documentation "An SQL set expression."))
417
418 (defmethod collect-table-refs ((sql sql-set-exp))
419   (let ((tabs nil))
420     (dolist (exp (slot-value sql 'sub-expressions))
421       (let ((refs (collect-table-refs exp)))
422         (if refs (setf tabs (append refs tabs)))))
423     (remove-duplicates tabs
424                        :test (lambda (tab1 tab2)
425                                (equal (slot-value tab1 'name)
426                                       (slot-value tab2 'name))))))
427
428 (defmethod output-sql ((expr sql-set-exp) database)
429   (with-slots (operator sub-expressions)
430       expr
431     (let ((subs (if (consp (car sub-expressions))
432                     (car sub-expressions)
433                     sub-expressions)))
434       (when (= (length subs) 1)
435         (output-sql operator database)
436         (write-char #\Space *sql-stream*))
437       (do ((sub subs (cdr sub)))
438           ((null (cdr sub)) (output-sql (car sub) database))
439         (output-sql (car sub) database)
440         (write-char #\Space *sql-stream*)
441         (output-sql operator database)
442         (write-char #\Space *sql-stream*))))
443   t)
444
445 (defclass sql-query (%sql-expression)
446   ((selections
447     :initarg :selections
448     :initform nil)
449    (all
450     :initarg :all
451     :initform nil)
452    (flatp
453     :initarg :flatp
454     :initform nil)
455    (set-operation
456     :initarg :set-operation
457     :initform nil)
458    (distinct
459     :initarg :distinct
460     :initform nil)
461    (from
462     :initarg :from
463     :initform nil)
464    (where
465     :initarg :where
466     :initform nil)
467    (group-by
468     :initarg :group-by
469     :initform nil)
470    (having
471     :initarg :having
472     :initform nil)
473    (limit
474     :initarg :limit
475     :initform nil)
476    (offset
477     :initarg :offset
478     :initform nil)
479    (order-by
480     :initarg :order-by
481     :initform nil)
482    (inner-join
483     :initarg :inner-join
484     :initform nil)
485    (on
486     :initarg :on
487     :initform nil))
488   (:documentation "An SQL SELECT query."))
489
490 (defclass sql-object-query (%sql-expression)
491   ((objects
492     :initarg :objects
493     :initform nil)
494    (flatp
495     :initarg :flatp
496     :initform nil)
497    (exp
498     :initarg :exp
499     :initform nil)
500    (refresh
501     :initarg :refresh
502     :initform nil)))
503
504 (defmethod collect-table-refs ((sql sql-query))
505   (remove-duplicates (collect-table-refs (slot-value sql 'where))
506                      :test (lambda (tab1 tab2)
507                              (equal (slot-value tab1 'name)
508                                     (slot-value tab2 'name)))))
509
510 (defvar *select-arguments*
511   '(:all :database :distinct :flatp :from :group-by :having :order-by
512     :set-operation :where :offset :limit :inner-join :on
513     ;; below keywords are not a SQL argument, but these keywords may terminate select
514     :caching :refresh))
515
516 (defun query-arg-p (sym)
517   (member sym *select-arguments*))
518
519 (defun query-get-selections (select-args)
520   "Return two values: the list of select-args up to the first keyword,
521 uninclusive, and the args from that keyword to the end."
522   (let ((first-key-arg (position-if #'query-arg-p select-args)))
523     (if first-key-arg
524         (values (subseq select-args 0 first-key-arg)
525                 (subseq select-args first-key-arg))
526         select-args)))
527
528 (defun make-query (&rest args)
529   (flet ((select-objects (target-args)
530            (and target-args
531                 (every #'(lambda (arg)
532                            (and (symbolp arg)
533                                 (find-class arg nil)))
534                        target-args))))
535     (multiple-value-bind (selections arglist)
536         (query-get-selections args)
537       (if (select-objects selections) 
538           (destructuring-bind (&key flatp refresh &allow-other-keys) arglist
539             (make-instance 'sql-object-query :objects selections
540                            :flatp flatp :refresh refresh
541                            :exp arglist))
542           (destructuring-bind (&key all flatp set-operation distinct from where
543                                     group-by having order-by 
544                                     offset limit inner-join on &allow-other-keys)
545               arglist
546             (if (null selections)
547                 (error "No target columns supplied to select statement."))
548             (if (null from)
549                 (error "No source tables supplied to select statement."))
550             (make-instance 'sql-query :selections selections
551                            :all all :flatp flatp :set-operation set-operation
552                            :distinct distinct :from from :where where
553                            :limit limit :offset offset
554                            :group-by group-by :having having :order-by order-by
555                            :inner-join inner-join :on on))))))
556
557 (defmethod output-sql ((query sql-query) database)
558   (with-slots (distinct selections from where group-by having order-by
559                         limit offset inner-join on all set-operation) 
560       query
561     (when *in-subselect*
562       (write-string "(" *sql-stream*))
563     (write-string "SELECT " *sql-stream*)
564     (when all 
565       (write-string "ALL " *sql-stream*))
566     (when (and distinct (not all))
567       (write-string "DISTINCT " *sql-stream*)
568       (unless (eql t distinct)
569         (write-string "ON " *sql-stream*)
570         (output-sql distinct database)
571         (write-char #\Space *sql-stream*)))
572     (output-sql (apply #'vector selections) database)
573     (when from
574       (write-string " FROM " *sql-stream*)
575       (flet ((ident-table-equal (a b) 
576                (and (if (and (eql (type-of a) 'sql-ident-table)
577                              (eql (type-of b) 'sql-ident-table))
578                         (string-equal (slot-value a 'alias)
579                                       (slot-value b 'alias))
580                         t)
581                     (string-equal (symbol-name (slot-value a 'name))
582                                   (symbol-name (slot-value b 'name))))))
583         (typecase from 
584           (list (output-sql (apply #'vector 
585                                    (remove-duplicates from 
586                                                       :test #'ident-table-equal))
587                             database))
588           (string (write-string from *sql-stream*))
589           (t (output-sql from database)))))
590     (when inner-join
591       (write-string " INNER JOIN " *sql-stream*)
592       (output-sql inner-join database))
593     (when on
594       (write-string " ON " *sql-stream*)
595       (output-sql on database))
596     (when where
597       (write-string " WHERE " *sql-stream*)
598       (let ((*in-subselect* t))
599         (output-sql where database)))
600     (when group-by
601       (write-string " GROUP BY " *sql-stream*)
602       (output-sql group-by database))
603     (when having
604       (write-string " HAVING " *sql-stream*)
605       (output-sql having database))
606     (when order-by
607       (write-string " ORDER BY " *sql-stream*)
608       (if (listp order-by)
609           (do ((order order-by (cdr order)))
610               ((null order))
611             (let ((item (car order)))
612               (typecase item 
613                 (cons 
614                  (output-sql (car item) database)
615                  (format *sql-stream* " ~A" (cadr item)))
616                 (t 
617                  (output-sql item database)))
618               (when (cdr order)
619                 (write-char #\, *sql-stream*))))
620           (output-sql order-by database)))
621     (when limit
622       (write-string " LIMIT " *sql-stream*)
623       (output-sql limit database))
624     (when offset
625       (write-string " OFFSET " *sql-stream*)
626       (output-sql offset database))
627     (when *in-subselect*
628       (write-string ")" *sql-stream*))
629     (when set-operation 
630       (write-char #\Space *sql-stream*)
631       (output-sql set-operation database)))
632   t)
633
634 (defmethod output-sql ((query sql-object-query) database)
635   (declare (ignore database))
636   (with-slots (objects)
637       query
638     (when objects
639       (format *sql-stream* "(~{~A~^ ~})" objects))))
640
641
642 ;; INSERT
643
644 (defclass sql-insert (%sql-expression)
645   ((into
646     :initarg :into
647     :initform nil)
648    (attributes
649     :initarg :attributes
650     :initform nil)
651    (values
652     :initarg :values
653     :initform nil)
654    (query
655     :initarg :query
656     :initform nil))
657   (:documentation
658    "An SQL INSERT statement."))
659
660 (defmethod output-sql ((ins sql-insert) database)
661   (with-slots (into attributes values query)
662     ins
663     (write-string "INSERT INTO " *sql-stream*)
664     (output-sql 
665      (typecase into
666        (string (sql-expression :attribute into))
667        (t into)) 
668      database)
669     (when attributes
670       (write-char #\Space *sql-stream*)
671       (output-sql attributes database))
672     (when values
673       (write-string " VALUES " *sql-stream*)
674       (output-sql values database))
675     (when query
676       (write-char #\Space *sql-stream*)
677       (output-sql query database)))
678   t)
679
680 ;; DELETE
681
682 (defclass sql-delete (%sql-expression)
683   ((from
684     :initarg :from
685     :initform nil)
686    (where
687     :initarg :where
688     :initform nil))
689   (:documentation
690    "An SQL DELETE statement."))
691
692 (defmethod output-sql ((stmt sql-delete) database)
693   (with-slots (from where)
694     stmt
695     (write-string "DELETE FROM " *sql-stream*)
696     (typecase from
697       (symbol (write-string (sql-escape from) *sql-stream*))
698       (t  (output-sql from database)))
699     (when where
700       (write-string " WHERE " *sql-stream*)
701       (output-sql where database)))
702   t)
703
704 ;; UPDATE
705
706 (defclass sql-update (%sql-expression)
707   ((table
708     :initarg :table
709     :initform nil)
710    (attributes
711     :initarg :attributes
712     :initform nil)
713    (values
714     :initarg :values
715     :initform nil)
716    (where
717     :initarg :where
718     :initform nil))
719   (:documentation "An SQL UPDATE statement."))
720
721 (defmethod output-sql ((expr sql-update) database)
722   (with-slots (table where attributes values)
723     expr
724     (flet ((update-assignments ()
725              (mapcar #'(lambda (a b)
726                          (make-instance 'sql-assignment-exp
727                                         :operator '=
728                                         :sub-expressions (list a b)))
729                      attributes values)))
730       (write-string "UPDATE " *sql-stream*)
731       (output-sql table database)
732       (write-string " SET " *sql-stream*)
733       (output-sql (apply #'vector (update-assignments)) database)
734       (when where
735         (write-string " WHERE " *sql-stream*)
736         (output-sql where database))))
737   t)
738
739 ;; CREATE TABLE
740
741 (defclass sql-create-table (%sql-expression)
742   ((name
743     :initarg :name
744     :initform nil)
745    (columns
746     :initarg :columns
747     :initform nil)
748    (modifiers
749     :initarg :modifiers
750     :initform nil)
751    (transactions
752     :initarg :transactions
753     :initform nil))
754   (:documentation
755    "An SQL CREATE TABLE statement."))
756
757 ;; Here's a real warhorse of a function!
758
759 (declaim (inline listify))
760 (defun listify (x)
761   (if (atom x)
762       (list x)
763       x))
764
765 (defmethod output-sql ((stmt sql-create-table) database)
766   (flet ((output-column (column-spec)
767            (destructuring-bind (name type &optional db-type &rest constraints)
768                column-spec
769              (let ((type (listify type)))
770                (output-sql name database)
771                (write-char #\Space *sql-stream*)
772                (write-string
773                 (if (stringp db-type) db-type ; override definition
774                   (database-get-type-specifier (car type) (cdr type) database
775                                                (database-underlying-type database)))
776                 *sql-stream*)
777                (let ((constraints (database-constraint-statement  
778                                    (if (and db-type (symbolp db-type))
779                                        (cons db-type constraints)
780                                        constraints)
781                                    database)))
782                  (when constraints
783                    (write-string " " *sql-stream*)
784                    (write-string constraints *sql-stream*)))))))
785     (with-slots (name columns modifiers transactions)
786       stmt
787       (write-string "CREATE TABLE " *sql-stream*)
788       (output-sql name database)
789       (write-string " (" *sql-stream*)
790       (do ((column columns (cdr column)))
791           ((null (cdr column))
792            (output-column (car column)))
793         (output-column (car column))
794         (write-string ", " *sql-stream*))
795       (when modifiers
796         (do ((modifier (listify modifiers) (cdr modifier)))
797             ((null modifier))
798           (write-string ", " *sql-stream*)
799           (write-string (car modifier) *sql-stream*)))
800       (write-char #\) *sql-stream*)
801       (when (and (eq :mysql (database-underlying-type database))
802                  transactions
803                  (db-type-transaction-capable? :mysql database))
804         (write-string " Type=InnoDB" *sql-stream*)))) 
805   t)
806
807
808 ;; CREATE VIEW
809
810 (defclass sql-create-view (%sql-expression)
811   ((name :initarg :name :initform nil)
812    (column-list :initarg :column-list :initform nil)
813    (query :initarg :query :initform nil)
814    (with-check-option :initarg :with-check-option :initform nil))
815   (:documentation "An SQL CREATE VIEW statement."))
816
817 (defmethod output-sql ((stmt sql-create-view) database)
818   (with-slots (name column-list query with-check-option) stmt
819     (write-string "CREATE VIEW " *sql-stream*)
820     (output-sql name database)
821     (when column-list (write-string " " *sql-stream*)
822           (output-sql (listify column-list) database))
823     (write-string " AS " *sql-stream*)
824     (output-sql query database)
825     (when with-check-option (write-string " WITH CHECK OPTION" *sql-stream*))))
826
827
828 ;;
829 ;; DATABASE-OUTPUT-SQL 
830 ;; 
831
832 (defmethod database-output-sql ((str string) database)
833   (declare (ignore database)
834            (optimize (speed 3) (safety 1) #+cmu (extensions:inhibit-warnings 3))
835            (simple-string str))
836   (let ((len (length str)))
837     (declare (type fixnum len))
838     (cond ((zerop len)
839            +empty-string+)
840           ((and (null (position #\' str))
841                 (null (position #\\ str)))
842            (concatenate 'string "'" str "'"))
843           (t
844            (let ((buf (make-string (+ (* len 2) 2) :initial-element #\')))
845              (do* ((i 0 (incf i))
846                    (j 1 (incf j)))
847                   ((= i len) (subseq buf 0 (1+ j)))
848                (declare (type fixnum i j))
849                (let ((char (aref str i)))
850                  (declare (character char))
851                  (cond ((char= char #\')
852                         (setf (aref buf j) #\')
853                         (incf j)
854                         (setf (aref buf j) #\'))
855                        ((and (char= char #\\)
856                              ;; MTP: only escape backslash with pgsql/mysql 
857                              (member (database-underlying-type database) 
858                                      '(:postgresql :mysql)
859                                      :test #'eq))
860                         (setf (aref buf j) #\\)
861                         (incf j)
862                         (setf (aref buf j) #\\))
863                        (t
864                         (setf (aref buf j) char))))))))))
865
866 (let ((keyword-package (symbol-package :foo)))
867   (defmethod database-output-sql ((sym symbol) database)
868   (if (null sym) 
869       +null-string+ 
870       (convert-to-db-default-case
871        (if (equal (symbol-package sym) keyword-package)
872            (concatenate 'string "'" (string sym) "'")
873            (symbol-name sym))
874        database))))
875
876 (defmethod database-output-sql ((tee (eql t)) database)
877   (declare (ignore database))
878   "'Y'")
879
880 (defmethod database-output-sql ((num number) database)
881   (declare (ignore database))
882   (princ-to-string num))
883
884 (defmethod database-output-sql ((arg list) database)
885   (if (null arg) 
886       +null-string+ 
887       (format nil "(~{~A~^,~})" (mapcar #'(lambda (val)
888                                             (sql-output val database))
889                                         arg))))
890
891 (defmethod database-output-sql ((arg vector) database)
892   (format nil "~{~A~^,~}" (map 'list #'(lambda (val)
893                                          (sql-output val database))
894                                arg)))
895
896 (defmethod output-sql-hash-key ((arg vector) database)
897   (list 'vector (map 'list (lambda (arg)
898                              (or (output-sql-hash-key arg database)
899                                  (return-from output-sql-hash-key nil)))
900                      arg)))
901
902 (defmethod database-output-sql ((self wall-time) database)
903   (declare (ignore database))
904   (db-timestring self))
905
906 (defmethod database-output-sql ((self duration) database)
907   (declare (ignore database))
908   (format nil "'~a'" (duration-timestring self)))
909
910 #+ignore 
911 (defmethod database-output-sql ((self money) database)
912   (database-output-sql (slot-value self 'odcl::units) database))
913
914 (defmethod database-output-sql (thing database)
915   (if (or (null thing)
916           (eq 'null thing))
917       +null-string+
918     (error 'sql-user-error
919            :message
920            (format nil
921                    "No type conversion to SQL for ~A is defined for DB ~A."
922                    (type-of thing) (type-of database)))))
923
924
925 ;;
926 ;; Column constraint types and conversion to SQL 
927 ;;
928
929 (defparameter *constraint-types*
930   (list 
931    (cons (symbol-name-default-case "NOT-NULL") "NOT NULL") 
932    (cons (symbol-name-default-case "PRIMARY-KEY") "PRIMARY KEY")
933    (cons (symbol-name-default-case "NOT") "NOT") 
934    (cons (symbol-name-default-case "NULL") "NULL") 
935    (cons (symbol-name-default-case "PRIMARY") "PRIMARY") 
936    (cons (symbol-name-default-case "KEY") "KEY")
937    (cons (symbol-name-default-case "UNSIGNED") "UNSIGNED") 
938    (cons (symbol-name-default-case "ZEROFILL") "ZEROFILL") 
939    (cons (symbol-name-default-case "AUTO-INCREMENT") "AUTO_INCREMENT")
940    (cons (symbol-name-default-case "UNIQUE") "UNIQUE")))
941
942 (defmethod database-constraint-statement (constraint-list database)
943   (declare (ignore database))
944   (make-constraints-description constraint-list))
945   
946 (defun make-constraints-description (constraint-list)
947   (if constraint-list
948       (let ((string ""))
949         (do ((constraint constraint-list (cdr constraint)))
950             ((null constraint) string)
951           (let ((output (assoc (symbol-name (car constraint))
952                                *constraint-types*
953                                :test #'equal)))
954             (if (null output)
955                 (error 'sql-user-error
956                        :message (format nil "unsupported column constraint '~A'"
957                                         constraint))
958                 (setq string (concatenate 'string string (cdr output))))
959             (if (< 1 (length constraint))
960                 (setq string (concatenate 'string string " "))))))))
961