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