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