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)
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 (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))))
160 (defmethod output-sql-hash-key ((expr sql-ident-attribute) database)
161 (declare (ignore database))
162 (with-slots (qualifier name type params)
164 (list 'sql-ident-attribute qualifier name type params)))
166 ;; For SQL Identifiers for tables
167 (defclass sql-ident-table (sql-ident)
169 :initarg :table-alias :initform nil))
170 (:documentation "An SQL table identifier."))
172 (defmethod make-load-form ((sql sql-ident-table) &optional environment)
173 (declare (ignore environment))
174 (with-slots (alias name)
176 `(make-instance 'sql-ident-table :name ',name :table-alias ',alias)))
178 (defun generate-sql (expr database)
179 (let ((*sql-stream* (make-string-output-stream)))
180 (output-sql expr database)
181 (get-output-stream-string *sql-stream*)))
183 (defmethod output-sql ((expr sql-ident-table) database)
184 (with-slots (name alias)
187 (write-string (sql-escape (convert-to-db-default-case (symbol-name name) database)) *sql-stream*)
189 (write-string (sql-escape (convert-to-db-default-case (symbol-name name) database)) *sql-stream*)
190 (write-char #\Space *sql-stream*)
191 (format *sql-stream* "~s" alias))))
195 (defmethod database-output-sql ((self duration) database)
196 (declare (ignore database))
197 (format nil "'~a'" (duration-timestring self)))
199 (defmethod database-output-sql ((self money) database)
200 (database-output-sql (slot-value self 'odcl::units) database))
204 (defmethod output-sql-hash-key ((expr sql-ident-table) database)
205 (declare (ignore database))
206 (with-slots (name alias)
208 (list 'sql-ident-table name alias)))
210 (defclass sql-relational-exp (%sql-expression)
215 :initarg :sub-expressions
217 (:documentation "An SQL relational expression."))
219 (defmethod collect-table-refs ((sql sql-relational-exp))
221 (dolist (exp (slot-value sql 'sub-expressions))
222 (let ((refs (collect-table-refs exp)))
223 (if refs (setf tabs (append refs tabs)))))
224 (remove-duplicates tabs
225 :test (lambda (tab1 tab2)
226 (equal (slot-value tab1 'name)
227 (slot-value tab2 'name))))))
232 ;; Write SQL for relational operators (like 'AND' and 'OR').
233 ;; should do arity checking of subexpressions
235 (defmethod output-sql ((expr sql-relational-exp) database)
236 (with-slots (operator sub-expressions)
238 (let ((subs (if (consp (car sub-expressions))
239 (car sub-expressions)
241 (write-char #\( *sql-stream*)
242 (do ((sub subs (cdr sub)))
243 ((null (cdr sub)) (output-sql (car sub) database))
244 (output-sql (car sub) database)
245 (write-char #\Space *sql-stream*)
246 (output-sql operator database)
247 (write-char #\Space *sql-stream*))
248 (write-char #\) *sql-stream*)))
251 (defclass sql-upcase-like (sql-relational-exp)
253 (:documentation "An SQL 'like' that upcases its arguments."))
255 ;; Write SQL for relational operators (like 'AND' and 'OR').
256 ;; should do arity checking of subexpressions
258 (defmethod output-sql ((expr sql-upcase-like) database)
259 (flet ((write-term (term)
260 (write-string "upper(" *sql-stream*)
261 (output-sql term database)
262 (write-char #\) *sql-stream*)))
263 (with-slots (sub-expressions)
265 (let ((subs (if (consp (car sub-expressions))
266 (car sub-expressions)
268 (write-char #\( *sql-stream*)
269 (do ((sub subs (cdr sub)))
270 ((null (cdr sub)) (write-term (car sub)))
271 (write-term (car sub))
272 (write-string " LIKE " *sql-stream*))
273 (write-char #\) *sql-stream*))))
276 (defclass sql-assignment-exp (sql-relational-exp)
278 (:documentation "An SQL Assignment expression."))
281 (defmethod output-sql ((expr sql-assignment-exp) database)
282 (with-slots (operator sub-expressions)
284 (do ((sub sub-expressions (cdr sub)))
285 ((null (cdr sub)) (output-sql (car sub) database))
286 (output-sql (car sub) database)
287 (write-char #\Space *sql-stream*)
288 (output-sql operator database)
289 (write-char #\Space *sql-stream*)))
292 (defclass sql-value-exp (%sql-expression)
300 "An SQL value expression.")
303 (defmethod collect-table-refs ((sql sql-value-exp))
305 (if (listp (slot-value sql 'components))
307 (dolist (exp (slot-value sql 'components))
308 (let ((refs (collect-table-refs exp)))
309 (if refs (setf tabs (append refs tabs)))))
310 (remove-duplicates tabs
311 :test (lambda (tab1 tab2)
312 (equal (slot-value tab1 'name)
313 (slot-value tab2 'name)))))
318 (defmethod output-sql ((expr sql-value-exp) database)
319 (with-slots (modifier components)
323 (write-char #\( *sql-stream*)
324 (output-sql modifier database)
325 (write-char #\Space *sql-stream*)
326 (output-sql components database)
327 (write-char #\) *sql-stream*))
328 (output-sql components database))))
330 (defclass sql-typecast-exp (sql-value-exp)
332 (:documentation "An SQL typecast expression."))
334 (defmethod output-sql ((expr sql-typecast-exp) database)
335 (database-output-sql expr database))
337 (defmethod database-output-sql ((expr sql-typecast-exp) database)
338 (with-slots (components)
340 (output-sql components database)))
343 (defmethod collect-table-refs ((sql sql-typecast-exp))
344 (when (slot-value sql 'components)
345 (collect-table-refs (slot-value sql 'components))))
347 (defclass sql-function-exp (%sql-expression)
355 "An SQL function expression."))
357 (defmethod collect-table-refs ((sql sql-function-exp))
359 (dolist (exp (slot-value sql 'components))
360 (let ((refs (collect-table-refs exp)))
361 (if refs (setf tabs (append refs tabs)))))
362 (remove-duplicates tabs
363 :test (lambda (tab1 tab2)
364 (equal (slot-value tab1 'name)
365 (slot-value tab2 'name))))))
367 (defmethod output-sql ((expr sql-function-exp) database)
368 (with-slots (name args)
370 (output-sql name database)
371 (when args (output-sql args database)))
374 (defclass sql-query (%sql-expression)
385 :initarg :set-operation
412 :initarg :order-by-descending
414 (:documentation "An SQL SELECT query."))
416 (defmethod collect-table-refs ((sql sql-query))
417 (remove-duplicates (collect-table-refs (slot-value sql 'where))
418 :test (lambda (tab1 tab2)
419 (equal (slot-value tab1 'name)
420 (slot-value tab2 'name)))))
422 (defvar *select-arguments*
423 '(:all :database :distinct :flatp :from :group-by :having :order-by
424 :order-by-descending :set-operation :where :offset :limit))
426 (defun query-arg-p (sym)
427 (member sym *select-arguments*))
429 (defun query-get-selections (select-args)
430 "Return two values: the list of select-args up to the first keyword,
431 uninclusive, and the args from that keyword to the end."
432 (let ((first-key-arg (position-if #'query-arg-p select-args)))
434 (values (subseq select-args 0 first-key-arg)
435 (subseq select-args first-key-arg))
438 (defun make-query (&rest args)
439 (flet ((select-objects (target-args)
441 (every #'(lambda (arg)
443 (find-class arg nil)))
445 (multiple-value-bind (selections arglist)
446 (query-get-selections args)
447 (if (select-objects selections)
448 (apply #'select args)
449 (destructuring-bind (&key all flatp set-operation distinct from where
450 group-by having order-by order-by-descending
451 offset limit &allow-other-keys)
453 (if (null selections)
454 (error "No target columns supplied to select statement."))
456 (error "No source tables supplied to select statement."))
457 (make-instance 'sql-query :selections selections
458 :all all :flatp flatp :set-operation set-operation
459 :distinct distinct :from from :where where
460 :limit limit :offset offset
461 :group-by group-by :having having :order-by order-by
462 :order-by-descending order-by-descending))))))
464 (defvar *in-subselect* nil)
466 (defmethod output-sql ((query sql-query) database)
467 (with-slots (distinct selections from where group-by having order-by
468 order-by-descending limit offset)
471 (write-string "(" *sql-stream*))
472 (write-string "SELECT " *sql-stream*)
474 (write-string "DISTINCT " *sql-stream*)
475 (unless (eql t distinct)
476 (write-string "ON " *sql-stream*)
477 (output-sql distinct database)
478 (write-char #\Space *sql-stream*)))
479 (output-sql (apply #'vector selections) database)
480 (write-string " FROM " *sql-stream*)
482 (output-sql (apply #'vector from) database)
483 (output-sql from database))
485 (write-string " WHERE " *sql-stream*)
486 (let ((*in-subselect* t))
487 (output-sql where database)))
489 (write-string " GROUP BY " *sql-stream*)
490 (output-sql group-by database))
492 (write-string " HAVING " *sql-stream*)
493 (output-sql having database))
495 (write-string " ORDER BY " *sql-stream*)
497 (do ((order order-by (cdr order)))
499 (output-sql (car order) database)
501 (write-char #\, *sql-stream*)))
502 (output-sql order-by database)))
503 (when order-by-descending
504 (write-string " ORDER BY " *sql-stream*)
505 (if (listp order-by-descending)
506 (do ((order order-by-descending (cdr order)))
508 (output-sql (car order) database)
510 (write-char #\, *sql-stream*)))
511 (output-sql order-by-descending database))
512 (write-string " DESC " *sql-stream*))
514 (write-string " LIMIT " *sql-stream*)
515 (output-sql limit database))
517 (write-string " OFFSET " *sql-stream*)
518 (output-sql offset database))
520 (write-string ")" *sql-stream*)))
525 (defclass sql-insert (%sql-expression)
539 "An SQL INSERT statement."))
541 (defmethod output-sql ((ins sql-insert) database)
542 (with-slots (into attributes values query)
544 (write-string "INSERT INTO " *sql-stream*)
545 (output-sql into database)
547 (write-char #\Space *sql-stream*)
548 (output-sql attributes database))
550 (write-string " VALUES " *sql-stream*)
551 (output-sql values database))
553 (write-char #\Space *sql-stream*)
554 (output-sql query database)))
559 (defclass sql-delete (%sql-expression)
567 "An SQL DELETE statement."))
569 (defmethod output-sql ((stmt sql-delete) database)
570 (with-slots (from where)
572 (write-string "DELETE FROM " *sql-stream*)
574 (symbol (write-string (sql-escape from) *sql-stream*))
575 (t (output-sql from database)))
577 (write-string " WHERE " *sql-stream*)
578 (output-sql where database)))
583 (defclass sql-update (%sql-expression)
596 (:documentation "An SQL UPDATE statement."))
598 (defmethod output-sql ((expr sql-update) database)
599 (with-slots (table where attributes values)
601 (flet ((update-assignments ()
602 (mapcar #'(lambda (a b)
603 (make-instance 'sql-assignment-exp
605 :sub-expressions (list a b)))
607 (write-string "UPDATE " *sql-stream*)
608 (output-sql table database)
609 (write-string " SET " *sql-stream*)
610 (output-sql (apply #'vector (update-assignments)) database)
612 (write-string " WHERE " *sql-stream*)
613 (output-sql where database))))
618 (defclass sql-create-table (%sql-expression)
629 :initarg :transactions
632 "An SQL CREATE TABLE statement."))
634 ;; Here's a real warhorse of a function!
641 (defmethod output-sql ((stmt sql-create-table) database)
642 (flet ((output-column (column-spec)
643 (destructuring-bind (name type &optional db-type &rest constraints)
645 (let ((type (listify type)))
646 (output-sql name database)
647 (write-char #\Space *sql-stream*)
649 (if (stringp db-type) db-type ; override definition
650 (database-get-type-specifier (car type) (cdr type) database))
653 (database-constraint-statement constraints database)))
655 (write-string " " *sql-stream*)
656 (write-string constraints *sql-stream*)))))))
657 (with-slots (name columns modifiers transactions)
659 (write-string "CREATE TABLE " *sql-stream*)
660 (output-sql name database)
661 (write-string " (" *sql-stream*)
662 (do ((column columns (cdr column)))
664 (output-column (car column)))
665 (output-column (car column))
666 (write-string ", " *sql-stream*))
668 (do ((modifier (listify modifiers) (cdr modifier)))
670 (write-string ", " *sql-stream*)
671 (write-string (car modifier) *sql-stream*)))
672 (write-char #\) *sql-stream*)
673 (when (and (eq :mysql (database-underlying-type database))
675 (db-type-transaction-capable? :mysql database))
676 (write-string " Type=InnoDB" *sql-stream*))))
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."))
689 (defmethod output-sql ((stmt sql-create-view) 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*))))
701 ;; Column constraint types
703 (defparameter *constraint-types*
705 (cons (symbol-name-default-case "NOT-NULL") "NOT NULL")
706 (cons (symbol-name-default-case "PRIMARY-KEY") "PRIMARY KEY")))
709 ;; Convert type spec to sql syntax
712 (defmethod database-constraint-description (constraint database)
713 (declare (ignore database))
714 (let ((output (assoc (symbol-name constraint) *constraint-types*
717 (error 'clsql-sql-syntax-error
718 :reason (format nil "unsupported column constraint '~a'"
722 (defmethod database-constraint-statement (constraint-list database)
723 (declare (ignore database))
724 (make-constraints-description constraint-list))
726 (defun make-constraints-description (constraint-list)
729 (do ((constraint constraint-list (cdr constraint)))
730 ((null constraint) string)
731 (let ((output (assoc (symbol-name (car constraint))
735 (error 'clsql-sql-syntax-error
736 :reason (format nil "unsupported column constraint '~a'"
738 (setq string (concatenate 'string string (cdr output))))
739 (if (< 1 (length constraint))
740 (setq string (concatenate 'string string " "))))))))