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 %make-database-identifier (inp &optional database)
72 "We want to quote an identifier if it came to us as a string or if it has special characters
74 (labels ((%escape-identifier (inp &optional orig)
75 "Quote an identifier unless it is already quoted"
78 ((and (eql #\" (elt inp 0))
79 (eql #\" (elt inp (- (length inp) 1))))
80 (make-instance '%database-identifier :unescaped (or orig inp) :escaped inp))
82 '%database-identifier :unescaped (or orig inp) :escaped
84 'string "\"" (replace-all inp "\"" "\\\"") "\""))))))
86 (string (%escape-identifier inp))
87 (%database-identifier inp)
89 (let ((s (sql-escape inp)))
90 (if (and (not (eql '* inp)) (special-char-p s))
91 (%escape-identifier (convert-to-db-default-case s database) inp)
92 (make-instance '%database-identifier :escaped s :unescaped inp)))))))
94 (defun combine-database-identifiers (ids &optional (database clsql-sys:*default-database*)
95 &aux res all-sym? pkg)
96 "Create a new database identifier by combining parts in a reasonable way
98 (setf ids (mapcar #'database-identifier ids)
99 all-sym? (every (lambda (i) (symbolp (unescaped i))) ids)
100 pkg (when all-sym? (symbol-package (unescaped (first ids)))))
104 (%database-identifier (cast (unescaped i)))
108 (convert-to-db-default-case (sql-escape i) database)))
114 (concatenate 'string (cast i1) "_" (cast i2))
116 (setf res (reduce #'comb ids))
118 (if all-sym? (intern res pkg) res)
121 (defun escaped-database-identifier (name &optional database find-class-p)
122 (escaped (database-identifier name database find-class-p)))
124 (defun unescaped-database-identifier (name &optional database find-class-p)
125 (unescaped (database-identifier name database find-class-p)))
127 (defun sql-output (sql-expr &optional (database *default-database*))
128 "Top-level call for generating SQL strings. Returns an SQL
129 string appropriate for DATABASE which corresponds to the
130 supplied lisp expression SQL-EXPR."
131 (progv '(*sql-stream*)
132 `(,(make-string-output-stream))
133 (output-sql sql-expr database)
134 (get-output-stream-string *sql-stream*)))
136 (defmethod output-sql (expr database)
137 (write-string (database-output-sql expr database) *sql-stream*)
141 (defvar *output-hash*
143 (make-hash-table :test #'equal :synchronized T :weakness :key-and-value)
145 (make-hash-table :test #'equal )
146 "For caching generated SQL strings.")
148 (defmethod output-sql :around ((sql t) database)
149 (if (null *output-hash*)
151 (let* ((hash-key (output-sql-hash-key sql database))
152 (hash-value (when hash-key (gethash hash-key *output-hash*))))
153 (cond ((and hash-key hash-value)
154 (write-string hash-value *sql-stream*))
156 (let ((*sql-stream* (make-string-output-stream)))
158 (setf hash-value (get-output-stream-string *sql-stream*))
159 (setf (gethash hash-key *output-hash*) hash-value))
160 (write-string hash-value *sql-stream*))
162 (call-next-method))))))
164 (defmethod output-sql-hash-key (expr database)
165 (declare (ignore expr database))
169 (defclass %sql-expression ()
172 (defmethod output-sql ((expr %sql-expression) database)
173 (declare (ignore database))
174 (write-string +null-string+ *sql-stream*))
176 (defmethod print-object ((self %sql-expression) stream)
177 (print-unreadable-object
178 (self stream :type t)
179 (write-string (sql-output self) stream))
182 ;; For straight up strings
184 (defclass sql (%sql-expression)
188 (:documentation "A literal SQL expression."))
190 (defmethod make-load-form ((sql sql) &optional environment)
191 (declare (ignore environment))
194 `(make-instance 'sql :string ',text)))
196 (defmethod output-sql ((expr sql) database)
197 (declare (ignore database))
198 (write-string (slot-value expr 'text) *sql-stream*)
201 (defmethod print-object ((ident sql) stream)
202 (format stream "#<~S \"~A\">"
204 (sql-output ident nil))
207 ;; For SQL Identifiers of generic type
209 (defclass sql-ident (%sql-expression)
212 :initform +null-string+))
213 (:documentation "An SQL identifer."))
215 (defmethod make-load-form ((sql sql-ident) &optional environment)
216 (declare (ignore environment))
219 `(make-instance 'sql-ident :name ',name)))
221 (defmethod output-sql ((expr %database-identifier) database)
222 (write-string (escaped expr) *sql-stream*))
224 (defmethod output-sql ((expr sql-ident) database)
225 (with-slots (name) expr
226 (write-string (escaped-database-identifier name database) *sql-stream*))
229 ;; For SQL Identifiers for attributes
231 (defclass sql-ident-attribute (sql-ident)
234 :initform +null-string+)
237 :initform +null-string+))
238 (:documentation "An SQL Attribute identifier."))
240 (defmethod collect-table-refs (sql)
241 (declare (ignore sql))
244 (defmethod collect-table-refs ((sql sql-ident-attribute))
245 (let ((qual (slot-value sql 'qualifier)))
247 ;; going to be used as a table, search classes
250 :name (database-identifier qual nil t))))))
252 (defmethod make-load-form ((sql sql-ident-attribute) &optional environment)
253 (declare (ignore environment))
254 (with-slots (qualifier type name)
256 `(make-instance 'sql-ident-attribute :name ',name
257 :qualifier ',qualifier
260 (defmethod output-sql-hash-key ((expr sql-ident-attribute) database)
261 (with-slots (qualifier name type)
263 (list (and database (database-underlying-type database))
265 (unescaped-database-identifier qualifier)
266 (unescaped-database-identifier name) type)))
268 ;; For SQL Identifiers for tables
270 (defclass sql-ident-table (sql-ident)
272 :initarg :table-alias :initform nil))
273 (:documentation "An SQL table identifier."))
275 (defmethod make-load-form ((sql sql-ident-table) &optional environment)
276 (declare (ignore environment))
277 (with-slots (alias name)
279 `(make-instance 'sql-ident-table :name ',name :table-alias ',alias)))
281 (defmethod output-sql ((expr sql-ident-table) database)
282 (with-slots (name alias) expr
283 (flet ((p (s) ;; the etypecase is in sql-escape too
285 (escaped-database-identifier s database)
289 (princ #\space *sql-stream*)
293 (defmethod output-sql ((expr sql-ident-attribute) database)
294 ;;; KMR: The TYPE field is used by CommonSQL for type conversion -- it
295 ;;; should not be output in SQL statements
296 (let ((*print-pretty* nil))
297 (with-slots (qualifier name type) expr
298 (format *sql-stream* "~@[~a.~]~a"
301 (escaped-database-identifier qualifier database T))
302 (escaped-database-identifier name database))
305 (defmethod output-sql-hash-key ((expr sql-ident-table) database)
306 (with-slots (name alias)
308 (list (and database (database-underlying-type database))
310 (unescaped-database-identifier name)
311 (unescaped-database-identifier alias))))
313 (defclass sql-relational-exp (%sql-expression)
318 :initarg :sub-expressions
320 (:documentation "An SQL relational expression."))
322 (defmethod make-load-form ((self sql-relational-exp) &optional environment)
323 (make-load-form-saving-slots self
324 :slot-names '(operator sub-expressions)
325 :environment environment))
327 (defmethod collect-table-refs ((sql sql-relational-exp))
329 (dolist (exp (slot-value sql 'sub-expressions))
330 (let ((refs (collect-table-refs exp)))
331 (if refs (setf tabs (append refs tabs)))))
332 (remove-duplicates tabs :test #'database-identifier-equal)))
337 ;; Write SQL for relational operators (like 'AND' and 'OR').
338 ;; should do arity checking of subexpressions
340 (defmethod output-sql ((expr sql-relational-exp) database)
341 (with-slots (operator sub-expressions) expr
342 ;; we do this as two runs so as not to emit confusing superflous parentheses
343 ;; The first loop renders all the child outputs so that we can skip anding with
344 ;; empty output (which causes sql errors)
345 ;; the next loop simply emits each sub-expression with the appropriate number of
346 ;; parens and operators
348 (string-trim +whitespace-chars+
349 (with-output-to-string (*sql-stream*)
350 (output-sql sub database)))))
351 (let ((str-subs (loop for sub in sub-expressions
352 for str-sub = (trim sub)
353 when (and str-sub (> (length str-sub) 0))
355 (case (length str-subs)
357 (1 (write-string (first str-subs) *sql-stream*))
359 (write-char #\( *sql-stream*)
360 (write-string (first str-subs) *sql-stream*)
361 (loop for str-sub in (rest str-subs)
363 (write-char #\Space *sql-stream*)
364 (output-sql operator database)
365 (write-char #\Space *sql-stream*)
366 (write-string str-sub *sql-stream*))
367 (write-char #\) *sql-stream*))
371 (defclass sql-upcase-like (sql-relational-exp)
373 (:documentation "An SQL 'like' that upcases its arguments."))
375 (defmethod output-sql ((expr sql-upcase-like) database)
376 (flet ((write-term (term)
377 (write-string "upper(" *sql-stream*)
378 (output-sql term database)
379 (write-char #\) *sql-stream*)))
380 (with-slots (sub-expressions)
382 (let ((subs (if (consp (car sub-expressions))
383 (car sub-expressions)
385 (write-char #\( *sql-stream*)
386 (do ((sub subs (cdr sub)))
387 ((null (cdr sub)) (write-term (car sub)))
388 (write-term (car sub))
389 (write-string " LIKE " *sql-stream*))
390 (write-char #\) *sql-stream*))))
393 (defclass sql-assignment-exp (sql-relational-exp)
395 (:documentation "An SQL Assignment expression."))
398 (defmethod output-sql ((expr sql-assignment-exp) database)
399 (with-slots (operator sub-expressions)
401 (do ((sub sub-expressions (cdr sub)))
402 ((null (cdr sub)) (output-sql (car sub) database))
403 (output-sql (car sub) database)
404 (write-char #\Space *sql-stream*)
405 (output-sql operator database)
406 (write-char #\Space *sql-stream*)))
409 (defclass sql-value-exp (%sql-expression)
417 "An SQL value expression.")
420 (defmethod collect-table-refs ((sql sql-value-exp))
422 (if (listp (slot-value sql 'components))
424 (dolist (exp (slot-value sql 'components))
425 (let ((refs (collect-table-refs exp)))
426 (if refs (setf tabs (append refs tabs)))))
427 (remove-duplicates tabs :test #'database-identifier-equal))
432 (defmethod output-sql ((expr sql-value-exp) database)
433 (with-slots (modifier components)
437 (write-char #\( *sql-stream*)
438 (output-sql modifier database)
439 (write-char #\Space *sql-stream*)
440 (output-sql components database)
441 (write-char #\) *sql-stream*))
442 (output-sql components database))))
444 (defclass sql-typecast-exp (sql-value-exp)
446 (:documentation "An SQL typecast expression."))
448 (defmethod output-sql ((expr sql-typecast-exp) database)
449 (with-slots (components)
451 (output-sql components database)))
453 (defmethod collect-table-refs ((sql sql-typecast-exp))
454 (when (slot-value sql 'components)
455 (collect-table-refs (slot-value sql 'components))))
457 (defclass sql-function-exp (%sql-expression)
465 "An SQL function expression."))
467 (defmethod collect-table-refs ((sql sql-function-exp))
469 (dolist (exp (slot-value sql 'args))
470 (let ((refs (collect-table-refs exp)))
471 (if refs (setf tabs (append refs tabs)))))
472 (remove-duplicates tabs :test #'database-identifier-equal)))
473 (defvar *in-subselect* nil)
475 (defmethod output-sql ((expr sql-function-exp) database)
476 (with-slots (name args)
478 (output-sql name database)
479 (let ((*in-subselect* nil)) ;; aboid double parens
480 (when args (output-sql args database))))
484 (defclass sql-between-exp (sql-function-exp)
486 (:documentation "An SQL between expression."))
488 (defmethod output-sql ((expr sql-between-exp) database)
491 (output-sql (first args) database)
492 (write-string " BETWEEN " *sql-stream*)
493 (output-sql (second args) database)
494 (write-string " AND " *sql-stream*)
495 (output-sql (third args) database))
498 (defclass sql-query-modifier-exp (%sql-expression)
499 ((modifier :initarg :modifier :initform nil)
500 (components :initarg :components :initform nil))
501 (:documentation "An SQL query modifier expression."))
503 (defmethod output-sql ((expr sql-query-modifier-exp) database)
504 (with-slots (modifier components)
506 (%write-operator modifier database)
507 (write-string " " *sql-stream*)
508 (output-sql (car components) database)
510 (mapc #'(lambda (comp)
511 (write-string ", " *sql-stream*)
512 (output-sql comp database))
516 (defclass sql-set-exp (%sql-expression)
521 :initarg :sub-expressions
523 (:documentation "An SQL set expression."))
525 (defmethod collect-table-refs ((sql sql-set-exp))
527 (dolist (exp (slot-value sql 'sub-expressions))
528 (let ((refs (collect-table-refs exp)))
529 (if refs (setf tabs (append refs tabs)))))
530 (remove-duplicates tabs :test #'database-identifier-equal)))
532 (defmethod output-sql ((expr sql-set-exp) database)
533 (with-slots (operator sub-expressions)
535 (let ((subs (if (consp (car sub-expressions))
536 (car sub-expressions)
538 (when (= (length subs) 1)
539 (output-sql operator database)
540 (write-char #\Space *sql-stream*))
541 (do ((sub subs (cdr sub)))
542 ((null (cdr sub)) (output-sql (car sub) database))
543 (output-sql (car sub) database)
544 (write-char #\Space *sql-stream*)
545 (output-sql operator database)
546 (write-char #\Space *sql-stream*))))
549 (defclass sql-query (%sql-expression)
560 :initarg :set-operation
592 (:documentation "An SQL SELECT query."))
594 (defclass sql-object-query (%sql-expression)
608 (defmethod collect-table-refs ((sql sql-query))
610 (collect-table-refs (slot-value sql 'where))
611 :test #'database-identifier-equal))
613 (defvar *select-arguments*
614 '(:all :database :distinct :flatp :from :group-by :having :order-by
615 :set-operation :where :offset :limit :inner-join :on
616 ;; below keywords are not a SQL argument, but these keywords may terminate select
619 (defun query-arg-p (sym)
620 (member sym *select-arguments*))
622 (defun query-get-selections (select-args)
623 "Return two values: the list of select-args up to the first keyword,
624 uninclusive, and the args from that keyword to the end."
625 (let ((first-key-arg (position-if #'query-arg-p select-args)))
627 (values (subseq select-args 0 first-key-arg)
628 (subseq select-args first-key-arg))
631 (defun make-query (&rest args)
632 (flet ((select-objects (target-args)
634 (every #'(lambda (arg)
636 (find-class arg nil)))
638 (multiple-value-bind (selections arglist)
639 (query-get-selections args)
640 (if (select-objects selections)
641 (destructuring-bind (&key flatp refresh &allow-other-keys) arglist
642 (make-instance 'sql-object-query :objects selections
643 :flatp flatp :refresh refresh
645 (destructuring-bind (&key all flatp set-operation distinct from where
646 group-by having order-by
647 offset limit inner-join on &allow-other-keys)
649 (if (null selections)
650 (error "No target columns supplied to select statement."))
652 (error "No source tables supplied to select statement."))
653 (make-instance 'sql-query :selections selections
654 :all all :flatp flatp :set-operation set-operation
655 :distinct distinct :from from :where where
656 :limit limit :offset offset
657 :group-by group-by :having having :order-by order-by
658 :inner-join inner-join :on on))))))
660 (defmethod output-sql ((query sql-query) database)
661 (with-slots (distinct selections from where group-by having order-by
662 limit offset inner-join on all set-operation)
665 (write-string "(" *sql-stream*))
666 (write-string "SELECT " *sql-stream*)
668 (write-string " ALL " *sql-stream*))
669 (when (and distinct (not all))
670 (write-string " DISTINCT " *sql-stream*)
671 (unless (eql t distinct)
672 (write-string " ON " *sql-stream*)
673 (output-sql distinct database)
674 (write-char #\Space *sql-stream*)))
675 (when (and limit (eql :mssql (database-underlying-type database)))
676 (write-string " TOP " *sql-stream*)
677 (output-sql limit database)
678 (write-string " " *sql-stream*))
679 (let ((*in-subselect* t))
680 (output-sql (apply #'vector selections) database))
682 (write-string " FROM " *sql-stream*)
686 (remove-duplicates from :test #'database-identifier-equal))
688 (string (write-string
689 (escaped-database-identifier from database)
691 (t (let ((*in-subselect* t))
692 (output-sql from database)))))
694 (write-string " INNER JOIN " *sql-stream*)
695 (output-sql inner-join database))
697 (write-string " ON " *sql-stream*)
698 (output-sql on database))
700 (let ((where-out (string-trim
701 '(#\newline #\space #\tab #\return)
702 (with-output-to-string (*sql-stream*)
703 (let ((*in-subselect* t))
704 (output-sql where database))))))
705 (when (> (length where-out) 0)
706 (write-string " WHERE " *sql-stream*)
707 (write-string where-out *sql-stream*))))
709 (write-string " GROUP BY " *sql-stream*)
711 (do ((order group-by (cdr order)))
713 (let ((item (car order)))
716 (output-sql (car item) database)
717 (format *sql-stream* " ~A" (cadr item)))
719 (output-sql item database)))
721 (write-char #\, *sql-stream*))))
722 (output-sql group-by database)))
724 (write-string " HAVING " *sql-stream*)
725 (output-sql having database))
727 (write-string " ORDER BY " *sql-stream*)
729 (do ((order order-by (cdr order)))
731 (let ((item (car order)))
734 (output-sql (car item) database)
735 (format *sql-stream* " ~A" (cadr item)))
737 (output-sql item database)))
739 (write-char #\, *sql-stream*))))
740 (output-sql order-by database)))
741 (when (and limit (not (eql :mssql (database-underlying-type database))))
742 (write-string " LIMIT " *sql-stream*)
743 (output-sql limit database))
745 (write-string " OFFSET " *sql-stream*)
746 (output-sql offset database))
748 (write-string ")" *sql-stream*))
750 (write-char #\Space *sql-stream*)
751 (output-sql set-operation database)))
754 (defmethod output-sql ((query sql-object-query) database)
755 (declare (ignore database))
756 (with-slots (objects)
759 (format *sql-stream* "(~{~A~^ ~})" objects))))
764 (defclass sql-insert (%sql-expression)
778 "An SQL INSERT statement."))
780 (defmethod output-sql ((ins sql-insert) database)
781 (with-slots (into attributes values query)
783 (write-string "INSERT INTO " *sql-stream*)
786 (string (sql-expression :table into))
790 (write-char #\Space *sql-stream*)
791 (output-sql attributes database))
793 (write-string " VALUES " *sql-stream*)
794 (output-sql values database))
796 (write-char #\Space *sql-stream*)
797 (output-sql query database)))
802 (defclass sql-delete (%sql-expression)
810 "An SQL DELETE statement."))
812 (defmethod output-sql ((stmt sql-delete) database)
813 (with-slots (from where)
815 (write-string "DELETE FROM " *sql-stream*)
817 ((or symbol string) (write-string (sql-escape from) *sql-stream*))
818 (t (output-sql from database)))
820 (write-string " WHERE " *sql-stream*)
821 (output-sql where database)))
826 (defclass sql-update (%sql-expression)
839 (:documentation "An SQL UPDATE statement."))
841 (defmethod output-sql ((expr sql-update) database)
842 (with-slots (table where attributes values)
844 (flet ((update-assignments ()
845 (mapcar #'(lambda (a b)
846 (make-instance 'sql-assignment-exp
848 :sub-expressions (list a b)))
850 (write-string "UPDATE " *sql-stream*)
851 (output-sql table database)
852 (write-string " SET " *sql-stream*)
853 (output-sql (apply #'vector (update-assignments)) database)
855 (write-string " WHERE " *sql-stream*)
856 (output-sql where database))))
861 (defclass sql-create-table (%sql-expression)
872 :initarg :transactions
875 "An SQL CREATE TABLE statement."))
877 ;; Here's a real warhorse of a function!
879 (declaim (inline listify))
885 (defmethod output-sql ((stmt sql-create-table) database)
886 (flet ((output-column (column-spec)
887 (destructuring-bind (name type &optional db-type &rest constraints)
889 (let ((type (listify type)))
890 (output-sql name database)
891 (write-char #\Space *sql-stream*)
893 (if (stringp db-type) db-type ; override definition
894 (database-get-type-specifier (car type) (cdr type) database
895 (database-underlying-type database)))
897 (let ((constraints (database-constraint-statement
898 (if (and db-type (symbolp db-type))
899 (cons db-type constraints)
903 (write-string " " *sql-stream*)
904 (write-string constraints *sql-stream*)))))))
905 (with-slots (name columns modifiers transactions)
907 (write-string "CREATE TABLE " *sql-stream*)
908 (write-string (escaped-database-identifier name database) *sql-stream*)
909 (write-string " (" *sql-stream*)
910 (do ((column columns (cdr column)))
912 (output-column (car column)))
913 (output-column (car column))
914 (write-string ", " *sql-stream*))
916 (do ((modifier (listify modifiers) (cdr modifier)))
918 (write-string ", " *sql-stream*)
919 (write-string (car modifier) *sql-stream*)))
920 (write-char #\) *sql-stream*)
921 (when (and (eq :mysql (database-underlying-type database))
923 (db-type-transaction-capable? :mysql database))
924 (write-string " Type=InnoDB" *sql-stream*))))
930 (defclass sql-create-view (%sql-expression)
931 ((name :initarg :name :initform nil)
932 (column-list :initarg :column-list :initform nil)
933 (query :initarg :query :initform nil)
934 (with-check-option :initarg :with-check-option :initform nil))
935 (:documentation "An SQL CREATE VIEW statement."))
937 (defmethod output-sql ((stmt sql-create-view) database)
938 (with-slots (name column-list query with-check-option) stmt
939 (write-string "CREATE VIEW " *sql-stream*)
940 (output-sql name database)
941 (when column-list (write-string " " *sql-stream*)
942 (output-sql (listify column-list) database))
943 (write-string " AS " *sql-stream*)
944 (output-sql query database)
945 (when with-check-option (write-string " WITH CHECK OPTION" *sql-stream*))))
949 ;; DATABASE-OUTPUT-SQL
952 (defmethod database-output-sql ((str string) database)
953 (declare (optimize (speed 3) (safety 1)
954 #+cmu (extensions:inhibit-warnings 3)))
955 (let ((len (length str)))
956 (declare (type fixnum len))
959 ((and (null (position #\' str))
960 (null (position #\\ str)))
961 (concatenate 'string "'" str "'"))
963 (let ((buf (make-string (+ (* len 2) 2) :initial-element #\')))
964 (declare (simple-string buf))
967 ((= i len) (subseq buf 0 (1+ j)))
968 (declare (type fixnum i j))
969 (let ((char (aref str i)))
970 (declare (character char))
971 (cond ((char= char #\')
972 (setf (aref buf j) #\')
974 (setf (aref buf j) #\'))
975 ((and (char= char #\\)
976 ;; MTP: only escape backslash with pgsql/mysql
977 (member (database-underlying-type database)
978 '(:postgresql :mysql)
980 (setf (aref buf j) #\\)
982 (setf (aref buf j) #\\))
984 (setf (aref buf j) char))))))))))
986 (let ((keyword-package (symbol-package :foo)))
987 (defmethod database-output-sql ((sym symbol) database)
990 (if (equal (symbol-package sym) keyword-package)
991 (concatenate 'string "'" (string sym) "'")
992 (symbol-name sym)))))
994 (defmethod database-output-sql ((tee (eql t)) database)
996 (let ((val (database-output-sql-as-type 'boolean t database (database-type database))))
999 (string (format nil "'~A'" val))
1000 (integer (format nil "~A" val)))))
1003 #+nil(defmethod database-output-sql ((tee (eql t)) database)
1004 (declare (ignore database))
1007 (defmethod database-output-sql ((num number) database)
1008 (declare (ignore database))
1009 (number-to-sql-string num))
1011 (defmethod database-output-sql ((arg list) database)
1014 (format nil "(~{~A~^,~})" (mapcar #'(lambda (val)
1015 (sql-output val database))
1018 (defmethod database-output-sql ((arg vector) database)
1019 (format nil "~{~A~^,~}" (map 'list #'(lambda (val)
1020 (sql-output val database))
1023 (defmethod output-sql-hash-key ((arg vector) database)
1024 (list 'vector (map 'list (lambda (arg)
1025 (or (output-sql-hash-key arg database)
1026 (return-from output-sql-hash-key nil)))
1029 (defmethod database-output-sql ((self wall-time) database)
1030 (declare (ignore database))
1031 (db-timestring self))
1033 (defmethod database-output-sql ((self date) database)
1034 (declare (ignore database))
1035 (db-datestring self))
1037 (defmethod database-output-sql ((self duration) database)
1038 (declare (ignore database))
1039 (format nil "'~a'" (duration-timestring self)))
1042 (defmethod database-output-sql ((self money) database)
1043 (database-output-sql (slot-value self 'odcl::units) database))
1045 (defmethod database-output-sql (thing database)
1046 (if (or (null thing)
1049 (error 'sql-user-error
1052 "No type conversion to SQL for ~A is defined for DB ~A."
1053 (type-of thing) (type-of database)))))
1057 ;; Column constraint types and conversion to SQL
1060 (defparameter *constraint-types*
1062 (cons (symbol-name-default-case "NOT-NULL") "NOT NULL")
1063 (cons (symbol-name-default-case "PRIMARY-KEY") "PRIMARY KEY")
1064 (cons (symbol-name-default-case "NOT") "NOT")
1065 (cons (symbol-name-default-case "NULL") "NULL")
1066 (cons (symbol-name-default-case "PRIMARY") "PRIMARY")
1067 (cons (symbol-name-default-case "KEY") "KEY")
1068 (cons (symbol-name-default-case "UNSIGNED") "UNSIGNED")
1069 (cons (symbol-name-default-case "ZEROFILL") "ZEROFILL")
1070 (cons (symbol-name-default-case "AUTO-INCREMENT") "AUTO_INCREMENT")
1071 (cons (symbol-name-default-case "DEFAULT") "DEFAULT")
1072 (cons (symbol-name-default-case "UNIQUE") "UNIQUE")
1073 (cons (symbol-name-default-case "IDENTITY") "IDENTITY (1,1)") ;; added for sql-server support
1076 (defmethod database-constraint-statement (constraint-list database)
1077 (declare (ignore database))
1078 (make-constraints-description constraint-list))
1080 (defun make-constraints-description (constraint-list)
1083 (do ((constraint constraint-list (cdr constraint)))
1084 ((null constraint) string)
1085 (let ((output (assoc (symbol-name (car constraint))
1089 (error 'sql-user-error
1090 :message (format nil "unsupported column constraint '~A'"
1092 (setq string (concatenate 'string string (cdr output))))
1093 (when (equal (symbol-name (car constraint)) "DEFAULT")
1094 (setq constraint (cdr constraint))
1095 (setq string (concatenate 'string string " " (car constraint))))
1096 (if (< 1 (length constraint))
1097 (setq string (concatenate 'string string " "))))))))
1099 (defmethod database-identifier ( name &optional database find-class-p
1101 "A function that takes whatever you give it, recurively coerces it,
1102 and returns a database-identifier.
1104 (escaped-database-identifiers *any-reasonable-object*) should be called to
1105 produce a string that is safe to splice directly into sql strings.
1107 This function should NOT throw errors when database is nil
1109 find-class-p should be T if we want to search for classes
1110 and check their use their view table. Should be used
1111 on symbols we are sure indicate tables
1114 ;; metaclasses has further typecases of this, so that it will
1115 ;; load less painfully (try-recompiles) in SBCL
1118 (flet ((flatten-id (id)
1119 "if we have multiple pieces that we need to represent as
1120 db-id lets do that by rendering out the id, then creating
1121 a new db-id with that string as escaped"
1122 (let ((s (sql-output id database)))
1123 (make-instance '%database-identifier :escaped s :unescaped s))))
1126 (string (%make-database-identifier name database))
1128 ;; if this is being used as a table, we should check
1129 ;; for a class with this name and use the identifier specified
1131 (if (and find-class-p (setf cls (find-standard-db-class name)))
1132 (database-identifier cls)
1133 (%make-database-identifier name database)))
1134 (%database-identifier name)
1135 ;; we know how to deref this without further escaping
1137 (with-slots ((inner-name name) alias) name
1140 (database-identifier inner-name))))
1141 ;; if this is a single name we can derefence it
1142 (sql-ident-attribute
1143 (with-slots (qualifier (inner-name name)) name
1146 (database-identifier inner-name))))
1148 (with-slots ((inner-name name)) name
1149 (database-identifier inner-name)))
1150 ;; dont know how to handle this really :/
1151 (%sql-expression (flatten-id name))