r9528: move special variable declaration
[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 (defvar *in-subselect* nil)
378
379 (defmethod output-sql ((expr sql-function-exp) database)
380   (with-slots (name args)
381     expr
382     (output-sql name database)
383     (let ((*in-subselect* nil)) ;; aboid double parens
384       (when args (output-sql args database))))
385   t)
386
387
388 (defclass sql-between-exp (sql-function-exp)
389   () 
390   (:documentation "An SQL between expression."))
391
392 (defmethod output-sql ((expr sql-between-exp) database)
393   (with-slots (name args)
394       expr 
395     (output-sql (first args) database)
396     (write-string " BETWEEN " *sql-stream*)
397     (output-sql (second args) database)
398     (write-string " AND " *sql-stream*)
399     (output-sql (third args) database))
400   t)
401
402 (defclass sql-query-modifier-exp (%sql-expression) 
403   ((modifier :initarg :modifier :initform nil)
404    (components :initarg :components :initform nil))
405   (:documentation "An SQL query modifier expression."))
406
407 (defmethod output-sql ((expr sql-query-modifier-exp) database)
408   (with-slots (modifier components)
409       expr
410     (output-sql modifier database)
411     (write-string " " *sql-stream*)
412     (output-sql (car components) database)
413     (when components 
414       (mapc #'(lambda (comp) 
415                 (write-string ", " *sql-stream*)
416                 (output-sql comp database))
417             (cdr components))))
418   t)
419
420 (defclass sql-set-exp (%sql-expression)
421   ((operator
422     :initarg :operator
423     :initform nil)
424    (sub-expressions
425     :initarg :sub-expressions
426     :initform nil))
427   (:documentation "An SQL set expression."))
428
429 (defmethod collect-table-refs ((sql sql-set-exp))
430   (let ((tabs nil))
431     (dolist (exp (slot-value sql 'sub-expressions))
432       (let ((refs (collect-table-refs exp)))
433         (if refs (setf tabs (append refs tabs)))))
434     (remove-duplicates tabs
435                        :test (lambda (tab1 tab2)
436                                (equal (slot-value tab1 'name)
437                                       (slot-value tab2 'name))))))
438
439 (defmethod output-sql ((expr sql-set-exp) database)
440   (with-slots (operator sub-expressions)
441       expr
442     (let ((subs (if (consp (car sub-expressions))
443                     (car sub-expressions)
444                     sub-expressions)))
445       (when (= (length subs) 1)
446         (output-sql operator database)
447         (write-char #\Space *sql-stream*))
448       (do ((sub subs (cdr sub)))
449           ((null (cdr sub)) (output-sql (car sub) database))
450         (output-sql (car sub) database)
451         (write-char #\Space *sql-stream*)
452         (output-sql operator database)
453         (write-char #\Space *sql-stream*))))
454   t)
455
456 (defclass sql-query (%sql-expression)
457   ((selections
458     :initarg :selections
459     :initform nil)
460    (all
461     :initarg :all
462     :initform nil)
463    (flatp
464     :initarg :flatp
465     :initform nil)
466    (set-operation
467     :initarg :set-operation
468     :initform nil)
469    (distinct
470     :initarg :distinct
471     :initform nil)
472    (from
473     :initarg :from
474     :initform nil)
475    (where
476     :initarg :where
477     :initform nil)
478    (group-by
479     :initarg :group-by
480     :initform nil)
481    (having
482     :initarg :having
483     :initform nil)
484    (limit
485     :initarg :limit
486     :initform nil)
487    (offset
488     :initarg :offset
489     :initform nil)
490    (order-by
491     :initarg :order-by
492     :initform nil)
493    (inner-join
494     :initarg :inner-join
495     :initform nil)
496    (on
497     :initarg :on
498     :initform nil))
499   (:documentation "An SQL SELECT query."))
500
501 (defclass sql-object-query (%sql-expression)
502   ((objects
503     :initarg :objects
504     :initform nil)
505    (flatp
506     :initarg :flatp
507     :initform nil)
508    (exp
509     :initarg :exp
510     :initform nil)
511    (refresh
512     :initarg :refresh
513     :initform nil)))
514
515 (defmethod collect-table-refs ((sql sql-query))
516   (remove-duplicates (collect-table-refs (slot-value sql 'where))
517                      :test (lambda (tab1 tab2)
518                              (equal (slot-value tab1 'name)
519                                     (slot-value tab2 'name)))))
520
521 (defvar *select-arguments*
522   '(:all :database :distinct :flatp :from :group-by :having :order-by
523     :set-operation :where :offset :limit :inner-join :on
524     ;; below keywords are not a SQL argument, but these keywords may terminate select
525     :caching :refresh))
526
527 (defun query-arg-p (sym)
528   (member sym *select-arguments*))
529
530 (defun query-get-selections (select-args)
531   "Return two values: the list of select-args up to the first keyword,
532 uninclusive, and the args from that keyword to the end."
533   (let ((first-key-arg (position-if #'query-arg-p select-args)))
534     (if first-key-arg
535         (values (subseq select-args 0 first-key-arg)
536                 (subseq select-args first-key-arg))
537         select-args)))
538
539 (defun make-query (&rest args)
540   (flet ((select-objects (target-args)
541            (and target-args
542                 (every #'(lambda (arg)
543                            (and (symbolp arg)
544                                 (find-class arg nil)))
545                        target-args))))
546     (multiple-value-bind (selections arglist)
547         (query-get-selections args)
548       (if (select-objects selections) 
549           (destructuring-bind (&key flatp refresh &allow-other-keys) arglist
550             (make-instance 'sql-object-query :objects selections
551                            :flatp flatp :refresh refresh
552                            :exp arglist))
553           (destructuring-bind (&key all flatp set-operation distinct from where
554                                     group-by having order-by 
555                                     offset limit inner-join on &allow-other-keys)
556               arglist
557             (if (null selections)
558                 (error "No target columns supplied to select statement."))
559             (if (null from)
560                 (error "No source tables supplied to select statement."))
561             (make-instance 'sql-query :selections selections
562                            :all all :flatp flatp :set-operation set-operation
563                            :distinct distinct :from from :where where
564                            :limit limit :offset offset
565                            :group-by group-by :having having :order-by order-by
566                            :inner-join inner-join :on on))))))
567
568 (defmethod output-sql ((query sql-query) database)
569   (with-slots (distinct selections from where group-by having order-by
570                         limit offset inner-join on all set-operation) 
571       query
572     (when *in-subselect*
573       (write-string "(" *sql-stream*))
574     (write-string "SELECT " *sql-stream*)
575     (when all 
576       (write-string "ALL " *sql-stream*))
577     (when (and distinct (not all))
578       (write-string "DISTINCT " *sql-stream*)
579       (unless (eql t distinct)
580         (write-string "ON " *sql-stream*)
581         (output-sql distinct database)
582         (write-char #\Space *sql-stream*)))
583     (output-sql (apply #'vector selections) database)
584     (when from
585       (write-string " FROM " *sql-stream*)
586       (typecase from 
587         (list (output-sql (apply #'vector from) 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 ;; Column constraint types
830 ;;
831 (defparameter *constraint-types*
832   (list 
833    (cons (symbol-name-default-case "NOT-NULL") "NOT NULL") 
834    (cons (symbol-name-default-case "PRIMARY-KEY") "PRIMARY KEY")
835    (cons (symbol-name-default-case "NOT") "NOT") 
836    (cons (symbol-name-default-case "NULL") "NULL") 
837    (cons (symbol-name-default-case "PRIMARY") "PRIMARY") 
838    (cons (symbol-name-default-case "KEY") "KEY")))
839
840 ;;
841 ;; Convert type spec to sql syntax
842 ;;
843
844 (defmethod database-constraint-description (constraint database)
845   (declare (ignore database))
846   (let ((output (assoc (symbol-name constraint) *constraint-types*
847                        :test #'equal)))
848     (if (null output)
849         (error 'sql-user-error
850                :message (format nil "unsupported column constraint '~A'"
851                                 constraint))
852         (cdr output))))
853
854 (defmethod database-constraint-statement (constraint-list database)
855   (declare (ignore database))
856   (make-constraints-description constraint-list))
857   
858 (defun make-constraints-description (constraint-list)
859   (if constraint-list
860       (let ((string ""))
861         (do ((constraint constraint-list (cdr constraint)))
862             ((null constraint) string)
863           (let ((output (assoc (symbol-name (car constraint))
864                                *constraint-types*
865                                :test #'equal)))
866             (if (null output)
867                 (error 'sql-user-error
868                        :message (format nil "unsupported column constraint '~A'"
869                                         constraint))
870                 (setq string (concatenate 'string string (cdr output))))
871             (if (< 1 (length constraint))
872                 (setq string (concatenate 'string string " "))))))))
873