1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
6 ;;;; Classes defining SQL expressions and methods for formatting the
7 ;;;; appropriate SQL commands.
9 ;;;; This file is part of CLSQL.
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 ;;;; *************************************************************************
16 (in-package #:clsql-sys)
18 (defvar +empty-string+ "''")
20 (defvar +null-string+ "NULL")
22 (defvar *sql-stream* nil
23 "stream which accumulates SQL output")
25 (defun sql-output (sql-expr &optional database)
26 (progv '(*sql-stream*)
27 `(,(make-string-output-stream))
28 (output-sql sql-expr database)
29 (get-output-stream-string *sql-stream*)))
32 (defclass %sql-expression ()
35 (defmethod output-sql ((expr %sql-expression) database)
36 (declare (ignore database))
37 (write-string +null-string+ *sql-stream*))
39 (defmethod print-object ((self %sql-expression) stream)
40 (print-unreadable-object
42 (write-string (sql-output self) stream)))
44 ;; For straight up strings
46 (defclass sql (%sql-expression)
50 (:documentation "A literal SQL expression."))
52 (defmethod make-load-form ((sql sql) &optional environment)
53 (declare (ignore environment))
56 `(make-instance 'sql :string ',text)))
58 (defmethod output-sql ((expr sql) database)
59 (declare (ignore database))
60 (write-string (slot-value expr 'text) *sql-stream*)
63 (defmethod print-object ((ident sql) stream)
64 (format stream "#<~S \"~A\">"
66 (sql-output ident nil)))
68 ;; For SQL Identifiers of generic type
69 (defclass sql-ident (%sql-expression)
73 (:documentation "An SQL identifer."))
75 (defmethod make-load-form ((sql sql-ident) &optional environment)
76 (declare (ignore environment))
79 `(make-instance 'sql-ident :name ',name)))
81 (defvar *output-hash* (make-hash-table :test #'equal))
83 (defmethod output-sql-hash-key (expr database)
84 (declare (ignore expr database))
88 (defmethod output-sql :around ((sql t) database)
89 (let* ((hash-key (output-sql-hash-key sql database))
90 (hash-value (when hash-key (gethash hash-key *output-hash*))))
91 (cond ((and hash-key hash-value)
92 (write-string hash-value *sql-stream*))
94 (let ((*sql-stream* (make-string-output-stream)))
96 (setf hash-value (get-output-stream-string *sql-stream*))
97 (setf (gethash hash-key *output-hash*) hash-value))
98 (write-string hash-value *sql-stream*))
100 (call-next-method)))))
102 (defmethod output-sql ((expr sql-ident) database)
103 (with-slots (name) expr
105 (convert-to-db-default-case
108 (symbol (symbol-name name)))
113 ;; For SQL Identifiers for attributes
115 (defclass sql-ident-attribute (sql-ident)
122 (:documentation "An SQL Attribute identifier."))
124 (defmethod collect-table-refs (sql)
125 (declare (ignore sql))
128 (defmethod collect-table-refs ((sql sql-ident-attribute))
129 (let ((qual (slot-value sql 'qualifier)))
130 (if (and qual (symbolp (slot-value sql 'qualifier)))
131 (list (make-instance 'sql-ident-table :name
132 (slot-value sql 'qualifier))))))
134 (defmethod make-load-form ((sql sql-ident-attribute) &optional environment)
135 (declare (ignore environment))
136 (with-slots (qualifier type name)
138 `(make-instance 'sql-ident-attribute :name ',name
139 :qualifier ',qualifier
142 (defmethod output-sql ((expr sql-ident-attribute) database)
143 (with-slots (qualifier name type) expr
144 (if (and (not qualifier) (not type))
146 ;; Honor care of name
148 (write-string name *sql-stream*))
150 (write-string (sql-escape (convert-to-db-default-case
151 (symbol-name name) database)) *sql-stream*)))
153 ;;; KMR: The TYPE field is used by CommonSQL for type conversion -- it
154 ;;; should not be output in SQL statements
156 (format *sql-stream* "~@[~A.~]~A~@[ ~A~]"
158 (convert-to-db-default-case (sql-escape qualifier) database))
159 (sql-escape (convert-to-db-default-case name database))
161 (convert-to-db-default-case (symbol-name type) database)))
162 (format *sql-stream* "~@[~A.~]~A"
165 (string (format nil "~s" qualifier))
166 (t (convert-to-db-default-case (sql-escape qualifier)
168 (sql-escape (convert-to-db-default-case name database))))
171 (defmethod output-sql-hash-key ((expr sql-ident-attribute) database)
172 (declare (ignore database))
173 (with-slots (qualifier name type)
175 (list 'sql-ident-attribute qualifier name type)))
177 ;; For SQL Identifiers for tables
178 (defclass sql-ident-table (sql-ident)
180 :initarg :table-alias :initform nil))
181 (:documentation "An SQL table identifier."))
183 (defmethod make-load-form ((sql sql-ident-table) &optional environment)
184 (declare (ignore environment))
185 (with-slots (alias name)
187 `(make-instance 'sql-ident-table :name ',name :table-alias ',alias)))
189 (defun generate-sql (expr database)
190 (let ((*sql-stream* (make-string-output-stream)))
191 (output-sql expr database)
192 (get-output-stream-string *sql-stream*)))
194 (defmethod output-sql ((expr sql-ident-table) database)
195 (with-slots (name alias)
198 (write-string (sql-escape (convert-to-db-default-case (symbol-name name) database)) *sql-stream*)
200 (write-string (sql-escape (convert-to-db-default-case (symbol-name name) database)) *sql-stream*)
201 (write-char #\Space *sql-stream*)
202 (format *sql-stream* "~s" alias))))
206 (defmethod database-output-sql ((self duration) database)
207 (declare (ignore database))
208 (format nil "'~a'" (duration-timestring self)))
210 (defmethod database-output-sql ((self money) database)
211 (database-output-sql (slot-value self 'odcl::units) database))
215 (defmethod output-sql-hash-key ((expr sql-ident-table) database)
216 (declare (ignore database))
217 (with-slots (name alias)
219 (list 'sql-ident-table name alias)))
221 (defclass sql-relational-exp (%sql-expression)
226 :initarg :sub-expressions
228 (:documentation "An SQL relational expression."))
230 (defmethod collect-table-refs ((sql sql-relational-exp))
232 (dolist (exp (slot-value sql 'sub-expressions))
233 (let ((refs (collect-table-refs exp)))
234 (if refs (setf tabs (append refs tabs)))))
235 (remove-duplicates tabs
236 :test (lambda (tab1 tab2)
237 (equal (slot-value tab1 'name)
238 (slot-value tab2 'name))))))
243 ;; Write SQL for relational operators (like 'AND' and 'OR').
244 ;; should do arity checking of subexpressions
246 (defmethod output-sql ((expr sql-relational-exp) database)
247 (with-slots (operator sub-expressions)
249 (let ((subs (if (consp (car sub-expressions))
250 (car sub-expressions)
252 (write-char #\( *sql-stream*)
253 (do ((sub subs (cdr sub)))
254 ((null (cdr sub)) (output-sql (car sub) database))
255 (output-sql (car sub) database)
256 (write-char #\Space *sql-stream*)
257 (output-sql operator database)
258 (write-char #\Space *sql-stream*))
259 (write-char #\) *sql-stream*)))
262 (defclass sql-upcase-like (sql-relational-exp)
264 (:documentation "An SQL 'like' that upcases its arguments."))
266 ;; Write SQL for relational operators (like 'AND' and 'OR').
267 ;; should do arity checking of subexpressions
269 (defmethod output-sql ((expr sql-upcase-like) database)
270 (flet ((write-term (term)
271 (write-string "upper(" *sql-stream*)
272 (output-sql term database)
273 (write-char #\) *sql-stream*)))
274 (with-slots (sub-expressions)
276 (let ((subs (if (consp (car sub-expressions))
277 (car sub-expressions)
279 (write-char #\( *sql-stream*)
280 (do ((sub subs (cdr sub)))
281 ((null (cdr sub)) (write-term (car sub)))
282 (write-term (car sub))
283 (write-string " LIKE " *sql-stream*))
284 (write-char #\) *sql-stream*))))
287 (defclass sql-assignment-exp (sql-relational-exp)
289 (:documentation "An SQL Assignment expression."))
292 (defmethod output-sql ((expr sql-assignment-exp) database)
293 (with-slots (operator sub-expressions)
295 (do ((sub sub-expressions (cdr sub)))
296 ((null (cdr sub)) (output-sql (car sub) database))
297 (output-sql (car sub) database)
298 (write-char #\Space *sql-stream*)
299 (output-sql operator database)
300 (write-char #\Space *sql-stream*)))
303 (defclass sql-value-exp (%sql-expression)
311 "An SQL value expression.")
314 (defmethod collect-table-refs ((sql sql-value-exp))
316 (if (listp (slot-value sql 'components))
318 (dolist (exp (slot-value sql 'components))
319 (let ((refs (collect-table-refs exp)))
320 (if refs (setf tabs (append refs tabs)))))
321 (remove-duplicates tabs
322 :test (lambda (tab1 tab2)
323 (equal (slot-value tab1 'name)
324 (slot-value tab2 'name)))))
329 (defmethod output-sql ((expr sql-value-exp) database)
330 (with-slots (modifier components)
334 (write-char #\( *sql-stream*)
335 (output-sql modifier database)
336 (write-char #\Space *sql-stream*)
337 (output-sql components database)
338 (write-char #\) *sql-stream*))
339 (output-sql components database))))
341 (defclass sql-typecast-exp (sql-value-exp)
343 (:documentation "An SQL typecast expression."))
345 (defmethod output-sql ((expr sql-typecast-exp) database)
346 (database-output-sql expr database))
348 (defmethod database-output-sql ((expr sql-typecast-exp) database)
349 (with-slots (components)
351 (output-sql components database)))
354 (defmethod collect-table-refs ((sql sql-typecast-exp))
355 (when (slot-value sql 'components)
356 (collect-table-refs (slot-value sql 'components))))
358 (defclass sql-function-exp (%sql-expression)
366 "An SQL function expression."))
368 (defmethod collect-table-refs ((sql sql-function-exp))
370 (dolist (exp (slot-value sql 'components))
371 (let ((refs (collect-table-refs exp)))
372 (if refs (setf tabs (append refs tabs)))))
373 (remove-duplicates tabs
374 :test (lambda (tab1 tab2)
375 (equal (slot-value tab1 'name)
376 (slot-value tab2 'name))))))
378 (defmethod output-sql ((expr sql-function-exp) database)
379 (with-slots (name args)
381 (output-sql name database)
382 (when args (output-sql args database)))
386 (defclass sql-between-exp (sql-function-exp)
388 (:documentation "An SQL between expression."))
390 (defmethod output-sql ((expr sql-between-exp) database)
391 (with-slots (name args)
393 (output-sql (first args) database)
394 (write-string " BETWEEN " *sql-stream*)
395 (output-sql (second args) database)
396 (write-string " AND " *sql-stream*)
397 (output-sql (third args) database))
400 (defclass sql-query-modifier-exp (%sql-expression)
401 ((modifier :initarg :modifier :initform nil)
402 (components :initarg :components :initform nil))
403 (:documentation "An SQL query modifier expression."))
405 (defmethod output-sql ((expr sql-query-modifier-exp) database)
406 (with-slots (modifier components)
408 (output-sql modifier database)
409 (write-string " " *sql-stream*)
410 (output-sql (car components) database)
412 (mapc #'(lambda (comp)
413 (write-string ", " *sql-stream*)
414 (output-sql comp database))
418 (defclass sql-set-exp (%sql-expression)
423 :initarg :sub-expressions
425 (:documentation "An SQL set expression."))
427 (defmethod collect-table-refs ((sql sql-set-exp))
429 (dolist (exp (slot-value sql 'sub-expressions))
430 (let ((refs (collect-table-refs exp)))
431 (if refs (setf tabs (append refs tabs)))))
432 (remove-duplicates tabs
433 :test (lambda (tab1 tab2)
434 (equal (slot-value tab1 'name)
435 (slot-value tab2 'name))))))
437 (defmethod output-sql ((expr sql-set-exp) database)
438 (with-slots (operator sub-expressions)
440 (let ((subs (if (consp (car sub-expressions))
441 (car sub-expressions)
443 (when (= (length subs) 1)
444 (output-sql operator database)
445 (write-char #\Space *sql-stream*))
446 (do ((sub subs (cdr sub)))
447 ((null (cdr sub)) (output-sql (car sub) database))
448 (output-sql (car sub) database)
449 (write-char #\Space *sql-stream*)
450 (output-sql operator database)
451 (write-char #\Space *sql-stream*))))
454 (defclass sql-query (%sql-expression)
465 :initarg :set-operation
497 (:documentation "An SQL SELECT query."))
499 (defclass sql-object-query (%sql-expression)
513 (defmethod collect-table-refs ((sql sql-query))
514 (remove-duplicates (collect-table-refs (slot-value sql 'where))
515 :test (lambda (tab1 tab2)
516 (equal (slot-value tab1 'name)
517 (slot-value tab2 'name)))))
519 (defvar *select-arguments*
520 '(:all :database :distinct :flatp :from :group-by :having :order-by
521 :set-operation :where :offset :limit :inner-join :on
522 ;; below keywords are not a SQL argument, but these keywords may terminate select
525 (defun query-arg-p (sym)
526 (member sym *select-arguments*))
528 (defun query-get-selections (select-args)
529 "Return two values: the list of select-args up to the first keyword,
530 uninclusive, and the args from that keyword to the end."
531 (let ((first-key-arg (position-if #'query-arg-p select-args)))
533 (values (subseq select-args 0 first-key-arg)
534 (subseq select-args first-key-arg))
537 (defun make-query (&rest args)
538 (flet ((select-objects (target-args)
540 (every #'(lambda (arg)
542 (find-class arg nil)))
544 (multiple-value-bind (selections arglist)
545 (query-get-selections args)
546 (if (select-objects selections)
547 (destructuring-bind (&key flatp refresh &allow-other-keys) arglist
548 (make-instance 'sql-object-query :objects selections
549 :flatp flatp :refresh refresh
551 (destructuring-bind (&key all flatp set-operation distinct from where
552 group-by having order-by
553 offset limit inner-join on &allow-other-keys)
555 (if (null selections)
556 (error "No target columns supplied to select statement."))
558 (error "No source tables supplied to select statement."))
559 (make-instance 'sql-query :selections selections
560 :all all :flatp flatp :set-operation set-operation
561 :distinct distinct :from from :where where
562 :limit limit :offset offset
563 :group-by group-by :having having :order-by order-by
564 :inner-join inner-join :on on))))))
566 (defvar *in-subselect* nil)
568 (defmethod output-sql ((query sql-query) database)
569 (with-slots (distinct selections from where group-by having order-by
570 limit offset inner-join on all set-operation)
573 (write-string "(" *sql-stream*))
574 (write-string "SELECT " *sql-stream*)
576 (write-string "ALL " *sql-stream*))
577 (when (and distinct (not all))
578 (write-string "DISTINCT " *sql-stream*)
579 (unless (eql t distinct)
580 (write-string "ON " *sql-stream*)
581 (output-sql distinct database)
582 (write-char #\Space *sql-stream*)))
583 (output-sql (apply #'vector selections) database)
585 (write-string " FROM " *sql-stream*)
587 (list (output-sql (apply #'vector from) database))
588 (string (write-string from *sql-stream*))
589 (t (output-sql from database))))
591 (write-string " INNER JOIN " *sql-stream*)
592 (output-sql inner-join database))
594 (write-string " ON " *sql-stream*)
595 (output-sql on database))
597 (write-string " WHERE " *sql-stream*)
598 (let ((*in-subselect* t))
599 (output-sql where database)))
601 (write-string " GROUP BY " *sql-stream*)
602 (output-sql group-by database))
604 (write-string " HAVING " *sql-stream*)
605 (output-sql having database))
607 (write-string " ORDER BY " *sql-stream*)
609 (do ((order order-by (cdr order)))
611 (let ((item (car order)))
614 (output-sql (car item) database)
615 (format *sql-stream* " ~A" (cadr item)))
617 (output-sql item database)))
619 (write-char #\, *sql-stream*))))
620 (output-sql order-by database)))
622 (write-string " LIMIT " *sql-stream*)
623 (output-sql limit database))
625 (write-string " OFFSET " *sql-stream*)
626 (output-sql offset database))
628 (write-string ")" *sql-stream*))
630 (write-char #\Space *sql-stream*)
631 (output-sql set-operation database)))
634 (defmethod output-sql ((query sql-object-query) database)
635 (declare (ignore database))
636 (with-slots (objects)
639 (format *sql-stream* "(~{~A~^ ~})" objects))))
644 (defclass sql-insert (%sql-expression)
658 "An SQL INSERT statement."))
660 (defmethod output-sql ((ins sql-insert) database)
661 (with-slots (into attributes values query)
663 (write-string "INSERT INTO " *sql-stream*)
666 (string (sql-expression :attribute into))
670 (write-char #\Space *sql-stream*)
671 (output-sql attributes database))
673 (write-string " VALUES " *sql-stream*)
674 (output-sql values database))
676 (write-char #\Space *sql-stream*)
677 (output-sql query database)))
682 (defclass sql-delete (%sql-expression)
690 "An SQL DELETE statement."))
692 (defmethod output-sql ((stmt sql-delete) database)
693 (with-slots (from where)
695 (write-string "DELETE FROM " *sql-stream*)
697 (symbol (write-string (sql-escape from) *sql-stream*))
698 (t (output-sql from database)))
700 (write-string " WHERE " *sql-stream*)
701 (output-sql where database)))
706 (defclass sql-update (%sql-expression)
719 (:documentation "An SQL UPDATE statement."))
721 (defmethod output-sql ((expr sql-update) database)
722 (with-slots (table where attributes values)
724 (flet ((update-assignments ()
725 (mapcar #'(lambda (a b)
726 (make-instance 'sql-assignment-exp
728 :sub-expressions (list a b)))
730 (write-string "UPDATE " *sql-stream*)
731 (output-sql table database)
732 (write-string " SET " *sql-stream*)
733 (output-sql (apply #'vector (update-assignments)) database)
735 (write-string " WHERE " *sql-stream*)
736 (output-sql where database))))
741 (defclass sql-create-table (%sql-expression)
752 :initarg :transactions
755 "An SQL CREATE TABLE statement."))
757 ;; Here's a real warhorse of a function!
759 (declaim (inline listify))
765 (defmethod output-sql ((stmt sql-create-table) database)
766 (flet ((output-column (column-spec)
767 (destructuring-bind (name type &optional db-type &rest constraints)
769 (let ((type (listify type)))
770 (output-sql name database)
771 (write-char #\Space *sql-stream*)
773 (if (stringp db-type) db-type ; override definition
774 (database-get-type-specifier (car type) (cdr type) database
775 (database-underlying-type database)))
777 (let ((constraints (database-constraint-statement
778 (if (and db-type (symbolp db-type))
779 (cons db-type constraints)
783 (write-string " " *sql-stream*)
784 (write-string constraints *sql-stream*)))))))
785 (with-slots (name columns modifiers transactions)
787 (write-string "CREATE TABLE " *sql-stream*)
788 (output-sql name database)
789 (write-string " (" *sql-stream*)
790 (do ((column columns (cdr column)))
792 (output-column (car column)))
793 (output-column (car column))
794 (write-string ", " *sql-stream*))
796 (do ((modifier (listify modifiers) (cdr modifier)))
798 (write-string ", " *sql-stream*)
799 (write-string (car modifier) *sql-stream*)))
800 (write-char #\) *sql-stream*)
801 (when (and (eq :mysql (database-underlying-type database))
803 (db-type-transaction-capable? :mysql database))
804 (write-string " Type=InnoDB" *sql-stream*))))
810 (defclass sql-create-view (%sql-expression)
811 ((name :initarg :name :initform nil)
812 (column-list :initarg :column-list :initform nil)
813 (query :initarg :query :initform nil)
814 (with-check-option :initarg :with-check-option :initform nil))
815 (:documentation "An SQL CREATE VIEW statement."))
817 (defmethod output-sql ((stmt sql-create-view) database)
818 (with-slots (name column-list query with-check-option) stmt
819 (write-string "CREATE VIEW " *sql-stream*)
820 (output-sql name database)
821 (when column-list (write-string " " *sql-stream*)
822 (output-sql (listify column-list) database))
823 (write-string " AS " *sql-stream*)
824 (output-sql query database)
825 (when with-check-option (write-string " WITH CHECK OPTION" *sql-stream*))))
829 ;; Column constraint types
831 (defparameter *constraint-types*
833 (cons (symbol-name-default-case "NOT-NULL") "NOT NULL")
834 (cons (symbol-name-default-case "PRIMARY-KEY") "PRIMARY KEY")
835 (cons (symbol-name-default-case "NOT") "NOT")
836 (cons (symbol-name-default-case "NULL") "NULL")
837 (cons (symbol-name-default-case "PRIMARY") "PRIMARY")
838 (cons (symbol-name-default-case "KEY") "KEY")))
841 ;; Convert type spec to sql syntax
844 (defmethod database-constraint-description (constraint database)
845 (declare (ignore database))
846 (let ((output (assoc (symbol-name constraint) *constraint-types*
849 (error 'sql-user-error
850 :message (format nil "unsupported column constraint '~A'"
854 (defmethod database-constraint-statement (constraint-list database)
855 (declare (ignore database))
856 (make-constraints-description constraint-list))
858 (defun make-constraints-description (constraint-list)
861 (do ((constraint constraint-list (cdr constraint)))
862 ((null constraint) string)
863 (let ((output (assoc (symbol-name (car constraint))
867 (error 'sql-user-error
868 :message (format nil "unsupported column constraint '~A'"
870 (setq string (concatenate 'string string (cdr output))))
871 (if (< 1 (length constraint))
872 (setq string (concatenate 'string string " "))))))))