changed how where clauses are output to ensure that we do not output a "where"
[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       (let ((where-out (string-trim '(#\newline #\space #\tab #\return)
629                                     (with-output-to-string (*sql-stream*)
630                                       (let ((*in-subselect* t))
631                                         (output-sql where database))))))
632         (when (> (length where-out) 0)
633           (write-string " WHERE " *sql-stream*)
634           (write-string where-out *sql-stream*))))
635     (when group-by
636       (write-string " GROUP BY " *sql-stream*)
637       (if (listp group-by)
638           (do ((order group-by (cdr order)))
639               ((null order))
640             (let ((item (car order)))
641               (typecase item
642                 (cons
643                  (output-sql (car item) database)
644                  (format *sql-stream* " ~A" (cadr item)))
645                 (t
646                  (output-sql item database)))
647               (when (cdr order)
648                 (write-char #\, *sql-stream*))))
649           (output-sql group-by database)))
650     (when having
651       (write-string " HAVING " *sql-stream*)
652       (output-sql having database))
653     (when order-by
654       (write-string " ORDER BY " *sql-stream*)
655       (if (listp order-by)
656           (do ((order order-by (cdr order)))
657               ((null order))
658             (let ((item (car order)))
659               (typecase item
660                 (cons
661                  (output-sql (car item) database)
662                  (format *sql-stream* " ~A" (cadr item)))
663                 (t
664                  (output-sql item database)))
665               (when (cdr order)
666                 (write-char #\, *sql-stream*))))
667           (output-sql order-by database)))
668     (when (and limit (not (eq :odbc (database-type database))))
669       (write-string " LIMIT " *sql-stream*)
670       (output-sql limit database))
671     (when offset
672       (write-string " OFFSET " *sql-stream*)
673       (output-sql offset database))
674     (when *in-subselect*
675       (write-string ")" *sql-stream*))
676     (when set-operation
677       (write-char #\Space *sql-stream*)
678       (output-sql set-operation database)))
679   t)
680
681 (defmethod output-sql ((query sql-object-query) database)
682   (declare (ignore database))
683   (with-slots (objects)
684       query
685     (when objects
686       (format *sql-stream* "(~{~A~^ ~})" objects))))
687
688
689 ;; INSERT
690
691 (defclass sql-insert (%sql-expression)
692   ((into
693     :initarg :into
694     :initform nil)
695    (attributes
696     :initarg :attributes
697     :initform nil)
698    (values
699     :initarg :values
700     :initform nil)
701    (query
702     :initarg :query
703     :initform nil))
704   (:documentation
705    "An SQL INSERT statement."))
706
707 (defmethod output-sql ((ins sql-insert) database)
708   (with-slots (into attributes values query)
709     ins
710     (write-string "INSERT INTO " *sql-stream*)
711     (output-sql
712      (typecase into
713        (string (sql-expression :table into))
714        (t into))
715      database)
716     (when attributes
717       (write-char #\Space *sql-stream*)
718       (output-sql attributes database))
719     (when values
720       (write-string " VALUES " *sql-stream*)
721       (output-sql values database))
722     (when query
723       (write-char #\Space *sql-stream*)
724       (output-sql query database)))
725   t)
726
727 ;; DELETE
728
729 (defclass sql-delete (%sql-expression)
730   ((from
731     :initarg :from
732     :initform nil)
733    (where
734     :initarg :where
735     :initform nil))
736   (:documentation
737    "An SQL DELETE statement."))
738
739 (defmethod output-sql ((stmt sql-delete) database)
740   (with-slots (from where)
741     stmt
742     (write-string "DELETE FROM " *sql-stream*)
743     (typecase from
744       ((or symbol string) (write-string (sql-escape from) *sql-stream*))
745       (t  (output-sql from database)))
746     (when where
747       (write-string " WHERE " *sql-stream*)
748       (output-sql where database)))
749   t)
750
751 ;; UPDATE
752
753 (defclass sql-update (%sql-expression)
754   ((table
755     :initarg :table
756     :initform nil)
757    (attributes
758     :initarg :attributes
759     :initform nil)
760    (values
761     :initarg :values
762     :initform nil)
763    (where
764     :initarg :where
765     :initform nil))
766   (:documentation "An SQL UPDATE statement."))
767
768 (defmethod output-sql ((expr sql-update) database)
769   (with-slots (table where attributes values)
770     expr
771     (flet ((update-assignments ()
772              (mapcar #'(lambda (a b)
773                          (make-instance 'sql-assignment-exp
774                                         :operator '=
775                                         :sub-expressions (list a b)))
776                      attributes values)))
777       (write-string "UPDATE " *sql-stream*)
778       (output-sql table database)
779       (write-string " SET " *sql-stream*)
780       (output-sql (apply #'vector (update-assignments)) database)
781       (when where
782         (write-string " WHERE " *sql-stream*)
783         (output-sql where database))))
784   t)
785
786 ;; CREATE TABLE
787
788 (defclass sql-create-table (%sql-expression)
789   ((name
790     :initarg :name
791     :initform nil)
792    (columns
793     :initarg :columns
794     :initform nil)
795    (modifiers
796     :initarg :modifiers
797     :initform nil)
798    (transactions
799     :initarg :transactions
800     :initform nil))
801   (:documentation
802    "An SQL CREATE TABLE statement."))
803
804 ;; Here's a real warhorse of a function!
805
806 (declaim (inline listify))
807 (defun listify (x)
808   (if (atom x)
809       (list x)
810       x))
811
812 (defmethod output-sql ((stmt sql-create-table) database)
813   (flet ((output-column (column-spec)
814            (destructuring-bind (name type &optional db-type &rest constraints)
815                column-spec
816              (let ((type (listify type)))
817                (output-sql name database)
818                (write-char #\Space *sql-stream*)
819                (write-string
820                 (if (stringp db-type) db-type ; override definition
821                   (database-get-type-specifier (car type) (cdr type) database
822                                                (database-underlying-type database)))
823                 *sql-stream*)
824                (let ((constraints (database-constraint-statement
825                                    (if (and db-type (symbolp db-type))
826                                        (cons db-type constraints)
827                                        constraints)
828                                    database)))
829                  (when constraints
830                    (write-string " " *sql-stream*)
831                    (write-string constraints *sql-stream*)))))))
832     (with-slots (name columns modifiers transactions)
833       stmt
834       (write-string "CREATE TABLE " *sql-stream*)
835       (etypecase name
836           (string (format *sql-stream* "~s" (sql-escape name)))
837           (symbol (write-string (sql-escape name) *sql-stream*))
838           (sql-ident (output-sql name database)))
839       (write-string " (" *sql-stream*)
840       (do ((column columns (cdr column)))
841           ((null (cdr column))
842            (output-column (car column)))
843         (output-column (car column))
844         (write-string ", " *sql-stream*))
845       (when modifiers
846         (do ((modifier (listify modifiers) (cdr modifier)))
847             ((null modifier))
848           (write-string ", " *sql-stream*)
849           (write-string (car modifier) *sql-stream*)))
850       (write-char #\) *sql-stream*)
851       (when (and (eq :mysql (database-underlying-type database))
852                  transactions
853                  (db-type-transaction-capable? :mysql database))
854         (write-string " Type=InnoDB" *sql-stream*))))
855   t)
856
857
858 ;; CREATE VIEW
859
860 (defclass sql-create-view (%sql-expression)
861   ((name :initarg :name :initform nil)
862    (column-list :initarg :column-list :initform nil)
863    (query :initarg :query :initform nil)
864    (with-check-option :initarg :with-check-option :initform nil))
865   (:documentation "An SQL CREATE VIEW statement."))
866
867 (defmethod output-sql ((stmt sql-create-view) database)
868   (with-slots (name column-list query with-check-option) stmt
869     (write-string "CREATE VIEW " *sql-stream*)
870     (output-sql name database)
871     (when column-list (write-string " " *sql-stream*)
872           (output-sql (listify column-list) database))
873     (write-string " AS " *sql-stream*)
874     (output-sql query database)
875     (when with-check-option (write-string " WITH CHECK OPTION" *sql-stream*))))
876
877
878 ;;
879 ;; DATABASE-OUTPUT-SQL
880 ;;
881
882 (defmethod database-output-sql ((str string) database)
883   (declare (optimize (speed 3) (safety 1)
884                      #+cmu (extensions:inhibit-warnings 3)))
885   (let ((len (length str)))
886     (declare (type fixnum len))
887     (cond ((zerop len)
888            +empty-string+)
889           ((and (null (position #\' str))
890                 (null (position #\\ str)))
891            (concatenate 'string "'" str "'"))
892           (t
893            (let ((buf (make-string (+ (* len 2) 2) :initial-element #\')))
894              (declare (simple-string buf))
895              (do* ((i 0 (incf i))
896                    (j 1 (incf j)))
897                   ((= i len) (subseq buf 0 (1+ j)))
898                (declare (type fixnum i j))
899                (let ((char (aref str i)))
900                  (declare (character char))
901                  (cond ((char= char #\')
902                         (setf (aref buf j) #\')
903                         (incf j)
904                         (setf (aref buf j) #\'))
905                        ((and (char= char #\\)
906                              ;; MTP: only escape backslash with pgsql/mysql
907                              (member (database-underlying-type database)
908                                      '(:postgresql :mysql)
909                                      :test #'eq))
910                         (setf (aref buf j) #\\)
911                         (incf j)
912                         (setf (aref buf j) #\\))
913                        (t
914                         (setf (aref buf j) char))))))))))
915
916 (let ((keyword-package (symbol-package :foo)))
917   (defmethod database-output-sql ((sym symbol) database)
918   (if (null sym)
919       +null-string+
920     (if (equal (symbol-package sym) keyword-package)
921         (concatenate 'string "'" (string sym) "'")
922       (symbol-name sym)))))
923
924 (defmethod database-output-sql ((tee (eql t)) database)
925   (if database
926       (let ((val (database-output-sql-as-type 'boolean t database (database-type database))))
927         (when val
928           (typecase val
929             (string (format nil "'~A'" val))
930             (integer (format nil "~A" val)))))
931     "'Y'"))
932
933 #+nil(defmethod database-output-sql ((tee (eql t)) database)
934   (declare (ignore database))
935   "'Y'")
936
937 (defmethod database-output-sql ((num number) database)
938   (declare (ignore database))
939   (number-to-sql-string num))
940
941 (defmethod database-output-sql ((arg list) database)
942   (if (null arg)
943       +null-string+
944       (format nil "(~{~A~^,~})" (mapcar #'(lambda (val)
945                                             (sql-output val database))
946                                         arg))))
947
948 (defmethod database-output-sql ((arg vector) database)
949   (format nil "~{~A~^,~}" (map 'list #'(lambda (val)
950                                          (sql-output val database))
951                                arg)))
952
953 (defmethod output-sql-hash-key ((arg vector) database)
954   (list 'vector (map 'list (lambda (arg)
955                              (or (output-sql-hash-key arg database)
956                                  (return-from output-sql-hash-key nil)))
957                      arg)))
958
959 (defmethod database-output-sql ((self wall-time) database)
960   (declare (ignore database))
961   (db-timestring self))
962
963 (defmethod database-output-sql ((self date) database)
964   (declare (ignore database))
965   (db-datestring self))
966
967 (defmethod database-output-sql ((self duration) database)
968   (declare (ignore database))
969   (format nil "'~a'" (duration-timestring self)))
970
971 #+ignore
972 (defmethod database-output-sql ((self money) database)
973   (database-output-sql (slot-value self 'odcl::units) database))
974
975 (defmethod database-output-sql (thing database)
976   (if (or (null thing)
977           (eq 'null thing))
978       +null-string+
979     (error 'sql-user-error
980            :message
981            (format nil
982                    "No type conversion to SQL for ~A is defined for DB ~A."
983                    (type-of thing) (type-of database)))))
984
985
986 ;;
987 ;; Column constraint types and conversion to SQL
988 ;;
989
990 (defparameter *constraint-types*
991   (list
992    (cons (symbol-name-default-case "NOT-NULL") "NOT NULL")
993    (cons (symbol-name-default-case "PRIMARY-KEY") "PRIMARY KEY")
994    (cons (symbol-name-default-case "NOT") "NOT")
995    (cons (symbol-name-default-case "NULL") "NULL")
996    (cons (symbol-name-default-case "PRIMARY") "PRIMARY")
997    (cons (symbol-name-default-case "KEY") "KEY")
998    (cons (symbol-name-default-case "UNSIGNED") "UNSIGNED")
999    (cons (symbol-name-default-case "ZEROFILL") "ZEROFILL")
1000    (cons (symbol-name-default-case "AUTO-INCREMENT") "AUTO_INCREMENT")
1001    (cons (symbol-name-default-case "UNIQUE") "UNIQUE")
1002    (cons (symbol-name-default-case "IDENTITY") "IDENTITY (1,1)") ;Added Identity for MS-SQLServer support
1003    ))
1004
1005 (defmethod database-constraint-statement (constraint-list database)
1006   (declare (ignore database))
1007   (make-constraints-description constraint-list))
1008
1009 (defun make-constraints-description (constraint-list)
1010   (if constraint-list
1011       (let ((string ""))
1012         (do ((constraint constraint-list (cdr constraint)))
1013             ((null constraint) string)
1014           (let ((output (assoc (symbol-name (car constraint))
1015                                *constraint-types*
1016                                :test #'equal)))
1017             (if (null output)
1018                 (error 'sql-user-error
1019                        :message (format nil "unsupported column constraint '~A'"
1020                                         constraint))
1021                 (setq string (concatenate 'string string (cdr output))))
1022             (if (< 1 (length constraint))
1023                 (setq string (concatenate 'string string " "))))))))
1024