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