cleaning up patches, and fixing missing pkey bugs in sqlite3
[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     (do ((sub sub-expressions (cdr sub)))
425         ((null (cdr sub)) (output-sql (car sub) database))
426       (output-sql (car sub) database)
427       (write-char #\Space *sql-stream*)
428       (%write-operator operator database)
429       (write-char #\Space *sql-stream*)))
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
454
455 (defmethod output-sql ((expr sql-value-exp) database)
456   (with-slots (modifier components)
457     expr
458     (if modifier
459         (progn
460           (write-char #\( *sql-stream*)
461           (cond
462             ((sql-operator modifier)
463              (%write-operator modifier database))
464             ((or (stringp modifier) (symbolp modifier))
465              (write-string
466               (escaped-database-identifier modifier)
467               *sql-stream*))
468             (t (output-sql modifier database)))
469           (write-char #\Space *sql-stream*)
470           (output-sql components database)
471           (write-char #\) *sql-stream*))
472         (output-sql components database))))
473
474 (defclass sql-typecast-exp (sql-value-exp)
475   ()
476   (:documentation "An SQL typecast expression."))
477
478 (defmethod output-sql ((expr sql-typecast-exp) database)
479   (with-slots (components)
480     expr
481     (output-sql components database)))
482
483 (defmethod collect-table-refs ((sql sql-typecast-exp))
484   (when (slot-value sql 'components)
485     (collect-table-refs (slot-value sql 'components))))
486
487 (defclass sql-function-exp (%sql-expression)
488   ((name
489     :initarg :name
490     :initform nil)
491    (args
492     :initarg :args
493     :initform nil))
494   (:documentation
495    "An SQL function expression."))
496
497 (defmethod collect-table-refs ((sql sql-function-exp))
498   (let ((tabs nil))
499     (dolist (exp (slot-value sql 'args))
500       (let ((refs (collect-table-refs exp)))
501         (if refs (setf tabs (append refs tabs)))))
502     (remove-duplicates tabs :test #'database-identifier-equal)))
503 (defvar *in-subselect* nil)
504
505 (defmethod output-sql ((expr sql-function-exp) database)
506   (with-slots (name args)
507     expr
508     (typecase name
509       ((or string symbol)
510        (write-string (escaped-database-identifier name) *sql-stream*))
511       (t (output-sql name database)))
512     (let ((*in-subselect* nil)) ;; aboid double parens
513       (when args (output-sql args database))))
514   t)
515
516
517 (defclass sql-between-exp (sql-function-exp)
518   ()
519   (:documentation "An SQL between expression."))
520
521 (defmethod output-sql ((expr sql-between-exp) database)
522   (with-slots (args)
523       expr
524     (output-sql (first args) database)
525     (write-string " BETWEEN " *sql-stream*)
526     (output-sql (second args) database)
527     (write-string " AND " *sql-stream*)
528     (output-sql (third args) database))
529   t)
530
531 (defclass sql-query-modifier-exp (%sql-expression)
532   ((modifier :initarg :modifier :initform nil)
533    (components :initarg :components :initform nil))
534   (:documentation "An SQL query modifier expression."))
535
536 (defmethod output-sql ((expr sql-query-modifier-exp) database)
537   (with-slots (modifier components)
538       expr
539     (%write-operator modifier database)
540     (write-string " " *sql-stream*)
541     (%write-operator (car components) database)
542     (when components
543       (mapc #'(lambda (comp)
544                 (write-string ", " *sql-stream*)
545                 (output-sql comp database))
546             (cdr components))))
547   t)
548
549 (defclass sql-set-exp (%sql-expression)
550   ((operator
551     :initarg :operator
552     :initform nil)
553    (sub-expressions
554     :initarg :sub-expressions
555     :initform nil))
556   (:documentation "An SQL set expression."))
557
558 (defmethod collect-table-refs ((sql sql-set-exp))
559   (let ((tabs nil))
560     (dolist (exp (slot-value sql 'sub-expressions))
561       (let ((refs (collect-table-refs exp)))
562         (if refs (setf tabs (append refs tabs)))))
563     (remove-duplicates tabs :test #'database-identifier-equal)))
564
565 (defmethod output-sql ((expr sql-set-exp) database)
566   (with-slots (operator sub-expressions)
567       expr
568     (let ((subs (if (consp (car sub-expressions))
569                     (car sub-expressions)
570                     sub-expressions)))
571       (when (= (length subs) 1)
572         (%write-operator operator database)
573         (write-char #\Space *sql-stream*))
574       (do ((sub subs (cdr sub)))
575           ((null (cdr sub)) (output-sql (car sub) database))
576         (output-sql (car sub) database)
577         (write-char #\Space *sql-stream*)
578         (%write-operator operator database)
579         (write-char #\Space *sql-stream*))))
580   t)
581
582 (defclass sql-query (%sql-expression)
583   ((selections
584     :initarg :selections
585     :initform nil)
586    (all
587     :initarg :all
588     :initform nil)
589    (flatp
590     :initarg :flatp
591     :initform nil)
592    (set-operation
593     :initarg :set-operation
594     :initform nil)
595    (distinct
596     :initarg :distinct
597     :initform nil)
598    (from
599     :initarg :from
600     :initform nil)
601    (where
602     :initarg :where
603     :initform nil)
604    (group-by
605     :initarg :group-by
606     :initform nil)
607    (having
608     :initarg :having
609     :initform nil)
610    (limit
611     :initarg :limit
612     :initform nil)
613    (offset
614     :initarg :offset
615     :initform nil)
616    (order-by
617     :initarg :order-by
618     :initform nil)
619    (inner-join
620     :initarg :inner-join
621     :initform nil)
622    (on
623     :initarg :on
624     :initform nil))
625   (:documentation "An SQL SELECT query."))
626
627 (defclass sql-object-query (%sql-expression)
628   ((objects
629     :initarg :objects
630     :initform nil)
631    (flatp
632     :initarg :flatp
633     :initform nil)
634    (exp
635     :initarg :exp
636     :initform nil)
637    (refresh
638     :initarg :refresh
639     :initform nil)))
640
641 (defmethod collect-table-refs ((sql sql-query))
642   (remove-duplicates
643    (collect-table-refs (slot-value sql 'where))
644    :test #'database-identifier-equal))
645
646 (defvar *select-arguments*
647   '(:all :database :distinct :flatp :from :group-by :having :order-by
648     :set-operation :where :offset :limit :inner-join :on
649     ;; below keywords are not a SQL argument, but these keywords may terminate select
650     :caching :refresh))
651
652 (defun query-arg-p (sym)
653   (member sym *select-arguments*))
654
655 (defun query-get-selections (select-args)
656   "Return two values: the list of select-args up to the first keyword,
657 uninclusive, and the args from that keyword to the end."
658   (let ((first-key-arg (position-if #'query-arg-p select-args)))
659     (if first-key-arg
660         (values (subseq select-args 0 first-key-arg)
661                 (subseq select-args first-key-arg))
662         select-args)))
663
664 (defun make-query (&rest args)
665   (flet ((select-objects (target-args)
666            (and target-args
667                 (every #'(lambda (arg)
668                            (and (symbolp arg)
669                                 (find-class arg nil)))
670                        target-args))))
671     (multiple-value-bind (selections arglist)
672         (query-get-selections args)
673       (if (select-objects selections)
674           (destructuring-bind (&key flatp refresh &allow-other-keys) arglist
675             (make-instance 'sql-object-query :objects selections
676                            :flatp flatp :refresh refresh
677                            :exp arglist))
678           (destructuring-bind (&key all flatp set-operation distinct from where
679                                     group-by having order-by
680                                     offset limit inner-join on &allow-other-keys)
681               arglist
682             (if (null selections)
683                 (error "No target columns supplied to select statement."))
684             (if (null from)
685                 (error "No source tables supplied to select statement."))
686             (make-instance 'sql-query :selections selections
687                            :all all :flatp flatp :set-operation set-operation
688                            :distinct distinct :from from :where where
689                            :limit limit :offset offset
690                            :group-by group-by :having having :order-by order-by
691                            :inner-join inner-join :on on))))))
692
693 (defun output-sql-where-clause (where database)
694   "ensure that we do not output a \"where\" sql keyword when we will
695     not output a clause. Also sets *in-subselect* to use SQL
696     parentheticals as needed."
697   (when where
698     (let ((where-out (string-trim
699                       '(#\newline #\space #\tab #\return)
700                       (with-output-to-string (*sql-stream*)
701                         (let ((*in-subselect* t))
702                           (output-sql where database))))))
703       (when (> (length where-out) 0)
704         (write-string " WHERE " *sql-stream*)
705         (write-string where-out *sql-stream*)))))
706
707 (defmethod output-sql ((query sql-query) database)
708   (with-slots (distinct selections from where group-by having order-by
709                         limit offset inner-join on all set-operation)
710       query
711     (when *in-subselect*
712       (write-string "(" *sql-stream*))
713     (write-string "SELECT " *sql-stream*)
714     (when all
715       (write-string " ALL " *sql-stream*))
716     (when (and distinct (not all))
717       (write-string " DISTINCT " *sql-stream*)
718       (unless (eql t distinct)
719         (write-string " ON " *sql-stream*)
720         (output-sql distinct database)
721         (write-char #\Space *sql-stream*)))
722     (when (and limit (eql :mssql (database-underlying-type database)))
723       (write-string " TOP " *sql-stream*)
724       (output-sql limit database)
725       (write-string " " *sql-stream*))
726     (let ((*in-subselect* t))
727       (output-sql (apply #'vector selections) database))
728     (when from
729       (write-string " FROM " *sql-stream*)
730       (typecase from
731         (list (output-sql
732                (apply #'vector
733                       (remove-duplicates from :test #'database-identifier-equal))
734                database))
735         (string (write-string
736                  (escaped-database-identifier from database)
737                  *sql-stream*))
738         (t (let ((*in-subselect* t))
739              (output-sql from database)))))
740     (when inner-join
741       (write-string " INNER JOIN " *sql-stream*)
742       (output-sql inner-join database))
743     (when on
744       (write-string " ON " *sql-stream*)
745       (output-sql on database))
746     (output-sql-where-clause where database)
747     (when group-by
748       (write-string " GROUP BY " *sql-stream*)
749       (if (listp group-by)
750           (do ((order group-by (cdr order)))
751               ((null order))
752             (let ((item (car order)))
753               (typecase item
754                 (cons
755                  (output-sql (car item) database)
756                  (format *sql-stream* " ~A" (cadr item)))
757                 (t
758                  (output-sql item database)))
759               (when (cdr order)
760                 (write-char #\, *sql-stream*))))
761           (output-sql group-by database)))
762     (when having
763       (write-string " HAVING " *sql-stream*)
764       (output-sql having database))
765     (when order-by
766       (write-string " ORDER BY " *sql-stream*)
767       (if (listp order-by)
768           (do ((order order-by (cdr order)))
769               ((null order))
770             (let ((item (car order)))
771               (typecase item
772                 (cons
773                  (output-sql (car item) database)
774                  (format *sql-stream* " ~A" (cadr item)))
775                 (t
776                  (output-sql item database)))
777               (when (cdr order)
778                 (write-char #\, *sql-stream*))))
779           (output-sql order-by database)))
780     (when (and limit (not (eql :mssql (database-underlying-type database))))
781       (write-string " LIMIT " *sql-stream*)
782       (output-sql limit database))
783     (when offset
784       (write-string " OFFSET " *sql-stream*)
785       (output-sql offset database))
786     (when *in-subselect*
787       (write-string ")" *sql-stream*))
788     (when set-operation
789       (write-char #\Space *sql-stream*)
790       (output-sql set-operation database)))
791   t)
792
793 (defmethod output-sql ((query sql-object-query) database)
794   (declare (ignore database))
795   (with-slots (objects)
796       query
797     (when objects
798       (format *sql-stream* "(~{~A~^ ~})" objects))))
799
800
801 ;; INSERT
802
803 (defclass sql-insert (%sql-expression)
804   ((into
805     :initarg :into
806     :initform nil)
807    (attributes
808     :initarg :attributes
809     :initform nil)
810    (values
811     :initarg :values
812     :initform nil)
813    (query
814     :initarg :query
815     :initform nil))
816   (:documentation
817    "An SQL INSERT statement."))
818
819 (defmethod output-sql ((ins sql-insert) database)
820   (with-slots (into attributes values query)
821     ins
822     (write-string "INSERT INTO " *sql-stream*)
823     (output-sql
824      (typecase into
825        (string (sql-expression :table into))
826        (t into))
827      database)
828     (when attributes
829       (write-char #\Space *sql-stream*)
830       (output-sql attributes database))
831     (when values
832       (write-string " VALUES " *sql-stream*)
833       (let ((clsql-sys::*in-subselect* t))
834         (output-sql values database)))
835     (when query
836       (write-char #\Space *sql-stream*)
837       (output-sql query database)))
838   t)
839
840 ;; DELETE
841
842 (defclass sql-delete (%sql-expression)
843   ((from
844     :initarg :from
845     :initform nil)
846    (where
847     :initarg :where
848     :initform nil))
849   (:documentation
850    "An SQL DELETE statement."))
851
852 (defmethod output-sql ((stmt sql-delete) database)
853   (with-slots (from where)
854     stmt
855     (write-string "DELETE FROM " *sql-stream*)
856     (typecase from
857       ((or symbol string) (write-string (sql-escape from) *sql-stream*))
858       (t  (output-sql from database)))
859     (output-sql-where-clause where database))
860   t)
861
862 ;; UPDATE
863
864 (defclass sql-update (%sql-expression)
865   ((table
866     :initarg :table
867     :initform nil)
868    (attributes
869     :initarg :attributes
870     :initform nil)
871    (values
872     :initarg :values
873     :initform nil)
874    (where
875     :initarg :where
876     :initform nil))
877   (:documentation "An SQL UPDATE statement."))
878
879 (defmethod output-sql ((expr sql-update) database)
880   (with-slots (table where attributes values)
881     expr
882     (flet ((update-assignments ()
883              (mapcar #'(lambda (a b)
884                          (make-instance 'sql-assignment-exp
885                                         :operator '=
886                                         :sub-expressions (list a b)))
887                      attributes values)))
888       (write-string "UPDATE " *sql-stream*)
889       (output-sql table database)
890       (write-string " SET " *sql-stream*)
891       (let ((clsql-sys::*in-subselect* t))
892         (output-sql (apply #'vector (update-assignments)) database))
893       (output-sql-where-clause where database)))
894   t)
895
896 ;; CREATE TABLE
897
898 (defclass sql-create-table (%sql-expression)
899   ((name
900     :initarg :name
901     :initform nil)
902    (columns
903     :initarg :columns
904     :initform nil)
905    (modifiers
906     :initarg :modifiers
907     :initform nil)
908    (transactions
909     :initarg :transactions
910     :initform nil))
911   (:documentation
912    "An SQL CREATE TABLE statement."))
913
914 ;; Here's a real warhorse of a function!
915
916 (declaim (inline listify))
917 (defun listify (x)
918   (if (listp x)
919       x
920       (list x)))
921
922 (defmethod output-sql ((stmt sql-create-table) database)
923   (flet ((output-column (column-spec)
924            (destructuring-bind (name type &optional db-type &rest constraints)
925                column-spec
926              (let ((type (listify type)))
927                (output-sql name database)
928                (write-char #\Space *sql-stream*)
929                (write-string
930                 (if (stringp db-type) db-type ; override definition
931                   (database-get-type-specifier (car type) (cdr type) database
932                                                (database-underlying-type database)))
933                 *sql-stream*)
934                (let ((constraints (database-constraint-statement
935                                    (if (and db-type (symbolp db-type))
936                                        (cons db-type constraints)
937                                        constraints)
938                                    database)))
939                  (when constraints
940                    (write-string " " *sql-stream*)
941                    (write-string constraints *sql-stream*)))))))
942     (with-slots (name columns modifiers transactions)
943       stmt
944       (write-string "CREATE TABLE " *sql-stream*)
945       (write-string (escaped-database-identifier name database) *sql-stream*)
946       (write-string " (" *sql-stream*)
947       (do ((column columns (cdr column)))
948           ((null (cdr column))
949            (output-column (car column)))
950         (output-column (car column))
951         (write-string ", " *sql-stream*))
952       (when modifiers
953         (do ((modifier (listify modifiers) (cdr modifier)))
954             ((null modifier))
955           (write-string ", " *sql-stream*)
956           (write-string (car modifier) *sql-stream*)))
957       (write-char #\) *sql-stream*)
958       (when (and (eq :mysql (database-underlying-type database))
959                  transactions
960                  (db-type-transaction-capable? :mysql database))
961         (write-string " ENGINE=innodb" *sql-stream*))))
962   t)
963
964
965 ;; CREATE VIEW
966
967 (defclass sql-create-view (%sql-expression)
968   ((name :initarg :name :initform nil)
969    (column-list :initarg :column-list :initform nil)
970    (query :initarg :query :initform nil)
971    (with-check-option :initarg :with-check-option :initform nil))
972   (:documentation "An SQL CREATE VIEW statement."))
973
974 (defmethod output-sql ((stmt sql-create-view) database)
975   (with-slots (name column-list query with-check-option) stmt
976     (write-string "CREATE VIEW " *sql-stream*)
977     (output-sql name database)
978     (when column-list (write-string " " *sql-stream*)
979           (output-sql (listify column-list) database))
980     (write-string " AS " *sql-stream*)
981     (output-sql query database)
982     (when with-check-option (write-string " WITH CHECK OPTION" *sql-stream*))))
983
984
985 ;;
986 ;; DATABASE-OUTPUT-SQL
987 ;;
988
989 (defmethod database-output-sql ((str string) database)
990   (declare (optimize (speed 3) (safety 1)
991                      #+cmu (extensions:inhibit-warnings 3)))
992   (let ((len (length str)))
993     (declare (type fixnum len))
994     (cond ((zerop len)
995            +empty-string+)
996           ((and (null (position #\' str))
997                 (null (position #\\ str)))
998            (concatenate 'string "'" str "'"))
999           (t
1000            (let ((buf (make-string (+ (* len 2) 2) :initial-element #\')))
1001              (declare (simple-string buf))
1002              (do* ((i 0 (incf i))
1003                    (j 1 (incf j)))
1004                   ((= i len) (subseq buf 0 (1+ j)))
1005                (declare (type fixnum i j))
1006                (let ((char (aref str i)))
1007                  (declare (character char))
1008                  (cond ((char= char #\')
1009                         (setf (aref buf j) #\')
1010                         (incf j)
1011                         (setf (aref buf j) #\'))
1012                        ((and (char= char #\\)
1013                              ;; MTP: only escape backslash with pgsql/mysql
1014                              (member (database-underlying-type database)
1015                                      '(:postgresql :mysql)
1016                                      :test #'eq))
1017                         (setf (aref buf j) #\\)
1018                         (incf j)
1019                         (setf (aref buf j) #\\))
1020                        (t
1021                         (setf (aref buf j) char))))))))))
1022
1023 (let ((keyword-package (symbol-package :foo)))
1024   (defmethod database-output-sql ((sym symbol) database)
1025   (if (null sym)
1026       +null-string+
1027       (if (equal (symbol-package sym) keyword-package)
1028           (database-output-sql (symbol-name sym) database)
1029           (escaped-database-identifier sym)))))
1030
1031 (defmethod database-output-sql ((tee (eql t)) database)
1032   (if database
1033       (let ((val (database-output-sql-as-type 'boolean t database (database-type database))))
1034         (when val
1035           (typecase val
1036             (string (format nil "'~A'" val))
1037             (integer (format nil "~A" val)))))
1038     "'Y'"))
1039
1040 #+nil(defmethod database-output-sql ((tee (eql t)) database)
1041   (declare (ignore database))
1042   "'Y'")
1043
1044 (defmethod database-output-sql ((num number) database)
1045   (declare (ignore database))
1046   (number-to-sql-string num))
1047
1048 (defmethod database-output-sql ((arg list) database)
1049   (if (null arg)
1050       +null-string+
1051       (format nil "(~{~A~^,~})" (mapcar #'(lambda (val)
1052                                             (sql-output val database))
1053                                         arg))))
1054
1055 (defmethod database-output-sql ((arg vector) database)
1056   (format nil "~{~A~^,~}" (map 'list #'(lambda (val)
1057                                          (sql-output val database))
1058                                arg)))
1059
1060 (defmethod output-sql-hash-key ((arg vector) database)
1061   (list 'vector (map 'list (lambda (arg)
1062                              (or (output-sql-hash-key arg database)
1063                                  (return-from output-sql-hash-key nil)))
1064                      arg)))
1065
1066 (defmethod database-output-sql ((self wall-time) database)
1067   (declare (ignore database))
1068   (db-timestring self))
1069
1070 (defmethod database-output-sql ((self date) database)
1071   (declare (ignore database))
1072   (db-datestring self))
1073
1074 (defmethod database-output-sql ((self duration) database)
1075   (declare (ignore database))
1076   (format nil "'~a'" (duration-timestring self)))
1077
1078 #+ignore
1079 (defmethod database-output-sql ((self money) database)
1080   (database-output-sql (slot-value self 'odcl::units) database))
1081
1082 (defmethod database-output-sql (thing database)
1083   (if (or (null thing)
1084           (eq 'null thing))
1085       +null-string+
1086     (error 'sql-user-error
1087            :message
1088            (format nil
1089                    "No type conversion to SQL for ~A is defined for DB ~A."
1090                    (type-of thing) (type-of database)))))
1091
1092
1093 ;;
1094 ;; Column constraint types and conversion to SQL
1095 ;;
1096 (defmethod database-constraint-statement (constraint-list database)
1097   (make-constraints-description constraint-list database))
1098
1099 ;; KEEP THIS SYNCED WITH database-translate-constraint
1100 (defparameter +auto-increment-names+
1101   '(:auto-increment :auto_increment :autoincrement :identity))
1102
1103 (defmethod database-translate-constraint (constraint database)
1104   (case constraint
1105     (:not-null "NOT NULL")
1106     (:primary-key "PRIMARY KEY")
1107     ((:auto-increment :auto_increment :autoincrement :identity)
1108      (ecase (database-underlying-type database)
1109        (:mssql "IDENTITY (1,1)")
1110        ((:sqlite :sqlite3) "PRIMARY KEY AUTOINCREMENT")
1111        (:mysql "AUTO_INCREMENT")))
1112     ;; everything else just get the name
1113     (T (string-upcase (symbol-name constraint)))))
1114
1115 (defun make-constraints-description (constraint-list database
1116                                      &aux (rest constraint-list) constraint)
1117   (when constraint-list
1118     (flet ((next ()
1119              (setf constraint (first rest)
1120                    rest (rest rest))
1121              constraint))
1122       (with-output-to-string (s)
1123         (loop while (next)
1124               do (unless (keywordp constraint)
1125                    (setf constraint (intern (symbol-name constraint) :keyword)))
1126                  (write-string (database-translate-constraint constraint database) s)
1127                  (when (eql :default constraint) (princ (next) s))
1128                  (write-char #\space s)
1129               )))))
1130
1131 (defmethod database-identifier ( name  &optional database find-class-p
1132                                  &aux cls)
1133   "A function that takes whatever you give it, recursively coerces it,
1134    and returns a database-identifier.
1135
1136    (escaped-database-identifiers *any-reasonable-object*) should be called to
1137      produce a string that is safe to splice directly into sql strings.
1138
1139    This function should NOT throw errors when database is nil
1140
1141    find-class-p should be T if we want to search for classes
1142         and check their use their view table.  Should be used
1143         on symbols we are sure indicate tables
1144
1145
1146    ;; metaclasses has further typecases of this, so that it will
1147    ;; load less painfully (try-recompiles) in SBCL
1148
1149   "
1150   (flet ((flatten-id (id)
1151            "if we have multiple pieces that we need to represent as
1152             db-id lets do that by rendering out the id, then creating
1153             a new db-id with that string as escaped"
1154            (let ((s (sql-output id database)))
1155              (make-instance '%database-identifier :escaped s :unescaped s))))
1156     (setf name (dequote name))
1157     (etypecase name
1158       (null nil)
1159       (string (%make-database-identifier name database))
1160       (symbol
1161        ;; if this is being used as a table, we should check
1162        ;; for a class with this name and use the identifier specified
1163        ;; on it
1164        (if (and find-class-p (setf cls (find-standard-db-class name)))
1165            (database-identifier cls)
1166            (%make-database-identifier name database)))
1167       (%database-identifier name)
1168       ;; we know how to deref this without further escaping
1169       (sql-ident-table
1170        (with-slots ((inner-name name) alias) name
1171          (if alias
1172              (flatten-id name)
1173              (database-identifier inner-name))))
1174       ;; if this is a single name we can derefence it
1175       (sql-ident-attribute
1176        (with-slots (qualifier (inner-name name)) name
1177          (if qualifier
1178              (flatten-id name)
1179              (database-identifier inner-name))))
1180       (sql-ident
1181        (with-slots ((inner-name name)) name
1182          (database-identifier inner-name)))
1183       ;; dont know how to handle this really :/
1184       (%sql-expression (flatten-id name))
1185       )))
1186
1187 (defun %clsql-subclauses (clauses)
1188   "a helper for dealing with lists of sql clauses"
1189   (loop for c in clauses
1190         when c
1191         collect (typecase c
1192                   (string (clsql-sys:sql-expression :string c))
1193                   (T c))))
1194
1195 (defun clsql-ands (clauses)
1196   "Correctly creates a sql 'and' expression for the clauses
1197     ignores any nil clauses
1198     returns a single child expression if there is only one
1199     returns an 'and' expression if there are many
1200     returns nil if there are no children"
1201   (let ((ex (%clsql-subclauses clauses)))
1202     (when ex
1203       (case (length ex)
1204         (1 (first ex))
1205         (t (apply #'clsql-sys:sql-and ex))))))
1206
1207 (defun clsql-and (&rest clauses)
1208   "Correctly creates a sql 'and' expression for the clauses
1209     ignores any nil clauses
1210     returns a single child expression if there is only one
1211     returns an 'and' expression if there are many
1212     returns nil if there are no children"
1213   (clsql-ands clauses))
1214
1215 (defun clsql-ors (clauses)
1216   "Correctly creates a sql 'or' expression for the clauses
1217     ignores any nil clauses
1218     returns a single child expression if there is only one
1219     returns an 'or' expression if there are many
1220     returns nil if there are no children"
1221   (let ((ex (%clsql-subclauses clauses)))
1222     (when ex
1223       (case (length ex)
1224         (1 (first ex))
1225         (t (apply #'clsql-sys:sql-or ex))))))
1226
1227 (defun clsql-or (&rest clauses)
1228   "Correctly creates a sql 'or' expression for the clauses
1229     ignores any nil clauses
1230     returns a single child expression if there is only one
1231     returns an 'or' expression if there are many
1232     returns nil if there are no children"
1233   (clsql-ors clauses))
1234