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) expr
145 (if (and (not qualifier) (not type))
147 ;; Honor care of name
149 (write-string name *sql-stream*))
151 (write-string (sql-escape (convert-to-db-default-case
152 (symbol-name name) database)) *sql-stream*)))
154 ;;; KMR: The TYPE field is used by CommonSQL for type conversion -- it
155 ;;; should not be output in SQL statements
157 (format *sql-stream* "~@[~A.~]~A~@[ ~A~]"
159 (convert-to-db-default-case (sql-escape qualifier) database))
160 (sql-escape (convert-to-db-default-case name database))
162 (convert-to-db-default-case (symbol-name type) database)))
163 (format *sql-stream* "~@[~A.~]~A"
166 (string (format nil "~s" qualifier))
167 (t (convert-to-db-default-case (sql-escape qualifier)
169 (sql-escape (convert-to-db-default-case name database))))
172 (defmethod output-sql-hash-key ((expr sql-ident-attribute) database)
173 (declare (ignore database))
174 (with-slots (qualifier name type)
176 (list 'sql-ident-attribute qualifier name type)))
178 ;; For SQL Identifiers for tables
179 (defclass sql-ident-table (sql-ident)
181 :initarg :table-alias :initform nil))
182 (:documentation "An SQL table identifier."))
184 (defmethod make-load-form ((sql sql-ident-table) &optional environment)
185 (declare (ignore environment))
186 (with-slots (alias name)
188 `(make-instance 'sql-ident-table :name ',name :table-alias ',alias)))
190 (defun generate-sql (expr database)
191 (let ((*sql-stream* (make-string-output-stream)))
192 (output-sql expr database)
193 (get-output-stream-string *sql-stream*)))
195 (defmethod output-sql ((expr sql-ident-table) database)
196 (with-slots (name alias)
199 (write-string (sql-escape (convert-to-db-default-case (symbol-name name) database)) *sql-stream*)
201 (write-string (sql-escape (convert-to-db-default-case (symbol-name name) database)) *sql-stream*)
202 (write-char #\Space *sql-stream*)
203 (format *sql-stream* "~s" alias))))
207 (defmethod database-output-sql ((self duration) database)
208 (declare (ignore database))
209 (format nil "'~a'" (duration-timestring self)))
211 (defmethod database-output-sql ((self money) database)
212 (database-output-sql (slot-value self 'odcl::units) database))
216 (defmethod output-sql-hash-key ((expr sql-ident-table) database)
217 (declare (ignore database))
218 (with-slots (name alias)
220 (list 'sql-ident-table name alias)))
222 (defclass sql-relational-exp (%sql-expression)
227 :initarg :sub-expressions
229 (:documentation "An SQL relational expression."))
231 (defmethod collect-table-refs ((sql sql-relational-exp))
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))))))
244 ;; Write SQL for relational operators (like 'AND' and 'OR').
245 ;; should do arity checking of subexpressions
247 (defmethod output-sql ((expr sql-relational-exp) database)
248 (with-slots (operator sub-expressions)
250 (let ((subs (if (consp (car sub-expressions))
251 (car sub-expressions)
253 (write-char #\( *sql-stream*)
254 (do ((sub subs (cdr sub)))
255 ((null (cdr sub)) (output-sql (car sub) database))
256 (output-sql (car sub) database)
257 (write-char #\Space *sql-stream*)
258 (output-sql operator database)
259 (write-char #\Space *sql-stream*))
260 (write-char #\) *sql-stream*)))
263 (defclass sql-upcase-like (sql-relational-exp)
265 (:documentation "An SQL 'like' that upcases its arguments."))
267 ;; Write SQL for relational operators (like 'AND' and 'OR').
268 ;; should do arity checking of subexpressions
270 (defmethod output-sql ((expr sql-upcase-like) database)
271 (flet ((write-term (term)
272 (write-string "upper(" *sql-stream*)
273 (output-sql term database)
274 (write-char #\) *sql-stream*)))
275 (with-slots (sub-expressions)
277 (let ((subs (if (consp (car sub-expressions))
278 (car sub-expressions)
280 (write-char #\( *sql-stream*)
281 (do ((sub subs (cdr sub)))
282 ((null (cdr sub)) (write-term (car sub)))
283 (write-term (car sub))
284 (write-string " LIKE " *sql-stream*))
285 (write-char #\) *sql-stream*))))
288 (defclass sql-assignment-exp (sql-relational-exp)
290 (:documentation "An SQL Assignment expression."))
293 (defmethod output-sql ((expr sql-assignment-exp) database)
294 (with-slots (operator sub-expressions)
296 (do ((sub sub-expressions (cdr sub)))
297 ((null (cdr sub)) (output-sql (car sub) database))
298 (output-sql (car sub) database)
299 (write-char #\Space *sql-stream*)
300 (output-sql operator database)
301 (write-char #\Space *sql-stream*)))
304 (defclass sql-value-exp (%sql-expression)
312 "An SQL value expression.")
315 (defmethod collect-table-refs ((sql sql-value-exp))
317 (if (listp (slot-value sql 'components))
319 (dolist (exp (slot-value sql 'components))
320 (let ((refs (collect-table-refs exp)))
321 (if refs (setf tabs (append refs tabs)))))
322 (remove-duplicates tabs
323 :test (lambda (tab1 tab2)
324 (equal (slot-value tab1 'name)
325 (slot-value tab2 'name)))))
330 (defmethod output-sql ((expr sql-value-exp) database)
331 (with-slots (modifier components)
335 (write-char #\( *sql-stream*)
336 (output-sql modifier database)
337 (write-char #\Space *sql-stream*)
338 (output-sql components database)
339 (write-char #\) *sql-stream*))
340 (output-sql components database))))
342 (defclass sql-typecast-exp (sql-value-exp)
344 (:documentation "An SQL typecast expression."))
346 (defmethod output-sql ((expr sql-typecast-exp) database)
347 (database-output-sql expr database))
349 (defmethod database-output-sql ((expr sql-typecast-exp) database)
350 (with-slots (components)
352 (output-sql components database)))
355 (defmethod collect-table-refs ((sql sql-typecast-exp))
356 (when (slot-value sql 'components)
357 (collect-table-refs (slot-value sql 'components))))
359 (defclass sql-function-exp (%sql-expression)
367 "An SQL function expression."))
369 (defmethod collect-table-refs ((sql sql-function-exp))
371 (dolist (exp (slot-value sql 'components))
372 (let ((refs (collect-table-refs exp)))
373 (if refs (setf tabs (append refs tabs)))))
374 (remove-duplicates tabs
375 :test (lambda (tab1 tab2)
376 (equal (slot-value tab1 'name)
377 (slot-value tab2 'name))))))
379 (defmethod output-sql ((expr sql-function-exp) database)
380 (with-slots (name args)
382 (output-sql name database)
383 (when args (output-sql args database)))
387 (defclass sql-between-exp (sql-function-exp)
389 (:documentation "An SQL between expression."))
391 (defmethod output-sql ((expr sql-between-exp) database)
392 (with-slots (name args)
394 (output-sql (first args) database)
395 (write-string " BETWEEN " *sql-stream*)
396 (output-sql (second args) database)
397 (write-string " AND " *sql-stream*)
398 (output-sql (third args) database))
401 (defclass sql-query-modifier-exp (%sql-expression)
402 ((modifier :initarg :modifier :initform nil)
403 (components :initarg :components :initform nil))
404 (:documentation "An SQL query modifier expression."))
406 (defmethod output-sql ((expr sql-query-modifier-exp) database)
407 (with-slots (modifier components)
409 (output-sql modifier database)
410 (write-string " " *sql-stream*)
411 (output-sql (car components) database)
413 (mapc #'(lambda (comp)
414 (write-string ", " *sql-stream*)
415 (output-sql comp database))
419 (defclass sql-set-exp (%sql-expression)
424 :initarg :sub-expressions
426 (:documentation "An SQL set expression."))
428 (defmethod collect-table-refs ((sql sql-set-exp))
430 (dolist (exp (slot-value sql 'sub-expressions))
431 (let ((refs (collect-table-refs exp)))
432 (if refs (setf tabs (append refs tabs)))))
433 (remove-duplicates tabs
434 :test (lambda (tab1 tab2)
435 (equal (slot-value tab1 'name)
436 (slot-value tab2 'name))))))
438 (defmethod output-sql ((expr sql-set-exp) database)
439 (with-slots (operator sub-expressions)
441 (let ((subs (if (consp (car sub-expressions))
442 (car sub-expressions)
444 (when (= (length subs) 1)
445 (output-sql operator database)
446 (write-char #\Space *sql-stream*))
447 (do ((sub subs (cdr sub)))
448 ((null (cdr sub)) (output-sql (car sub) database))
449 (output-sql (car sub) database)
450 (write-char #\Space *sql-stream*)
451 (output-sql operator database)
452 (write-char #\Space *sql-stream*))))
455 (defclass sql-query (%sql-expression)
466 :initarg :set-operation
498 (:documentation "An SQL SELECT query."))
500 (defclass sql-object-query (%sql-expression)
514 (defmethod collect-table-refs ((sql sql-query))
515 (remove-duplicates (collect-table-refs (slot-value sql 'where))
516 :test (lambda (tab1 tab2)
517 (equal (slot-value tab1 'name)
518 (slot-value tab2 'name)))))
520 (defvar *select-arguments*
521 '(:all :database :distinct :flatp :from :group-by :having :order-by
522 :set-operation :where :offset :limit :inner-join :on
523 ;; below keywords are not a SQL argument, but these keywords may terminate select
526 (defun query-arg-p (sym)
527 (member sym *select-arguments*))
529 (defun query-get-selections (select-args)
530 "Return two values: the list of select-args up to the first keyword,
531 uninclusive, and the args from that keyword to the end."
532 (let ((first-key-arg (position-if #'query-arg-p select-args)))
534 (values (subseq select-args 0 first-key-arg)
535 (subseq select-args first-key-arg))
538 (defun make-query (&rest args)
539 (flet ((select-objects (target-args)
541 (every #'(lambda (arg)
543 (find-class arg nil)))
545 (multiple-value-bind (selections arglist)
546 (query-get-selections args)
547 (if (select-objects selections)
548 (destructuring-bind (&key flatp refresh &allow-other-keys) arglist
549 (make-instance 'sql-object-query :objects selections
550 :flatp flatp :refresh refresh
552 (destructuring-bind (&key all flatp set-operation distinct from where
553 group-by having order-by
554 offset limit inner-join on &allow-other-keys)
556 (if (null selections)
557 (error "No target columns supplied to select statement."))
559 (error "No source tables supplied to select statement."))
560 (make-instance 'sql-query :selections selections
561 :all all :flatp flatp :set-operation set-operation
562 :distinct distinct :from from :where where
563 :limit limit :offset offset
564 :group-by group-by :having having :order-by order-by
565 :inner-join inner-join :on on))))))
567 (defvar *in-subselect* nil)
569 (defmethod output-sql ((query sql-query) database)
570 (with-slots (distinct selections from where group-by having order-by
571 limit offset inner-join on all set-operation)
574 (write-string "(" *sql-stream*))
575 (write-string "SELECT " *sql-stream*)
577 (write-string "ALL " *sql-stream*))
578 (when (and distinct (not all))
579 (write-string "DISTINCT " *sql-stream*)
580 (unless (eql t distinct)
581 (write-string "ON " *sql-stream*)
582 (output-sql distinct database)
583 (write-char #\Space *sql-stream*)))
584 (output-sql (apply #'vector selections) database)
586 (write-string " FROM " *sql-stream*)
588 (list (output-sql (apply #'vector from) database))
589 (string (write-string from *sql-stream*))
590 (t (output-sql from database))))
592 (write-string " INNER JOIN " *sql-stream*)
593 (output-sql inner-join database))
595 (write-string " ON " *sql-stream*)
596 (output-sql on database))
598 (write-string " WHERE " *sql-stream*)
599 (let ((*in-subselect* t))
600 (output-sql where database)))
602 (write-string " GROUP BY " *sql-stream*)
603 (output-sql group-by database))
605 (write-string " HAVING " *sql-stream*)
606 (output-sql having database))
608 (write-string " ORDER BY " *sql-stream*)
610 (do ((order order-by (cdr order)))
612 (let ((item (car order)))
615 (output-sql (car item) database)
616 (format *sql-stream* " ~A" (cadr item)))
618 (output-sql item database)))
620 (write-char #\, *sql-stream*))))
621 (output-sql order-by database)))
623 (write-string " LIMIT " *sql-stream*)
624 (output-sql limit database))
626 (write-string " OFFSET " *sql-stream*)
627 (output-sql offset database))
629 (write-string ")" *sql-stream*))
631 (write-char #\Space *sql-stream*)
632 (output-sql set-operation database)))
635 (defmethod output-sql ((query sql-object-query) database)
636 (declare (ignore database))
637 (with-slots (objects)
640 (format *sql-stream* "(~{~A~^ ~})" objects))))
645 (defclass sql-insert (%sql-expression)
659 "An SQL INSERT statement."))
661 (defmethod output-sql ((ins sql-insert) database)
662 (with-slots (into attributes values query)
664 (write-string "INSERT INTO " *sql-stream*)
665 (output-sql into database)
667 (write-char #\Space *sql-stream*)
668 (output-sql attributes database))
670 (write-string " VALUES " *sql-stream*)
671 (output-sql values database))
673 (write-char #\Space *sql-stream*)
674 (output-sql query database)))
679 (defclass sql-delete (%sql-expression)
687 "An SQL DELETE statement."))
689 (defmethod output-sql ((stmt sql-delete) database)
690 (with-slots (from where)
692 (write-string "DELETE FROM " *sql-stream*)
694 (symbol (write-string (sql-escape from) *sql-stream*))
695 (t (output-sql from database)))
697 (write-string " WHERE " *sql-stream*)
698 (output-sql where database)))
703 (defclass sql-update (%sql-expression)
716 (:documentation "An SQL UPDATE statement."))
718 (defmethod output-sql ((expr sql-update) database)
719 (with-slots (table where attributes values)
721 (flet ((update-assignments ()
722 (mapcar #'(lambda (a b)
723 (make-instance 'sql-assignment-exp
725 :sub-expressions (list a b)))
727 (write-string "UPDATE " *sql-stream*)
728 (output-sql table database)
729 (write-string " SET " *sql-stream*)
730 (output-sql (apply #'vector (update-assignments)) database)
732 (write-string " WHERE " *sql-stream*)
733 (output-sql where database))))
738 (defclass sql-create-table (%sql-expression)
749 :initarg :transactions
752 "An SQL CREATE TABLE statement."))
754 ;; Here's a real warhorse of a function!
756 (declaim (inline listify))
762 (defmethod output-sql ((stmt sql-create-table) database)
763 (flet ((output-column (column-spec)
764 (destructuring-bind (name type &optional db-type &rest constraints)
766 (let ((type (listify type)))
767 (output-sql name database)
768 (write-char #\Space *sql-stream*)
770 (if (stringp db-type) db-type ; override definition
771 (database-get-type-specifier (car type) (cdr type) database))
773 (let ((constraints (database-constraint-statement
774 (if (and db-type (symbolp db-type))
775 (cons db-type constraints)
779 (write-string " " *sql-stream*)
780 (write-string constraints *sql-stream*)))))))
781 (with-slots (name columns modifiers transactions)
783 (write-string "CREATE TABLE " *sql-stream*)
784 (output-sql name database)
785 (write-string " (" *sql-stream*)
786 (do ((column columns (cdr column)))
788 (output-column (car column)))
789 (output-column (car column))
790 (write-string ", " *sql-stream*))
792 (do ((modifier (listify modifiers) (cdr modifier)))
794 (write-string ", " *sql-stream*)
795 (write-string (car modifier) *sql-stream*)))
796 (write-char #\) *sql-stream*)
797 (when (and (eq :mysql (database-underlying-type database))
799 (db-type-transaction-capable? :mysql database))
800 (write-string " Type=InnoDB" *sql-stream*))))
806 (defclass sql-create-view (%sql-expression)
807 ((name :initarg :name :initform nil)
808 (column-list :initarg :column-list :initform nil)
809 (query :initarg :query :initform nil)
810 (with-check-option :initarg :with-check-option :initform nil))
811 (:documentation "An SQL CREATE VIEW statement."))
813 (defmethod output-sql ((stmt sql-create-view) database)
814 (with-slots (name column-list query with-check-option) stmt
815 (write-string "CREATE VIEW " *sql-stream*)
816 (output-sql name database)
817 (when column-list (write-string " " *sql-stream*)
818 (output-sql (listify column-list) database))
819 (write-string " AS " *sql-stream*)
820 (output-sql query database)
821 (when with-check-option (write-string " WITH CHECK OPTION" *sql-stream*))))
825 ;; Column constraint types
827 (defparameter *constraint-types*
829 (cons (symbol-name-default-case "NOT-NULL") "NOT NULL")
830 (cons (symbol-name-default-case "PRIMARY-KEY") "PRIMARY KEY")
831 (cons (symbol-name-default-case "NOT") "NOT")
832 (cons (symbol-name-default-case "NULL") "NULL")
833 (cons (symbol-name-default-case "PRIMARY") "PRIMARY")
834 (cons (symbol-name-default-case "KEY") "KEY")))
837 ;; Convert type spec to sql syntax
840 (defmethod database-constraint-description (constraint database)
841 (declare (ignore database))
842 (let ((output (assoc (symbol-name constraint) *constraint-types*
845 (error 'sql-user-error
846 :message (format nil "unsupported column constraint '~A'"
850 (defmethod database-constraint-statement (constraint-list database)
851 (declare (ignore database))
852 (make-constraints-description constraint-list))
854 (defun make-constraints-description (constraint-list)
857 (do ((constraint constraint-list (cdr constraint)))
858 ((null constraint) string)
859 (let ((output (assoc (symbol-name (car constraint))
863 (error 'sql-user-error
864 :message (format nil "unsupported column constraint '~A'"
866 (setq string (concatenate 'string string (cdr output))))
867 (if (< 1 (length constraint))
868 (setq string (concatenate 'string string " "))))))))