1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
4 ;;;; Classes defining SQL expressions and methods for formatting the
5 ;;;; appropriate SQL commands.
7 ;;;; This file is part of CLSQL.
9 ;;;; CLSQL users are granted the rights to distribute and use this software
10 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
11 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
12 ;;;; *************************************************************************
14 (in-package #:clsql-sys)
16 (defvar +empty-string+ "''")
18 (defvar +null-string+ "NULL")
20 (defvar *sql-stream* nil
21 "stream which accumulates SQL output")
23 (defclass %database-identifier ()
24 ((escaped :accessor escaped :initarg :escaped :initform nil)
25 (unescaped :accessor unescaped :initarg :unescaped :initform nil))
27 "A database identifier represents a string/symbol ready to be spliced
28 into a sql string. It keeps references to both the escaped and
29 unescaped versions so that unescaped versions can be compared to the
30 results of list-tables/views/attributes etc. It also allows you to be
31 sure that an identifier is escaped only once.
33 (escaped-database-identifiers *any-reasonable-object*) should be called to
34 produce a string that is safe to splice directly into sql strings.
36 (unescaped-database-identifier *any-reasonable-object*) is generally what
37 you pass to it with the exception that symbols have been
38 clsql-sys:sql-escape which converts to a string and changes - to _ (so
39 that unescaped can be compared to the results of eg: list-tables)
42 (defmethod escaped ((it null)) it)
43 (defmethod unescaped ((it null)) it)
45 (defun database-identifier-equal (i1 i2 &optional (database clsql-sys:*default-database*))
46 (setf i1 (database-identifier i1 database)
47 i2 (database-identifier i2 database))
49 (if (symbolp (unescaped i))
50 (sql-escape (unescaped i))
52 (or ;; check for an exact match
53 (equal (escaped-database-identifier i1)
54 (escaped-database-identifier i2))
55 ;; check for an inexact match if we had symbols in the mix
56 (string-equal (cast i1) (cast i2)))))
58 (defun delistify-dsd (list)
59 "Some MOPs, like openmcl 0.14.2, cons attribute values in a list."
60 (if (and (listp list) (null (cdr list)))
64 (defun special-char-p (s)
65 "Check if a string has any special characters"
66 (loop for char across s
67 thereis (find char '(#\space #\, #\. #\! #\@ #\# #\$ #\% #\' #\"
68 #\^ #\& #\* #\| #\( #\) #\- #\+ #\< #\>
71 (defun special-cased-symbol-p (sym)
72 "Should the symbols case be preserved, or should we convert to default casing"
73 (let ((name (symbol-name sym)))
74 (case (readtable-case *readtable*)
75 (:upcase (not (string= (string-upcase name) name)))
76 (:downcase (not (string= (string-downcase name) name)))
79 (defun %make-database-identifier (inp &optional database)
80 "We want to quote an identifier if it came to us as a string or if it has special characters
82 (labels ((%escape-identifier (inp &optional orig)
83 "Quote an identifier unless it is already quoted"
86 ((and (eql #\" (elt inp 0))
87 (eql #\" (elt inp (- (length inp) 1))))
88 (make-instance '%database-identifier :unescaped (or orig inp) :escaped inp))
90 '%database-identifier :unescaped (or orig inp) :escaped
92 'string "\"" (replace-all inp "\"" "\\\"") "\""))))))
94 (string (%escape-identifier inp))
95 (%database-identifier inp)
97 (let ((s (sql-escape inp)))
98 (if (and (not (eql '* inp)) (special-char-p s))
100 (if (special-cased-symbol-p inp)
102 (convert-to-db-default-case s database)) inp)
103 (make-instance '%database-identifier :escaped s :unescaped inp))
106 (defun combine-database-identifiers (ids &optional (database clsql-sys:*default-database*)
107 &aux res all-sym? pkg)
108 "Create a new database identifier by combining parts in a reasonable way
110 (setf ids (mapcar #'database-identifier ids)
111 all-sym? (every (lambda (i) (symbolp (unescaped i))) ids)
112 pkg (when all-sym? (symbol-package (unescaped (first ids)))))
116 (%database-identifier (cast (unescaped i)))
120 (convert-to-db-default-case (sql-escape i) database)))
126 (concatenate 'string (cast i1) "_" (cast i2))
128 (setf res (reduce #'comb ids))
130 (if all-sym? (intern res pkg) res)
133 (defun escaped-database-identifier (name &optional database find-class-p)
134 (escaped (database-identifier name database find-class-p)))
136 (defun unescaped-database-identifier (name &optional database find-class-p)
137 (unescaped (database-identifier name database find-class-p)))
139 (defun sql-output (sql-expr &optional (database *default-database*))
140 "Top-level call for generating SQL strings. Returns an SQL
141 string appropriate for DATABASE which corresponds to the
142 supplied lisp expression SQL-EXPR."
143 (with-output-to-string (*sql-stream*)
144 (output-sql sql-expr database)))
146 (defmethod output-sql (expr database)
147 (write-string (database-output-sql expr database) *sql-stream*)
151 (defvar *output-hash*
152 (make-weak-hash-table :test #'equal)
153 "For caching generated SQL strings, set to NIL to disable."
156 (defmethod output-sql :around ((sql t) database)
157 (if (null *output-hash*)
159 (let* ((hash-key (output-sql-hash-key sql database))
160 (hash-value (when hash-key (gethash hash-key *output-hash*))))
161 (cond ((and hash-key hash-value)
162 (write-string hash-value *sql-stream*))
164 (let ((*sql-stream* (make-string-output-stream)))
166 (setf hash-value (get-output-stream-string *sql-stream*))
167 (setf (gethash hash-key *output-hash*) hash-value))
168 (write-string hash-value *sql-stream*))
170 (call-next-method))))))
172 (defmethod output-sql-hash-key (expr database)
173 (declare (ignore expr database))
177 (defclass %sql-expression ()
180 (defmethod output-sql ((expr %sql-expression) database)
181 (declare (ignore database))
182 (write-string +null-string+ *sql-stream*))
184 (defmethod print-object ((self %sql-expression) stream)
185 (print-unreadable-object
186 (self stream :type t)
187 (write-string (sql-output self) stream))
190 ;; For straight up strings
192 (defclass sql (%sql-expression)
196 (:documentation "A literal SQL expression."))
198 (defmethod make-load-form ((sql sql) &optional environment)
199 (declare (ignore environment))
202 `(make-instance 'sql :string ',text)))
204 (defmethod output-sql ((expr sql) database)
205 (declare (ignore database))
206 (write-string (slot-value expr 'text) *sql-stream*)
209 (defmethod print-object ((ident sql) stream)
210 (format stream "#<~S \"~A\">"
212 (sql-output ident nil))
215 ;; For SQL Identifiers of generic type
217 (defclass sql-ident (%sql-expression)
220 :initform +null-string+))
221 (:documentation "An SQL identifer."))
223 (defmethod make-load-form ((sql sql-ident) &optional environment)
224 (declare (ignore environment))
227 `(make-instance 'sql-ident :name ',name)))
229 (defmethod output-sql ((expr %database-identifier) database)
230 (write-string (escaped expr) *sql-stream*))
232 (defmethod output-sql ((expr sql-ident) database)
233 (with-slots (name) expr
234 (write-string (escaped-database-identifier name database) *sql-stream*))
237 ;; For SQL Identifiers for attributes
239 (defclass sql-ident-attribute (sql-ident)
242 :initform +null-string+)
245 :initform +null-string+))
246 (:documentation "An SQL Attribute identifier."))
248 (defmethod collect-table-refs (sql)
249 (declare (ignore sql))
252 (defmethod collect-table-refs ((sql sql-ident-attribute))
253 (let ((qual (slot-value sql 'qualifier)))
255 ;; going to be used as a table, search classes
258 :name (database-identifier qual nil t))))))
260 (defmethod make-load-form ((sql sql-ident-attribute) &optional environment)
261 (declare (ignore environment))
262 (with-slots (qualifier type name)
264 `(make-instance 'sql-ident-attribute :name ',name
265 :qualifier ',qualifier
268 (defmethod output-sql-hash-key ((expr sql-ident-attribute) database)
269 (with-slots (qualifier name type)
271 (list (and database (database-underlying-type database))
273 (unescaped-database-identifier qualifier)
274 (unescaped-database-identifier name) type)))
276 ;; For SQL Identifiers for tables
278 (defclass sql-ident-table (sql-ident)
280 :initarg :table-alias :initform nil))
281 (:documentation "An SQL table identifier."))
283 (defmethod make-load-form ((sql sql-ident-table) &optional environment)
284 (declare (ignore environment))
285 (with-slots (alias name)
287 `(make-instance 'sql-ident-table :name ',name :table-alias ',alias)))
289 (defmethod output-sql ((expr sql-ident-table) database)
290 (with-slots (name alias) expr
291 (flet ((p (s) ;; the etypecase is in sql-escape too
293 (escaped-database-identifier s database)
297 (princ #\space *sql-stream*)
301 (defmethod output-sql ((expr sql-ident-attribute) database)
302 ;;; KMR: The TYPE field is used by CommonSQL for type conversion -- it
303 ;;; should not be output in SQL statements
304 (let ((*print-pretty* nil))
305 (with-slots (qualifier name type) expr
306 (format *sql-stream* "~@[~a.~]~a"
309 (escaped-database-identifier qualifier database T))
310 (escaped-database-identifier name database))
313 (defmethod output-sql-hash-key ((expr sql-ident-table) database)
314 (with-slots (name alias)
316 (list (and database (database-underlying-type database))
318 (unescaped-database-identifier name)
319 (unescaped-database-identifier alias))))
321 (defclass sql-relational-exp (%sql-expression)
326 :initarg :sub-expressions
328 (:documentation "An SQL relational expression."))
330 (defmethod make-load-form ((self sql-relational-exp) &optional environment)
331 (make-load-form-saving-slots self
332 :slot-names '(operator sub-expressions)
333 :environment environment))
335 (defmethod collect-table-refs ((sql sql-relational-exp))
337 (dolist (exp (slot-value sql 'sub-expressions))
338 (let ((refs (collect-table-refs exp)))
339 (if refs (setf tabs (append refs tabs)))))
340 (remove-duplicates tabs :test #'database-identifier-equal)))
345 ;; Write SQL for relational operators (like 'AND' and 'OR').
346 ;; should do arity checking of subexpressions
348 (defun %write-operator (operator database)
350 (string (write-string operator *sql-stream*))
351 (symbol (write-string (symbol-name operator) *sql-stream*))
352 (T (output-sql operator database))))
354 (defmethod output-sql ((expr sql-relational-exp) database)
355 (with-slots (operator sub-expressions) expr
356 ;; we do this as two runs so as not to emit confusing superflous parentheses
357 ;; The first loop renders all the child outputs so that we can skip anding with
358 ;; empty output (which causes sql errors)
359 ;; the next loop simply emits each sub-expression with the appropriate number of
360 ;; parens and operators
362 (string-trim +whitespace-chars+
363 (with-output-to-string (*sql-stream*)
364 (output-sql sub database)))))
365 (let ((str-subs (loop for sub in sub-expressions
366 for str-sub = (trim sub)
367 when (and str-sub (> (length str-sub) 0))
369 (case (length str-subs)
371 (1 (write-string (first str-subs) *sql-stream*))
373 (write-char #\( *sql-stream*)
374 (write-string (first str-subs) *sql-stream*)
375 (loop for str-sub in (rest str-subs)
377 (write-char #\Space *sql-stream*)
378 ;; do this so that symbols can be output as database identifiers
379 ;; rather than allowing symbols to inject sql
380 (%write-operator operator database)
381 (write-char #\Space *sql-stream*)
382 (write-string str-sub *sql-stream*))
383 (write-char #\) *sql-stream*))
387 (defclass sql-upcase-like (sql-relational-exp)
389 (:documentation "An SQL 'like' that upcases its arguments."))
391 (defmethod output-sql ((expr sql-upcase-like) database)
392 (flet ((write-term (term)
393 (write-string "upper(" *sql-stream*)
394 (output-sql term database)
395 (write-char #\) *sql-stream*)))
396 (with-slots (sub-expressions)
398 (let ((subs (if (consp (car sub-expressions))
399 (car sub-expressions)
401 (write-char #\( *sql-stream*)
402 (do ((sub subs (cdr sub)))
403 ((null (cdr sub)) (write-term (car sub)))
404 (write-term (car sub))
405 (write-string " LIKE " *sql-stream*))
406 (write-char #\) *sql-stream*))))
409 (defclass sql-assignment-exp (sql-relational-exp)
411 (:documentation "An SQL Assignment expression."))
414 (defmethod output-sql ((expr sql-assignment-exp) database)
415 (with-slots (operator sub-expressions)
417 (do ((sub sub-expressions (cdr sub)))
418 ((null (cdr sub)) (output-sql (car sub) database))
419 (output-sql (car sub) database)
420 (write-char #\Space *sql-stream*)
421 (%write-operator operator database)
422 (write-char #\Space *sql-stream*)))
425 (defclass sql-value-exp (%sql-expression)
433 "An SQL value expression.")
436 (defmethod collect-table-refs ((sql sql-value-exp))
438 (if (listp (slot-value sql 'components))
440 (dolist (exp (slot-value sql 'components))
441 (let ((refs (collect-table-refs exp)))
442 (if refs (setf tabs (append refs tabs)))))
443 (remove-duplicates tabs :test #'database-identifier-equal))
448 (defmethod output-sql ((expr sql-value-exp) database)
449 (with-slots (modifier components)
453 (write-char #\( *sql-stream*)
455 ((sql-operator modifier)
456 (%write-operator modifier database))
457 ((or (stringp modifier) (symbolp modifier))
459 (escaped-database-identifier modifier)
461 (t (output-sql modifier database)))
462 (write-char #\Space *sql-stream*)
463 (output-sql components database)
464 (write-char #\) *sql-stream*))
465 (output-sql components database))))
467 (defclass sql-typecast-exp (sql-value-exp)
469 (:documentation "An SQL typecast expression."))
471 (defmethod output-sql ((expr sql-typecast-exp) database)
472 (with-slots (components)
474 (output-sql components database)))
476 (defmethod collect-table-refs ((sql sql-typecast-exp))
477 (when (slot-value sql 'components)
478 (collect-table-refs (slot-value sql 'components))))
480 (defclass sql-function-exp (%sql-expression)
488 "An SQL function expression."))
490 (defmethod collect-table-refs ((sql sql-function-exp))
492 (dolist (exp (slot-value sql 'args))
493 (let ((refs (collect-table-refs exp)))
494 (if refs (setf tabs (append refs tabs)))))
495 (remove-duplicates tabs :test #'database-identifier-equal)))
496 (defvar *in-subselect* nil)
498 (defmethod output-sql ((expr sql-function-exp) database)
499 (with-slots (name args)
503 (write-string (escaped-database-identifier name) *sql-stream*))
504 (t (output-sql name database)))
505 (let ((*in-subselect* nil)) ;; aboid double parens
506 (when args (output-sql args database))))
510 (defclass sql-between-exp (sql-function-exp)
512 (:documentation "An SQL between expression."))
514 (defmethod output-sql ((expr sql-between-exp) database)
517 (output-sql (first args) database)
518 (write-string " BETWEEN " *sql-stream*)
519 (output-sql (second args) database)
520 (write-string " AND " *sql-stream*)
521 (output-sql (third args) database))
524 (defclass sql-query-modifier-exp (%sql-expression)
525 ((modifier :initarg :modifier :initform nil)
526 (components :initarg :components :initform nil))
527 (:documentation "An SQL query modifier expression."))
529 (defmethod output-sql ((expr sql-query-modifier-exp) database)
530 (with-slots (modifier components)
532 (%write-operator modifier database)
533 (write-string " " *sql-stream*)
534 (%write-operator (car components) database)
536 (mapc #'(lambda (comp)
537 (write-string ", " *sql-stream*)
538 (output-sql comp database))
542 (defclass sql-set-exp (%sql-expression)
547 :initarg :sub-expressions
549 (:documentation "An SQL set expression."))
551 (defmethod collect-table-refs ((sql sql-set-exp))
553 (dolist (exp (slot-value sql 'sub-expressions))
554 (let ((refs (collect-table-refs exp)))
555 (if refs (setf tabs (append refs tabs)))))
556 (remove-duplicates tabs :test #'database-identifier-equal)))
558 (defmethod output-sql ((expr sql-set-exp) database)
559 (with-slots (operator sub-expressions)
561 (let ((subs (if (consp (car sub-expressions))
562 (car sub-expressions)
564 (when (= (length subs) 1)
565 (%write-operator operator database)
566 (write-char #\Space *sql-stream*))
567 (do ((sub subs (cdr sub)))
568 ((null (cdr sub)) (output-sql (car sub) database))
569 (output-sql (car sub) database)
570 (write-char #\Space *sql-stream*)
571 (%write-operator operator database)
572 (write-char #\Space *sql-stream*))))
575 (defclass sql-query (%sql-expression)
586 :initarg :set-operation
618 (:documentation "An SQL SELECT query."))
620 (defclass sql-object-query (%sql-expression)
634 (defmethod collect-table-refs ((sql sql-query))
636 (collect-table-refs (slot-value sql 'where))
637 :test #'database-identifier-equal))
639 (defvar *select-arguments*
640 '(:all :database :distinct :flatp :from :group-by :having :order-by
641 :set-operation :where :offset :limit :inner-join :on
642 ;; below keywords are not a SQL argument, but these keywords may terminate select
645 (defun query-arg-p (sym)
646 (member sym *select-arguments*))
648 (defun query-get-selections (select-args)
649 "Return two values: the list of select-args up to the first keyword,
650 uninclusive, and the args from that keyword to the end."
651 (let ((first-key-arg (position-if #'query-arg-p select-args)))
653 (values (subseq select-args 0 first-key-arg)
654 (subseq select-args first-key-arg))
657 (defun make-query (&rest args)
658 (flet ((select-objects (target-args)
660 (every #'(lambda (arg)
662 (find-class arg nil)))
664 (multiple-value-bind (selections arglist)
665 (query-get-selections args)
666 (if (select-objects selections)
667 (destructuring-bind (&key flatp refresh &allow-other-keys) arglist
668 (make-instance 'sql-object-query :objects selections
669 :flatp flatp :refresh refresh
671 (destructuring-bind (&key all flatp set-operation distinct from where
672 group-by having order-by
673 offset limit inner-join on &allow-other-keys)
675 (if (null selections)
676 (error "No target columns supplied to select statement."))
678 (error "No source tables supplied to select statement."))
679 (make-instance 'sql-query :selections selections
680 :all all :flatp flatp :set-operation set-operation
681 :distinct distinct :from from :where where
682 :limit limit :offset offset
683 :group-by group-by :having having :order-by order-by
684 :inner-join inner-join :on on))))))
686 (defun output-sql-where-clause (where database)
687 "ensure that we do not output a \"where\" sql keyword when we will
688 not output a clause. Also sets *in-subselect* to use SQL
689 parentheticals as needed."
691 (let ((where-out (string-trim
692 '(#\newline #\space #\tab #\return)
693 (with-output-to-string (*sql-stream*)
694 (let ((*in-subselect* t))
695 (output-sql where database))))))
696 (when (> (length where-out) 0)
697 (write-string " WHERE " *sql-stream*)
698 (write-string where-out *sql-stream*)))))
700 (defmethod output-sql ((query sql-query) database)
701 (with-slots (distinct selections from where group-by having order-by
702 limit offset inner-join on all set-operation)
705 (write-string "(" *sql-stream*))
706 (write-string "SELECT " *sql-stream*)
708 (write-string " ALL " *sql-stream*))
709 (when (and distinct (not all))
710 (write-string " DISTINCT " *sql-stream*)
711 (unless (eql t distinct)
712 (write-string " ON " *sql-stream*)
713 (output-sql distinct database)
714 (write-char #\Space *sql-stream*)))
715 (when (and limit (eql :mssql (database-underlying-type database)))
716 (write-string " TOP " *sql-stream*)
717 (output-sql limit database)
718 (write-string " " *sql-stream*))
719 (let ((*in-subselect* t))
720 (output-sql (apply #'vector selections) database))
722 (write-string " FROM " *sql-stream*)
726 (remove-duplicates from :test #'database-identifier-equal))
728 (string (write-string
729 (escaped-database-identifier from database)
731 (t (let ((*in-subselect* t))
732 (output-sql from database)))))
734 (write-string " INNER JOIN " *sql-stream*)
735 (output-sql inner-join database))
737 (write-string " ON " *sql-stream*)
738 (output-sql on database))
739 (output-sql-where-clause where database)
741 (write-string " GROUP BY " *sql-stream*)
743 (do ((order group-by (cdr order)))
745 (let ((item (car order)))
748 (output-sql (car item) database)
749 (format *sql-stream* " ~A" (cadr item)))
751 (output-sql item database)))
753 (write-char #\, *sql-stream*))))
754 (output-sql group-by database)))
756 (write-string " HAVING " *sql-stream*)
757 (output-sql having database))
759 (write-string " ORDER BY " *sql-stream*)
761 (do ((order order-by (cdr order)))
763 (let ((item (car order)))
766 (output-sql (car item) database)
767 (format *sql-stream* " ~A" (cadr item)))
769 (output-sql item database)))
771 (write-char #\, *sql-stream*))))
772 (output-sql order-by database)))
773 (when (and limit (not (eql :mssql (database-underlying-type database))))
774 (write-string " LIMIT " *sql-stream*)
775 (output-sql limit database))
777 (write-string " OFFSET " *sql-stream*)
778 (output-sql offset database))
780 (write-string ")" *sql-stream*))
782 (write-char #\Space *sql-stream*)
783 (output-sql set-operation database)))
786 (defmethod output-sql ((query sql-object-query) database)
787 (declare (ignore database))
788 (with-slots (objects)
791 (format *sql-stream* "(~{~A~^ ~})" objects))))
796 (defclass sql-insert (%sql-expression)
810 "An SQL INSERT statement."))
812 (defmethod output-sql ((ins sql-insert) database)
813 (with-slots (into attributes values query)
815 (write-string "INSERT INTO " *sql-stream*)
818 (string (sql-expression :table into))
822 (write-char #\Space *sql-stream*)
823 (output-sql attributes database))
825 (write-string " VALUES " *sql-stream*)
826 (let ((clsql-sys::*in-subselect* t))
827 (output-sql values database)))
829 (write-char #\Space *sql-stream*)
830 (output-sql query database)))
835 (defclass sql-delete (%sql-expression)
843 "An SQL DELETE statement."))
845 (defmethod output-sql ((stmt sql-delete) database)
846 (with-slots (from where)
848 (write-string "DELETE FROM " *sql-stream*)
850 ((or symbol string) (write-string (sql-escape from) *sql-stream*))
851 (t (output-sql from database)))
852 (output-sql-where-clause where database))
857 (defclass sql-update (%sql-expression)
870 (:documentation "An SQL UPDATE statement."))
872 (defmethod output-sql ((expr sql-update) database)
873 (with-slots (table where attributes values)
875 (flet ((update-assignments ()
876 (mapcar #'(lambda (a b)
877 (make-instance 'sql-assignment-exp
879 :sub-expressions (list a b)))
881 (write-string "UPDATE " *sql-stream*)
882 (output-sql table database)
883 (write-string " SET " *sql-stream*)
884 (let ((clsql-sys::*in-subselect* t))
885 (output-sql (apply #'vector (update-assignments)) database))
886 (output-sql-where-clause where database)))
891 (defclass sql-create-table (%sql-expression)
902 :initarg :transactions
905 "An SQL CREATE TABLE statement."))
907 ;; Here's a real warhorse of a function!
909 (declaim (inline listify))
915 (defmethod output-sql ((stmt sql-create-table) database)
916 (flet ((output-column (column-spec)
917 (destructuring-bind (name type &optional db-type &rest constraints)
919 (let ((type (listify type)))
920 (output-sql name database)
921 (write-char #\Space *sql-stream*)
923 (if (stringp db-type) db-type ; override definition
924 (database-get-type-specifier (car type) (cdr type) database
925 (database-underlying-type database)))
927 (let ((constraints (database-constraint-statement
928 (if (and db-type (symbolp db-type))
929 (cons db-type constraints)
933 (write-string " " *sql-stream*)
934 (write-string constraints *sql-stream*)))))))
935 (with-slots (name columns modifiers transactions)
937 (write-string "CREATE TABLE " *sql-stream*)
938 (write-string (escaped-database-identifier name database) *sql-stream*)
939 (write-string " (" *sql-stream*)
940 (do ((column columns (cdr column)))
942 (output-column (car column)))
943 (output-column (car column))
944 (write-string ", " *sql-stream*))
946 (do ((modifier (listify modifiers) (cdr modifier)))
948 (write-string ", " *sql-stream*)
949 (write-string (car modifier) *sql-stream*)))
950 (write-char #\) *sql-stream*)
951 (when (and (eq :mysql (database-underlying-type database))
953 (db-type-transaction-capable? :mysql database))
954 (write-string " ENGINE=innodb" *sql-stream*))))
960 (defclass sql-create-view (%sql-expression)
961 ((name :initarg :name :initform nil)
962 (column-list :initarg :column-list :initform nil)
963 (query :initarg :query :initform nil)
964 (with-check-option :initarg :with-check-option :initform nil))
965 (:documentation "An SQL CREATE VIEW statement."))
967 (defmethod output-sql ((stmt sql-create-view) database)
968 (with-slots (name column-list query with-check-option) stmt
969 (write-string "CREATE VIEW " *sql-stream*)
970 (output-sql name database)
971 (when column-list (write-string " " *sql-stream*)
972 (output-sql (listify column-list) database))
973 (write-string " AS " *sql-stream*)
974 (output-sql query database)
975 (when with-check-option (write-string " WITH CHECK OPTION" *sql-stream*))))
979 ;; DATABASE-OUTPUT-SQL
982 (defmethod database-output-sql ((str string) database)
983 (declare (optimize (speed 3) (safety 1)
984 #+cmu (extensions:inhibit-warnings 3)))
985 (let ((len (length str)))
986 (declare (type fixnum len))
989 ((and (null (position #\' str))
990 (null (position #\\ str)))
991 (concatenate 'string "'" str "'"))
993 (let ((buf (make-string (+ (* len 2) 2) :initial-element #\')))
994 (declare (simple-string buf))
997 ((= i len) (subseq buf 0 (1+ j)))
998 (declare (type fixnum i j))
999 (let ((char (aref str i)))
1000 (declare (character char))
1001 (cond ((char= char #\')
1002 (setf (aref buf j) #\')
1004 (setf (aref buf j) #\'))
1005 ((and (char= char #\\)
1006 ;; MTP: only escape backslash with pgsql/mysql
1007 (member (database-underlying-type database)
1008 '(:postgresql :mysql)
1010 (setf (aref buf j) #\\)
1012 (setf (aref buf j) #\\))
1014 (setf (aref buf j) char))))))))))
1016 (let ((keyword-package (symbol-package :foo)))
1017 (defmethod database-output-sql ((sym symbol) database)
1020 (if (equal (symbol-package sym) keyword-package)
1021 (database-output-sql (symbol-name sym) database)
1022 (escaped-database-identifier sym)))))
1024 (defmethod database-output-sql ((tee (eql t)) database)
1026 (let ((val (database-output-sql-as-type 'boolean t database (database-type database))))
1029 (string (format nil "'~A'" val))
1030 (integer (format nil "~A" val)))))
1033 #+nil(defmethod database-output-sql ((tee (eql t)) database)
1034 (declare (ignore database))
1037 (defmethod database-output-sql ((num number) database)
1038 (declare (ignore database))
1039 (number-to-sql-string num))
1041 (defmethod database-output-sql ((arg list) database)
1044 (format nil "(~{~A~^,~})" (mapcar #'(lambda (val)
1045 (sql-output val database))
1048 (defmethod database-output-sql ((arg vector) database)
1049 (format nil "~{~A~^,~}" (map 'list #'(lambda (val)
1050 (sql-output val database))
1053 (defmethod output-sql-hash-key ((arg vector) database)
1054 (list 'vector (map 'list (lambda (arg)
1055 (or (output-sql-hash-key arg database)
1056 (return-from output-sql-hash-key nil)))
1059 (defmethod database-output-sql ((self wall-time) database)
1060 (declare (ignore database))
1061 (db-timestring self))
1063 (defmethod database-output-sql ((self date) database)
1064 (declare (ignore database))
1065 (db-datestring self))
1067 (defmethod database-output-sql ((self duration) database)
1068 (declare (ignore database))
1069 (format nil "'~a'" (duration-timestring self)))
1072 (defmethod database-output-sql ((self money) database)
1073 (database-output-sql (slot-value self 'odcl::units) database))
1075 (defmethod database-output-sql (thing database)
1076 (if (or (null thing)
1079 (error 'sql-user-error
1082 "No type conversion to SQL for ~A is defined for DB ~A."
1083 (type-of thing) (type-of database)))))
1087 ;; Column constraint types and conversion to SQL
1090 (defparameter *constraint-types*
1092 (cons (symbol-name-default-case "NOT-NULL") "NOT NULL")
1093 (cons (symbol-name-default-case "PRIMARY-KEY") "PRIMARY KEY")
1094 (cons (symbol-name-default-case "NOT") "NOT")
1095 (cons (symbol-name-default-case "NULL") "NULL")
1096 (cons (symbol-name-default-case "PRIMARY") "PRIMARY")
1097 (cons (symbol-name-default-case "KEY") "KEY")
1098 (cons (symbol-name-default-case "UNSIGNED") "UNSIGNED")
1099 (cons (symbol-name-default-case "ZEROFILL") "ZEROFILL")
1100 (cons (symbol-name-default-case "AUTO-INCREMENT") "AUTO_INCREMENT")
1101 (cons (symbol-name-default-case "DEFAULT") "DEFAULT")
1102 (cons (symbol-name-default-case "UNIQUE") "UNIQUE")
1103 (cons (symbol-name-default-case "IDENTITY") "IDENTITY (1,1)") ;; added for sql-server support
1106 (defmethod database-constraint-statement (constraint-list database)
1107 (declare (ignore database))
1108 (make-constraints-description constraint-list))
1110 (defun make-constraints-description (constraint-list)
1113 (do ((constraint constraint-list (cdr constraint)))
1114 ((null constraint) string)
1115 (let ((output (assoc (symbol-name (car constraint))
1119 (error 'sql-user-error
1120 :message (format nil "unsupported column constraint '~A'"
1122 (setq string (concatenate 'string string (cdr output))))
1123 (when (equal (symbol-name (car constraint)) "DEFAULT")
1124 (setq constraint (cdr constraint))
1125 (setq string (concatenate 'string string " " (car constraint))))
1126 (if (< 1 (length constraint))
1127 (setq string (concatenate 'string string " "))))))))
1129 (defmethod database-identifier ( name &optional database find-class-p
1131 "A function that takes whatever you give it, recursively coerces it,
1132 and returns a database-identifier.
1134 (escaped-database-identifiers *any-reasonable-object*) should be called to
1135 produce a string that is safe to splice directly into sql strings.
1137 This function should NOT throw errors when database is nil
1139 find-class-p should be T if we want to search for classes
1140 and check their use their view table. Should be used
1141 on symbols we are sure indicate tables
1144 ;; metaclasses has further typecases of this, so that it will
1145 ;; load less painfully (try-recompiles) in SBCL
1148 (flet ((flatten-id (id)
1149 "if we have multiple pieces that we need to represent as
1150 db-id lets do that by rendering out the id, then creating
1151 a new db-id with that string as escaped"
1152 (let ((s (sql-output id database)))
1153 (make-instance '%database-identifier :escaped s :unescaped s))))
1154 (setf name (dequote name))
1157 (string (%make-database-identifier name database))
1159 ;; if this is being used as a table, we should check
1160 ;; for a class with this name and use the identifier specified
1162 (if (and find-class-p (setf cls (find-standard-db-class name)))
1163 (database-identifier cls)
1164 (%make-database-identifier name database)))
1165 (%database-identifier name)
1166 ;; we know how to deref this without further escaping
1168 (with-slots ((inner-name name) alias) name
1171 (database-identifier inner-name))))
1172 ;; if this is a single name we can derefence it
1173 (sql-ident-attribute
1174 (with-slots (qualifier (inner-name name)) name
1177 (database-identifier inner-name))))
1179 (with-slots ((inner-name name)) name
1180 (database-identifier inner-name)))
1181 ;; dont know how to handle this really :/
1182 (%sql-expression (flatten-id name))