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