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