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