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 ;;;; *************************************************************************
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)
126 (:documentation "An SQL Attribute identifier."))
128 (defmethod collect-table-refs (sql)
129 (declare (ignore sql))
132 (defmethod collect-table-refs ((sql sql-ident-attribute))
133 (let ((qual (slot-value sql 'qualifier)))
134 (if (and qual (symbolp (slot-value sql 'qualifier)))
135 (list (make-instance 'sql-ident-table :name
136 (slot-value sql 'qualifier))))))
138 (defmethod make-load-form ((sql sql-ident-attribute) &optional environment)
139 (declare (ignore environment))
140 (with-slots (qualifier type name)
142 `(make-instance 'sql-ident-attribute :name ',name
143 :qualifier ',qualifier
146 (defmethod output-sql ((expr sql-ident-attribute) database)
147 (with-slots (qualifier name type params)
149 (if (and (not qualifier) (not type))
150 (write-string (sql-escape (convert-to-db-default-case
151 (symbol-name name) database)) *sql-stream*)
152 ;;; KMR: The TYPE field is used by CommonSQL for type conversion -- it
153 ;;; should not be output in SQL statements
155 (format *sql-stream* "~@[~A.~]~A~@[ ~A~]"
157 (convert-to-db-default-case (sql-escape qualifier) database))
158 (sql-escape (convert-to-db-default-case name database))
160 (convert-to-db-default-case (symbol-name type) database)))
161 (format *sql-stream* "~@[~A.~]~A"
163 (convert-to-db-default-case (sql-escape qualifier) database))
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 params)
171 (list 'sql-ident-attribute qualifier name type params)))
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)))
381 (defclass sql-query (%sql-expression)
392 :initarg :set-operation
419 :initarg :order-by-descending
427 (:documentation "An SQL SELECT query."))
429 (defclass sql-object-query (%sql-expression)
443 (defmethod collect-table-refs ((sql sql-query))
444 (remove-duplicates (collect-table-refs (slot-value sql 'where))
445 :test (lambda (tab1 tab2)
446 (equal (slot-value tab1 'name)
447 (slot-value tab2 'name)))))
449 (defvar *select-arguments*
450 '(:all :database :distinct :flatp :from :group-by :having :order-by
451 :order-by-descending :set-operation :where :offset :limit
454 (defun query-arg-p (sym)
455 (member sym *select-arguments*))
457 (defun query-get-selections (select-args)
458 "Return two values: the list of select-args up to the first keyword,
459 uninclusive, and the args from that keyword to the end."
460 (let ((first-key-arg (position-if #'query-arg-p select-args)))
462 (values (subseq select-args 0 first-key-arg)
463 (subseq select-args first-key-arg))
466 (defun make-query (&rest args)
467 (flet ((select-objects (target-args)
469 (every #'(lambda (arg)
471 (find-class arg nil)))
473 (multiple-value-bind (selections arglist)
474 (query-get-selections args)
475 (if (select-objects selections)
476 (destructuring-bind (&key flatp refresh &allow-other-keys) arglist
477 (make-instance 'sql-object-query :objects selections
478 :flatp flatp :refresh refresh
480 (destructuring-bind (&key all flatp set-operation distinct from where
481 group-by having order-by order-by-descending
482 offset limit inner-join on &allow-other-keys)
484 (if (null selections)
485 (error "No target columns supplied to select statement."))
487 (error "No source tables supplied to select statement."))
488 (make-instance 'sql-query :selections selections
489 :all all :flatp flatp :set-operation set-operation
490 :distinct distinct :from from :where where
491 :limit limit :offset offset
492 :group-by group-by :having having :order-by order-by
493 :order-by-descending order-by-descending
494 :inner-join inner-join :on on))))))
496 (defvar *in-subselect* nil)
498 (defmethod output-sql ((query sql-query) database)
499 (with-slots (distinct selections from where group-by having order-by
500 order-by-descending limit offset inner-join on)
503 (write-string "(" *sql-stream*))
504 (write-string "SELECT " *sql-stream*)
506 (write-string "DISTINCT " *sql-stream*)
507 (unless (eql t distinct)
508 (write-string "ON " *sql-stream*)
509 (output-sql distinct database)
510 (write-char #\Space *sql-stream*)))
511 (output-sql (apply #'vector selections) database)
513 (write-string " FROM " *sql-stream*)
515 (output-sql (apply #'vector from) database)
516 (output-sql from database)))
518 (write-string " INNER JOIN " *sql-stream*)
519 (output-sql inner-join database))
521 (write-string " ON " *sql-stream*)
522 (output-sql on database))
524 (write-string " WHERE " *sql-stream*)
525 (let ((*in-subselect* t))
526 (output-sql where database)))
528 (write-string " GROUP BY " *sql-stream*)
529 (output-sql group-by database))
531 (write-string " HAVING " *sql-stream*)
532 (output-sql having database))
534 (write-string " ORDER BY " *sql-stream*)
536 (do ((order order-by (cdr order)))
538 (output-sql (car order) database)
540 (write-char #\, *sql-stream*)))
541 (output-sql order-by database)))
542 (when order-by-descending
543 (write-string " ORDER BY " *sql-stream*)
544 (if (listp order-by-descending)
545 (do ((order order-by-descending (cdr order)))
547 (output-sql (car order) database)
549 (write-char #\, *sql-stream*)))
550 (output-sql order-by-descending database))
551 (write-string " DESC " *sql-stream*))
553 (write-string " LIMIT " *sql-stream*)
554 (output-sql limit database))
556 (write-string " OFFSET " *sql-stream*)
557 (output-sql offset database))
559 (write-string ")" *sql-stream*)))
562 (defmethod output-sql ((query sql-object-query) database)
563 (with-slots (objects)
566 (format *sql-stream* "(~{~A~^ ~})" objects))))
571 (defclass sql-insert (%sql-expression)
585 "An SQL INSERT statement."))
587 (defmethod output-sql ((ins sql-insert) database)
588 (with-slots (into attributes values query)
590 (write-string "INSERT INTO " *sql-stream*)
591 (output-sql into database)
593 (write-char #\Space *sql-stream*)
594 (output-sql attributes database))
596 (write-string " VALUES " *sql-stream*)
597 (output-sql values database))
599 (write-char #\Space *sql-stream*)
600 (output-sql query database)))
605 (defclass sql-delete (%sql-expression)
613 "An SQL DELETE statement."))
615 (defmethod output-sql ((stmt sql-delete) database)
616 (with-slots (from where)
618 (write-string "DELETE FROM " *sql-stream*)
620 (symbol (write-string (sql-escape from) *sql-stream*))
621 (t (output-sql from database)))
623 (write-string " WHERE " *sql-stream*)
624 (output-sql where database)))
629 (defclass sql-update (%sql-expression)
642 (:documentation "An SQL UPDATE statement."))
644 (defmethod output-sql ((expr sql-update) database)
645 (with-slots (table where attributes values)
647 (flet ((update-assignments ()
648 (mapcar #'(lambda (a b)
649 (make-instance 'sql-assignment-exp
651 :sub-expressions (list a b)))
653 (write-string "UPDATE " *sql-stream*)
654 (output-sql table database)
655 (write-string " SET " *sql-stream*)
656 (output-sql (apply #'vector (update-assignments)) database)
658 (write-string " WHERE " *sql-stream*)
659 (output-sql where database))))
664 (defclass sql-create-table (%sql-expression)
675 :initarg :transactions
678 "An SQL CREATE TABLE statement."))
680 ;; Here's a real warhorse of a function!
687 (defmethod output-sql ((stmt sql-create-table) database)
688 (flet ((output-column (column-spec)
689 (destructuring-bind (name type &optional db-type &rest constraints)
691 (let ((type (listify type)))
692 (output-sql name database)
693 (write-char #\Space *sql-stream*)
695 (if (stringp db-type) db-type ; override definition
696 (database-get-type-specifier (car type) (cdr type) database))
699 (database-constraint-statement constraints database)))
701 (write-string " " *sql-stream*)
702 (write-string constraints *sql-stream*)))))))
703 (with-slots (name columns modifiers transactions)
705 (write-string "CREATE TABLE " *sql-stream*)
706 (output-sql name database)
707 (write-string " (" *sql-stream*)
708 (do ((column columns (cdr column)))
710 (output-column (car column)))
711 (output-column (car column))
712 (write-string ", " *sql-stream*))
714 (do ((modifier (listify modifiers) (cdr modifier)))
716 (write-string ", " *sql-stream*)
717 (write-string (car modifier) *sql-stream*)))
718 (write-char #\) *sql-stream*)
719 (when (and (eq :mysql (database-underlying-type database))
721 (db-type-transaction-capable? :mysql database))
722 (write-string " Type=InnoDB" *sql-stream*))))
728 (defclass sql-create-view (%sql-expression)
729 ((name :initarg :name :initform nil)
730 (column-list :initarg :column-list :initform nil)
731 (query :initarg :query :initform nil)
732 (with-check-option :initarg :with-check-option :initform nil))
733 (:documentation "An SQL CREATE VIEW statement."))
735 (defmethod output-sql ((stmt sql-create-view) database)
736 (with-slots (name column-list query with-check-option) stmt
737 (write-string "CREATE VIEW " *sql-stream*)
738 (output-sql name database)
739 (when column-list (write-string " " *sql-stream*)
740 (output-sql (listify column-list) database))
741 (write-string " AS " *sql-stream*)
742 (output-sql query database)
743 (when with-check-option (write-string " WITH CHECK OPTION" *sql-stream*))))
747 ;; Column constraint types
749 (defparameter *constraint-types*
751 (cons (symbol-name-default-case "NOT-NULL") "NOT NULL")
752 (cons (symbol-name-default-case "PRIMARY-KEY") "PRIMARY KEY")))
755 ;; Convert type spec to sql syntax
758 (defmethod database-constraint-description (constraint database)
759 (declare (ignore database))
760 (let ((output (assoc (symbol-name constraint) *constraint-types*
763 (error 'clsql-sql-syntax-error
764 :reason (format nil "unsupported column constraint '~a'"
768 (defmethod database-constraint-statement (constraint-list database)
769 (declare (ignore database))
770 (make-constraints-description constraint-list))
772 (defun make-constraints-description (constraint-list)
775 (do ((constraint constraint-list (cdr constraint)))
776 ((null constraint) string)
777 (let ((output (assoc (symbol-name (car constraint))
781 (error 'clsql-sql-syntax-error
782 :reason (format nil "unsupported column constraint '~a'"
784 (setq string (concatenate 'string string (cdr output))))
785 (if (< 1 (length constraint))
786 (setq string (concatenate 'string string " "))))))))