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