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