r8941: add functions, not yet used
[clsql.git] / sql / classes.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 (defvar *default-schema* "UNCOMMONSQL")
26
27 (defvar *object-schemas* (make-hash-table :test #'equal)
28   "Hash of schema name to class constituent lists.")
29
30 (defun in-schema (schemaname)
31   (setf *default-schema* schemaname))
32
33 (defun sql-output (sql-expr &optional database)
34   (progv '(*sql-stream*)
35       `(,(make-string-output-stream))
36     (output-sql sql-expr database)
37     (get-output-stream-string *sql-stream*)))
38
39
40 (defclass %sql-expression ()
41   ())
42
43 (defmethod output-sql ((expr %sql-expression) &optional
44                        (database *default-database*))
45   (declare (ignore database))
46   (write-string +null-string+ *sql-stream*))
47
48 (defmethod print-object ((self %sql-expression) stream)
49   (print-unreadable-object
50    (self stream :type t)
51    (write-string (sql-output self) stream)))
52
53 ;; For straight up strings
54
55 (defclass sql (%sql-expression)
56   ((text
57     :initarg :string
58     :initform ""))
59   (:documentation "A literal SQL expression."))
60
61 (defmethod make-load-form ((sql sql) &optional environment)
62   (declare (ignore environment))
63   (with-slots (text)
64     sql
65     `(make-instance 'sql :string ',text)))
66
67 (defmethod output-sql ((expr sql) &optional (database *default-database*))
68   (declare (ignore database))
69   (write-string (slot-value expr 'text) *sql-stream*)
70   t)
71
72 (defmethod print-object ((ident sql) stream)
73   (format stream "#<~S \"~A\">"
74           (type-of ident)
75           (sql-output ident)))
76
77 ;; For SQL Identifiers of generic type
78 (defclass sql-ident (%sql-expression)
79   ((name
80     :initarg :name
81     :initform "NULL"))
82   (:documentation "An SQL identifer."))
83
84 (defmethod make-load-form ((sql sql-ident) &optional environment)
85   (declare (ignore environment))
86   (with-slots (name)
87     sql
88     `(make-instance 'sql-ident :name ',name)))
89
90 (defvar *output-hash* (make-hash-table :test #'equal))
91
92 (defmethod output-sql-hash-key (expr &optional (database *default-database*))
93   (declare (ignore expr database))
94   nil)
95
96 (defmethod output-sql :around ((sql t) &optional (database *default-database*))
97   (declare (ignore database))
98   (let* ((hash-key (output-sql-hash-key sql))
99          (hash-value (when hash-key (gethash hash-key *output-hash*))))
100     (cond ((and hash-key hash-value)
101            (write-string hash-value *sql-stream*))
102           (hash-key
103            (let ((*sql-stream* (make-string-output-stream)))
104              (call-next-method)
105              (setf hash-value (get-output-stream-string *sql-stream*))
106              (setf (gethash hash-key *output-hash*) hash-value))
107            (write-string hash-value *sql-stream*))
108           (t
109            (call-next-method)))))
110
111 (defmethod output-sql ((expr sql-ident) &optional
112                        (database *default-database*))
113   (declare (ignore database))
114   (with-slots (name)
115     expr
116     (etypecase name
117       (string
118        (write-string name *sql-stream*))
119       (symbol
120        (write-string (symbol-name name) *sql-stream*)))
121     t))
122
123 ;; For SQL Identifiers for attributes
124
125 (defclass sql-ident-attribute (sql-ident)
126   ((qualifier
127     :initarg :qualifier
128     :initform "NULL")
129    (type
130     :initarg :type
131     :initform "NULL")
132    (params
133     :initarg :params
134     :initform nil))
135   (:documentation "An SQL Attribute identifier."))
136
137 (defmethod collect-table-refs (sql)
138   (declare (ignore sql))
139   nil)
140
141 (defmethod collect-table-refs ((sql sql-ident-attribute))
142   (let ((qual (slot-value sql 'qualifier)))
143     (if (and qual (symbolp (slot-value sql 'qualifier)))
144         (list (make-instance 'sql-ident-table :name
145                              (slot-value sql 'qualifier))))))
146
147 (defmethod make-load-form ((sql sql-ident-attribute) &optional environment)
148   (declare (ignore environment))
149   (with-slots (qualifier type name)
150     sql
151     `(make-instance 'sql-ident-attribute :name ',name
152       :qualifier ',qualifier
153       :type ',type)))
154
155 (defmethod output-sql ((expr sql-ident-attribute) &optional
156                        (database *default-database*))
157   (declare (ignore database))
158   (with-slots (qualifier name type params)
159     expr
160     (if (and name (not qualifier) (not type))
161         (write-string (sql-escape (symbol-name name)) *sql-stream*)
162         (format *sql-stream* "~@[~A.~]~A~@[ ~A~]"
163                 (if qualifier (sql-escape qualifier) qualifier)
164                 (sql-escape name)
165                 type))
166     t))
167
168 (defmethod output-sql-hash-key ((expr sql-ident-attribute) &optional
169                                 (database *default-database*))
170   (declare (ignore database))
171   (with-slots (qualifier name type params)
172     expr
173     (list 'sql-ident-attribute qualifier name type params)))
174
175 ;; For SQL Identifiers for tables
176 (defclass sql-ident-table (sql-ident)
177   ((alias
178     :initarg :table-alias :initform nil))
179   (:documentation "An SQL table identifier."))
180
181 (defmethod make-load-form ((sql sql-ident-table) &optional environment)
182   (declare (ignore environment))
183   (with-slots (alias name)
184     sql
185     `(make-instance 'sql-ident-table :name name :alias ',alias)))
186
187 (defun generate-sql (expr)
188   (let ((*sql-stream* (make-string-output-stream)))
189     (output-sql expr)
190     (get-output-stream-string *sql-stream*)))
191
192 (defmethod output-sql ((expr sql-ident-table) &optional
193                        (database *default-database*))
194   (declare (ignore database))
195   (with-slots (name alias)
196     expr
197     (if (null alias)
198         (write-string (sql-escape (symbol-name name)) *sql-stream*)
199         (progn
200           (write-string (sql-escape (symbol-name name)) *sql-stream*)
201           (write-char #\Space *sql-stream*)
202           (format *sql-stream* "~s" alias))))
203   t)
204
205 #|
206 (defmethod database-output-sql ((self duration) database)
207   (declare (ignore database))
208   (format nil "'~a'" (duration-timestring self)))
209
210 (defmethod database-output-sql ((self money) database)
211   (database-output-sql (slot-value self 'odcl::units) database))
212 |#
213
214
215 (defmethod output-sql-hash-key ((expr sql-ident-table) &optional
216                                 (database *default-database*))
217   (declare (ignore database))
218   (with-slots (name alias)
219     expr
220     (list 'sql-ident-table name alias)))
221
222 (defclass sql-relational-exp (%sql-expression)
223   ((operator
224     :initarg :operator
225     :initform nil)
226    (sub-expressions
227     :initarg :sub-expressions
228     :initform nil))
229   (:documentation "An SQL relational expression."))
230
231 (defmethod collect-table-refs ((sql sql-relational-exp))
232   (let ((tabs nil))
233     (dolist (exp (slot-value sql 'sub-expressions))
234       (let ((refs (collect-table-refs exp)))
235         (if refs (setf tabs (append refs tabs)))))
236     (remove-duplicates tabs
237                        :test (lambda (tab1 tab2)
238                                (equal (slot-value tab1 'name)
239                                       (slot-value tab2 'name))))))
240
241
242
243
244 ;; Write SQL for relational operators (like 'AND' and 'OR').
245 ;; should do arity checking of subexpressions
246
247 (defmethod output-sql ((expr sql-relational-exp) &optional
248                        (database *default-database*))
249   (with-slots (operator sub-expressions)
250     expr
251     (let ((subs (if (consp (car sub-expressions))
252                     (car sub-expressions)
253                     sub-expressions)))
254       (write-char #\( *sql-stream*)
255       (do ((sub subs (cdr sub)))
256           ((null (cdr sub)) (output-sql (car sub) database))
257         (output-sql (car sub) database)
258         (write-char #\Space *sql-stream*)
259         (output-sql operator database)
260         (write-char #\Space *sql-stream*))
261       (write-char #\) *sql-stream*)))
262   t)
263
264 (defclass sql-upcase-like (sql-relational-exp)
265   ()
266   (:documentation "An SQL 'like' that upcases its arguments."))
267   
268 ;; Write SQL for relational operators (like 'AND' and 'OR').
269 ;; should do arity checking of subexpressions
270   
271 (defmethod output-sql ((expr sql-upcase-like) &optional
272                        (database *default-database*))
273   (flet ((write-term (term)
274            (write-string "upper(" *sql-stream*)
275            (output-sql term database)
276            (write-char #\) *sql-stream*)))
277     (with-slots (sub-expressions)
278       expr
279       (let ((subs (if (consp (car sub-expressions))
280                       (car sub-expressions)
281                       sub-expressions)))
282         (write-char #\( *sql-stream*)
283         (do ((sub subs (cdr sub)))
284             ((null (cdr sub)) (write-term (car sub)))
285           (write-term (car sub))
286           (write-string " LIKE " *sql-stream*))
287         (write-char #\) *sql-stream*))))
288   t)
289
290 (defclass sql-assignment-exp (sql-relational-exp)
291   ()
292   (:documentation "An SQL Assignment expression."))
293
294
295 (defmethod output-sql ((expr sql-assignment-exp) &optional
296                        (database *default-database*))
297   (with-slots (operator sub-expressions)
298     expr
299     (do ((sub sub-expressions (cdr sub)))
300         ((null (cdr sub)) (output-sql (car sub) database))
301       (output-sql (car sub) database)
302       (write-char #\Space *sql-stream*)
303       (output-sql operator database)
304       (write-char #\Space *sql-stream*)))
305   t)
306
307 (defclass sql-value-exp (%sql-expression)
308   ((modifier
309     :initarg :modifier
310     :initform nil)
311    (components
312     :initarg :components
313     :initform nil))
314   (:documentation
315    "An SQL value expression.")
316   )
317
318 (defmethod collect-table-refs ((sql sql-value-exp))
319   (let ((tabs nil))
320     (if (listp (slot-value sql 'components))
321         (progn
322           (dolist (exp (slot-value sql 'components))
323             (let ((refs (collect-table-refs exp)))
324               (if refs (setf tabs (append refs tabs)))))
325           (remove-duplicates tabs
326                              :test (lambda (tab1 tab2)
327                                      (equal (slot-value tab1 'name)
328                                             (slot-value tab2 'name)))))
329         nil)))
330
331
332
333 (defmethod output-sql ((expr sql-value-exp) &optional
334                        (database *default-database*))
335   (with-slots (modifier components)
336     expr
337     (if modifier
338         (progn
339           (write-char #\( *sql-stream*)
340           (output-sql modifier database)
341           (write-char #\Space *sql-stream*)
342           (output-sql components database)
343           (write-char #\) *sql-stream*))
344         (output-sql components database))))
345
346 (defclass sql-typecast-exp (sql-value-exp)
347   ()
348   (:documentation "An SQL typecast expression."))
349
350 (defmethod output-sql ((expr sql-typecast-exp) &optional
351                        (database *default-database*))
352   (database-output-sql expr database))
353
354 (defmethod database-output-sql ((expr sql-typecast-exp) database)
355   (with-slots (components)
356     expr
357     (output-sql components database)))
358
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 'components))
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
384 (defmethod output-sql ((expr sql-function-exp) &optional
385                        (database *default-database*))
386   (with-slots (name args)
387     expr
388     (output-sql name database)
389     (when args (output-sql args database)))
390   t)
391
392 (defclass sql-query (%sql-expression)
393   ((selections
394     :initarg :selections
395     :initform nil)
396    (all
397     :initarg :all
398     :initform nil)
399    (flatp
400     :initarg :flatp
401     :initform nil)
402    (set-operation
403     :initarg :set-operation
404     :initform nil)
405    (distinct
406     :initarg :distinct
407     :initform nil)
408    (from
409     :initarg :from
410     :initform nil)
411    (where
412     :initarg :where
413     :initform nil)
414    (group-by
415     :initarg :group-by
416     :initform nil)
417    (having
418     :initarg :having
419     :initform nil)
420    (limit
421     :initarg :limit
422     :initform nil)
423    (offset
424     :initarg :offset
425     :initform nil)
426    (order-by
427     :initarg :order-by
428     :initform nil)
429    (order-by-descending
430     :initarg :order-by-descending
431     :initform nil))
432   (:documentation "An SQL SELECT query."))
433
434 (defmethod collect-table-refs ((sql sql-query))
435   (remove-duplicates (collect-table-refs (slot-value sql 'where))
436                      :test (lambda (tab1 tab2)
437                              (equal (slot-value tab1 'name)
438                                     (slot-value tab2 'name)))))
439
440 (defvar *select-arguments*
441   '(:all :database :distinct :flatp :from :group-by :having :order-by
442     :order-by-descending :set-operation :where :offset :limit))
443
444 (defun query-arg-p (sym)
445   (member sym *select-arguments*))
446
447 (defun query-get-selections (select-args)
448   "Return two values: the list of select-args up to the first keyword,
449 uninclusive, and the args from that keyword to the end."
450   (let ((first-key-arg (position-if #'query-arg-p select-args)))
451     (if first-key-arg
452         (values (subseq select-args 0 first-key-arg)
453                 (subseq select-args first-key-arg))
454         select-args)))
455
456 (defmethod make-query (&rest args)
457   (multiple-value-bind (selections arglist)
458       (query-get-selections args)
459     (destructuring-bind (&key all flatp set-operation distinct from where
460                               group-by having order-by order-by-descending
461                               offset limit &allow-other-keys)
462         arglist
463       (if (null selections)
464           (error "No target columns supplied to select statement."))
465       (if (null from)
466           (error "No source tables supplied to select statement."))
467       (make-instance 'sql-query :selections selections
468                      :all all :flatp flatp :set-operation set-operation
469                      :distinct distinct :from from :where where
470                      :limit limit :offset offset
471                      :group-by group-by :having having :order-by order-by
472                      :order-by-descending order-by-descending))))
473
474 (defvar *in-subselect* nil)
475
476 (defmethod output-sql ((query sql-query) &optional
477                        (database *default-database*))
478   (with-slots (distinct selections from where group-by having order-by
479                         order-by-descending limit offset)
480       query
481     (when *in-subselect*
482       (write-string "(" *sql-stream*))
483     (write-string "SELECT " *sql-stream*)
484     (when distinct
485       (write-string "DISTINCT " *sql-stream*)
486       (unless (eql t distinct)
487         (write-string "ON " *sql-stream*)
488         (output-sql distinct database)
489         (write-char #\Space *sql-stream*)))
490     (output-sql (apply #'vector selections) database)
491     (write-string " FROM " *sql-stream*)
492     (if (listp from)
493         (output-sql (apply #'vector from) database)
494         (output-sql from database))
495     (when where
496       (write-string " WHERE " *sql-stream*)
497       (let ((*in-subselect* t))
498         (output-sql where database)))
499     (when group-by
500       (write-string " GROUP BY " *sql-stream*)
501       (output-sql group-by database))
502     (when having
503       (write-string " HAVING " *sql-stream*)
504       (output-sql having database))
505     (when order-by
506       (write-string " ORDER BY " *sql-stream*)
507       (if (listp order-by)
508           (do ((order order-by (cdr order)))
509               ((null order))
510             (output-sql (car order) database)
511             (when (cdr order)
512               (write-char #\, *sql-stream*)))
513           (output-sql order-by database)))
514     (when order-by-descending
515       (write-string " ORDER BY " *sql-stream*)
516       (if (listp order-by-descending)
517           (do ((order order-by-descending (cdr order)))
518               ((null order))
519             (output-sql (car order) database)
520             (when (cdr order)
521               (write-char #\, *sql-stream*)))
522           (output-sql order-by-descending database))
523       (write-string " DESC " *sql-stream*))
524     (when limit
525       (write-string " LIMIT " *sql-stream*)
526       (output-sql limit database))
527     (when offset
528       (write-string " OFFSET " *sql-stream*)
529       (output-sql offset database))
530     (when *in-subselect*
531       (write-string ")" *sql-stream*)))
532   t)
533
534 ;; INSERT
535
536 (defclass sql-insert (%sql-expression)
537   ((into
538     :initarg :into
539     :initform nil)
540    (attributes
541     :initarg :attributes
542     :initform nil)
543    (values
544     :initarg :values
545     :initform nil)
546    (query
547     :initarg :query
548     :initform nil))
549   (:documentation
550    "An SQL INSERT statement."))
551
552 (defmethod output-sql ((ins sql-insert) &optional
553                        (database *default-database*))
554   (with-slots (into attributes values query)
555     ins
556     (write-string "INSERT INTO " *sql-stream*)
557     (output-sql into database)
558     (when attributes
559       (write-char #\Space *sql-stream*)
560       (output-sql attributes database))
561     (when values
562       (write-string " VALUES " *sql-stream*)
563       (output-sql values database))
564     (when query
565       (write-char #\Space *sql-stream*)
566       (output-sql query database)))
567   t)
568
569 ;; DELETE
570
571 (defclass sql-delete (%sql-expression)
572   ((from
573     :initarg :from
574     :initform nil)
575    (where
576     :initarg :where
577     :initform nil))
578   (:documentation
579    "An SQL DELETE statement."))
580
581 (defmethod output-sql ((stmt sql-delete) &optional
582                        (database *default-database*))
583   (with-slots (from where)
584     stmt
585     (write-string "DELETE FROM " *sql-stream*)
586     (typecase from
587       (symbol (write-string (sql-escape from) *sql-stream*))
588       (t  (output-sql from database)))
589     (when where
590       (write-string " WHERE " *sql-stream*)
591       (output-sql where database)))
592   t)
593
594 ;; UPDATE
595
596 (defclass sql-update (%sql-expression)
597   ((table
598     :initarg :table
599     :initform nil)
600    (attributes
601     :initarg :attributes
602     :initform nil)
603    (values
604     :initarg :values
605     :initform nil)
606    (where
607     :initarg :where
608     :initform nil))
609   (:documentation "An SQL UPDATE statement."))
610
611 (defmethod output-sql ((expr sql-update) &optional
612                        (database *default-database*))
613   (with-slots (table where attributes values)
614     expr
615     (flet ((update-assignments ()
616              (mapcar #'(lambda (a b)
617                          (make-instance 'sql-assignment-exp
618                                         :operator '=
619                                         :sub-expressions (list a b)))
620                      attributes values)))
621       (write-string "UPDATE " *sql-stream*)
622       (output-sql table database)
623       (write-string " SET " *sql-stream*)
624       (output-sql (apply #'vector (update-assignments)) database)
625       (when where
626         (write-string " WHERE " *sql-stream*)
627         (output-sql where database))))
628   t)
629
630 ;; CREATE TABLE
631
632 (defclass sql-create-table (%sql-expression)
633   ((name
634     :initarg :name
635     :initform nil)
636    (columns
637     :initarg :columns
638     :initform nil)
639    (modifiers
640     :initarg :modifiers
641     :initform nil))
642   (:documentation
643    "An SQL CREATE TABLE statement."))
644
645 ;; Here's a real warhorse of a function!
646
647 (defun listify (x)
648   (if (atom x)
649       (list x)
650       x))
651
652 (defmethod output-sql ((stmt sql-create-table) &optional
653                        (database *default-database*))
654   (flet ((output-column (column-spec)
655            (destructuring-bind (name type &rest constraints)
656                column-spec
657              (let ((type (listify type)))
658                (output-sql name database)
659                (write-char #\Space *sql-stream*)
660                (write-string
661                 (database-get-type-specifier (car type) (cdr type) database)
662                 *sql-stream*)
663                (let ((constraints
664                       (database-constraint-statement constraints database)))
665                  (when constraints
666                    (write-string " " *sql-stream*)
667                    (write-string constraints *sql-stream*)))))))
668     (with-slots (name columns modifiers)
669       stmt
670       (write-string "CREATE TABLE " *sql-stream*)
671       (output-sql name database)
672       (write-string " (" *sql-stream*)
673       (do ((column columns (cdr column)))
674           ((null (cdr column))
675            (output-column (car column)))
676         (output-column (car column))
677         (write-string ", " *sql-stream*))
678       (when modifiers
679         (do ((modifier (listify modifiers) (cdr modifier)))
680             ((null modifier))
681           (write-string ", " *sql-stream*)
682           (write-string (car modifier) *sql-stream*)))
683       (write-char #\) *sql-stream*)))
684   t)
685
686
687 ;; CREATE VIEW
688
689 (defclass sql-create-view (%sql-expression)
690   ((name :initarg :name :initform nil)
691    (column-list :initarg :column-list :initform nil)
692    (query :initarg :query :initform nil)
693    (with-check-option :initarg :with-check-option :initform nil))
694   (:documentation "An SQL CREATE VIEW statement."))
695
696 (defmethod output-sql ((stmt sql-create-view) &optional database)
697   (with-slots (name column-list query with-check-option) stmt
698     (write-string "CREATE VIEW " *sql-stream*)
699     (output-sql name database)
700     (when column-list (write-string " " *sql-stream*)
701           (output-sql (listify column-list) database))
702     (write-string " AS " *sql-stream*)
703     (output-sql query database)
704     (when with-check-option (write-string " WITH CHECK OPTION" *sql-stream*))))
705
706
707 ;;
708 ;; Column constraint types
709 ;;
710 (defparameter *constraint-types*
711   '(("NOT-NULL" . "NOT NULL")
712     ("PRIMARY-KEY" . "PRIMARY KEY")))
713
714 ;;
715 ;; Convert type spec to sql syntax
716 ;;
717
718 (defmethod database-constraint-description (constraint database)
719   (declare (ignore database))
720   (let ((output (assoc (symbol-name constraint) *constraint-types*
721                        :test #'equal)))
722     (if (null output)
723         (error 'clsql-sql-syntax-error
724                :reason (format nil "unsupported column constraint '~a'"
725                                constraint))
726         (cdr output))))
727
728 (defmethod database-constraint-statement (constraint-list database)
729   (declare (ignore database))
730   (make-constraints-description constraint-list))
731   
732 (defun make-constraints-description (constraint-list)
733   (if constraint-list
734       (let ((string ""))
735         (do ((constraint constraint-list (cdr constraint)))
736             ((null constraint) string)
737           (let ((output (assoc (symbol-name (car constraint))
738                                *constraint-types*
739                                :test #'equal)))
740             (if (null output)
741                 (error 'clsql-sql-syntax-error
742                        :reason (format nil "unsupported column constraint '~a'"
743                                        constraint))
744                 (setq string (concatenate 'string string (cdr output))))
745             (if (< 1 (length constraint))
746                 (setq string (concatenate 'string string " "))))))))
747