r9615: * sql/expressions.lisp: Avoid duplicate FROM names when selecting
[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 (defmethod output-sql ((expr sql-ident-table) database)
190   (with-slots (name alias)
191     expr
192     (if (null alias)
193         (write-string (sql-escape (convert-to-db-default-case (symbol-name name) database)) *sql-stream*)
194         (progn
195           (write-string (sql-escape (convert-to-db-default-case (symbol-name name) database)) *sql-stream*)
196           (write-char #\Space *sql-stream*)
197           (format *sql-stream* "~s" alias))))
198   t)
199
200 #|
201 (defmethod database-output-sql ((self duration) database)
202   (declare (ignore database))
203   (format nil "'~a'" (duration-timestring self)))
204
205 (defmethod database-output-sql ((self money) database)
206   (database-output-sql (slot-value self 'odcl::units) database))
207 |#
208
209
210 (defmethod output-sql-hash-key ((expr sql-ident-table) database)
211   (declare (ignore database))
212   (with-slots (name alias)
213     expr
214     (list 'sql-ident-table name alias)))
215
216 (defclass sql-relational-exp (%sql-expression)
217   ((operator
218     :initarg :operator
219     :initform nil)
220    (sub-expressions
221     :initarg :sub-expressions
222     :initform nil))
223   (:documentation "An SQL relational expression."))
224
225 (defmethod collect-table-refs ((sql sql-relational-exp))
226   (let ((tabs nil))
227     (dolist (exp (slot-value sql 'sub-expressions))
228       (let ((refs (collect-table-refs exp)))
229         (if refs (setf tabs (append refs tabs)))))
230     (remove-duplicates tabs
231                        :test (lambda (tab1 tab2)
232                                (equal (slot-value tab1 'name)
233                                       (slot-value tab2 'name))))))
234
235
236
237
238 ;; Write SQL for relational operators (like 'AND' and 'OR').
239 ;; should do arity checking of subexpressions
240
241 (defmethod output-sql ((expr sql-relational-exp) database)
242   (with-slots (operator sub-expressions)
243     expr
244     (let ((subs (if (consp (car sub-expressions))
245                     (car sub-expressions)
246                     sub-expressions)))
247       (write-char #\( *sql-stream*)
248       (do ((sub subs (cdr sub)))
249           ((null (cdr sub)) (output-sql (car sub) database))
250         (output-sql (car sub) database)
251         (write-char #\Space *sql-stream*)
252         (output-sql operator database)
253         (write-char #\Space *sql-stream*))
254       (write-char #\) *sql-stream*)))
255   t)
256
257 (defclass sql-upcase-like (sql-relational-exp)
258   ()
259   (:documentation "An SQL 'like' that upcases its arguments."))
260   
261 ;; Write SQL for relational operators (like 'AND' and 'OR').
262 ;; should do arity checking of subexpressions
263   
264 (defmethod output-sql ((expr sql-upcase-like) database)
265   (flet ((write-term (term)
266            (write-string "upper(" *sql-stream*)
267            (output-sql term database)
268            (write-char #\) *sql-stream*)))
269     (with-slots (sub-expressions)
270       expr
271       (let ((subs (if (consp (car sub-expressions))
272                       (car sub-expressions)
273                       sub-expressions)))
274         (write-char #\( *sql-stream*)
275         (do ((sub subs (cdr sub)))
276             ((null (cdr sub)) (write-term (car sub)))
277           (write-term (car sub))
278           (write-string " LIKE " *sql-stream*))
279         (write-char #\) *sql-stream*))))
280   t)
281
282 (defclass sql-assignment-exp (sql-relational-exp)
283   ()
284   (:documentation "An SQL Assignment expression."))
285
286
287 (defmethod output-sql ((expr sql-assignment-exp) database)
288   (with-slots (operator sub-expressions)
289     expr
290     (do ((sub sub-expressions (cdr sub)))
291         ((null (cdr sub)) (output-sql (car sub) database))
292       (output-sql (car sub) database)
293       (write-char #\Space *sql-stream*)
294       (output-sql operator database)
295       (write-char #\Space *sql-stream*)))
296   t)
297
298 (defclass sql-value-exp (%sql-expression)
299   ((modifier
300     :initarg :modifier
301     :initform nil)
302    (components
303     :initarg :components
304     :initform nil))
305   (:documentation
306    "An SQL value expression.")
307   )
308
309 (defmethod collect-table-refs ((sql sql-value-exp))
310   (let ((tabs nil))
311     (if (listp (slot-value sql 'components))
312         (progn
313           (dolist (exp (slot-value sql 'components))
314             (let ((refs (collect-table-refs exp)))
315               (if refs (setf tabs (append refs tabs)))))
316           (remove-duplicates tabs
317                              :test (lambda (tab1 tab2)
318                                      (equal (slot-value tab1 'name)
319                                             (slot-value tab2 'name)))))
320         nil)))
321
322
323
324 (defmethod output-sql ((expr sql-value-exp) database)
325   (with-slots (modifier components)
326     expr
327     (if modifier
328         (progn
329           (write-char #\( *sql-stream*)
330           (output-sql modifier database)
331           (write-char #\Space *sql-stream*)
332           (output-sql components database)
333           (write-char #\) *sql-stream*))
334         (output-sql components database))))
335
336 (defclass sql-typecast-exp (sql-value-exp)
337   ()
338   (:documentation "An SQL typecast expression."))
339
340 (defmethod output-sql ((expr sql-typecast-exp) database)
341   (database-output-sql expr database))
342
343 (defmethod database-output-sql ((expr sql-typecast-exp) database)
344   (with-slots (components)
345     expr
346     (output-sql components database)))
347
348
349 (defmethod collect-table-refs ((sql sql-typecast-exp))
350   (when (slot-value sql 'components)
351     (collect-table-refs (slot-value sql 'components))))
352
353 (defclass sql-function-exp (%sql-expression)
354   ((name
355     :initarg :name
356     :initform nil)
357    (args
358     :initarg :args
359     :initform nil))
360   (:documentation
361    "An SQL function expression."))
362
363 (defmethod collect-table-refs ((sql sql-function-exp))
364   (let ((tabs nil))
365     (dolist (exp (slot-value sql 'components))
366       (let ((refs (collect-table-refs exp)))
367         (if refs (setf tabs (append refs tabs)))))
368     (remove-duplicates tabs
369                        :test (lambda (tab1 tab2)
370                                (equal (slot-value tab1 'name)
371                                       (slot-value tab2 'name))))))
372 (defvar *in-subselect* nil)
373
374 (defmethod output-sql ((expr sql-function-exp) database)
375   (with-slots (name args)
376     expr
377     (output-sql name database)
378     (let ((*in-subselect* nil)) ;; aboid double parens
379       (when args (output-sql args database))))
380   t)
381
382
383 (defclass sql-between-exp (sql-function-exp)
384   () 
385   (:documentation "An SQL between expression."))
386
387 (defmethod output-sql ((expr sql-between-exp) database)
388   (with-slots (name args)
389       expr 
390     (output-sql (first args) database)
391     (write-string " BETWEEN " *sql-stream*)
392     (output-sql (second args) database)
393     (write-string " AND " *sql-stream*)
394     (output-sql (third args) database))
395   t)
396
397 (defclass sql-query-modifier-exp (%sql-expression) 
398   ((modifier :initarg :modifier :initform nil)
399    (components :initarg :components :initform nil))
400   (:documentation "An SQL query modifier expression."))
401
402 (defmethod output-sql ((expr sql-query-modifier-exp) database)
403   (with-slots (modifier components)
404       expr
405     (output-sql modifier database)
406     (write-string " " *sql-stream*)
407     (output-sql (car components) database)
408     (when components 
409       (mapc #'(lambda (comp) 
410                 (write-string ", " *sql-stream*)
411                 (output-sql comp database))
412             (cdr components))))
413   t)
414
415 (defclass sql-set-exp (%sql-expression)
416   ((operator
417     :initarg :operator
418     :initform nil)
419    (sub-expressions
420     :initarg :sub-expressions
421     :initform nil))
422   (:documentation "An SQL set expression."))
423
424 (defmethod collect-table-refs ((sql sql-set-exp))
425   (let ((tabs nil))
426     (dolist (exp (slot-value sql 'sub-expressions))
427       (let ((refs (collect-table-refs exp)))
428         (if refs (setf tabs (append refs tabs)))))
429     (remove-duplicates tabs
430                        :test (lambda (tab1 tab2)
431                                (equal (slot-value tab1 'name)
432                                       (slot-value tab2 'name))))))
433
434 (defmethod output-sql ((expr sql-set-exp) database)
435   (with-slots (operator sub-expressions)
436       expr
437     (let ((subs (if (consp (car sub-expressions))
438                     (car sub-expressions)
439                     sub-expressions)))
440       (when (= (length subs) 1)
441         (output-sql operator database)
442         (write-char #\Space *sql-stream*))
443       (do ((sub subs (cdr sub)))
444           ((null (cdr sub)) (output-sql (car sub) database))
445         (output-sql (car sub) database)
446         (write-char #\Space *sql-stream*)
447         (output-sql operator database)
448         (write-char #\Space *sql-stream*))))
449   t)
450
451 (defclass sql-query (%sql-expression)
452   ((selections
453     :initarg :selections
454     :initform nil)
455    (all
456     :initarg :all
457     :initform nil)
458    (flatp
459     :initarg :flatp
460     :initform nil)
461    (set-operation
462     :initarg :set-operation
463     :initform nil)
464    (distinct
465     :initarg :distinct
466     :initform nil)
467    (from
468     :initarg :from
469     :initform nil)
470    (where
471     :initarg :where
472     :initform nil)
473    (group-by
474     :initarg :group-by
475     :initform nil)
476    (having
477     :initarg :having
478     :initform nil)
479    (limit
480     :initarg :limit
481     :initform nil)
482    (offset
483     :initarg :offset
484     :initform nil)
485    (order-by
486     :initarg :order-by
487     :initform nil)
488    (inner-join
489     :initarg :inner-join
490     :initform nil)
491    (on
492     :initarg :on
493     :initform nil))
494   (:documentation "An SQL SELECT query."))
495
496 (defclass sql-object-query (%sql-expression)
497   ((objects
498     :initarg :objects
499     :initform nil)
500    (flatp
501     :initarg :flatp
502     :initform nil)
503    (exp
504     :initarg :exp
505     :initform nil)
506    (refresh
507     :initarg :refresh
508     :initform nil)))
509
510 (defmethod collect-table-refs ((sql sql-query))
511   (remove-duplicates (collect-table-refs (slot-value sql 'where))
512                      :test (lambda (tab1 tab2)
513                              (equal (slot-value tab1 'name)
514                                     (slot-value tab2 'name)))))
515
516 (defvar *select-arguments*
517   '(:all :database :distinct :flatp :from :group-by :having :order-by
518     :set-operation :where :offset :limit :inner-join :on
519     ;; below keywords are not a SQL argument, but these keywords may terminate select
520     :caching :refresh))
521
522 (defun query-arg-p (sym)
523   (member sym *select-arguments*))
524
525 (defun query-get-selections (select-args)
526   "Return two values: the list of select-args up to the first keyword,
527 uninclusive, and the args from that keyword to the end."
528   (let ((first-key-arg (position-if #'query-arg-p select-args)))
529     (if first-key-arg
530         (values (subseq select-args 0 first-key-arg)
531                 (subseq select-args first-key-arg))
532         select-args)))
533
534 (defun make-query (&rest args)
535   (flet ((select-objects (target-args)
536            (and target-args
537                 (every #'(lambda (arg)
538                            (and (symbolp arg)
539                                 (find-class arg nil)))
540                        target-args))))
541     (multiple-value-bind (selections arglist)
542         (query-get-selections args)
543       (if (select-objects selections) 
544           (destructuring-bind (&key flatp refresh &allow-other-keys) arglist
545             (make-instance 'sql-object-query :objects selections
546                            :flatp flatp :refresh refresh
547                            :exp arglist))
548           (destructuring-bind (&key all flatp set-operation distinct from where
549                                     group-by having order-by 
550                                     offset limit inner-join on &allow-other-keys)
551               arglist
552             (if (null selections)
553                 (error "No target columns supplied to select statement."))
554             (if (null from)
555                 (error "No source tables supplied to select statement."))
556             (make-instance 'sql-query :selections selections
557                            :all all :flatp flatp :set-operation set-operation
558                            :distinct distinct :from from :where where
559                            :limit limit :offset offset
560                            :group-by group-by :having having :order-by order-by
561                            :inner-join inner-join :on on))))))
562
563 (defmethod output-sql ((query sql-query) database)
564   (with-slots (distinct selections from where group-by having order-by
565                         limit offset inner-join on all set-operation) 
566       query
567     (when *in-subselect*
568       (write-string "(" *sql-stream*))
569     (write-string "SELECT " *sql-stream*)
570     (when all 
571       (write-string "ALL " *sql-stream*))
572     (when (and distinct (not all))
573       (write-string "DISTINCT " *sql-stream*)
574       (unless (eql t distinct)
575         (write-string "ON " *sql-stream*)
576         (output-sql distinct database)
577         (write-char #\Space *sql-stream*)))
578     (output-sql (apply #'vector selections) database)
579     (when from
580       (write-string " FROM " *sql-stream*)
581       (typecase from 
582         (list (output-sql (apply #'vector (remove-duplicates 
583                                            from 
584                                            :test #'(lambda (a b)
585                                                      (string-equal (symbol-name (slot-value a 'name))
586                                                                    (symbol-name (slot-value b 'name))))))
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 ;; 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-statement (constraint-list database)
845   (declare (ignore database))
846   (make-constraints-description constraint-list))
847   
848 (defun make-constraints-description (constraint-list)
849   (if constraint-list
850       (let ((string ""))
851         (do ((constraint constraint-list (cdr constraint)))
852             ((null constraint) string)
853           (let ((output (assoc (symbol-name (car constraint))
854                                *constraint-types*
855                                :test #'equal)))
856             (if (null output)
857                 (error 'sql-user-error
858                        :message (format nil "unsupported column constraint '~A'"
859                                         constraint))
860                 (setq string (concatenate 'string string (cdr output))))
861             (if (< 1 (length constraint))
862                 (setq string (concatenate 'string string " "))))))))
863