b54029e4b727121c4d299ab888f00cd4f5950eb6
[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)))
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) expr
246      ;; we do this as two runs so as not to emit confusing superflous parentheses
247      ;; The first loop renders all the child outputs so that we can skip anding with
248      ;; empty output (which causes sql errors)
249      ;; the next loop simply emits each sub-expression with the appropriate number of
250      ;; parens and operators
251      (flet ((trim (sub)
252               (string-trim +whitespace-chars+
253                            (with-output-to-string (*sql-stream*)
254                              (output-sql sub database)))))
255        (let ((str-subs (loop for sub in sub-expressions
256                              for str-sub = (trim sub)
257                            when (and str-sub (> (length str-sub) 0))
258                              collect str-sub)))
259          (case (length str-subs)
260            (0 nil)
261            (1 (write-string (first str-subs) *sql-stream*))
262            (t
263               (write-char #\( *sql-stream*)
264               (write-string (first str-subs) *sql-stream*)
265               (loop for str-sub in (rest str-subs)
266                     do
267                  (write-char #\Space *sql-stream*)
268                  (output-sql operator database)
269                  (write-char #\Space *sql-stream*)
270                  (write-string str-sub *sql-stream*))
271               (write-char #\) *sql-stream*))
272            ))))
273   t)
274
275 (defclass sql-upcase-like (sql-relational-exp)
276   ()
277   (:documentation "An SQL 'like' that upcases its arguments."))
278
279 (defmethod output-sql ((expr sql-upcase-like) database)
280   (flet ((write-term (term)
281            (write-string "upper(" *sql-stream*)
282            (output-sql term database)
283            (write-char #\) *sql-stream*)))
284     (with-slots (sub-expressions)
285       expr
286       (let ((subs (if (consp (car sub-expressions))
287                       (car sub-expressions)
288                       sub-expressions)))
289         (write-char #\( *sql-stream*)
290         (do ((sub subs (cdr sub)))
291             ((null (cdr sub)) (write-term (car sub)))
292           (write-term (car sub))
293           (write-string " LIKE " *sql-stream*))
294         (write-char #\) *sql-stream*))))
295   t)
296
297 (defclass sql-assignment-exp (sql-relational-exp)
298   ()
299   (:documentation "An SQL Assignment expression."))
300
301
302 (defmethod output-sql ((expr sql-assignment-exp) database)
303   (with-slots (operator sub-expressions)
304     expr
305     (do ((sub sub-expressions (cdr sub)))
306         ((null (cdr sub)) (output-sql (car sub) database))
307       (output-sql (car sub) database)
308       (write-char #\Space *sql-stream*)
309       (output-sql operator database)
310       (write-char #\Space *sql-stream*)))
311   t)
312
313 (defclass sql-value-exp (%sql-expression)
314   ((modifier
315     :initarg :modifier
316     :initform nil)
317    (components
318     :initarg :components
319     :initform nil))
320   (:documentation
321    "An SQL value expression.")
322   )
323
324 (defmethod collect-table-refs ((sql sql-value-exp))
325   (let ((tabs nil))
326     (if (listp (slot-value sql 'components))
327         (progn
328           (dolist (exp (slot-value sql 'components))
329             (let ((refs (collect-table-refs exp)))
330               (if refs (setf tabs (append refs tabs)))))
331           (remove-duplicates tabs
332                              :test (lambda (tab1 tab2)
333                                      (equal (slot-value tab1 'name)
334                                             (slot-value tab2 'name)))))
335         nil)))
336
337
338
339 (defmethod output-sql ((expr sql-value-exp) database)
340   (with-slots (modifier components)
341     expr
342     (if modifier
343         (progn
344           (write-char #\( *sql-stream*)
345           (output-sql modifier database)
346           (write-char #\Space *sql-stream*)
347           (output-sql components database)
348           (write-char #\) *sql-stream*))
349         (output-sql components database))))
350
351 (defclass sql-typecast-exp (sql-value-exp)
352   ()
353   (:documentation "An SQL typecast expression."))
354
355 (defmethod output-sql ((expr sql-typecast-exp) database)
356   (with-slots (components)
357     expr
358     (output-sql components database)))
359
360 (defmethod collect-table-refs ((sql sql-typecast-exp))
361   (when (slot-value sql 'components)
362     (collect-table-refs (slot-value sql 'components))))
363
364 (defclass sql-function-exp (%sql-expression)
365   ((name
366     :initarg :name
367     :initform nil)
368    (args
369     :initarg :args
370     :initform nil))
371   (:documentation
372    "An SQL function expression."))
373
374 (defmethod collect-table-refs ((sql sql-function-exp))
375   (let ((tabs nil))
376     (dolist (exp (slot-value sql 'args))
377       (let ((refs (collect-table-refs exp)))
378         (if refs (setf tabs (append refs tabs)))))
379     (remove-duplicates tabs
380                        :test (lambda (tab1 tab2)
381                                (equal (slot-value tab1 'name)
382                                       (slot-value tab2 'name))))))
383 (defvar *in-subselect* nil)
384
385 (defmethod output-sql ((expr sql-function-exp) database)
386   (with-slots (name args)
387     expr
388     (output-sql name database)
389     (let ((*in-subselect* nil)) ;; aboid double parens
390       (when args (output-sql args database))))
391   t)
392
393
394 (defclass sql-between-exp (sql-function-exp)
395   ()
396   (:documentation "An SQL between expression."))
397
398 (defmethod output-sql ((expr sql-between-exp) database)
399   (with-slots (args)
400       expr
401     (output-sql (first args) database)
402     (write-string " BETWEEN " *sql-stream*)
403     (output-sql (second args) database)
404     (write-string " AND " *sql-stream*)
405     (output-sql (third args) database))
406   t)
407
408 (defclass sql-query-modifier-exp (%sql-expression)
409   ((modifier :initarg :modifier :initform nil)
410    (components :initarg :components :initform nil))
411   (:documentation "An SQL query modifier expression."))
412
413 (defmethod output-sql ((expr sql-query-modifier-exp) database)
414   (with-slots (modifier components)
415       expr
416     (output-sql modifier database)
417     (write-string " " *sql-stream*)
418     (output-sql (car components) database)
419     (when components
420       (mapc #'(lambda (comp)
421                 (write-string ", " *sql-stream*)
422                 (output-sql comp database))
423             (cdr components))))
424   t)
425
426 (defclass sql-set-exp (%sql-expression)
427   ((operator
428     :initarg :operator
429     :initform nil)
430    (sub-expressions
431     :initarg :sub-expressions
432     :initform nil))
433   (:documentation "An SQL set expression."))
434
435 (defmethod collect-table-refs ((sql sql-set-exp))
436   (let ((tabs nil))
437     (dolist (exp (slot-value sql 'sub-expressions))
438       (let ((refs (collect-table-refs exp)))
439         (if refs (setf tabs (append refs tabs)))))
440     (remove-duplicates tabs
441                        :test (lambda (tab1 tab2)
442                                (equal (slot-value tab1 'name)
443                                       (slot-value tab2 'name))))))
444
445 (defmethod output-sql ((expr sql-set-exp) database)
446   (with-slots (operator sub-expressions)
447       expr
448     (let ((subs (if (consp (car sub-expressions))
449                     (car sub-expressions)
450                     sub-expressions)))
451       (when (= (length subs) 1)
452         (output-sql operator database)
453         (write-char #\Space *sql-stream*))
454       (do ((sub subs (cdr sub)))
455           ((null (cdr sub)) (output-sql (car sub) database))
456         (output-sql (car sub) database)
457         (write-char #\Space *sql-stream*)
458         (output-sql operator database)
459         (write-char #\Space *sql-stream*))))
460   t)
461
462 (defclass sql-query (%sql-expression)
463   ((selections
464     :initarg :selections
465     :initform nil)
466    (all
467     :initarg :all
468     :initform nil)
469    (flatp
470     :initarg :flatp
471     :initform nil)
472    (set-operation
473     :initarg :set-operation
474     :initform nil)
475    (distinct
476     :initarg :distinct
477     :initform nil)
478    (from
479     :initarg :from
480     :initform nil)
481    (where
482     :initarg :where
483     :initform nil)
484    (group-by
485     :initarg :group-by
486     :initform nil)
487    (having
488     :initarg :having
489     :initform nil)
490    (limit
491     :initarg :limit
492     :initform nil)
493    (offset
494     :initarg :offset
495     :initform nil)
496    (order-by
497     :initarg :order-by
498     :initform nil)
499    (inner-join
500     :initarg :inner-join
501     :initform nil)
502    (on
503     :initarg :on
504     :initform nil))
505   (:documentation "An SQL SELECT query."))
506
507 (defclass sql-object-query (%sql-expression)
508   ((objects
509     :initarg :objects
510     :initform nil)
511    (flatp
512     :initarg :flatp
513     :initform nil)
514    (exp
515     :initarg :exp
516     :initform nil)
517    (refresh
518     :initarg :refresh
519     :initform nil)))
520
521 (defmethod collect-table-refs ((sql sql-query))
522   (remove-duplicates (collect-table-refs (slot-value sql 'where))
523                      :test (lambda (tab1 tab2)
524                              (equal (slot-value tab1 'name)
525                                     (slot-value tab2 'name)))))
526
527 (defvar *select-arguments*
528   '(:all :database :distinct :flatp :from :group-by :having :order-by
529     :set-operation :where :offset :limit :inner-join :on
530     ;; below keywords are not a SQL argument, but these keywords may terminate select
531     :caching :refresh))
532
533 (defun query-arg-p (sym)
534   (member sym *select-arguments*))
535
536 (defun query-get-selections (select-args)
537   "Return two values: the list of select-args up to the first keyword,
538 uninclusive, and the args from that keyword to the end."
539   (let ((first-key-arg (position-if #'query-arg-p select-args)))
540     (if first-key-arg
541         (values (subseq select-args 0 first-key-arg)
542                 (subseq select-args first-key-arg))
543         select-args)))
544
545 (defun make-query (&rest args)
546   (flet ((select-objects (target-args)
547            (and target-args
548                 (every #'(lambda (arg)
549                            (and (symbolp arg)
550                                 (find-class arg nil)))
551                        target-args))))
552     (multiple-value-bind (selections arglist)
553         (query-get-selections args)
554       (if (select-objects selections)
555           (destructuring-bind (&key flatp refresh &allow-other-keys) arglist
556             (make-instance 'sql-object-query :objects selections
557                            :flatp flatp :refresh refresh
558                            :exp arglist))
559           (destructuring-bind (&key all flatp set-operation distinct from where
560                                     group-by having order-by
561                                     offset limit inner-join on &allow-other-keys)
562               arglist
563             (if (null selections)
564                 (error "No target columns supplied to select statement."))
565             (if (null from)
566                 (error "No source tables supplied to select statement."))
567             (make-instance 'sql-query :selections selections
568                            :all all :flatp flatp :set-operation set-operation
569                            :distinct distinct :from from :where where
570                            :limit limit :offset offset
571                            :group-by group-by :having having :order-by order-by
572                            :inner-join inner-join :on on))))))
573
574 (defmethod output-sql ((query sql-query) database)
575   (with-slots (distinct selections from where group-by having order-by
576                         limit offset inner-join on all set-operation)
577       query
578     (when *in-subselect*
579       (write-string "(" *sql-stream*))
580     (write-string "SELECT " *sql-stream*)
581     (when all
582       (write-string "ALL " *sql-stream*))
583     (when (and distinct (not all))
584       (write-string "DISTINCT " *sql-stream*)
585       (unless (eql t distinct)
586         (write-string "ON " *sql-stream*)
587         (output-sql distinct database)
588         (write-char #\Space *sql-stream*)))
589     (let ((*in-subselect* t))
590       (output-sql (apply #'vector selections) database))
591     (when from
592       (write-string " FROM " *sql-stream*)
593       (flet ((ident-table-equal (a b)
594                (and (if (and (eql (type-of a) 'sql-ident-table)
595                              (eql (type-of b) 'sql-ident-table))
596                         (string-equal (slot-value a 'alias)
597                                       (slot-value b 'alias))
598                         t)
599                     (string-equal (sql-escape (slot-value a 'name))
600                                   (sql-escape (slot-value b 'name))))))
601         (typecase from
602           (list (output-sql (apply #'vector
603                                    (remove-duplicates from
604                                                       :test #'ident-table-equal))
605                             database))
606           (string (format *sql-stream* "~s" (sql-escape from)))
607           (t (let ((*in-subselect* t))
608                (output-sql from database))))))
609     (when inner-join
610       (write-string " INNER JOIN " *sql-stream*)
611       (output-sql inner-join database))
612     (when on
613       (write-string " ON " *sql-stream*)
614       (output-sql on database))
615     (when where
616       (write-string " WHERE " *sql-stream*)
617       (let ((*in-subselect* t))
618         (output-sql where database)))
619     (when group-by
620       (write-string " GROUP BY " *sql-stream*)
621       (if (listp group-by)
622           (do ((order group-by (cdr order)))
623               ((null order))
624             (let ((item (car order)))
625               (typecase item
626                 (cons
627                  (output-sql (car item) database)
628                  (format *sql-stream* " ~A" (cadr item)))
629                 (t
630                  (output-sql item database)))
631               (when (cdr order)
632                 (write-char #\, *sql-stream*))))
633           (output-sql group-by database)))
634     (when having
635       (write-string " HAVING " *sql-stream*)
636       (output-sql having database))
637     (when order-by
638       (write-string " ORDER BY " *sql-stream*)
639       (if (listp order-by)
640           (do ((order order-by (cdr order)))
641               ((null order))
642             (let ((item (car order)))
643               (typecase item
644                 (cons
645                  (output-sql (car item) database)
646                  (format *sql-stream* " ~A" (cadr item)))
647                 (t
648                  (output-sql item database)))
649               (when (cdr order)
650                 (write-char #\, *sql-stream*))))
651           (output-sql order-by database)))
652     (when limit
653       (write-string " LIMIT " *sql-stream*)
654       (output-sql limit database))
655     (when offset
656       (write-string " OFFSET " *sql-stream*)
657       (output-sql offset database))
658     (when *in-subselect*
659       (write-string ")" *sql-stream*))
660     (when set-operation
661       (write-char #\Space *sql-stream*)
662       (output-sql set-operation database)))
663   t)
664
665 (defmethod output-sql ((query sql-object-query) database)
666   (declare (ignore database))
667   (with-slots (objects)
668       query
669     (when objects
670       (format *sql-stream* "(~{~A~^ ~})" objects))))
671
672
673 ;; INSERT
674
675 (defclass sql-insert (%sql-expression)
676   ((into
677     :initarg :into
678     :initform nil)
679    (attributes
680     :initarg :attributes
681     :initform nil)
682    (values
683     :initarg :values
684     :initform nil)
685    (query
686     :initarg :query
687     :initform nil))
688   (:documentation
689    "An SQL INSERT statement."))
690
691 (defmethod output-sql ((ins sql-insert) database)
692   (with-slots (into attributes values query)
693     ins
694     (write-string "INSERT INTO " *sql-stream*)
695     (output-sql
696      (typecase into
697        (string (sql-expression :table into))
698        (t into))
699      database)
700     (when attributes
701       (write-char #\Space *sql-stream*)
702       (output-sql attributes database))
703     (when values
704       (write-string " VALUES " *sql-stream*)
705       (output-sql values database))
706     (when query
707       (write-char #\Space *sql-stream*)
708       (output-sql query database)))
709   t)
710
711 ;; DELETE
712
713 (defclass sql-delete (%sql-expression)
714   ((from
715     :initarg :from
716     :initform nil)
717    (where
718     :initarg :where
719     :initform nil))
720   (:documentation
721    "An SQL DELETE statement."))
722
723 (defmethod output-sql ((stmt sql-delete) database)
724   (with-slots (from where)
725     stmt
726     (write-string "DELETE FROM " *sql-stream*)
727     (typecase from
728       ((or symbol string) (write-string (sql-escape from) *sql-stream*))
729       (t  (output-sql from database)))
730     (when where
731       (write-string " WHERE " *sql-stream*)
732       (output-sql where database)))
733   t)
734
735 ;; UPDATE
736
737 (defclass sql-update (%sql-expression)
738   ((table
739     :initarg :table
740     :initform nil)
741    (attributes
742     :initarg :attributes
743     :initform nil)
744    (values
745     :initarg :values
746     :initform nil)
747    (where
748     :initarg :where
749     :initform nil))
750   (:documentation "An SQL UPDATE statement."))
751
752 (defmethod output-sql ((expr sql-update) database)
753   (with-slots (table where attributes values)
754     expr
755     (flet ((update-assignments ()
756              (mapcar #'(lambda (a b)
757                          (make-instance 'sql-assignment-exp
758                                         :operator '=
759                                         :sub-expressions (list a b)))
760                      attributes values)))
761       (write-string "UPDATE " *sql-stream*)
762       (output-sql table database)
763       (write-string " SET " *sql-stream*)
764       (output-sql (apply #'vector (update-assignments)) database)
765       (when where
766         (write-string " WHERE " *sql-stream*)
767         (output-sql where database))))
768   t)
769
770 ;; CREATE TABLE
771
772 (defclass sql-create-table (%sql-expression)
773   ((name
774     :initarg :name
775     :initform nil)
776    (columns
777     :initarg :columns
778     :initform nil)
779    (modifiers
780     :initarg :modifiers
781     :initform nil)
782    (transactions
783     :initarg :transactions
784     :initform nil))
785   (:documentation
786    "An SQL CREATE TABLE statement."))
787
788 ;; Here's a real warhorse of a function!
789
790 (declaim (inline listify))
791 (defun listify (x)
792   (if (atom x)
793       (list x)
794       x))
795
796 (defmethod output-sql ((stmt sql-create-table) database)
797   (flet ((output-column (column-spec)
798            (destructuring-bind (name type &optional db-type &rest constraints)
799                column-spec
800              (let ((type (listify type)))
801                (output-sql name database)
802                (write-char #\Space *sql-stream*)
803                (write-string
804                 (if (stringp db-type) db-type ; override definition
805                   (database-get-type-specifier (car type) (cdr type) database
806                                                (database-underlying-type database)))
807                 *sql-stream*)
808                (let ((constraints (database-constraint-statement
809                                    (if (and db-type (symbolp db-type))
810                                        (cons db-type constraints)
811                                        constraints)
812                                    database)))
813                  (when constraints
814                    (write-string " " *sql-stream*)
815                    (write-string constraints *sql-stream*)))))))
816     (with-slots (name columns modifiers transactions)
817       stmt
818       (write-string "CREATE TABLE " *sql-stream*)
819       (etypecase name
820           (string (format *sql-stream* "~s" (sql-escape name)))
821           (symbol (write-string (sql-escape name) *sql-stream*))
822           (sql-ident (output-sql name database)))
823       (write-string " (" *sql-stream*)
824       (do ((column columns (cdr column)))
825           ((null (cdr column))
826            (output-column (car column)))
827         (output-column (car column))
828         (write-string ", " *sql-stream*))
829       (when modifiers
830         (do ((modifier (listify modifiers) (cdr modifier)))
831             ((null modifier))
832           (write-string ", " *sql-stream*)
833           (write-string (car modifier) *sql-stream*)))
834       (write-char #\) *sql-stream*)
835       (when (and (eq :mysql (database-underlying-type database))
836                  transactions
837                  (db-type-transaction-capable? :mysql database))
838         (write-string " Type=InnoDB" *sql-stream*))))
839   t)
840
841
842 ;; CREATE VIEW
843
844 (defclass sql-create-view (%sql-expression)
845   ((name :initarg :name :initform nil)
846    (column-list :initarg :column-list :initform nil)
847    (query :initarg :query :initform nil)
848    (with-check-option :initarg :with-check-option :initform nil))
849   (:documentation "An SQL CREATE VIEW statement."))
850
851 (defmethod output-sql ((stmt sql-create-view) database)
852   (with-slots (name column-list query with-check-option) stmt
853     (write-string "CREATE VIEW " *sql-stream*)
854     (output-sql name database)
855     (when column-list (write-string " " *sql-stream*)
856           (output-sql (listify column-list) database))
857     (write-string " AS " *sql-stream*)
858     (output-sql query database)
859     (when with-check-option (write-string " WITH CHECK OPTION" *sql-stream*))))
860
861
862 ;;
863 ;; DATABASE-OUTPUT-SQL
864 ;;
865
866 (defmethod database-output-sql ((str string) database)
867   (declare (optimize (speed 3) (safety 1)
868                      #+cmu (extensions:inhibit-warnings 3)))
869   (let ((len (length str)))
870     (declare (type fixnum len))
871     (cond ((zerop len)
872            +empty-string+)
873           ((and (null (position #\' str))
874                 (null (position #\\ str)))
875            (concatenate 'string "'" str "'"))
876           (t
877            (let ((buf (make-string (+ (* len 2) 2) :initial-element #\')))
878              (declare (simple-string buf))
879              (do* ((i 0 (incf i))
880                    (j 1 (incf j)))
881                   ((= i len) (subseq buf 0 (1+ j)))
882                (declare (type fixnum i j))
883                (let ((char (aref str i)))
884                  (declare (character char))
885                  (cond ((char= char #\')
886                         (setf (aref buf j) #\')
887                         (incf j)
888                         (setf (aref buf j) #\'))
889                        ((and (char= char #\\)
890                              ;; MTP: only escape backslash with pgsql/mysql
891                              (member (database-underlying-type database)
892                                      '(:postgresql :mysql)
893                                      :test #'eq))
894                         (setf (aref buf j) #\\)
895                         (incf j)
896                         (setf (aref buf j) #\\))
897                        (t
898                         (setf (aref buf j) char))))))))))
899
900 (let ((keyword-package (symbol-package :foo)))
901   (defmethod database-output-sql ((sym symbol) database)
902   (if (null sym)
903       +null-string+
904     (if (equal (symbol-package sym) keyword-package)
905         (concatenate 'string "'" (string sym) "'")
906       (symbol-name sym)))))
907
908 (defmethod database-output-sql ((tee (eql t)) database)
909   (if database
910       (let ((val (database-output-sql-as-type 'boolean t database (database-type database))))
911         (when val
912           (typecase val
913             (string (format nil "'~A'" val))
914             (integer (format nil "~A" val)))))
915     "'Y'"))
916
917 #+nil(defmethod database-output-sql ((tee (eql t)) database)
918   (declare (ignore database))
919   "'Y'")
920
921 (defmethod database-output-sql ((num number) database)
922   (declare (ignore database))
923   (number-to-sql-string num))
924
925 (defmethod database-output-sql ((arg list) database)
926   (if (null arg)
927       +null-string+
928       (format nil "(~{~A~^,~})" (mapcar #'(lambda (val)
929                                             (sql-output val database))
930                                         arg))))
931
932 (defmethod database-output-sql ((arg vector) database)
933   (format nil "~{~A~^,~}" (map 'list #'(lambda (val)
934                                          (sql-output val database))
935                                arg)))
936
937 (defmethod output-sql-hash-key ((arg vector) database)
938   (list 'vector (map 'list (lambda (arg)
939                              (or (output-sql-hash-key arg database)
940                                  (return-from output-sql-hash-key nil)))
941                      arg)))
942
943 (defmethod database-output-sql ((self wall-time) database)
944   (declare (ignore database))
945   (db-timestring self))
946
947 (defmethod database-output-sql ((self date) database)
948   (declare (ignore database))
949   (db-datestring self))
950
951 (defmethod database-output-sql ((self duration) database)
952   (declare (ignore database))
953   (format nil "'~a'" (duration-timestring self)))
954
955 #+ignore
956 (defmethod database-output-sql ((self money) database)
957   (database-output-sql (slot-value self 'odcl::units) database))
958
959 (defmethod database-output-sql (thing database)
960   (if (or (null thing)
961           (eq 'null thing))
962       +null-string+
963     (error 'sql-user-error
964            :message
965            (format nil
966                    "No type conversion to SQL for ~A is defined for DB ~A."
967                    (type-of thing) (type-of database)))))
968
969
970 ;;
971 ;; Column constraint types and conversion to SQL
972 ;;
973
974 (defparameter *constraint-types*
975   (list
976    (cons (symbol-name-default-case "NOT-NULL") "NOT NULL")
977    (cons (symbol-name-default-case "PRIMARY-KEY") "PRIMARY KEY")
978    (cons (symbol-name-default-case "NOT") "NOT")
979    (cons (symbol-name-default-case "NULL") "NULL")
980    (cons (symbol-name-default-case "PRIMARY") "PRIMARY")
981    (cons (symbol-name-default-case "KEY") "KEY")
982    (cons (symbol-name-default-case "UNSIGNED") "UNSIGNED")
983    (cons (symbol-name-default-case "ZEROFILL") "ZEROFILL")
984    (cons (symbol-name-default-case "AUTO-INCREMENT") "AUTO_INCREMENT")
985    (cons (symbol-name-default-case "UNIQUE") "UNIQUE")))
986
987 (defmethod database-constraint-statement (constraint-list database)
988   (declare (ignore database))
989   (make-constraints-description constraint-list))
990
991 (defun make-constraints-description (constraint-list)
992   (if constraint-list
993       (let ((string ""))
994         (do ((constraint constraint-list (cdr constraint)))
995             ((null constraint) string)
996           (let ((output (assoc (symbol-name (car constraint))
997                                *constraint-types*
998                                :test #'equal)))
999             (if (null output)
1000                 (error 'sql-user-error
1001                        :message (format nil "unsupported column constraint '~A'"
1002                                         constraint))
1003                 (setq string (concatenate 'string string (cdr output))))
1004             (if (< 1 (length constraint))
1005                 (setq string (concatenate 'string string " "))))))))
1006