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