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