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