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