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)
106 (convert-to-db-default-case
109 (symbol (symbol-name name)))
114 ;; For SQL Identifiers for attributes
116 (defclass sql-ident-attribute (sql-ident)
123 (:documentation "An SQL Attribute identifier."))
125 (defmethod collect-table-refs (sql)
126 (declare (ignore sql))
129 (defmethod collect-table-refs ((sql sql-ident-attribute))
130 (let ((qual (slot-value sql 'qualifier)))
131 (if (and qual (symbolp (slot-value sql 'qualifier)))
132 (list (make-instance 'sql-ident-table :name
133 (slot-value sql 'qualifier))))))
135 (defmethod make-load-form ((sql sql-ident-attribute) &optional environment)
136 (declare (ignore environment))
137 (with-slots (qualifier type name)
139 `(make-instance 'sql-ident-attribute :name ',name
140 :qualifier ',qualifier
143 (defmethod output-sql ((expr sql-ident-attribute) database)
144 (with-slots (qualifier name type)
146 (if (and (not qualifier) (not type))
147 (write-string (sql-escape (convert-to-db-default-case
148 (symbol-name name) database)) *sql-stream*)
149 ;;; KMR: The TYPE field is used by CommonSQL for type conversion -- it
150 ;;; should not be output in SQL statements
152 (format *sql-stream* "~@[~A.~]~A~@[ ~A~]"
154 (convert-to-db-default-case (sql-escape qualifier) database))
155 (sql-escape (convert-to-db-default-case name database))
157 (convert-to-db-default-case (symbol-name type) database)))
158 (format *sql-stream* "~@[~A.~]~A"
161 (string (format nil "~s" qualifier))
162 (t (convert-to-db-default-case (sql-escape qualifier)
164 (sql-escape (convert-to-db-default-case name database))))
167 (defmethod output-sql-hash-key ((expr sql-ident-attribute) database)
168 (declare (ignore database))
169 (with-slots (qualifier name type)
171 (list 'sql-ident-attribute qualifier name type)))
173 ;; For SQL Identifiers for tables
174 (defclass sql-ident-table (sql-ident)
176 :initarg :table-alias :initform nil))
177 (:documentation "An SQL table identifier."))
179 (defmethod make-load-form ((sql sql-ident-table) &optional environment)
180 (declare (ignore environment))
181 (with-slots (alias name)
183 `(make-instance 'sql-ident-table :name ',name :table-alias ',alias)))
185 (defun generate-sql (expr database)
186 (let ((*sql-stream* (make-string-output-stream)))
187 (output-sql expr database)
188 (get-output-stream-string *sql-stream*)))
190 (defmethod output-sql ((expr sql-ident-table) database)
191 (with-slots (name alias)
194 (write-string (sql-escape (convert-to-db-default-case (symbol-name name) database)) *sql-stream*)
196 (write-string (sql-escape (convert-to-db-default-case (symbol-name name) database)) *sql-stream*)
197 (write-char #\Space *sql-stream*)
198 (format *sql-stream* "~s" alias))))
202 (defmethod database-output-sql ((self duration) database)
203 (declare (ignore database))
204 (format nil "'~a'" (duration-timestring self)))
206 (defmethod database-output-sql ((self money) database)
207 (database-output-sql (slot-value self 'odcl::units) database))
211 (defmethod output-sql-hash-key ((expr sql-ident-table) database)
212 (declare (ignore database))
213 (with-slots (name alias)
215 (list 'sql-ident-table name alias)))
217 (defclass sql-relational-exp (%sql-expression)
222 :initarg :sub-expressions
224 (:documentation "An SQL relational expression."))
226 (defmethod collect-table-refs ((sql sql-relational-exp))
228 (dolist (exp (slot-value sql 'sub-expressions))
229 (let ((refs (collect-table-refs exp)))
230 (if refs (setf tabs (append refs tabs)))))
231 (remove-duplicates tabs
232 :test (lambda (tab1 tab2)
233 (equal (slot-value tab1 'name)
234 (slot-value tab2 'name))))))
239 ;; Write SQL for relational operators (like 'AND' and 'OR').
240 ;; should do arity checking of subexpressions
242 (defmethod output-sql ((expr sql-relational-exp) database)
243 (with-slots (operator sub-expressions)
245 (let ((subs (if (consp (car sub-expressions))
246 (car sub-expressions)
248 (write-char #\( *sql-stream*)
249 (do ((sub subs (cdr sub)))
250 ((null (cdr sub)) (output-sql (car sub) database))
251 (output-sql (car sub) database)
252 (write-char #\Space *sql-stream*)
253 (output-sql operator database)
254 (write-char #\Space *sql-stream*))
255 (write-char #\) *sql-stream*)))
258 (defclass sql-upcase-like (sql-relational-exp)
260 (:documentation "An SQL 'like' that upcases its arguments."))
262 ;; Write SQL for relational operators (like 'AND' and 'OR').
263 ;; should do arity checking of subexpressions
265 (defmethod output-sql ((expr sql-upcase-like) 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)
272 (let ((subs (if (consp (car sub-expressions))
273 (car 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*))))
283 (defclass sql-assignment-exp (sql-relational-exp)
285 (:documentation "An SQL Assignment expression."))
288 (defmethod output-sql ((expr sql-assignment-exp) database)
289 (with-slots (operator sub-expressions)
291 (do ((sub sub-expressions (cdr sub)))
292 ((null (cdr sub)) (output-sql (car sub) database))
293 (output-sql (car sub) database)
294 (write-char #\Space *sql-stream*)
295 (output-sql operator database)
296 (write-char #\Space *sql-stream*)))
299 (defclass sql-value-exp (%sql-expression)
307 "An SQL value expression.")
310 (defmethod collect-table-refs ((sql sql-value-exp))
312 (if (listp (slot-value sql 'components))
314 (dolist (exp (slot-value sql 'components))
315 (let ((refs (collect-table-refs exp)))
316 (if refs (setf tabs (append refs tabs)))))
317 (remove-duplicates tabs
318 :test (lambda (tab1 tab2)
319 (equal (slot-value tab1 'name)
320 (slot-value tab2 'name)))))
325 (defmethod output-sql ((expr sql-value-exp) database)
326 (with-slots (modifier components)
330 (write-char #\( *sql-stream*)
331 (output-sql modifier database)
332 (write-char #\Space *sql-stream*)
333 (output-sql components database)
334 (write-char #\) *sql-stream*))
335 (output-sql components database))))
337 (defclass sql-typecast-exp (sql-value-exp)
339 (:documentation "An SQL typecast expression."))
341 (defmethod output-sql ((expr sql-typecast-exp) database)
342 (database-output-sql expr database))
344 (defmethod database-output-sql ((expr sql-typecast-exp) database)
345 (with-slots (components)
347 (output-sql components database)))
350 (defmethod collect-table-refs ((sql sql-typecast-exp))
351 (when (slot-value sql 'components)
352 (collect-table-refs (slot-value sql 'components))))
354 (defclass sql-function-exp (%sql-expression)
362 "An SQL function expression."))
364 (defmethod collect-table-refs ((sql sql-function-exp))
366 (dolist (exp (slot-value sql 'components))
367 (let ((refs (collect-table-refs exp)))
368 (if refs (setf tabs (append refs tabs)))))
369 (remove-duplicates tabs
370 :test (lambda (tab1 tab2)
371 (equal (slot-value tab1 'name)
372 (slot-value tab2 'name))))))
374 (defmethod output-sql ((expr sql-function-exp) database)
375 (with-slots (name args)
377 (output-sql name database)
378 (when args (output-sql args database)))
382 (defclass sql-between-exp (sql-function-exp)
384 (:documentation "An SQL between expression."))
386 (defmethod output-sql ((expr sql-between-exp) database)
387 (with-slots (name args)
389 (output-sql (first args) database)
390 (write-string " BETWEEN " *sql-stream*)
391 (output-sql (second args) database)
392 (write-string " AND " *sql-stream*)
393 (output-sql (third args) database))
396 (defclass sql-query-modifier-exp (%sql-expression)
397 ((modifier :initarg :modifier :initform nil)
398 (components :initarg :components :initform nil))
399 (:documentation "An SQL query modifier expression."))
401 (defmethod output-sql ((expr sql-query-modifier-exp) database)
402 (with-slots (modifier components)
404 (output-sql modifier database)
405 (write-string " " *sql-stream*)
406 (output-sql (car components) database)
408 (mapc #'(lambda (comp)
409 (write-string ", " *sql-stream*)
410 (output-sql comp database))
414 (defclass sql-set-exp (%sql-expression)
419 :initarg :sub-expressions
421 (:documentation "An SQL set expression."))
423 (defmethod collect-table-refs ((sql sql-set-exp))
425 (dolist (exp (slot-value sql 'sub-expressions))
426 (let ((refs (collect-table-refs exp)))
427 (if refs (setf tabs (append refs tabs)))))
428 (remove-duplicates tabs
429 :test (lambda (tab1 tab2)
430 (equal (slot-value tab1 'name)
431 (slot-value tab2 'name))))))
433 (defmethod output-sql ((expr sql-set-exp) database)
434 (with-slots (operator sub-expressions)
436 (let ((subs (if (consp (car sub-expressions))
437 (car sub-expressions)
439 (when (= (length subs) 1)
440 (output-sql operator database)
441 (write-char #\Space *sql-stream*))
442 (do ((sub subs (cdr sub)))
443 ((null (cdr sub)) (output-sql (car sub) database))
444 (output-sql (car sub) database)
445 (write-char #\Space *sql-stream*)
446 (output-sql operator database)
447 (write-char #\Space *sql-stream*))))
450 (defclass sql-query (%sql-expression)
461 :initarg :set-operation
493 (:documentation "An SQL SELECT query."))
495 (defclass sql-object-query (%sql-expression)
509 (defmethod collect-table-refs ((sql sql-query))
510 (remove-duplicates (collect-table-refs (slot-value sql 'where))
511 :test (lambda (tab1 tab2)
512 (equal (slot-value tab1 'name)
513 (slot-value tab2 'name)))))
515 (defvar *select-arguments*
516 '(:all :database :distinct :flatp :from :group-by :having :order-by
517 :set-operation :where :offset :limit :inner-join :on
518 ;; below keywords are not a SQL argument, but these keywords may terminate select
521 (defun query-arg-p (sym)
522 (member sym *select-arguments*))
524 (defun query-get-selections (select-args)
525 "Return two values: the list of select-args up to the first keyword,
526 uninclusive, and the args from that keyword to the end."
527 (let ((first-key-arg (position-if #'query-arg-p select-args)))
529 (values (subseq select-args 0 first-key-arg)
530 (subseq select-args first-key-arg))
533 (defun make-query (&rest args)
534 (flet ((select-objects (target-args)
536 (every #'(lambda (arg)
538 (find-class arg nil)))
540 (multiple-value-bind (selections arglist)
541 (query-get-selections args)
542 (if (select-objects selections)
543 (destructuring-bind (&key flatp refresh &allow-other-keys) arglist
544 (make-instance 'sql-object-query :objects selections
545 :flatp flatp :refresh refresh
547 (destructuring-bind (&key all flatp set-operation distinct from where
548 group-by having order-by
549 offset limit inner-join on &allow-other-keys)
551 (if (null selections)
552 (error "No target columns supplied to select statement."))
554 (error "No source tables supplied to select statement."))
555 (make-instance 'sql-query :selections selections
556 :all all :flatp flatp :set-operation set-operation
557 :distinct distinct :from from :where where
558 :limit limit :offset offset
559 :group-by group-by :having having :order-by order-by
560 :inner-join inner-join :on on))))))
562 (defvar *in-subselect* nil)
564 (defmethod output-sql ((query sql-query) database)
565 (with-slots (distinct selections from where group-by having order-by
566 limit offset inner-join on all set-operation)
569 (write-string "(" *sql-stream*))
570 (write-string "SELECT " *sql-stream*)
572 (write-string "ALL " *sql-stream*))
573 (when (and distinct (not all))
574 (write-string "DISTINCT " *sql-stream*)
575 (unless (eql t distinct)
576 (write-string "ON " *sql-stream*)
577 (output-sql distinct database)
578 (write-char #\Space *sql-stream*)))
579 (output-sql (apply #'vector selections) database)
581 (write-string " FROM " *sql-stream*)
583 (list (output-sql (apply #'vector from) database))
584 (string (write-string
586 (convert-to-db-default-case from database)) *sql-stream*))
587 (t (output-sql from database))))
589 (write-string " INNER JOIN " *sql-stream*)
590 (output-sql inner-join database))
592 (write-string " ON " *sql-stream*)
593 (output-sql on database))
595 (write-string " WHERE " *sql-stream*)
596 (let ((*in-subselect* t))
597 (output-sql where database)))
599 (write-string " GROUP BY " *sql-stream*)
600 (output-sql group-by database))
602 (write-string " HAVING " *sql-stream*)
603 (output-sql having database))
605 (write-string " ORDER BY " *sql-stream*)
607 (do ((order order-by (cdr order)))
609 (let ((item (car order)))
612 (output-sql (car item) database)
613 (format *sql-stream* " ~A" (cadr item)))
615 (output-sql item database)))
617 (write-char #\, *sql-stream*))))
618 (output-sql order-by database)))
620 (write-string " LIMIT " *sql-stream*)
621 (output-sql limit database))
623 (write-string " OFFSET " *sql-stream*)
624 (output-sql offset database))
626 (write-string ")" *sql-stream*))
628 (write-char #\Space *sql-stream*)
629 (output-sql set-operation database)))
632 (defmethod output-sql ((query sql-object-query) database)
633 (declare (ignore database))
634 (with-slots (objects)
637 (format *sql-stream* "(~{~A~^ ~})" objects))))
642 (defclass sql-insert (%sql-expression)
656 "An SQL INSERT statement."))
658 (defmethod output-sql ((ins sql-insert) database)
659 (with-slots (into attributes values query)
661 (write-string "INSERT INTO " *sql-stream*)
662 (output-sql into database)
664 (write-char #\Space *sql-stream*)
665 (output-sql attributes database))
667 (write-string " VALUES " *sql-stream*)
668 (output-sql values database))
670 (write-char #\Space *sql-stream*)
671 (output-sql query database)))
676 (defclass sql-delete (%sql-expression)
684 "An SQL DELETE statement."))
686 (defmethod output-sql ((stmt sql-delete) database)
687 (with-slots (from where)
689 (write-string "DELETE FROM " *sql-stream*)
691 (symbol (write-string (sql-escape from) *sql-stream*))
692 (t (output-sql from database)))
694 (write-string " WHERE " *sql-stream*)
695 (output-sql where database)))
700 (defclass sql-update (%sql-expression)
713 (:documentation "An SQL UPDATE statement."))
715 (defmethod output-sql ((expr sql-update) database)
716 (with-slots (table where attributes values)
718 (flet ((update-assignments ()
719 (mapcar #'(lambda (a b)
720 (make-instance 'sql-assignment-exp
722 :sub-expressions (list a b)))
724 (write-string "UPDATE " *sql-stream*)
725 (output-sql table database)
726 (write-string " SET " *sql-stream*)
727 (output-sql (apply #'vector (update-assignments)) database)
729 (write-string " WHERE " *sql-stream*)
730 (output-sql where database))))
735 (defclass sql-create-table (%sql-expression)
746 :initarg :transactions
749 "An SQL CREATE TABLE statement."))
751 ;; Here's a real warhorse of a function!
753 (declaim (inline listify))
759 (defmethod output-sql ((stmt sql-create-table) database)
760 (flet ((output-column (column-spec)
761 (destructuring-bind (name type &optional db-type &rest constraints)
763 (let ((type (listify type)))
764 (output-sql name database)
765 (write-char #\Space *sql-stream*)
767 (if (stringp db-type) db-type ; override definition
768 (database-get-type-specifier (car type) (cdr type) database))
770 (let ((constraints (database-constraint-statement
771 (if (and db-type (symbolp db-type))
772 (cons db-type constraints)
776 (write-string " " *sql-stream*)
777 (write-string constraints *sql-stream*)))))))
778 (with-slots (name columns modifiers transactions)
780 (write-string "CREATE TABLE " *sql-stream*)
781 (output-sql name database)
782 (write-string " (" *sql-stream*)
783 (do ((column columns (cdr column)))
785 (output-column (car column)))
786 (output-column (car column))
787 (write-string ", " *sql-stream*))
789 (do ((modifier (listify modifiers) (cdr modifier)))
791 (write-string ", " *sql-stream*)
792 (write-string (car modifier) *sql-stream*)))
793 (write-char #\) *sql-stream*)
794 (when (and (eq :mysql (database-underlying-type database))
796 (db-type-transaction-capable? :mysql database))
797 (write-string " Type=InnoDB" *sql-stream*))))
803 (defclass sql-create-view (%sql-expression)
804 ((name :initarg :name :initform nil)
805 (column-list :initarg :column-list :initform nil)
806 (query :initarg :query :initform nil)
807 (with-check-option :initarg :with-check-option :initform nil))
808 (:documentation "An SQL CREATE VIEW statement."))
810 (defmethod output-sql ((stmt sql-create-view) database)
811 (with-slots (name column-list query with-check-option) stmt
812 (write-string "CREATE VIEW " *sql-stream*)
813 (output-sql name database)
814 (when column-list (write-string " " *sql-stream*)
815 (output-sql (listify column-list) database))
816 (write-string " AS " *sql-stream*)
817 (output-sql query database)
818 (when with-check-option (write-string " WITH CHECK OPTION" *sql-stream*))))
822 ;; Column constraint types
824 (defparameter *constraint-types*
826 (cons (symbol-name-default-case "NOT-NULL") "NOT NULL")
827 (cons (symbol-name-default-case "PRIMARY-KEY") "PRIMARY KEY")
828 (cons (symbol-name-default-case "NOT") "NOT")
829 (cons (symbol-name-default-case "NULL") "NULL")
830 (cons (symbol-name-default-case "PRIMARY") "PRIMARY")
831 (cons (symbol-name-default-case "KEY") "KEY")))
834 ;; Convert type spec to sql syntax
837 (defmethod database-constraint-description (constraint database)
838 (declare (ignore database))
839 (let ((output (assoc (symbol-name constraint) *constraint-types*
842 (error 'sql-user-error
843 :message (format nil "unsupported column constraint '~A'"
847 (defmethod database-constraint-statement (constraint-list database)
848 (declare (ignore database))
849 (make-constraints-description constraint-list))
851 (defun make-constraints-description (constraint-list)
854 (do ((constraint constraint-list (cdr constraint)))
855 ((null constraint) string)
856 (let ((output (assoc (symbol-name (car constraint))
860 (error 'sql-user-error
861 :message (format nil "unsupported column constraint '~A'"
863 (setq string (concatenate 'string string (cdr output))))
864 (if (< 1 (length constraint))
865 (setq string (concatenate 'string string " "))))))))