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