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