A few type declarations
[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   #+sbcl
143   (make-hash-table :test #'equal :synchronized T :weakness :key-and-value)
144   #-sbcl
145   (make-hash-table :test #'equal )
146   "For caching generated SQL strings.")
147
148 (defmethod output-sql :around ((sql t) database)
149   (if (null *output-hash*)
150       (call-next-method)
151       (let* ((hash-key (output-sql-hash-key sql database))
152              (hash-value (when hash-key (gethash hash-key *output-hash*))))
153         (cond ((and hash-key hash-value)
154                (write-string hash-value *sql-stream*))
155               (hash-key
156                (let ((*sql-stream* (make-string-output-stream)))
157                  (call-next-method)
158                  (setf hash-value (get-output-stream-string *sql-stream*))
159                  (setf (gethash hash-key *output-hash*) hash-value))
160                (write-string hash-value *sql-stream*))
161               (t
162                (call-next-method))))))
163
164 (defmethod output-sql-hash-key (expr database)
165   (declare (ignore expr database))
166   nil)
167
168
169 (defclass %sql-expression ()
170   ())
171
172 (defmethod output-sql ((expr %sql-expression) database)
173   (declare (ignore database))
174   (write-string +null-string+ *sql-stream*))
175
176 (defmethod print-object ((self %sql-expression) stream)
177   (print-unreadable-object
178    (self stream :type t)
179    (write-string (sql-output self) stream))
180   self)
181
182 ;; For straight up strings
183
184 (defclass sql (%sql-expression)
185   ((text
186     :initarg :string
187     :initform ""))
188   (:documentation "A literal SQL expression."))
189
190 (defmethod make-load-form ((sql sql) &optional environment)
191   (declare (ignore environment))
192   (with-slots (text)
193     sql
194     `(make-instance 'sql :string ',text)))
195
196 (defmethod output-sql ((expr sql) database)
197   (declare (ignore database))
198   (write-string (slot-value expr 'text) *sql-stream*)
199   t)
200
201 (defmethod print-object ((ident sql) stream)
202   (format stream "#<~S \"~A\">"
203           (type-of ident)
204           (sql-output ident nil))
205   ident)
206
207 ;; For SQL Identifiers of generic type
208
209 (defclass sql-ident (%sql-expression)
210   ((name
211     :initarg :name
212     :initform +null-string+))
213   (:documentation "An SQL identifer."))
214
215 (defmethod make-load-form ((sql sql-ident) &optional environment)
216   (declare (ignore environment))
217   (with-slots (name)
218     sql
219     `(make-instance 'sql-ident :name ',name)))
220
221 (defmethod output-sql ((expr %database-identifier) database)
222   (write-string (escaped expr) *sql-stream*))
223
224 (defmethod output-sql ((expr sql-ident) database)
225   (with-slots (name) expr
226     (write-string (escaped-database-identifier name database) *sql-stream*))
227   t)
228
229 ;; For SQL Identifiers for attributes
230
231 (defclass sql-ident-attribute (sql-ident)
232   ((qualifier
233     :initarg :qualifier
234     :initform +null-string+)
235    (type
236     :initarg :type
237     :initform +null-string+))
238   (:documentation "An SQL Attribute identifier."))
239
240 (defmethod collect-table-refs (sql)
241   (declare (ignore sql))
242   nil)
243
244 (defmethod collect-table-refs ((sql sql-ident-attribute))
245   (let ((qual (slot-value sql 'qualifier)))
246     (when qual
247       ;; going to be used as a table, search classes
248       (list (make-instance
249              'sql-ident-table
250              :name (database-identifier qual nil t))))))
251
252 (defmethod make-load-form ((sql sql-ident-attribute) &optional environment)
253   (declare (ignore environment))
254   (with-slots (qualifier type name)
255     sql
256     `(make-instance 'sql-ident-attribute :name ',name
257       :qualifier ',qualifier
258       :type ',type)))
259
260 (defmethod output-sql-hash-key ((expr sql-ident-attribute) database)
261   (with-slots (qualifier name type)
262       expr
263     (list (and database (database-underlying-type database))
264           'sql-ident-attribute
265           (unescaped-database-identifier qualifier)
266           (unescaped-database-identifier name) type)))
267
268 ;; For SQL Identifiers for tables
269
270 (defclass sql-ident-table (sql-ident)
271   ((alias
272     :initarg :table-alias :initform nil))
273   (:documentation "An SQL table identifier."))
274
275 (defmethod make-load-form ((sql sql-ident-table) &optional environment)
276   (declare (ignore environment))
277   (with-slots (alias name)
278     sql
279     `(make-instance 'sql-ident-table :name ',name :table-alias ',alias)))
280
281 (defmethod output-sql ((expr sql-ident-table) database)
282   (with-slots (name alias) expr
283     (flet ((p (s) ;; the etypecase is in sql-escape too
284              (write-string
285               (escaped-database-identifier s database)
286               *sql-stream*)))
287       (p name)
288       (when alias
289         (princ #\space *sql-stream*)
290         (p alias))))
291   t)
292
293 (defmethod output-sql ((expr sql-ident-attribute) database)
294 ;;; KMR: The TYPE field is used by CommonSQL for type conversion -- it
295 ;;; should not be output in SQL statements
296   (let ((*print-pretty* nil))
297     (with-slots (qualifier name type) expr
298       (format *sql-stream* "~@[~a.~]~a"
299               (when qualifier
300                 ;; check for classes
301                 (escaped-database-identifier qualifier database T))
302               (escaped-database-identifier name database))
303       t)))
304
305 (defmethod output-sql-hash-key ((expr sql-ident-table) database)
306   (with-slots (name alias)
307       expr
308     (list (and database (database-underlying-type database))
309           'sql-ident-table
310           (unescaped-database-identifier name)
311           (unescaped-database-identifier alias))))
312
313 (defclass sql-relational-exp (%sql-expression)
314   ((operator
315     :initarg :operator
316     :initform nil)
317    (sub-expressions
318     :initarg :sub-expressions
319     :initform nil))
320   (:documentation "An SQL relational expression."))
321
322 (defmethod make-load-form ((self sql-relational-exp) &optional environment)
323   (make-load-form-saving-slots self
324                                :slot-names '(operator sub-expressions)
325                                :environment environment))
326
327 (defmethod collect-table-refs ((sql sql-relational-exp))
328   (let ((tabs nil))
329     (dolist (exp (slot-value sql 'sub-expressions))
330       (let ((refs (collect-table-refs exp)))
331         (if refs (setf tabs (append refs tabs)))))
332     (remove-duplicates tabs :test #'database-identifier-equal)))
333
334
335
336
337 ;; Write SQL for relational operators (like 'AND' and 'OR').
338 ;; should do arity checking of subexpressions
339
340 (defun %write-operator (operator database)
341   (typecase operator
342     (string (write-string operator *sql-stream*))
343     (symbol (write-string (symbol-name operator) *sql-stream*))
344     (T (output-sql operator database))))
345
346 (defmethod output-sql ((expr sql-relational-exp) database)
347   (with-slots (operator sub-expressions) expr
348      ;; we do this as two runs so as not to emit confusing superflous parentheses
349      ;; The first loop renders all the child outputs so that we can skip anding with
350      ;; empty output (which causes sql errors)
351      ;; the next loop simply emits each sub-expression with the appropriate number of
352      ;; parens and operators
353      (flet ((trim (sub)
354               (string-trim +whitespace-chars+
355                            (with-output-to-string (*sql-stream*)
356                              (output-sql sub database)))))
357        (let ((str-subs (loop for sub in sub-expressions
358                              for str-sub = (trim sub)
359                            when (and str-sub (> (length str-sub) 0))
360                              collect str-sub)))
361          (case (length str-subs)
362            (0 nil)
363            (1 (write-string (first str-subs) *sql-stream*))
364            (t
365               (write-char #\( *sql-stream*)
366               (write-string (first str-subs) *sql-stream*)
367               (loop for str-sub in (rest str-subs)
368                     do
369                  (write-char #\Space *sql-stream*)
370                  ;; do this so that symbols can be output as database identifiers
371                  ;; rather than allowing symbols to inject sql
372                  (%write-operator operator database)
373                  (write-char #\Space *sql-stream*)
374                  (write-string str-sub *sql-stream*))
375               (write-char #\) *sql-stream*))
376            ))))
377   t)
378
379 (defclass sql-upcase-like (sql-relational-exp)
380   ()
381   (:documentation "An SQL 'like' that upcases its arguments."))
382
383 (defmethod output-sql ((expr sql-upcase-like) database)
384   (flet ((write-term (term)
385            (write-string "upper(" *sql-stream*)
386            (output-sql term database)
387            (write-char #\) *sql-stream*)))
388     (with-slots (sub-expressions)
389       expr
390       (let ((subs (if (consp (car sub-expressions))
391                       (car sub-expressions)
392                       sub-expressions)))
393         (write-char #\( *sql-stream*)
394         (do ((sub subs (cdr sub)))
395             ((null (cdr sub)) (write-term (car sub)))
396           (write-term (car sub))
397           (write-string " LIKE " *sql-stream*))
398         (write-char #\) *sql-stream*))))
399   t)
400
401 (defclass sql-assignment-exp (sql-relational-exp)
402   ()
403   (:documentation "An SQL Assignment expression."))
404
405
406 (defmethod output-sql ((expr sql-assignment-exp) database)
407   (with-slots (operator sub-expressions)
408     expr
409     (do ((sub sub-expressions (cdr sub)))
410         ((null (cdr sub)) (output-sql (car sub) database))
411       (output-sql (car sub) database)
412       (write-char #\Space *sql-stream*)
413       (%write-operator operator database)
414       (write-char #\Space *sql-stream*)))
415   t)
416
417 (defclass sql-value-exp (%sql-expression)
418   ((modifier
419     :initarg :modifier
420     :initform nil)
421    (components
422     :initarg :components
423     :initform nil))
424   (:documentation
425    "An SQL value expression.")
426   )
427
428 (defmethod collect-table-refs ((sql sql-value-exp))
429   (let ((tabs nil))
430     (if (listp (slot-value sql 'components))
431         (progn
432           (dolist (exp (slot-value sql 'components))
433             (let ((refs (collect-table-refs exp)))
434               (if refs (setf tabs (append refs tabs)))))
435           (remove-duplicates tabs :test #'database-identifier-equal))
436         nil)))
437
438
439
440 (defmethod output-sql ((expr sql-value-exp) database)
441   (with-slots (modifier components)
442     expr
443     (if modifier
444         (progn
445           (write-char #\( *sql-stream*)
446           (cond
447             ((sql-operator modifier)
448              (%write-operator modifier database))
449             ((or (stringp modifier) (symbolp modifier))
450              (write-string
451               (escaped-database-identifier modifier)
452               *sql-stream*))
453             (t (output-sql modifier database)))
454           (write-char #\Space *sql-stream*)
455           (output-sql components database)
456           (write-char #\) *sql-stream*))
457         (output-sql components database))))
458
459 (defclass sql-typecast-exp (sql-value-exp)
460   ()
461   (:documentation "An SQL typecast expression."))
462
463 (defmethod output-sql ((expr sql-typecast-exp) database)
464   (with-slots (components)
465     expr
466     (output-sql components database)))
467
468 (defmethod collect-table-refs ((sql sql-typecast-exp))
469   (when (slot-value sql 'components)
470     (collect-table-refs (slot-value sql 'components))))
471
472 (defclass sql-function-exp (%sql-expression)
473   ((name
474     :initarg :name
475     :initform nil)
476    (args
477     :initarg :args
478     :initform nil))
479   (:documentation
480    "An SQL function expression."))
481
482 (defmethod collect-table-refs ((sql sql-function-exp))
483   (let ((tabs nil))
484     (dolist (exp (slot-value sql 'args))
485       (let ((refs (collect-table-refs exp)))
486         (if refs (setf tabs (append refs tabs)))))
487     (remove-duplicates tabs :test #'database-identifier-equal)))
488 (defvar *in-subselect* nil)
489
490 (defmethod output-sql ((expr sql-function-exp) database)
491   (with-slots (name args)
492     expr
493     (typecase name
494       ((or string symbol)
495        (write-string (escaped-database-identifier name) *sql-stream*))
496       (t (output-sql name database)))
497     (let ((*in-subselect* nil)) ;; aboid double parens
498       (when args (output-sql args database))))
499   t)
500
501
502 (defclass sql-between-exp (sql-function-exp)
503   ()
504   (:documentation "An SQL between expression."))
505
506 (defmethod output-sql ((expr sql-between-exp) database)
507   (with-slots (args)
508       expr
509     (output-sql (first args) database)
510     (write-string " BETWEEN " *sql-stream*)
511     (output-sql (second args) database)
512     (write-string " AND " *sql-stream*)
513     (output-sql (third args) database))
514   t)
515
516 (defclass sql-query-modifier-exp (%sql-expression)
517   ((modifier :initarg :modifier :initform nil)
518    (components :initarg :components :initform nil))
519   (:documentation "An SQL query modifier expression."))
520
521 (defmethod output-sql ((expr sql-query-modifier-exp) database)
522   (with-slots (modifier components)
523       expr
524     (%write-operator modifier database)
525     (write-string " " *sql-stream*)
526     (%write-operator (car components) database)
527     (when components
528       (mapc #'(lambda (comp)
529                 (write-string ", " *sql-stream*)
530                 (output-sql comp database))
531             (cdr components))))
532   t)
533
534 (defclass sql-set-exp (%sql-expression)
535   ((operator
536     :initarg :operator
537     :initform nil)
538    (sub-expressions
539     :initarg :sub-expressions
540     :initform nil))
541   (:documentation "An SQL set expression."))
542
543 (defmethod collect-table-refs ((sql sql-set-exp))
544   (let ((tabs nil))
545     (dolist (exp (slot-value sql 'sub-expressions))
546       (let ((refs (collect-table-refs exp)))
547         (if refs (setf tabs (append refs tabs)))))
548     (remove-duplicates tabs :test #'database-identifier-equal)))
549
550 (defmethod output-sql ((expr sql-set-exp) database)
551   (with-slots (operator sub-expressions)
552       expr
553     (let ((subs (if (consp (car sub-expressions))
554                     (car sub-expressions)
555                     sub-expressions)))
556       (when (= (length subs) 1)
557         (%write-operator operator database)
558         (write-char #\Space *sql-stream*))
559       (do ((sub subs (cdr sub)))
560           ((null (cdr sub)) (output-sql (car sub) database))
561         (output-sql (car sub) database)
562         (write-char #\Space *sql-stream*)
563         (%write-operator operator database)
564         (write-char #\Space *sql-stream*))))
565   t)
566
567 (defclass sql-query (%sql-expression)
568   ((selections
569     :initarg :selections
570     :initform nil)
571    (all
572     :initarg :all
573     :initform nil)
574    (flatp
575     :initarg :flatp
576     :initform nil)
577    (set-operation
578     :initarg :set-operation
579     :initform nil)
580    (distinct
581     :initarg :distinct
582     :initform nil)
583    (from
584     :initarg :from
585     :initform nil)
586    (where
587     :initarg :where
588     :initform nil)
589    (group-by
590     :initarg :group-by
591     :initform nil)
592    (having
593     :initarg :having
594     :initform nil)
595    (limit
596     :initarg :limit
597     :initform nil)
598    (offset
599     :initarg :offset
600     :initform nil)
601    (order-by
602     :initarg :order-by
603     :initform nil)
604    (inner-join
605     :initarg :inner-join
606     :initform nil)
607    (on
608     :initarg :on
609     :initform nil))
610   (:documentation "An SQL SELECT query."))
611
612 (defclass sql-object-query (%sql-expression)
613   ((objects
614     :initarg :objects
615     :initform nil)
616    (flatp
617     :initarg :flatp
618     :initform nil)
619    (exp
620     :initarg :exp
621     :initform nil)
622    (refresh
623     :initarg :refresh
624     :initform nil)))
625
626 (defmethod collect-table-refs ((sql sql-query))
627   (remove-duplicates
628    (collect-table-refs (slot-value sql 'where))
629    :test #'database-identifier-equal))
630
631 (defvar *select-arguments*
632   '(:all :database :distinct :flatp :from :group-by :having :order-by
633     :set-operation :where :offset :limit :inner-join :on
634     ;; below keywords are not a SQL argument, but these keywords may terminate select
635     :caching :refresh))
636
637 (defun query-arg-p (sym)
638   (member sym *select-arguments*))
639
640 (defun query-get-selections (select-args)
641   "Return two values: the list of select-args up to the first keyword,
642 uninclusive, and the args from that keyword to the end."
643   (let ((first-key-arg (position-if #'query-arg-p select-args)))
644     (if first-key-arg
645         (values (subseq select-args 0 first-key-arg)
646                 (subseq select-args first-key-arg))
647         select-args)))
648
649 (defun make-query (&rest args)
650   (flet ((select-objects (target-args)
651            (and target-args
652                 (every #'(lambda (arg)
653                            (and (symbolp arg)
654                                 (find-class arg nil)))
655                        target-args))))
656     (multiple-value-bind (selections arglist)
657         (query-get-selections args)
658       (if (select-objects selections)
659           (destructuring-bind (&key flatp refresh &allow-other-keys) arglist
660             (make-instance 'sql-object-query :objects selections
661                            :flatp flatp :refresh refresh
662                            :exp arglist))
663           (destructuring-bind (&key all flatp set-operation distinct from where
664                                     group-by having order-by
665                                     offset limit inner-join on &allow-other-keys)
666               arglist
667             (if (null selections)
668                 (error "No target columns supplied to select statement."))
669             (if (null from)
670                 (error "No source tables supplied to select statement."))
671             (make-instance 'sql-query :selections selections
672                            :all all :flatp flatp :set-operation set-operation
673                            :distinct distinct :from from :where where
674                            :limit limit :offset offset
675                            :group-by group-by :having having :order-by order-by
676                            :inner-join inner-join :on on))))))
677
678 (defmethod output-sql ((query sql-query) database)
679   (with-slots (distinct selections from where group-by having order-by
680                         limit offset inner-join on all set-operation)
681       query
682     (when *in-subselect*
683       (write-string "(" *sql-stream*))
684     (write-string "SELECT " *sql-stream*)
685     (when all
686       (write-string " ALL " *sql-stream*))
687     (when (and distinct (not all))
688       (write-string " DISTINCT " *sql-stream*)
689       (unless (eql t distinct)
690         (write-string " ON " *sql-stream*)
691         (output-sql distinct database)
692         (write-char #\Space *sql-stream*)))
693     (when (and limit (eql :mssql (database-underlying-type database)))
694       (write-string " TOP " *sql-stream*)
695       (output-sql limit database)
696       (write-string " " *sql-stream*))
697     (let ((*in-subselect* t))
698       (output-sql (apply #'vector selections) database))
699     (when from
700       (write-string " FROM " *sql-stream*)
701       (typecase from
702         (list (output-sql
703                (apply #'vector
704                       (remove-duplicates from :test #'database-identifier-equal))
705                database))
706         (string (write-string
707                  (escaped-database-identifier from database)
708                  *sql-stream*))
709         (t (let ((*in-subselect* t))
710              (output-sql from database)))))
711     (when inner-join
712       (write-string " INNER JOIN " *sql-stream*)
713       (output-sql inner-join database))
714     (when on
715       (write-string " ON " *sql-stream*)
716       (output-sql on database))
717     (when where
718       (let ((where-out (string-trim
719                         '(#\newline #\space #\tab #\return)
720                         (with-output-to-string (*sql-stream*)
721                           (let ((*in-subselect* t))
722                             (output-sql where database))))))
723         (when (> (length where-out) 0)
724           (write-string " WHERE " *sql-stream*)
725           (write-string where-out *sql-stream*))))
726     (when group-by
727       (write-string " GROUP BY " *sql-stream*)
728       (if (listp group-by)
729           (do ((order group-by (cdr order)))
730               ((null order))
731             (let ((item (car order)))
732               (typecase item
733                 (cons
734                  (output-sql (car item) database)
735                  (format *sql-stream* " ~A" (cadr item)))
736                 (t
737                  (output-sql item database)))
738               (when (cdr order)
739                 (write-char #\, *sql-stream*))))
740           (output-sql group-by database)))
741     (when having
742       (write-string " HAVING " *sql-stream*)
743       (output-sql having database))
744     (when order-by
745       (write-string " ORDER BY " *sql-stream*)
746       (if (listp order-by)
747           (do ((order order-by (cdr order)))
748               ((null order))
749             (let ((item (car order)))
750               (typecase item
751                 (cons
752                  (output-sql (car item) database)
753                  (format *sql-stream* " ~A" (cadr item)))
754                 (t
755                  (output-sql item database)))
756               (when (cdr order)
757                 (write-char #\, *sql-stream*))))
758           (output-sql order-by database)))
759     (when (and limit (not (eql :mssql (database-underlying-type database))))
760       (write-string " LIMIT " *sql-stream*)
761       (output-sql limit database))
762     (when offset
763       (write-string " OFFSET " *sql-stream*)
764       (output-sql offset database))
765     (when *in-subselect*
766       (write-string ")" *sql-stream*))
767     (when set-operation
768       (write-char #\Space *sql-stream*)
769       (output-sql set-operation database)))
770   t)
771
772 (defmethod output-sql ((query sql-object-query) database)
773   (declare (ignore database))
774   (with-slots (objects)
775       query
776     (when objects
777       (format *sql-stream* "(~{~A~^ ~})" objects))))
778
779
780 ;; INSERT
781
782 (defclass sql-insert (%sql-expression)
783   ((into
784     :initarg :into
785     :initform nil)
786    (attributes
787     :initarg :attributes
788     :initform nil)
789    (values
790     :initarg :values
791     :initform nil)
792    (query
793     :initarg :query
794     :initform nil))
795   (:documentation
796    "An SQL INSERT statement."))
797
798 (defmethod output-sql ((ins sql-insert) database)
799   (with-slots (into attributes values query)
800     ins
801     (write-string "INSERT INTO " *sql-stream*)
802     (output-sql
803      (typecase into
804        (string (sql-expression :table into))
805        (t into))
806      database)
807     (when attributes
808       (write-char #\Space *sql-stream*)
809       (output-sql attributes database))
810     (when values
811       (write-string " VALUES " *sql-stream*)
812       (output-sql values database))
813     (when query
814       (write-char #\Space *sql-stream*)
815       (output-sql query database)))
816   t)
817
818 ;; DELETE
819
820 (defclass sql-delete (%sql-expression)
821   ((from
822     :initarg :from
823     :initform nil)
824    (where
825     :initarg :where
826     :initform nil))
827   (:documentation
828    "An SQL DELETE statement."))
829
830 (defmethod output-sql ((stmt sql-delete) database)
831   (with-slots (from where)
832     stmt
833     (write-string "DELETE FROM " *sql-stream*)
834     (typecase from
835       ((or symbol string) (write-string (sql-escape from) *sql-stream*))
836       (t  (output-sql from database)))
837     (when where
838       (write-string " WHERE " *sql-stream*)
839       (output-sql where database)))
840   t)
841
842 ;; UPDATE
843
844 (defclass sql-update (%sql-expression)
845   ((table
846     :initarg :table
847     :initform nil)
848    (attributes
849     :initarg :attributes
850     :initform nil)
851    (values
852     :initarg :values
853     :initform nil)
854    (where
855     :initarg :where
856     :initform nil))
857   (:documentation "An SQL UPDATE statement."))
858
859 (defmethod output-sql ((expr sql-update) database)
860   (with-slots (table where attributes values)
861     expr
862     (flet ((update-assignments ()
863              (mapcar #'(lambda (a b)
864                          (make-instance 'sql-assignment-exp
865                                         :operator '=
866                                         :sub-expressions (list a b)))
867                      attributes values)))
868       (write-string "UPDATE " *sql-stream*)
869       (output-sql table database)
870       (write-string " SET " *sql-stream*)
871       (output-sql (apply #'vector (update-assignments)) database)
872       (when where
873         (write-string " WHERE " *sql-stream*)
874         (output-sql 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 " Type=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, recurively 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     (etypecase name
1143       (null nil)
1144       (string (%make-database-identifier name database))
1145       (symbol
1146        ;; if this is being used as a table, we should check
1147        ;; for a class with this name and use the identifier specified
1148        ;; on it
1149        (if (and find-class-p (setf cls (find-standard-db-class name)))
1150            (database-identifier cls)
1151            (%make-database-identifier name database)))
1152       (%database-identifier name)
1153       ;; we know how to deref this without further escaping
1154       (sql-ident-table
1155        (with-slots ((inner-name name) alias) name
1156          (if alias
1157              (flatten-id name)
1158              (database-identifier inner-name))))
1159       ;; if this is a single name we can derefence it
1160       (sql-ident-attribute
1161        (with-slots (qualifier (inner-name name)) name
1162          (if qualifier
1163              (flatten-id name)
1164              (database-identifier inner-name))))
1165       (sql-ident
1166        (with-slots ((inner-name name)) name
1167          (database-identifier inner-name)))
1168       ;; dont know how to handle this really :/
1169       (%sql-expression (flatten-id name))
1170       )))
1171