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