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