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