29363afbdbdda080c79ecacad004f26cb1a87d33
[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 (defclass %database-identifier ()
24   ((escaped :accessor escaped :initarg :escaped :initform nil)
25    (unescaped :accessor unescaped :initarg :unescaped :initform nil))
26   (:documentation
27    "A database identifier represents a string/symbol ready to be spliced
28     into a sql string.  It keeps references to both the escaped and
29     unescaped versions so that unescaped versions can be compared to the
30     results of list-tables/views/attributes etc.  It also allows you to be
31     sure that an identifier is escaped only once.
32
33     (escaped-database-identifiers *any-reasonable-object*) should be called to
34       produce a string that is safe to splice directly into sql strings.
35
36     (unescaped-database-identifier *any-reasonable-object*) is generally what
37       you pass to it with the exception that symbols have been
38       clsql-sys:sql-escape which converts to a string and changes - to _ (so
39       that unescaped can be compared to the results of eg: list-tables)
40    "))
41
42 (defmethod escaped ((it null)) it)
43 (defmethod unescaped ((it null)) it)
44
45 (defun database-identifier-equal (i1 i2 &optional (database clsql-sys:*default-database*))
46   (setf i1 (database-identifier i1 database)
47         i2 (database-identifier i2 database))
48   (flet ((cast (i)
49              (if (symbolp (unescaped i))
50                  (sql-escape (unescaped i))
51                  (unescaped i))))
52     (or ;; check for an exact match
53      (equal (escaped-database-identifier i1)
54             (escaped-database-identifier i2))
55      ;; check for an inexact match if we had symbols in the mix
56      (string-equal (cast i1) (cast i2)))))
57
58 (defun delistify-dsd (list)
59   "Some MOPs, like openmcl 0.14.2, cons attribute values in a list."
60   (if (and (listp list) (null (cdr list)))
61       (car list)
62       list))
63
64 (defun special-char-p (s)
65   "Check if a string has any special characters"
66   (loop for char across s
67        thereis (find char '(#\space #\, #\. #\! #\@ #\# #\$ #\% #\' #\"
68                             #\^ #\& #\* #\| #\( #\) #\- #\+ #\< #\>
69                             #\{ #\}))))
70
71 (defun special-cased-symbol-p (sym)
72   "Should the symbols case be preserved, or should we convert to default casing"
73   (let ((name (symbol-name sym)))
74     (case (readtable-case *readtable*)
75       (:upcase (not (string= (string-upcase name) name)))
76       (:downcase (not (string= (string-downcase name) name)))
77       (t t))))
78
79 (defun %make-database-identifier (inp &optional database)
80   "We want to quote an identifier if it came to us as a string or if it has special characters
81    in it."
82   (labels ((%escape-identifier (inp &optional orig)
83              "Quote an identifier unless it is already quoted"
84              (cond
85                ;; already quoted
86                ((and (eql #\" (elt inp 0))
87                      (eql #\" (elt inp (- (length inp) 1))))
88                 (make-instance '%database-identifier :unescaped (or orig inp) :escaped inp))
89                (T (make-instance
90                    '%database-identifier :unescaped (or orig inp) :escaped
91                    (concatenate
92                     'string "\"" (replace-all inp "\"" "\\\"") "\""))))))
93     (typecase inp
94       (string (%escape-identifier inp))
95       (%database-identifier inp)
96       (symbol
97        (let ((s (sql-escape inp)))
98          (if (and (not (eql '* inp)) (special-char-p s))
99              (%escape-identifier
100               (if (special-cased-symbol-p inp)
101                   s
102                   (convert-to-db-default-case s database)) inp)
103              (make-instance '%database-identifier :escaped s :unescaped inp))
104          )))))
105
106 (defun combine-database-identifiers (ids &optional (database clsql-sys:*default-database*)
107                                      &aux res all-sym? pkg)
108   "Create a new database identifier by combining parts in a reasonable way
109   "
110   (setf ids (mapcar #'database-identifier ids)
111         all-sym? (every (lambda (i) (symbolp (unescaped i))) ids)
112         pkg (when all-sym? (symbol-package (unescaped (first ids)))))
113   (labels ((cast ( i )
114                (typecase i
115                  (null nil)
116                  (%database-identifier (cast (unescaped i)))
117                  (symbol
118                   (if all-sym?
119                       (sql-escape i)
120                       (convert-to-db-default-case (sql-escape i) database)))
121                  (string i)))
122            (comb (i1 i2)
123              (setf i1 (cast i1)
124                    i2 (cast i2))
125              (if (and i1 i2)
126                  (concatenate 'string (cast i1) "_" (cast i2))
127                  (or i1 i2))))
128     (setf res (reduce #'comb ids))
129     (database-identifier
130      (if all-sym? (intern res pkg) res)
131      database)))
132
133 (defun escaped-database-identifier (name &optional database find-class-p)
134   (escaped (database-identifier name database find-class-p)))
135
136 (defun unescaped-database-identifier (name &optional database find-class-p)
137   (unescaped (database-identifier name database find-class-p)))
138
139 (defun sql-output (sql-expr &optional (database *default-database*))
140   "Top-level call for generating SQL strings. Returns an SQL
141   string appropriate for DATABASE which corresponds to the
142   supplied lisp expression SQL-EXPR."
143   (with-output-to-string (*sql-stream*)
144     (output-sql sql-expr database)))
145
146 (defmethod output-sql (expr database)
147   (write-string (database-output-sql expr database) *sql-stream*)
148   (values))
149
150
151 (defvar *output-hash*
152       (make-weak-hash-table :test #'equal)
153   "For caching generated SQL strings, set to NIL to disable."
154   )
155
156 (defmethod output-sql :around ((sql t) database)
157   (if (null *output-hash*)
158       (call-next-method)
159       (let* ((hash-key (output-sql-hash-key sql database))
160              (hash-value (when hash-key (gethash hash-key *output-hash*))))
161         (cond ((and hash-key hash-value)
162                (write-string hash-value *sql-stream*))
163               (hash-key
164                (let ((*sql-stream* (make-string-output-stream)))
165                  (call-next-method)
166                  (setf hash-value (get-output-stream-string *sql-stream*))
167                  (setf (gethash hash-key *output-hash*) hash-value))
168                (write-string hash-value *sql-stream*))
169               (t
170                (call-next-method))))))
171
172 (defmethod output-sql-hash-key (expr database)
173   (declare (ignore expr database))
174   nil)
175
176
177 (defclass %sql-expression ()
178   ())
179
180 (defmethod output-sql ((expr %sql-expression) database)
181   (declare (ignore database))
182   (write-string +null-string+ *sql-stream*))
183
184 (defmethod print-object ((self %sql-expression) stream)
185   (print-unreadable-object
186    (self stream :type t)
187    (write-string (sql-output self) stream))
188   self)
189
190 ;; For straight up strings
191
192 (defclass sql (%sql-expression)
193   ((text
194     :initarg :string
195     :initform ""))
196   (:documentation "A literal SQL expression."))
197
198 (defmethod make-load-form ((sql sql) &optional environment)
199   (declare (ignore environment))
200   (with-slots (text)
201     sql
202     `(make-instance 'sql :string ',text)))
203
204 (defmethod output-sql ((expr sql) database)
205   (declare (ignore database))
206   (write-string (slot-value expr 'text) *sql-stream*)
207   t)
208
209 (defmethod print-object ((ident sql) stream)
210   (format stream "#<~S \"~A\">"
211           (type-of ident)
212           (sql-output ident nil))
213   ident)
214
215 ;; For SQL Identifiers of generic type
216
217 (defclass sql-ident (%sql-expression)
218   ((name
219     :initarg :name
220     :initform +null-string+))
221   (:documentation "An SQL identifer."))
222
223 (defmethod make-load-form ((sql sql-ident) &optional environment)
224   (declare (ignore environment))
225   (with-slots (name)
226     sql
227     `(make-instance 'sql-ident :name ',name)))
228
229 (defmethod output-sql ((expr %database-identifier) database)
230   (write-string (escaped expr) *sql-stream*))
231
232 (defmethod output-sql ((expr sql-ident) database)
233   (with-slots (name) expr
234     (write-string (escaped-database-identifier name database) *sql-stream*))
235   t)
236
237 ;; For SQL Identifiers for attributes
238
239 (defclass sql-ident-attribute (sql-ident)
240   ((qualifier
241     :initarg :qualifier
242     :initform +null-string+)
243    (type
244     :initarg :type
245     :initform +null-string+))
246   (:documentation "An SQL Attribute identifier."))
247
248 (defmethod collect-table-refs (sql)
249   (declare (ignore sql))
250   nil)
251
252 (defmethod collect-table-refs ((sql sql-ident-attribute))
253   (let ((qual (slot-value sql 'qualifier)))
254     (when qual
255       ;; going to be used as a table, search classes
256       (list (make-instance
257              'sql-ident-table
258              :name (database-identifier qual nil t))))))
259
260 (defmethod make-load-form ((sql sql-ident-attribute) &optional environment)
261   (declare (ignore environment))
262   (with-slots (qualifier type name)
263     sql
264     `(make-instance 'sql-ident-attribute :name ',name
265       :qualifier ',qualifier
266       :type ',type)))
267
268 (defmethod output-sql-hash-key ((expr sql-ident-attribute) database)
269   (with-slots (qualifier name type)
270       expr
271     (list (and database (database-underlying-type database))
272           'sql-ident-attribute
273           (unescaped-database-identifier qualifier)
274           (unescaped-database-identifier name) type)))
275
276 ;; For SQL Identifiers for tables
277
278 (defclass sql-ident-table (sql-ident)
279   ((alias
280     :initarg :table-alias :initform nil))
281   (:documentation "An SQL table identifier."))
282
283 (defmethod make-load-form ((sql sql-ident-table) &optional environment)
284   (declare (ignore environment))
285   (with-slots (alias name)
286     sql
287     `(make-instance 'sql-ident-table :name ',name :table-alias ',alias)))
288
289 (defmethod output-sql ((expr sql-ident-table) database)
290   (with-slots (name alias) expr
291     (flet ((p (s) ;; the etypecase is in sql-escape too
292              (write-string
293               (escaped-database-identifier s database)
294               *sql-stream*)))
295       (p name)
296       (when alias
297         (princ #\space *sql-stream*)
298         (p alias))))
299   t)
300
301 (defmethod output-sql ((expr sql-ident-attribute) database)
302 ;;; KMR: The TYPE field is used by CommonSQL for type conversion -- it
303 ;;; should not be output in SQL statements
304   (let ((*print-pretty* nil))
305     (with-slots (qualifier name type) expr
306       (format *sql-stream* "~@[~a.~]~a"
307               (when qualifier
308                 ;; check for classes
309                 (escaped-database-identifier qualifier database T))
310               (escaped-database-identifier name database))
311       t)))
312
313 (defmethod output-sql-hash-key ((expr sql-ident-table) database)
314   (with-slots (name alias)
315       expr
316     (list (and database (database-underlying-type database))
317           'sql-ident-table
318           (unescaped-database-identifier name)
319           (unescaped-database-identifier alias))))
320
321 (defclass sql-relational-exp (%sql-expression)
322   ((operator
323     :initarg :operator
324     :initform nil)
325    (sub-expressions
326     :initarg :sub-expressions
327     :initform nil))
328   (:documentation "An SQL relational expression."))
329
330 (defmethod make-load-form ((self sql-relational-exp) &optional environment)
331   (make-load-form-saving-slots self
332                                :slot-names '(operator sub-expressions)
333                                :environment environment))
334
335 (defmethod collect-table-refs ((sql sql-relational-exp))
336   (let ((tabs nil))
337     (dolist (exp (slot-value sql 'sub-expressions))
338       (let ((refs (collect-table-refs exp)))
339         (if refs (setf tabs (append refs tabs)))))
340     (remove-duplicates tabs :test #'database-identifier-equal)))
341
342
343
344
345 ;; Write SQL for relational operators (like 'AND' and 'OR').
346 ;; should do arity checking of subexpressions
347
348 (defun %write-operator (operator database)
349   (typecase operator
350     (string (write-string operator *sql-stream*))
351     (symbol (write-string (symbol-name operator) *sql-stream*))
352     (T (output-sql operator database))))
353
354 (defmethod output-sql ((expr sql-relational-exp) database)
355   (with-slots (operator sub-expressions) expr
356      ;; we do this as two runs so as not to emit confusing superflous parentheses
357      ;; The first loop renders all the child outputs so that we can skip anding with
358      ;; empty output (which causes sql errors)
359      ;; the next loop simply emits each sub-expression with the appropriate number of
360      ;; parens and operators
361      (flet ((trim (sub)
362               (string-trim +whitespace-chars+
363                            (with-output-to-string (*sql-stream*)
364                              (output-sql sub database)))))
365        (let ((str-subs (loop for sub in sub-expressions
366                              for str-sub = (trim sub)
367                            when (and str-sub (> (length str-sub) 0))
368                              collect str-sub)))
369          (case (length str-subs)
370            (0 nil)
371            (1 (write-string (first str-subs) *sql-stream*))
372            (t
373               (write-char #\( *sql-stream*)
374               (write-string (first str-subs) *sql-stream*)
375               (loop for str-sub in (rest str-subs)
376                     do
377                  (write-char #\Space *sql-stream*)
378                  ;; do this so that symbols can be output as database identifiers
379                  ;; rather than allowing symbols to inject sql
380                  (%write-operator operator database)
381                  (write-char #\Space *sql-stream*)
382                  (write-string str-sub *sql-stream*))
383               (write-char #\) *sql-stream*))
384            ))))
385   t)
386
387 (defclass sql-upcase-like (sql-relational-exp)
388   ()
389   (:documentation "An SQL 'like' that upcases its arguments."))
390
391 (defmethod output-sql ((expr sql-upcase-like) database)
392   (flet ((write-term (term)
393            (write-string "upper(" *sql-stream*)
394            (output-sql term database)
395            (write-char #\) *sql-stream*)))
396     (with-slots (sub-expressions)
397       expr
398       (let ((subs (if (consp (car sub-expressions))
399                       (car sub-expressions)
400                       sub-expressions)))
401         (write-char #\( *sql-stream*)
402         (do ((sub subs (cdr sub)))
403             ((null (cdr sub)) (write-term (car sub)))
404           (write-term (car sub))
405           (write-string " LIKE " *sql-stream*))
406         (write-char #\) *sql-stream*))))
407   t)
408
409 (defclass sql-assignment-exp (sql-relational-exp)
410   ()
411   (:documentation "An SQL Assignment expression."))
412
413
414 (defmethod output-sql ((expr sql-assignment-exp) database)
415   (with-slots (operator sub-expressions)
416     expr
417     (do ((sub sub-expressions (cdr sub)))
418         ((null (cdr sub)) (output-sql (car sub) database))
419       (output-sql (car sub) database)
420       (write-char #\Space *sql-stream*)
421       (%write-operator operator database)
422       (write-char #\Space *sql-stream*)))
423   t)
424
425 (defclass sql-value-exp (%sql-expression)
426   ((modifier
427     :initarg :modifier
428     :initform nil)
429    (components
430     :initarg :components
431     :initform nil))
432   (:documentation
433    "An SQL value expression.")
434   )
435
436 (defmethod collect-table-refs ((sql sql-value-exp))
437   (let ((tabs nil))
438     (if (listp (slot-value sql 'components))
439         (progn
440           (dolist (exp (slot-value sql 'components))
441             (let ((refs (collect-table-refs exp)))
442               (if refs (setf tabs (append refs tabs)))))
443           (remove-duplicates tabs :test #'database-identifier-equal))
444         nil)))
445
446
447
448 (defmethod output-sql ((expr sql-value-exp) database)
449   (with-slots (modifier components)
450     expr
451     (if modifier
452         (progn
453           (write-char #\( *sql-stream*)
454           (cond
455             ((sql-operator modifier)
456              (%write-operator modifier database))
457             ((or (stringp modifier) (symbolp modifier))
458              (write-string
459               (escaped-database-identifier modifier)
460               *sql-stream*))
461             (t (output-sql modifier database)))
462           (write-char #\Space *sql-stream*)
463           (output-sql components database)
464           (write-char #\) *sql-stream*))
465         (output-sql components database))))
466
467 (defclass sql-typecast-exp (sql-value-exp)
468   ()
469   (:documentation "An SQL typecast expression."))
470
471 (defmethod output-sql ((expr sql-typecast-exp) database)
472   (with-slots (components)
473     expr
474     (output-sql components database)))
475
476 (defmethod collect-table-refs ((sql sql-typecast-exp))
477   (when (slot-value sql 'components)
478     (collect-table-refs (slot-value sql 'components))))
479
480 (defclass sql-function-exp (%sql-expression)
481   ((name
482     :initarg :name
483     :initform nil)
484    (args
485     :initarg :args
486     :initform nil))
487   (:documentation
488    "An SQL function expression."))
489
490 (defmethod collect-table-refs ((sql sql-function-exp))
491   (let ((tabs nil))
492     (dolist (exp (slot-value sql 'args))
493       (let ((refs (collect-table-refs exp)))
494         (if refs (setf tabs (append refs tabs)))))
495     (remove-duplicates tabs :test #'database-identifier-equal)))
496 (defvar *in-subselect* nil)
497
498 (defmethod output-sql ((expr sql-function-exp) database)
499   (with-slots (name args)
500     expr
501     (typecase name
502       ((or string symbol)
503        (write-string (escaped-database-identifier name) *sql-stream*))
504       (t (output-sql name database)))
505     (let ((*in-subselect* nil)) ;; aboid double parens
506       (when args (output-sql args database))))
507   t)
508
509
510 (defclass sql-between-exp (sql-function-exp)
511   ()
512   (:documentation "An SQL between expression."))
513
514 (defmethod output-sql ((expr sql-between-exp) database)
515   (with-slots (args)
516       expr
517     (output-sql (first args) database)
518     (write-string " BETWEEN " *sql-stream*)
519     (output-sql (second args) database)
520     (write-string " AND " *sql-stream*)
521     (output-sql (third args) database))
522   t)
523
524 (defclass sql-query-modifier-exp (%sql-expression)
525   ((modifier :initarg :modifier :initform nil)
526    (components :initarg :components :initform nil))
527   (:documentation "An SQL query modifier expression."))
528
529 (defmethod output-sql ((expr sql-query-modifier-exp) database)
530   (with-slots (modifier components)
531       expr
532     (%write-operator modifier database)
533     (write-string " " *sql-stream*)
534     (%write-operator (car components) database)
535     (when components
536       (mapc #'(lambda (comp)
537                 (write-string ", " *sql-stream*)
538                 (output-sql comp database))
539             (cdr components))))
540   t)
541
542 (defclass sql-set-exp (%sql-expression)
543   ((operator
544     :initarg :operator
545     :initform nil)
546    (sub-expressions
547     :initarg :sub-expressions
548     :initform nil))
549   (:documentation "An SQL set expression."))
550
551 (defmethod collect-table-refs ((sql sql-set-exp))
552   (let ((tabs nil))
553     (dolist (exp (slot-value sql 'sub-expressions))
554       (let ((refs (collect-table-refs exp)))
555         (if refs (setf tabs (append refs tabs)))))
556     (remove-duplicates tabs :test #'database-identifier-equal)))
557
558 (defmethod output-sql ((expr sql-set-exp) database)
559   (with-slots (operator sub-expressions)
560       expr
561     (let ((subs (if (consp (car sub-expressions))
562                     (car sub-expressions)
563                     sub-expressions)))
564       (when (= (length subs) 1)
565         (%write-operator operator database)
566         (write-char #\Space *sql-stream*))
567       (do ((sub subs (cdr sub)))
568           ((null (cdr sub)) (output-sql (car sub) database))
569         (output-sql (car sub) database)
570         (write-char #\Space *sql-stream*)
571         (%write-operator operator database)
572         (write-char #\Space *sql-stream*))))
573   t)
574
575 (defclass sql-query (%sql-expression)
576   ((selections
577     :initarg :selections
578     :initform nil)
579    (all
580     :initarg :all
581     :initform nil)
582    (flatp
583     :initarg :flatp
584     :initform nil)
585    (set-operation
586     :initarg :set-operation
587     :initform nil)
588    (distinct
589     :initarg :distinct
590     :initform nil)
591    (from
592     :initarg :from
593     :initform nil)
594    (where
595     :initarg :where
596     :initform nil)
597    (group-by
598     :initarg :group-by
599     :initform nil)
600    (having
601     :initarg :having
602     :initform nil)
603    (limit
604     :initarg :limit
605     :initform nil)
606    (offset
607     :initarg :offset
608     :initform nil)
609    (order-by
610     :initarg :order-by
611     :initform nil)
612    (inner-join
613     :initarg :inner-join
614     :initform nil)
615    (on
616     :initarg :on
617     :initform nil))
618   (:documentation "An SQL SELECT query."))
619
620 (defclass sql-object-query (%sql-expression)
621   ((objects
622     :initarg :objects
623     :initform nil)
624    (flatp
625     :initarg :flatp
626     :initform nil)
627    (exp
628     :initarg :exp
629     :initform nil)
630    (refresh
631     :initarg :refresh
632     :initform nil)))
633
634 (defmethod collect-table-refs ((sql sql-query))
635   (remove-duplicates
636    (collect-table-refs (slot-value sql 'where))
637    :test #'database-identifier-equal))
638
639 (defvar *select-arguments*
640   '(:all :database :distinct :flatp :from :group-by :having :order-by
641     :set-operation :where :offset :limit :inner-join :on
642     ;; below keywords are not a SQL argument, but these keywords may terminate select
643     :caching :refresh))
644
645 (defun query-arg-p (sym)
646   (member sym *select-arguments*))
647
648 (defun query-get-selections (select-args)
649   "Return two values: the list of select-args up to the first keyword,
650 uninclusive, and the args from that keyword to the end."
651   (let ((first-key-arg (position-if #'query-arg-p select-args)))
652     (if first-key-arg
653         (values (subseq select-args 0 first-key-arg)
654                 (subseq select-args first-key-arg))
655         select-args)))
656
657 (defun make-query (&rest args)
658   (flet ((select-objects (target-args)
659            (and target-args
660                 (every #'(lambda (arg)
661                            (and (symbolp arg)
662                                 (find-class arg nil)))
663                        target-args))))
664     (multiple-value-bind (selections arglist)
665         (query-get-selections args)
666       (if (select-objects selections)
667           (destructuring-bind (&key flatp refresh &allow-other-keys) arglist
668             (make-instance 'sql-object-query :objects selections
669                            :flatp flatp :refresh refresh
670                            :exp arglist))
671           (destructuring-bind (&key all flatp set-operation distinct from where
672                                     group-by having order-by
673                                     offset limit inner-join on &allow-other-keys)
674               arglist
675             (if (null selections)
676                 (error "No target columns supplied to select statement."))
677             (if (null from)
678                 (error "No source tables supplied to select statement."))
679             (make-instance 'sql-query :selections selections
680                            :all all :flatp flatp :set-operation set-operation
681                            :distinct distinct :from from :where where
682                            :limit limit :offset offset
683                            :group-by group-by :having having :order-by order-by
684                            :inner-join inner-join :on on))))))
685
686 (defun output-sql-where-clause (where database)
687   "ensure that we do not output a \"where\" sql keyword when we will
688     not output a clause. Also sets *in-subselect* to use SQL
689     parentheticals as needed."
690   (when where
691     (let ((where-out (string-trim
692                       '(#\newline #\space #\tab #\return)
693                       (with-output-to-string (*sql-stream*)
694                         (let ((*in-subselect* t))
695                           (output-sql where database))))))
696       (when (> (length where-out) 0)
697         (write-string " WHERE " *sql-stream*)
698         (write-string where-out *sql-stream*)))))
699
700 (defmethod output-sql ((query sql-query) database)
701   (with-slots (distinct selections from where group-by having order-by
702                         limit offset inner-join on all set-operation)
703       query
704     (when *in-subselect*
705       (write-string "(" *sql-stream*))
706     (write-string "SELECT " *sql-stream*)
707     (when all
708       (write-string " ALL " *sql-stream*))
709     (when (and distinct (not all))
710       (write-string " DISTINCT " *sql-stream*)
711       (unless (eql t distinct)
712         (write-string " ON " *sql-stream*)
713         (output-sql distinct database)
714         (write-char #\Space *sql-stream*)))
715     (when (and limit (eql :mssql (database-underlying-type database)))
716       (write-string " TOP " *sql-stream*)
717       (output-sql limit database)
718       (write-string " " *sql-stream*))
719     (let ((*in-subselect* t))
720       (output-sql (apply #'vector selections) database))
721     (when from
722       (write-string " FROM " *sql-stream*)
723       (typecase from
724         (list (output-sql
725                (apply #'vector
726                       (remove-duplicates from :test #'database-identifier-equal))
727                database))
728         (string (write-string
729                  (escaped-database-identifier from database)
730                  *sql-stream*))
731         (t (let ((*in-subselect* t))
732              (output-sql from database)))))
733     (when inner-join
734       (write-string " INNER JOIN " *sql-stream*)
735       (output-sql inner-join database))
736     (when on
737       (write-string " ON " *sql-stream*)
738       (output-sql on database))
739     (output-sql-where-clause where database)
740     (when group-by
741       (write-string " GROUP BY " *sql-stream*)
742       (if (listp group-by)
743           (do ((order group-by (cdr order)))
744               ((null order))
745             (let ((item (car order)))
746               (typecase item
747                 (cons
748                  (output-sql (car item) database)
749                  (format *sql-stream* " ~A" (cadr item)))
750                 (t
751                  (output-sql item database)))
752               (when (cdr order)
753                 (write-char #\, *sql-stream*))))
754           (output-sql group-by database)))
755     (when having
756       (write-string " HAVING " *sql-stream*)
757       (output-sql having database))
758     (when order-by
759       (write-string " ORDER BY " *sql-stream*)
760       (if (listp order-by)
761           (do ((order order-by (cdr order)))
762               ((null order))
763             (let ((item (car order)))
764               (typecase item
765                 (cons
766                  (output-sql (car item) database)
767                  (format *sql-stream* " ~A" (cadr item)))
768                 (t
769                  (output-sql item database)))
770               (when (cdr order)
771                 (write-char #\, *sql-stream*))))
772           (output-sql order-by database)))
773     (when (and limit (not (eql :mssql (database-underlying-type database))))
774       (write-string " LIMIT " *sql-stream*)
775       (output-sql limit database))
776     (when offset
777       (write-string " OFFSET " *sql-stream*)
778       (output-sql offset database))
779     (when *in-subselect*
780       (write-string ")" *sql-stream*))
781     (when set-operation
782       (write-char #\Space *sql-stream*)
783       (output-sql set-operation database)))
784   t)
785
786 (defmethod output-sql ((query sql-object-query) database)
787   (declare (ignore database))
788   (with-slots (objects)
789       query
790     (when objects
791       (format *sql-stream* "(~{~A~^ ~})" objects))))
792
793
794 ;; INSERT
795
796 (defclass sql-insert (%sql-expression)
797   ((into
798     :initarg :into
799     :initform nil)
800    (attributes
801     :initarg :attributes
802     :initform nil)
803    (values
804     :initarg :values
805     :initform nil)
806    (query
807     :initarg :query
808     :initform nil))
809   (:documentation
810    "An SQL INSERT statement."))
811
812 (defmethod output-sql ((ins sql-insert) database)
813   (with-slots (into attributes values query)
814     ins
815     (write-string "INSERT INTO " *sql-stream*)
816     (output-sql
817      (typecase into
818        (string (sql-expression :table into))
819        (t into))
820      database)
821     (when attributes
822       (write-char #\Space *sql-stream*)
823       (output-sql attributes database))
824     (when values
825       (write-string " VALUES " *sql-stream*)
826       (let ((clsql-sys::*in-subselect* t))
827         (output-sql values database)))
828     (when query
829       (write-char #\Space *sql-stream*)
830       (output-sql query database)))
831   t)
832
833 ;; DELETE
834
835 (defclass sql-delete (%sql-expression)
836   ((from
837     :initarg :from
838     :initform nil)
839    (where
840     :initarg :where
841     :initform nil))
842   (:documentation
843    "An SQL DELETE statement."))
844
845 (defmethod output-sql ((stmt sql-delete) database)
846   (with-slots (from where)
847     stmt
848     (write-string "DELETE FROM " *sql-stream*)
849     (typecase from
850       ((or symbol string) (write-string (sql-escape from) *sql-stream*))
851       (t  (output-sql from database)))
852     (output-sql-where-clause where database))
853   t)
854
855 ;; UPDATE
856
857 (defclass sql-update (%sql-expression)
858   ((table
859     :initarg :table
860     :initform nil)
861    (attributes
862     :initarg :attributes
863     :initform nil)
864    (values
865     :initarg :values
866     :initform nil)
867    (where
868     :initarg :where
869     :initform nil))
870   (:documentation "An SQL UPDATE statement."))
871
872 (defmethod output-sql ((expr sql-update) database)
873   (with-slots (table where attributes values)
874     expr
875     (flet ((update-assignments ()
876              (mapcar #'(lambda (a b)
877                          (make-instance 'sql-assignment-exp
878                                         :operator '=
879                                         :sub-expressions (list a b)))
880                      attributes values)))
881       (write-string "UPDATE " *sql-stream*)
882       (output-sql table database)
883       (write-string " SET " *sql-stream*)
884       (let ((clsql-sys::*in-subselect* t))
885         (output-sql (apply #'vector (update-assignments)) database))
886       (output-sql-where-clause where database)))
887   t)
888
889 ;; CREATE TABLE
890
891 (defclass sql-create-table (%sql-expression)
892   ((name
893     :initarg :name
894     :initform nil)
895    (columns
896     :initarg :columns
897     :initform nil)
898    (modifiers
899     :initarg :modifiers
900     :initform nil)
901    (transactions
902     :initarg :transactions
903     :initform nil))
904   (:documentation
905    "An SQL CREATE TABLE statement."))
906
907 ;; Here's a real warhorse of a function!
908
909 (declaim (inline listify))
910 (defun listify (x)
911   (if (listp x)
912       x
913       (list x)))
914
915 (defmethod output-sql ((stmt sql-create-table) database)
916   (flet ((output-column (column-spec)
917            (destructuring-bind (name type &optional db-type &rest constraints)
918                column-spec
919              (let ((type (listify type)))
920                (output-sql name database)
921                (write-char #\Space *sql-stream*)
922                (write-string
923                 (if (stringp db-type) db-type ; override definition
924                   (database-get-type-specifier (car type) (cdr type) database
925                                                (database-underlying-type database)))
926                 *sql-stream*)
927                (let ((constraints (database-constraint-statement
928                                    (if (and db-type (symbolp db-type))
929                                        (cons db-type constraints)
930                                        constraints)
931                                    database)))
932                  (when constraints
933                    (write-string " " *sql-stream*)
934                    (write-string constraints *sql-stream*)))))))
935     (with-slots (name columns modifiers transactions)
936       stmt
937       (write-string "CREATE TABLE " *sql-stream*)
938       (write-string (escaped-database-identifier name database) *sql-stream*)
939       (write-string " (" *sql-stream*)
940       (do ((column columns (cdr column)))
941           ((null (cdr column))
942            (output-column (car column)))
943         (output-column (car column))
944         (write-string ", " *sql-stream*))
945       (when modifiers
946         (do ((modifier (listify modifiers) (cdr modifier)))
947             ((null modifier))
948           (write-string ", " *sql-stream*)
949           (write-string (car modifier) *sql-stream*)))
950       (write-char #\) *sql-stream*)
951       (when (and (eq :mysql (database-underlying-type database))
952                  transactions
953                  (db-type-transaction-capable? :mysql database))
954         (write-string " ENGINE=innodb" *sql-stream*))))
955   t)
956
957
958 ;; CREATE VIEW
959
960 (defclass sql-create-view (%sql-expression)
961   ((name :initarg :name :initform nil)
962    (column-list :initarg :column-list :initform nil)
963    (query :initarg :query :initform nil)
964    (with-check-option :initarg :with-check-option :initform nil))
965   (:documentation "An SQL CREATE VIEW statement."))
966
967 (defmethod output-sql ((stmt sql-create-view) database)
968   (with-slots (name column-list query with-check-option) stmt
969     (write-string "CREATE VIEW " *sql-stream*)
970     (output-sql name database)
971     (when column-list (write-string " " *sql-stream*)
972           (output-sql (listify column-list) database))
973     (write-string " AS " *sql-stream*)
974     (output-sql query database)
975     (when with-check-option (write-string " WITH CHECK OPTION" *sql-stream*))))
976
977
978 ;;
979 ;; DATABASE-OUTPUT-SQL
980 ;;
981
982 (defmethod database-output-sql ((str string) database)
983   (declare (optimize (speed 3) (safety 1)
984                      #+cmu (extensions:inhibit-warnings 3)))
985   (let ((len (length str)))
986     (declare (type fixnum len))
987     (cond ((zerop len)
988            +empty-string+)
989           ((and (null (position #\' str))
990                 (null (position #\\ str)))
991            (concatenate 'string "'" str "'"))
992           (t
993            (let ((buf (make-string (+ (* len 2) 2) :initial-element #\')))
994              (declare (simple-string buf))
995              (do* ((i 0 (incf i))
996                    (j 1 (incf j)))
997                   ((= i len) (subseq buf 0 (1+ j)))
998                (declare (type fixnum i j))
999                (let ((char (aref str i)))
1000                  (declare (character char))
1001                  (cond ((char= char #\')
1002                         (setf (aref buf j) #\')
1003                         (incf j)
1004                         (setf (aref buf j) #\'))
1005                        ((and (char= char #\\)
1006                              ;; MTP: only escape backslash with pgsql/mysql
1007                              (member (database-underlying-type database)
1008                                      '(:postgresql :mysql)
1009                                      :test #'eq))
1010                         (setf (aref buf j) #\\)
1011                         (incf j)
1012                         (setf (aref buf j) #\\))
1013                        (t
1014                         (setf (aref buf j) char))))))))))
1015
1016 (let ((keyword-package (symbol-package :foo)))
1017   (defmethod database-output-sql ((sym symbol) database)
1018   (if (null sym)
1019       +null-string+
1020       (if (equal (symbol-package sym) keyword-package)
1021           (database-output-sql (symbol-name sym) database)
1022           (escaped-database-identifier sym)))))
1023
1024 (defmethod database-output-sql ((tee (eql t)) database)
1025   (if database
1026       (let ((val (database-output-sql-as-type 'boolean t database (database-type database))))
1027         (when val
1028           (typecase val
1029             (string (format nil "'~A'" val))
1030             (integer (format nil "~A" val)))))
1031     "'Y'"))
1032
1033 #+nil(defmethod database-output-sql ((tee (eql t)) database)
1034   (declare (ignore database))
1035   "'Y'")
1036
1037 (defmethod database-output-sql ((num number) database)
1038   (declare (ignore database))
1039   (number-to-sql-string num))
1040
1041 (defmethod database-output-sql ((arg list) database)
1042   (if (null arg)
1043       +null-string+
1044       (format nil "(~{~A~^,~})" (mapcar #'(lambda (val)
1045                                             (sql-output val database))
1046                                         arg))))
1047
1048 (defmethod database-output-sql ((arg vector) database)
1049   (format nil "~{~A~^,~}" (map 'list #'(lambda (val)
1050                                          (sql-output val database))
1051                                arg)))
1052
1053 (defmethod output-sql-hash-key ((arg vector) database)
1054   (list 'vector (map 'list (lambda (arg)
1055                              (or (output-sql-hash-key arg database)
1056                                  (return-from output-sql-hash-key nil)))
1057                      arg)))
1058
1059 (defmethod database-output-sql ((self wall-time) database)
1060   (declare (ignore database))
1061   (db-timestring self))
1062
1063 (defmethod database-output-sql ((self date) database)
1064   (declare (ignore database))
1065   (db-datestring self))
1066
1067 (defmethod database-output-sql ((self duration) database)
1068   (declare (ignore database))
1069   (format nil "'~a'" (duration-timestring self)))
1070
1071 #+ignore
1072 (defmethod database-output-sql ((self money) database)
1073   (database-output-sql (slot-value self 'odcl::units) database))
1074
1075 (defmethod database-output-sql (thing database)
1076   (if (or (null thing)
1077           (eq 'null thing))
1078       +null-string+
1079     (error 'sql-user-error
1080            :message
1081            (format nil
1082                    "No type conversion to SQL for ~A is defined for DB ~A."
1083                    (type-of thing) (type-of database)))))
1084
1085
1086 ;;
1087 ;; Column constraint types and conversion to SQL
1088 ;;
1089
1090 (defparameter *constraint-types*
1091   (list
1092    (cons (symbol-name-default-case "NOT-NULL") "NOT NULL")
1093    (cons (symbol-name-default-case "PRIMARY-KEY") "PRIMARY KEY")
1094    (cons (symbol-name-default-case "NOT") "NOT")
1095    (cons (symbol-name-default-case "NULL") "NULL")
1096    (cons (symbol-name-default-case "PRIMARY") "PRIMARY")
1097    (cons (symbol-name-default-case "KEY") "KEY")
1098    (cons (symbol-name-default-case "UNSIGNED") "UNSIGNED")
1099    (cons (symbol-name-default-case "ZEROFILL") "ZEROFILL")
1100    (cons (symbol-name-default-case "AUTO-INCREMENT") "AUTO_INCREMENT")
1101    (cons (symbol-name-default-case "DEFAULT") "DEFAULT")
1102    (cons (symbol-name-default-case "UNIQUE") "UNIQUE")
1103    (cons (symbol-name-default-case "IDENTITY") "IDENTITY (1,1)") ;; added for sql-server support
1104    ))
1105
1106 (defmethod database-constraint-statement (constraint-list database)
1107   (declare (ignore database))
1108   (make-constraints-description constraint-list))
1109
1110 (defun make-constraints-description (constraint-list)
1111   (if constraint-list
1112       (let ((string ""))
1113         (do ((constraint constraint-list (cdr constraint)))
1114             ((null constraint) string)
1115           (let ((output (assoc (symbol-name (car constraint))
1116                                *constraint-types*
1117                                :test #'equal)))
1118             (if (null output)
1119                 (error 'sql-user-error
1120                        :message (format nil "unsupported column constraint '~A'"
1121                                         constraint))
1122                 (setq string (concatenate 'string string (cdr output))))
1123             (when (equal (symbol-name (car constraint)) "DEFAULT")
1124               (setq constraint (cdr constraint))
1125               (setq string (concatenate 'string string " " (car constraint))))
1126             (if (< 1 (length constraint))
1127                 (setq string (concatenate 'string string " "))))))))
1128
1129 (defmethod database-identifier ( name  &optional database find-class-p
1130                                  &aux cls)
1131   "A function that takes whatever you give it, recursively coerces it,
1132    and returns a database-identifier.
1133
1134    (escaped-database-identifiers *any-reasonable-object*) should be called to
1135      produce a string that is safe to splice directly into sql strings.
1136
1137    This function should NOT throw errors when database is nil
1138
1139    find-class-p should be T if we want to search for classes
1140         and check their use their view table.  Should be used
1141         on symbols we are sure indicate tables
1142
1143
1144    ;; metaclasses has further typecases of this, so that it will
1145    ;; load less painfully (try-recompiles) in SBCL
1146
1147   "
1148   (flet ((flatten-id (id)
1149            "if we have multiple pieces that we need to represent as
1150             db-id lets do that by rendering out the id, then creating
1151             a new db-id with that string as escaped"
1152            (let ((s (sql-output id database)))
1153              (make-instance '%database-identifier :escaped s :unescaped s))))
1154     (setf name (dequote name))
1155     (etypecase name
1156       (null nil)
1157       (string (%make-database-identifier name database))
1158       (symbol
1159        ;; if this is being used as a table, we should check
1160        ;; for a class with this name and use the identifier specified
1161        ;; on it
1162        (if (and find-class-p (setf cls (find-standard-db-class name)))
1163            (database-identifier cls)
1164            (%make-database-identifier name database)))
1165       (%database-identifier name)
1166       ;; we know how to deref this without further escaping
1167       (sql-ident-table
1168        (with-slots ((inner-name name) alias) name
1169          (if alias
1170              (flatten-id name)
1171              (database-identifier inner-name))))
1172       ;; if this is a single name we can derefence it
1173       (sql-ident-attribute
1174        (with-slots (qualifier (inner-name name)) name
1175          (if qualifier
1176              (flatten-id name)
1177              (database-identifier inner-name))))
1178       (sql-ident
1179        (with-slots ((inner-name name)) name
1180          (database-identifier inner-name)))
1181       ;; dont know how to handle this really :/
1182       (%sql-expression (flatten-id name))
1183       )))
1184
1185 (defun %clsql-subclauses (clauses)
1186   "a helper for dealing with lists of sql clauses"
1187   (loop for c in clauses
1188         when c
1189         collect (typecase c
1190                   (string (clsql-sys:sql-expression :string c))
1191                   (T c))))
1192
1193 (defun clsql-ands (clauses)
1194   "Correctly creates a sql 'and' expression for the clauses
1195     ignores any nil clauses
1196     returns a single child expression if there is only one
1197     returns an 'and' expression if there are many
1198     returns nil if there are no children"
1199   (let ((ex (%clsql-subclauses clauses)))
1200     (when ex
1201       (case (length ex)
1202         (1 (first ex))
1203         (t (apply #'clsql-sys:sql-and ex))))))
1204
1205 (defun clsql-and (&rest clauses)
1206   "Correctly creates a sql 'and' expression for the clauses
1207     ignores any nil clauses
1208     returns a single child expression if there is only one
1209     returns an 'and' expression if there are many
1210     returns nil if there are no children"
1211   (clsql-ands clauses))
1212
1213 (defun clsql-ors (clauses)
1214   "Correctly creates a sql 'or' expression for the clauses
1215     ignores any nil clauses
1216     returns a single child expression if there is only one
1217     returns an 'or' expression if there are many
1218     returns nil if there are no children"
1219   (let ((ex (%clsql-subclauses clauses)))
1220     (when ex
1221       (case (length ex)
1222         (1 (first ex))
1223         (t (apply #'clsql-sys:sql-or ex))))))
1224
1225 (defun clsql-or (&rest clauses)
1226   "Correctly creates a sql 'or' expression for the clauses
1227     ignores any nil clauses
1228     returns a single child expression if there is only one
1229     returns an 'or' expression if there are many
1230     returns nil if there are no children"
1231   (clsql-ors clauses))
1232