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