r10820: 12 Nov 2005 Kevin Rosenberg <kevin@rosenberg.net>
[clsql.git] / sql / expressions.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;;
4 ;;;; $Id$
5 ;;;;
6 ;;;; Classes defining SQL expressions and methods for formatting the
7 ;;;; appropriate SQL commands.
8 ;;;;
9 ;;;; This file is part of CLSQL.
10 ;;;;
11 ;;;; CLSQL users are granted the rights to distribute and use this software
12 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
13 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
14 ;;;; *************************************************************************
15
16 (in-package #:clsql-sys)
17
18 (defvar +empty-string+ "''")
19
20 (defvar +null-string+ "NULL")
21
22 (defvar *sql-stream* nil
23   "stream which accumulates SQL output")
24
25 (defun sql-output (sql-expr &optional database)
26   "Top-level call for generating SQL strings. Returns an SQL
27   string appropriate for DATABASE which corresponds to the
28   supplied lisp expression SQL-EXPR."
29   (progv '(*sql-stream*)
30       `(,(make-string-output-stream))
31     (output-sql sql-expr database)
32     (get-output-stream-string *sql-stream*)))
33
34 (defmethod output-sql (expr database)
35   (write-string (database-output-sql expr database) *sql-stream*)
36   (values))
37
38 (defvar *output-hash* (make-hash-table :test #'equal)
39   "For caching generated SQL strings.")
40
41 (defmethod output-sql :around ((sql t) database)
42   (let* ((hash-key (output-sql-hash-key sql database))
43          (hash-value (when hash-key (gethash hash-key *output-hash*))))
44     (cond ((and hash-key hash-value)
45            (write-string hash-value *sql-stream*))
46           (hash-key
47            (let ((*sql-stream* (make-string-output-stream)))
48              (call-next-method)
49              (setf hash-value (get-output-stream-string *sql-stream*))
50              (setf (gethash hash-key *output-hash*) hash-value))
51            (write-string hash-value *sql-stream*))
52           (t
53            (call-next-method)))))
54
55 (defmethod output-sql-hash-key (expr database)
56   (declare (ignore expr database))
57   nil)
58
59
60 (defclass %sql-expression ()
61   ())
62
63 (defmethod output-sql ((expr %sql-expression) database)
64   (declare (ignore database))
65   (write-string +null-string+ *sql-stream*))
66
67 (defmethod print-object ((self %sql-expression) stream)
68   (print-unreadable-object
69    (self stream :type t)
70    (write-string (sql-output self) stream))
71   self)
72
73 ;; For straight up strings
74
75 (defclass sql (%sql-expression)
76   ((text
77     :initarg :string
78     :initform ""))
79   (:documentation "A literal SQL expression."))
80
81 (defmethod make-load-form ((sql sql) &optional environment)
82   (declare (ignore environment))
83   (with-slots (text)
84     sql
85     `(make-instance 'sql :string ',text)))
86
87 (defmethod output-sql ((expr sql) database)
88   (declare (ignore database))
89   (write-string (slot-value expr 'text) *sql-stream*)
90   t)
91
92 (defmethod print-object ((ident sql) stream)
93   (format stream "#<~S \"~A\">"
94           (type-of ident)
95           (sql-output ident nil))
96   ident)
97
98 ;; For SQL Identifiers of generic type
99
100 (defclass sql-ident (%sql-expression)
101   ((name
102     :initarg :name
103     :initform +null-string+))
104   (:documentation "An SQL identifer."))
105
106 (defmethod make-load-form ((sql sql-ident) &optional environment)
107   (declare (ignore environment))
108   (with-slots (name)
109     sql
110     `(make-instance 'sql-ident :name ',name)))
111
112 (defmethod output-sql ((expr sql-ident) database)
113   (with-slots (name) expr
114     (write-string
115      (convert-to-db-default-case
116       (etypecase name
117         (string name)
118         (symbol (symbol-name name)))
119       database)
120      *sql-stream*))
121   t)
122
123 ;; For SQL Identifiers for attributes
124
125 (defclass sql-ident-attribute (sql-ident)
126   ((qualifier
127     :initarg :qualifier
128     :initform +null-string+)
129    (type
130     :initarg :type
131     :initform +null-string+))
132   (:documentation "An SQL Attribute identifier."))
133
134 (defmethod collect-table-refs (sql)
135   (declare (ignore sql))
136   nil)
137
138 (defmethod collect-table-refs ((sql sql-ident-attribute))
139   (let ((qual (slot-value sql 'qualifier)))
140     (if (and qual (symbolp (slot-value sql 'qualifier)))
141         (list (make-instance 'sql-ident-table :name
142                              (slot-value sql 'qualifier))))))
143
144 (defmethod make-load-form ((sql sql-ident-attribute) &optional environment)
145   (declare (ignore environment))
146   (with-slots (qualifier type name)
147     sql
148     `(make-instance 'sql-ident-attribute :name ',name
149       :qualifier ',qualifier
150       :type ',type)))
151
152 (defmethod output-sql ((expr sql-ident-attribute) database)
153   (with-slots (qualifier name type) expr
154     (if (and (not qualifier) (not type))
155         (etypecase name
156           ;; Honor care of name
157           (string
158            (write-string name *sql-stream*))
159           (symbol
160            (write-string (sql-escape (convert-to-db-default-case
161                                       (symbol-name name) database)) *sql-stream*)))
162
163         ;;; KMR: The TYPE field is used by CommonSQL for type conversion -- it
164       ;;; should not be output in SQL statements
165       #+ignore
166       (format *sql-stream* "~@[~A.~]~A~@[ ~A~]"
167               (when qualifier
168                 (convert-to-db-default-case (sql-escape qualifier) database))
169               (sql-escape (convert-to-db-default-case name database))
170               (when type
171                 (convert-to-db-default-case (symbol-name type) database)))
172       (format *sql-stream* "~@[~A.~]~A"
173               (when qualifier
174                 (typecase qualifier
175                   (string (format nil "~s" qualifier))
176                   (t (convert-to-db-default-case (sql-escape qualifier)
177                                                  database))))
178               (sql-escape (convert-to-db-default-case name database))))
179     t))
180
181 (defmethod output-sql-hash-key ((expr sql-ident-attribute) database)
182   (with-slots (qualifier name type)
183       expr
184     (list (and database (database-underlying-type database))
185           'sql-ident-attribute qualifier name type)))
186
187 ;; For SQL Identifiers for tables
188
189 (defclass sql-ident-table (sql-ident)
190   ((alias
191     :initarg :table-alias :initform nil))
192   (:documentation "An SQL table identifier."))
193
194 (defmethod make-load-form ((sql sql-ident-table) &optional environment)
195   (declare (ignore environment))
196   (with-slots (alias name)
197     sql
198     `(make-instance 'sql-ident-table :name ',name :table-alias ',alias)))
199
200 (defmethod output-sql ((expr sql-ident-table) database)
201   (with-slots (name alias) expr
202      (let ((namestr (if (symbolp name)
203                         (symbol-name name)
204                       name)))
205        (if (null alias)
206            (write-string
207             (sql-escape (convert-to-db-default-case namestr database))
208             *sql-stream*)
209          (progn
210            (write-string
211             (sql-escape (convert-to-db-default-case namestr database))
212             *sql-stream*)
213            (write-char #\Space *sql-stream*)
214            (format *sql-stream* "~s" alias)))))
215   t)
216
217 (defmethod output-sql-hash-key ((expr sql-ident-table) database)
218   (with-slots (name alias)
219       expr
220     (list (and database (database-underlying-type database))
221           'sql-ident-table name alias)))
222
223 (defclass sql-relational-exp (%sql-expression)
224   ((operator
225     :initarg :operator
226     :initform nil)
227    (sub-expressions
228     :initarg :sub-expressions
229     :initform nil))
230   (:documentation "An SQL relational expression."))
231
232 (defmethod make-load-form ((self sql-relational-exp) &optional environment)
233   (make-load-form-saving-slots self
234                                :slot-names '(operator sub-expressions)
235                                :environment environment))
236
237 (defmethod collect-table-refs ((sql sql-relational-exp))
238   (let ((tabs nil))
239     (dolist (exp (slot-value sql 'sub-expressions))
240       (let ((refs (collect-table-refs exp)))
241         (if refs (setf tabs (append refs tabs)))))
242     (remove-duplicates tabs
243                        :test (lambda (tab1 tab2)
244                                (equal (slot-value tab1 'name)
245                                       (slot-value tab2 'name))))))
246
247
248
249
250 ;; Write SQL for relational operators (like 'AND' and 'OR').
251 ;; should do arity checking of subexpressions
252
253 (defmethod output-sql ((expr sql-relational-exp) database)
254   (with-slots (operator sub-expressions)
255     expr
256     (let ((subs (if (consp (car sub-expressions))
257                     (car sub-expressions)
258                     sub-expressions)))
259       (write-char #\( *sql-stream*)
260       (do ((sub subs (cdr sub)))
261           ((null (cdr sub)) (output-sql (car sub) database))
262         (output-sql (car sub) database)
263         (write-char #\Space *sql-stream*)
264         (output-sql operator database)
265         (write-char #\Space *sql-stream*))
266       (write-char #\) *sql-stream*)))
267   t)
268
269 (defclass sql-upcase-like (sql-relational-exp)
270   ()
271   (:documentation "An SQL 'like' that upcases its arguments."))
272
273 (defmethod output-sql ((expr sql-upcase-like) database)
274   (flet ((write-term (term)
275            (write-string "upper(" *sql-stream*)
276            (output-sql term database)
277            (write-char #\) *sql-stream*)))
278     (with-slots (sub-expressions)
279       expr
280       (let ((subs (if (consp (car sub-expressions))
281                       (car sub-expressions)
282                       sub-expressions)))
283         (write-char #\( *sql-stream*)
284         (do ((sub subs (cdr sub)))
285             ((null (cdr sub)) (write-term (car sub)))
286           (write-term (car sub))
287           (write-string " LIKE " *sql-stream*))
288         (write-char #\) *sql-stream*))))
289   t)
290
291 (defclass sql-assignment-exp (sql-relational-exp)
292   ()
293   (:documentation "An SQL Assignment expression."))
294
295
296 (defmethod output-sql ((expr sql-assignment-exp) database)
297   (with-slots (operator sub-expressions)
298     expr
299     (do ((sub sub-expressions (cdr sub)))
300         ((null (cdr sub)) (output-sql (car sub) database))
301       (output-sql (car sub) database)
302       (write-char #\Space *sql-stream*)
303       (output-sql operator database)
304       (write-char #\Space *sql-stream*)))
305   t)
306
307 (defclass sql-value-exp (%sql-expression)
308   ((modifier
309     :initarg :modifier
310     :initform nil)
311    (components
312     :initarg :components
313     :initform nil))
314   (:documentation
315    "An SQL value expression.")
316   )
317
318 (defmethod collect-table-refs ((sql sql-value-exp))
319   (let ((tabs nil))
320     (if (listp (slot-value sql 'components))
321         (progn
322           (dolist (exp (slot-value sql 'components))
323             (let ((refs (collect-table-refs exp)))
324               (if refs (setf tabs (append refs tabs)))))
325           (remove-duplicates tabs
326                              :test (lambda (tab1 tab2)
327                                      (equal (slot-value tab1 'name)
328                                             (slot-value tab2 'name)))))
329         nil)))
330
331
332
333 (defmethod output-sql ((expr sql-value-exp) database)
334   (with-slots (modifier components)
335     expr
336     (if modifier
337         (progn
338           (write-char #\( *sql-stream*)
339           (output-sql modifier database)
340           (write-char #\Space *sql-stream*)
341           (output-sql components database)
342           (write-char #\) *sql-stream*))
343         (output-sql components database))))
344
345 (defclass sql-typecast-exp (sql-value-exp)
346   ()
347   (:documentation "An SQL typecast expression."))
348
349 (defmethod output-sql ((expr sql-typecast-exp) database)
350   (with-slots (components)
351     expr
352     (output-sql components database)))
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 'args))
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       (flet ((ident-table-equal (a b)
587                (and (if (and (eql (type-of a) 'sql-ident-table)
588                              (eql (type-of b) 'sql-ident-table))
589                         (string-equal (slot-value a 'alias)
590                                       (slot-value b 'alias))
591                         t)
592                     (string-equal (symbol-name (slot-value a 'name))
593                                   (symbol-name (slot-value b 'name))))))
594         (typecase from
595           (list (output-sql (apply #'vector
596                                    (remove-duplicates from
597                                                       :test #'ident-table-equal))
598                             database))
599           (string (write-string from *sql-stream*))
600           (t (output-sql from database)))))
601     (when inner-join
602       (write-string " INNER JOIN " *sql-stream*)
603       (output-sql inner-join database))
604     (when on
605       (write-string " ON " *sql-stream*)
606       (output-sql on database))
607     (when where
608       (write-string " WHERE " *sql-stream*)
609       (let ((*in-subselect* t))
610         (output-sql where database)))
611     (when group-by
612       (write-string " GROUP BY " *sql-stream*)
613       (if (listp group-by)
614           (do ((order group-by (cdr order)))
615               ((null order))
616             (let ((item (car order)))
617               (typecase item
618                 (cons
619                  (output-sql (car item) database)
620                  (format *sql-stream* " ~A" (cadr item)))
621                 (t
622                  (output-sql item database)))
623               (when (cdr order)
624                 (write-char #\, *sql-stream*))))
625           (output-sql group-by database)))
626     (when having
627       (write-string " HAVING " *sql-stream*)
628       (output-sql having database))
629     (when order-by
630       (write-string " ORDER BY " *sql-stream*)
631       (if (listp order-by)
632           (do ((order order-by (cdr order)))
633               ((null order))
634             (let ((item (car order)))
635               (typecase item
636                 (cons
637                  (output-sql (car item) database)
638                  (format *sql-stream* " ~A" (cadr item)))
639                 (t
640                  (output-sql item database)))
641               (when (cdr order)
642                 (write-char #\, *sql-stream*))))
643           (output-sql order-by database)))
644     (when limit
645       (write-string " LIMIT " *sql-stream*)
646       (output-sql limit database))
647     (when offset
648       (write-string " OFFSET " *sql-stream*)
649       (output-sql offset database))
650     (when *in-subselect*
651       (write-string ")" *sql-stream*))
652     (when set-operation
653       (write-char #\Space *sql-stream*)
654       (output-sql set-operation database)))
655   t)
656
657 (defmethod output-sql ((query sql-object-query) database)
658   (declare (ignore database))
659   (with-slots (objects)
660       query
661     (when objects
662       (format *sql-stream* "(~{~A~^ ~})" objects))))
663
664
665 ;; INSERT
666
667 (defclass sql-insert (%sql-expression)
668   ((into
669     :initarg :into
670     :initform nil)
671    (attributes
672     :initarg :attributes
673     :initform nil)
674    (values
675     :initarg :values
676     :initform nil)
677    (query
678     :initarg :query
679     :initform nil))
680   (:documentation
681    "An SQL INSERT statement."))
682
683 (defmethod output-sql ((ins sql-insert) database)
684   (with-slots (into attributes values query)
685     ins
686     (write-string "INSERT INTO " *sql-stream*)
687     (output-sql
688      (typecase into
689        (string (sql-expression :attribute into))
690        (t into))
691      database)
692     (when attributes
693       (write-char #\Space *sql-stream*)
694       (output-sql attributes database))
695     (when values
696       (write-string " VALUES " *sql-stream*)
697       (output-sql values database))
698     (when query
699       (write-char #\Space *sql-stream*)
700       (output-sql query database)))
701   t)
702
703 ;; DELETE
704
705 (defclass sql-delete (%sql-expression)
706   ((from
707     :initarg :from
708     :initform nil)
709    (where
710     :initarg :where
711     :initform nil))
712   (:documentation
713    "An SQL DELETE statement."))
714
715 (defmethod output-sql ((stmt sql-delete) database)
716   (with-slots (from where)
717     stmt
718     (write-string "DELETE FROM " *sql-stream*)
719     (typecase from
720       ((or symbol string) (write-string (sql-escape from) *sql-stream*))
721       (t  (output-sql from database)))
722     (when where
723       (write-string " WHERE " *sql-stream*)
724       (output-sql where database)))
725   t)
726
727 ;; UPDATE
728
729 (defclass sql-update (%sql-expression)
730   ((table
731     :initarg :table
732     :initform nil)
733    (attributes
734     :initarg :attributes
735     :initform nil)
736    (values
737     :initarg :values
738     :initform nil)
739    (where
740     :initarg :where
741     :initform nil))
742   (:documentation "An SQL UPDATE statement."))
743
744 (defmethod output-sql ((expr sql-update) database)
745   (with-slots (table where attributes values)
746     expr
747     (flet ((update-assignments ()
748              (mapcar #'(lambda (a b)
749                          (make-instance 'sql-assignment-exp
750                                         :operator '=
751                                         :sub-expressions (list a b)))
752                      attributes values)))
753       (write-string "UPDATE " *sql-stream*)
754       (output-sql table database)
755       (write-string " SET " *sql-stream*)
756       (output-sql (apply #'vector (update-assignments)) database)
757       (when where
758         (write-string " WHERE " *sql-stream*)
759         (output-sql where database))))
760   t)
761
762 ;; CREATE TABLE
763
764 (defclass sql-create-table (%sql-expression)
765   ((name
766     :initarg :name
767     :initform nil)
768    (columns
769     :initarg :columns
770     :initform nil)
771    (modifiers
772     :initarg :modifiers
773     :initform nil)
774    (transactions
775     :initarg :transactions
776     :initform nil))
777   (:documentation
778    "An SQL CREATE TABLE statement."))
779
780 ;; Here's a real warhorse of a function!
781
782 (declaim (inline listify))
783 (defun listify (x)
784   (if (atom x)
785       (list x)
786       x))
787
788 (defmethod output-sql ((stmt sql-create-table) database)
789   (flet ((output-column (column-spec)
790            (destructuring-bind (name type &optional db-type &rest constraints)
791                column-spec
792              (let ((type (listify type)))
793                (output-sql name database)
794                (write-char #\Space *sql-stream*)
795                (write-string
796                 (if (stringp db-type) db-type ; override definition
797                   (database-get-type-specifier (car type) (cdr type) database
798                                                (database-underlying-type database)))
799                 *sql-stream*)
800                (let ((constraints (database-constraint-statement
801                                    (if (and db-type (symbolp db-type))
802                                        (cons db-type constraints)
803                                        constraints)
804                                    database)))
805                  (when constraints
806                    (write-string " " *sql-stream*)
807                    (write-string constraints *sql-stream*)))))))
808     (with-slots (name columns modifiers transactions)
809       stmt
810       (write-string "CREATE TABLE " *sql-stream*)
811       (output-sql name database)
812       (write-string " (" *sql-stream*)
813       (do ((column columns (cdr column)))
814           ((null (cdr column))
815            (output-column (car column)))
816         (output-column (car column))
817         (write-string ", " *sql-stream*))
818       (when modifiers
819         (do ((modifier (listify modifiers) (cdr modifier)))
820             ((null modifier))
821           (write-string ", " *sql-stream*)
822           (write-string (car modifier) *sql-stream*)))
823       (write-char #\) *sql-stream*)
824       (when (and (eq :mysql (database-underlying-type database))
825                  transactions
826                  (db-type-transaction-capable? :mysql database))
827         (write-string " Type=InnoDB" *sql-stream*))))
828   t)
829
830
831 ;; CREATE VIEW
832
833 (defclass sql-create-view (%sql-expression)
834   ((name :initarg :name :initform nil)
835    (column-list :initarg :column-list :initform nil)
836    (query :initarg :query :initform nil)
837    (with-check-option :initarg :with-check-option :initform nil))
838   (:documentation "An SQL CREATE VIEW statement."))
839
840 (defmethod output-sql ((stmt sql-create-view) database)
841   (with-slots (name column-list query with-check-option) stmt
842     (write-string "CREATE VIEW " *sql-stream*)
843     (output-sql name database)
844     (when column-list (write-string " " *sql-stream*)
845           (output-sql (listify column-list) database))
846     (write-string " AS " *sql-stream*)
847     (output-sql query database)
848     (when with-check-option (write-string " WITH CHECK OPTION" *sql-stream*))))
849
850
851 ;;
852 ;; DATABASE-OUTPUT-SQL
853 ;;
854
855 (defmethod database-output-sql ((str string) database)
856   (declare (optimize (speed 3) (safety 1)
857                      #+cmu (extensions:inhibit-warnings 3)))
858   (let ((len (length str)))
859     (declare (type fixnum len))
860     (cond ((zerop len)
861            +empty-string+)
862           ((and (null (position #\' str))
863                 (null (position #\\ str)))
864            (concatenate 'string "'" str "'"))
865           (t
866            (let ((buf (make-string (+ (* len 2) 2) :initial-element #\')))
867              (declare (simple-string buf))
868              (do* ((i 0 (incf i))
869                    (j 1 (incf j)))
870                   ((= i len) (subseq buf 0 (1+ j)))
871                (declare (type fixnum i j))
872                (let ((char (aref str i)))
873                  (declare (character char))
874                  (cond ((char= char #\')
875                         (setf (aref buf j) #\')
876                         (incf j)
877                         (setf (aref buf j) #\'))
878                        ((and (char= char #\\)
879                              ;; MTP: only escape backslash with pgsql/mysql
880                              (member (database-underlying-type database)
881                                      '(:postgresql :mysql)
882                                      :test #'eq))
883                         (setf (aref buf j) #\\)
884                         (incf j)
885                         (setf (aref buf j) #\\))
886                        (t
887                         (setf (aref buf j) char))))))))))
888
889 (let ((keyword-package (symbol-package :foo)))
890   (defmethod database-output-sql ((sym symbol) database)
891   (if (null sym)
892       +null-string+
893       (convert-to-db-default-case
894        (if (equal (symbol-package sym) keyword-package)
895            (concatenate 'string "'" (string sym) "'")
896            (symbol-name sym))
897        database))))
898
899 (defmethod database-output-sql ((tee (eql t)) database)
900   (declare (ignore database))
901   "'Y'")
902
903 (defmethod database-output-sql ((num number) database)
904   (declare (ignore database))
905   (number-to-sql-string num))
906
907 (defmethod database-output-sql ((arg list) database)
908   (if (null arg)
909       +null-string+
910       (format nil "(~{~A~^,~})" (mapcar #'(lambda (val)
911                                             (sql-output val database))
912                                         arg))))
913
914 (defmethod database-output-sql ((arg vector) database)
915   (format nil "~{~A~^,~}" (map 'list #'(lambda (val)
916                                          (sql-output val database))
917                                arg)))
918
919 (defmethod output-sql-hash-key ((arg vector) database)
920   (list 'vector (map 'list (lambda (arg)
921                              (or (output-sql-hash-key arg database)
922                                  (return-from output-sql-hash-key nil)))
923                      arg)))
924
925 (defmethod database-output-sql ((self wall-time) database)
926   (declare (ignore database))
927   (db-timestring self))
928
929 (defmethod database-output-sql ((self date) database)
930   (declare (ignore database))
931   (db-datestring self))
932
933 (defmethod database-output-sql ((self duration) database)
934   (declare (ignore database))
935   (format nil "'~a'" (duration-timestring self)))
936
937 #+ignore
938 (defmethod database-output-sql ((self money) database)
939   (database-output-sql (slot-value self 'odcl::units) database))
940
941 (defmethod database-output-sql (thing database)
942   (if (or (null thing)
943           (eq 'null thing))
944       +null-string+
945     (error 'sql-user-error
946            :message
947            (format nil
948                    "No type conversion to SQL for ~A is defined for DB ~A."
949                    (type-of thing) (type-of database)))))
950
951
952 ;;
953 ;; Column constraint types and conversion to SQL
954 ;;
955
956 (defparameter *constraint-types*
957   (list
958    (cons (symbol-name-default-case "NOT-NULL") "NOT NULL")
959    (cons (symbol-name-default-case "PRIMARY-KEY") "PRIMARY KEY")
960    (cons (symbol-name-default-case "NOT") "NOT")
961    (cons (symbol-name-default-case "NULL") "NULL")
962    (cons (symbol-name-default-case "PRIMARY") "PRIMARY")
963    (cons (symbol-name-default-case "KEY") "KEY")
964    (cons (symbol-name-default-case "UNSIGNED") "UNSIGNED")
965    (cons (symbol-name-default-case "ZEROFILL") "ZEROFILL")
966    (cons (symbol-name-default-case "AUTO-INCREMENT") "AUTO_INCREMENT")
967    (cons (symbol-name-default-case "UNIQUE") "UNIQUE")))
968
969 (defmethod database-constraint-statement (constraint-list database)
970   (declare (ignore database))
971   (make-constraints-description constraint-list))
972
973 (defun make-constraints-description (constraint-list)
974   (if constraint-list
975       (let ((string ""))
976         (do ((constraint constraint-list (cdr constraint)))
977             ((null constraint) string)
978           (let ((output (assoc (symbol-name (car constraint))
979                                *constraint-types*
980                                :test #'equal)))
981             (if (null output)
982                 (error 'sql-user-error
983                        :message (format nil "unsupported column constraint '~A'"
984                                         constraint))
985                 (setq string (concatenate 'string string (cdr output))))
986             (if (< 1 (length constraint))
987                 (setq string (concatenate 'string string " "))))))))
988