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