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 (multiple-value-bind (selections arglist)
440 (query-get-selections args)
441 (destructuring-bind (&key all flatp set-operation distinct from where
442 group-by having order-by order-by-descending
443 offset limit &allow-other-keys)
445 (if (null selections)
446 (error "No target columns supplied to select statement."))
448 (error "No source tables supplied to select statement."))
449 (make-instance 'sql-query :selections selections
450 :all all :flatp flatp :set-operation set-operation
451 :distinct distinct :from from :where where
452 :limit limit :offset offset
453 :group-by group-by :having having :order-by order-by
454 :order-by-descending order-by-descending))))
456 (defvar *in-subselect* nil)
458 (defmethod output-sql ((query sql-query) database)
459 (with-slots (distinct selections from where group-by having order-by
460 order-by-descending limit offset)
463 (write-string "(" *sql-stream*))
464 (write-string "SELECT " *sql-stream*)
466 (write-string "DISTINCT " *sql-stream*)
467 (unless (eql t distinct)
468 (write-string "ON " *sql-stream*)
469 (output-sql distinct database)
470 (write-char #\Space *sql-stream*)))
471 (output-sql (apply #'vector selections) database)
472 (write-string " FROM " *sql-stream*)
474 (output-sql (apply #'vector from) database)
475 (output-sql from database))
477 (write-string " WHERE " *sql-stream*)
478 (let ((*in-subselect* t))
479 (output-sql where database)))
481 (write-string " GROUP BY " *sql-stream*)
482 (output-sql group-by database))
484 (write-string " HAVING " *sql-stream*)
485 (output-sql having database))
487 (write-string " ORDER BY " *sql-stream*)
489 (do ((order order-by (cdr order)))
491 (output-sql (car order) database)
493 (write-char #\, *sql-stream*)))
494 (output-sql order-by database)))
495 (when order-by-descending
496 (write-string " ORDER BY " *sql-stream*)
497 (if (listp order-by-descending)
498 (do ((order order-by-descending (cdr order)))
500 (output-sql (car order) database)
502 (write-char #\, *sql-stream*)))
503 (output-sql order-by-descending database))
504 (write-string " DESC " *sql-stream*))
506 (write-string " LIMIT " *sql-stream*)
507 (output-sql limit database))
509 (write-string " OFFSET " *sql-stream*)
510 (output-sql offset database))
512 (write-string ")" *sql-stream*)))
517 (defclass sql-insert (%sql-expression)
531 "An SQL INSERT statement."))
533 (defmethod output-sql ((ins sql-insert) database)
534 (with-slots (into attributes values query)
536 (write-string "INSERT INTO " *sql-stream*)
537 (output-sql into database)
539 (write-char #\Space *sql-stream*)
540 (output-sql attributes database))
542 (write-string " VALUES " *sql-stream*)
543 (output-sql values database))
545 (write-char #\Space *sql-stream*)
546 (output-sql query database)))
551 (defclass sql-delete (%sql-expression)
559 "An SQL DELETE statement."))
561 (defmethod output-sql ((stmt sql-delete) database)
562 (with-slots (from where)
564 (write-string "DELETE FROM " *sql-stream*)
566 (symbol (write-string (sql-escape from) *sql-stream*))
567 (t (output-sql from database)))
569 (write-string " WHERE " *sql-stream*)
570 (output-sql where database)))
575 (defclass sql-update (%sql-expression)
588 (:documentation "An SQL UPDATE statement."))
590 (defmethod output-sql ((expr sql-update) database)
591 (with-slots (table where attributes values)
593 (flet ((update-assignments ()
594 (mapcar #'(lambda (a b)
595 (make-instance 'sql-assignment-exp
597 :sub-expressions (list a b)))
599 (write-string "UPDATE " *sql-stream*)
600 (output-sql table database)
601 (write-string " SET " *sql-stream*)
602 (output-sql (apply #'vector (update-assignments)) database)
604 (write-string " WHERE " *sql-stream*)
605 (output-sql where database))))
610 (defclass sql-create-table (%sql-expression)
621 :initarg :transactions
624 "An SQL CREATE TABLE statement."))
626 ;; Here's a real warhorse of a function!
633 (defmethod output-sql ((stmt sql-create-table) database)
634 (flet ((output-column (column-spec)
635 (destructuring-bind (name type &optional db-type &rest constraints)
637 (let ((type (listify type)))
638 (output-sql name database)
639 (write-char #\Space *sql-stream*)
641 (if (stringp db-type) db-type ; override definition
642 (database-get-type-specifier (car type) (cdr type) database))
645 (database-constraint-statement constraints database)))
647 (write-string " " *sql-stream*)
648 (write-string constraints *sql-stream*)))))))
649 (with-slots (name columns modifiers transactions)
651 (write-string "CREATE TABLE " *sql-stream*)
652 (output-sql name database)
653 (write-string " (" *sql-stream*)
654 (do ((column columns (cdr column)))
656 (output-column (car column)))
657 (output-column (car column))
658 (write-string ", " *sql-stream*))
660 (do ((modifier (listify modifiers) (cdr modifier)))
662 (write-string ", " *sql-stream*)
663 (write-string (car modifier) *sql-stream*)))
664 (write-char #\) *sql-stream*)
665 (when (and (eq :mysql (database-underlying-type database))
667 (db-type-transaction-capable? :mysql database))
668 (write-string " Type=InnoDB" *sql-stream*))))
674 (defclass sql-create-view (%sql-expression)
675 ((name :initarg :name :initform nil)
676 (column-list :initarg :column-list :initform nil)
677 (query :initarg :query :initform nil)
678 (with-check-option :initarg :with-check-option :initform nil))
679 (:documentation "An SQL CREATE VIEW statement."))
681 (defmethod output-sql ((stmt sql-create-view) database)
682 (with-slots (name column-list query with-check-option) stmt
683 (write-string "CREATE VIEW " *sql-stream*)
684 (output-sql name database)
685 (when column-list (write-string " " *sql-stream*)
686 (output-sql (listify column-list) database))
687 (write-string " AS " *sql-stream*)
688 (output-sql query database)
689 (when with-check-option (write-string " WITH CHECK OPTION" *sql-stream*))))
693 ;; Column constraint types
695 (defparameter *constraint-types*
697 (cons (symbol-name-default-case "NOT-NULL") "NOT NULL")
698 (cons (symbol-name-default-case "PRIMARY-KEY") "PRIMARY KEY")))
701 ;; Convert type spec to sql syntax
704 (defmethod database-constraint-description (constraint database)
705 (declare (ignore database))
706 (let ((output (assoc (symbol-name constraint) *constraint-types*
709 (error 'clsql-sql-syntax-error
710 :reason (format nil "unsupported column constraint '~a'"
714 (defmethod database-constraint-statement (constraint-list database)
715 (declare (ignore database))
716 (make-constraints-description constraint-list))
718 (defun make-constraints-description (constraint-list)
721 (do ((constraint constraint-list (cdr constraint)))
722 ((null constraint) string)
723 (let ((output (assoc (symbol-name (car constraint))
727 (error 'clsql-sql-syntax-error
728 :reason (format nil "unsupported column constraint '~a'"
730 (setq string (concatenate 'string string (cdr output))))
731 (if (< 1 (length constraint))
732 (setq string (concatenate 'string string " "))))))))