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*)
140 (defvar *output-hash* (make-hash-table :test #'equal)
141 "For caching generated SQL strings.")
143 (defmethod output-sql :around ((sql t) database)
144 (let* ((hash-key (output-sql-hash-key sql database))
145 (hash-value (when hash-key (gethash hash-key *output-hash*))))
146 (cond ((and hash-key hash-value)
147 (write-string hash-value *sql-stream*))
149 (let ((*sql-stream* (make-string-output-stream)))
151 (setf hash-value (get-output-stream-string *sql-stream*))
152 (setf (gethash hash-key *output-hash*) hash-value))
153 (write-string hash-value *sql-stream*))
155 (call-next-method)))))
157 (defmethod output-sql-hash-key (expr database)
158 (declare (ignore expr database))
162 (defclass %sql-expression ()
165 (defmethod output-sql ((expr %sql-expression) database)
166 (declare (ignore database))
167 (write-string +null-string+ *sql-stream*))
169 (defmethod print-object ((self %sql-expression) stream)
170 (print-unreadable-object
171 (self stream :type t)
172 (write-string (sql-output self) stream))
175 ;; For straight up strings
177 (defclass sql (%sql-expression)
181 (:documentation "A literal SQL expression."))
183 (defmethod make-load-form ((sql sql) &optional environment)
184 (declare (ignore environment))
187 `(make-instance 'sql :string ',text)))
189 (defmethod output-sql ((expr sql) database)
190 (declare (ignore database))
191 (write-string (slot-value expr 'text) *sql-stream*)
194 (defmethod print-object ((ident sql) stream)
195 (format stream "#<~S \"~A\">"
197 (sql-output ident nil))
200 ;; For SQL Identifiers of generic type
202 (defclass sql-ident (%sql-expression)
205 :initform +null-string+))
206 (:documentation "An SQL identifer."))
208 (defmethod make-load-form ((sql sql-ident) &optional environment)
209 (declare (ignore environment))
212 `(make-instance 'sql-ident :name ',name)))
214 (defmethod output-sql ((expr %database-identifier) database)
215 (write-string (escaped expr) *sql-stream*))
217 (defmethod output-sql ((expr sql-ident) database)
218 (with-slots (name) expr
219 (write-string (escaped-database-identifier name database) *sql-stream*))
222 ;; For SQL Identifiers for attributes
224 (defclass sql-ident-attribute (sql-ident)
227 :initform +null-string+)
230 :initform +null-string+))
231 (:documentation "An SQL Attribute identifier."))
233 (defmethod collect-table-refs (sql)
234 (declare (ignore sql))
237 (defmethod collect-table-refs ((sql sql-ident-attribute))
238 (let ((qual (slot-value sql 'qualifier)))
240 ;; going to be used as a table, search classes
243 :name (database-identifier qual nil t))))))
245 (defmethod make-load-form ((sql sql-ident-attribute) &optional environment)
246 (declare (ignore environment))
247 (with-slots (qualifier type name)
249 `(make-instance 'sql-ident-attribute :name ',name
250 :qualifier ',qualifier
253 (defmethod output-sql-hash-key ((expr sql-ident-attribute) database)
254 (with-slots (qualifier name type)
256 (list (and database (database-underlying-type database))
257 'sql-ident-attribute qualifier name type)))
259 ;; For SQL Identifiers for tables
261 (defclass sql-ident-table (sql-ident)
263 :initarg :table-alias :initform nil))
264 (:documentation "An SQL table identifier."))
266 (defmethod make-load-form ((sql sql-ident-table) &optional environment)
267 (declare (ignore environment))
268 (with-slots (alias name)
270 `(make-instance 'sql-ident-table :name ',name :table-alias ',alias)))
272 (defmethod output-sql ((expr sql-ident-table) database)
273 (with-slots (name alias) expr
274 (flet ((p (s) ;; the etypecase is in sql-escape too
276 (escaped-database-identifier s database)
280 (princ #\space *sql-stream*)
284 (defmethod output-sql ((expr sql-ident-attribute) database)
285 ;;; KMR: The TYPE field is used by CommonSQL for type conversion -- it
286 ;;; should not be output in SQL statements
287 (let ((*print-pretty* nil))
288 (with-slots (qualifier name type) expr
289 (format *sql-stream* "~@[~a.~]~a"
292 (escaped-database-identifier qualifier database T))
293 (escaped-database-identifier name database))
296 (defmethod output-sql-hash-key ((expr sql-ident-table) database)
297 (with-slots (name alias)
299 (list (and database (database-underlying-type database))
300 'sql-ident-table name alias)))
302 (defclass sql-relational-exp (%sql-expression)
307 :initarg :sub-expressions
309 (:documentation "An SQL relational expression."))
311 (defmethod make-load-form ((self sql-relational-exp) &optional environment)
312 (make-load-form-saving-slots self
313 :slot-names '(operator sub-expressions)
314 :environment environment))
316 (defmethod collect-table-refs ((sql sql-relational-exp))
318 (dolist (exp (slot-value sql 'sub-expressions))
319 (let ((refs (collect-table-refs exp)))
320 (if refs (setf tabs (append refs tabs)))))
321 (remove-duplicates tabs :test #'database-identifier-equal)))
326 ;; Write SQL for relational operators (like 'AND' and 'OR').
327 ;; should do arity checking of subexpressions
329 (defmethod output-sql ((expr sql-relational-exp) database)
330 (with-slots (operator sub-expressions) expr
331 ;; we do this as two runs so as not to emit confusing superflous parentheses
332 ;; The first loop renders all the child outputs so that we can skip anding with
333 ;; empty output (which causes sql errors)
334 ;; the next loop simply emits each sub-expression with the appropriate number of
335 ;; parens and operators
337 (string-trim +whitespace-chars+
338 (with-output-to-string (*sql-stream*)
339 (output-sql sub database)))))
340 (let ((str-subs (loop for sub in sub-expressions
341 for str-sub = (trim sub)
342 when (and str-sub (> (length str-sub) 0))
344 (case (length str-subs)
346 (1 (write-string (first str-subs) *sql-stream*))
348 (write-char #\( *sql-stream*)
349 (write-string (first str-subs) *sql-stream*)
350 (loop for str-sub in (rest str-subs)
352 (write-char #\Space *sql-stream*)
353 (output-sql operator database)
354 (write-char #\Space *sql-stream*)
355 (write-string str-sub *sql-stream*))
356 (write-char #\) *sql-stream*))
360 (defclass sql-upcase-like (sql-relational-exp)
362 (:documentation "An SQL 'like' that upcases its arguments."))
364 (defmethod output-sql ((expr sql-upcase-like) database)
365 (flet ((write-term (term)
366 (write-string "upper(" *sql-stream*)
367 (output-sql term database)
368 (write-char #\) *sql-stream*)))
369 (with-slots (sub-expressions)
371 (let ((subs (if (consp (car sub-expressions))
372 (car sub-expressions)
374 (write-char #\( *sql-stream*)
375 (do ((sub subs (cdr sub)))
376 ((null (cdr sub)) (write-term (car sub)))
377 (write-term (car sub))
378 (write-string " LIKE " *sql-stream*))
379 (write-char #\) *sql-stream*))))
382 (defclass sql-assignment-exp (sql-relational-exp)
384 (:documentation "An SQL Assignment expression."))
387 (defmethod output-sql ((expr sql-assignment-exp) database)
388 (with-slots (operator sub-expressions)
390 (do ((sub sub-expressions (cdr sub)))
391 ((null (cdr sub)) (output-sql (car sub) database))
392 (output-sql (car sub) database)
393 (write-char #\Space *sql-stream*)
394 (output-sql operator database)
395 (write-char #\Space *sql-stream*)))
398 (defclass sql-value-exp (%sql-expression)
406 "An SQL value expression.")
409 (defmethod collect-table-refs ((sql sql-value-exp))
411 (if (listp (slot-value sql 'components))
413 (dolist (exp (slot-value sql 'components))
414 (let ((refs (collect-table-refs exp)))
415 (if refs (setf tabs (append refs tabs)))))
416 (remove-duplicates tabs :test #'database-identifier-equal))
421 (defmethod output-sql ((expr sql-value-exp) database)
422 (with-slots (modifier components)
426 (write-char #\( *sql-stream*)
427 (output-sql modifier database)
428 (write-char #\Space *sql-stream*)
429 (output-sql components database)
430 (write-char #\) *sql-stream*))
431 (output-sql components database))))
433 (defclass sql-typecast-exp (sql-value-exp)
435 (:documentation "An SQL typecast expression."))
437 (defmethod output-sql ((expr sql-typecast-exp) database)
438 (with-slots (components)
440 (output-sql components database)))
442 (defmethod collect-table-refs ((sql sql-typecast-exp))
443 (when (slot-value sql 'components)
444 (collect-table-refs (slot-value sql 'components))))
446 (defclass sql-function-exp (%sql-expression)
454 "An SQL function expression."))
456 (defmethod collect-table-refs ((sql sql-function-exp))
458 (dolist (exp (slot-value sql 'args))
459 (let ((refs (collect-table-refs exp)))
460 (if refs (setf tabs (append refs tabs)))))
461 (remove-duplicates tabs :test #'database-identifier-equal)))
462 (defvar *in-subselect* nil)
464 (defmethod output-sql ((expr sql-function-exp) database)
465 (with-slots (name args)
467 (output-sql name database)
468 (let ((*in-subselect* nil)) ;; aboid double parens
469 (when args (output-sql args database))))
473 (defclass sql-between-exp (sql-function-exp)
475 (:documentation "An SQL between expression."))
477 (defmethod output-sql ((expr sql-between-exp) database)
480 (output-sql (first args) database)
481 (write-string " BETWEEN " *sql-stream*)
482 (output-sql (second args) database)
483 (write-string " AND " *sql-stream*)
484 (output-sql (third args) database))
487 (defclass sql-query-modifier-exp (%sql-expression)
488 ((modifier :initarg :modifier :initform nil)
489 (components :initarg :components :initform nil))
490 (:documentation "An SQL query modifier expression."))
492 (defmethod output-sql ((expr sql-query-modifier-exp) database)
493 (with-slots (modifier components)
495 (%write-operator modifier database)
496 (write-string " " *sql-stream*)
497 (output-sql (car components) database)
499 (mapc #'(lambda (comp)
500 (write-string ", " *sql-stream*)
501 (output-sql comp database))
505 (defclass sql-set-exp (%sql-expression)
510 :initarg :sub-expressions
512 (:documentation "An SQL set expression."))
514 (defmethod collect-table-refs ((sql sql-set-exp))
516 (dolist (exp (slot-value sql 'sub-expressions))
517 (let ((refs (collect-table-refs exp)))
518 (if refs (setf tabs (append refs tabs)))))
519 (remove-duplicates tabs :test #'database-identifier-equal)))
521 (defmethod output-sql ((expr sql-set-exp) database)
522 (with-slots (operator sub-expressions)
524 (let ((subs (if (consp (car sub-expressions))
525 (car sub-expressions)
527 (when (= (length subs) 1)
528 (output-sql operator database)
529 (write-char #\Space *sql-stream*))
530 (do ((sub subs (cdr sub)))
531 ((null (cdr sub)) (output-sql (car sub) database))
532 (output-sql (car sub) database)
533 (write-char #\Space *sql-stream*)
534 (output-sql operator database)
535 (write-char #\Space *sql-stream*))))
538 (defclass sql-query (%sql-expression)
549 :initarg :set-operation
581 (:documentation "An SQL SELECT query."))
583 (defclass sql-object-query (%sql-expression)
597 (defmethod collect-table-refs ((sql sql-query))
599 (collect-table-refs (slot-value sql 'where))
600 :test #'database-identifier-equal))
602 (defvar *select-arguments*
603 '(:all :database :distinct :flatp :from :group-by :having :order-by
604 :set-operation :where :offset :limit :inner-join :on
605 ;; below keywords are not a SQL argument, but these keywords may terminate select
608 (defun query-arg-p (sym)
609 (member sym *select-arguments*))
611 (defun query-get-selections (select-args)
612 "Return two values: the list of select-args up to the first keyword,
613 uninclusive, and the args from that keyword to the end."
614 (let ((first-key-arg (position-if #'query-arg-p select-args)))
616 (values (subseq select-args 0 first-key-arg)
617 (subseq select-args first-key-arg))
620 (defun make-query (&rest args)
621 (flet ((select-objects (target-args)
623 (every #'(lambda (arg)
625 (find-class arg nil)))
627 (multiple-value-bind (selections arglist)
628 (query-get-selections args)
629 (if (select-objects selections)
630 (destructuring-bind (&key flatp refresh &allow-other-keys) arglist
631 (make-instance 'sql-object-query :objects selections
632 :flatp flatp :refresh refresh
634 (destructuring-bind (&key all flatp set-operation distinct from where
635 group-by having order-by
636 offset limit inner-join on &allow-other-keys)
638 (if (null selections)
639 (error "No target columns supplied to select statement."))
641 (error "No source tables supplied to select statement."))
642 (make-instance 'sql-query :selections selections
643 :all all :flatp flatp :set-operation set-operation
644 :distinct distinct :from from :where where
645 :limit limit :offset offset
646 :group-by group-by :having having :order-by order-by
647 :inner-join inner-join :on on))))))
649 (defmethod output-sql ((query sql-query) database)
650 (with-slots (distinct selections from where group-by having order-by
651 limit offset inner-join on all set-operation)
654 (write-string "(" *sql-stream*))
655 (write-string "SELECT " *sql-stream*)
657 (write-string " ALL " *sql-stream*))
658 (when (and distinct (not all))
659 (write-string " DISTINCT " *sql-stream*)
660 (unless (eql t distinct)
661 (write-string " ON " *sql-stream*)
662 (output-sql distinct database)
663 (write-char #\Space *sql-stream*)))
664 (when (and limit (eql :mssql (database-underlying-type database)))
665 (write-string " TOP " *sql-stream*)
666 (output-sql limit database)
667 (write-string " " *sql-stream*))
668 (let ((*in-subselect* t))
669 (output-sql (apply #'vector selections) database))
671 (write-string " FROM " *sql-stream*)
675 (remove-duplicates from :test #'database-identifier-equal))
677 (string (write-string
678 (escaped-database-identifier from database)
680 (t (let ((*in-subselect* t))
681 (output-sql from database)))))
683 (write-string " INNER JOIN " *sql-stream*)
684 (output-sql inner-join database))
686 (write-string " ON " *sql-stream*)
687 (output-sql on database))
689 (let ((where-out (string-trim
690 '(#\newline #\space #\tab #\return)
691 (with-output-to-string (*sql-stream*)
692 (let ((*in-subselect* t))
693 (output-sql where database))))))
694 (when (> (length where-out) 0)
695 (write-string " WHERE " *sql-stream*)
696 (write-string where-out *sql-stream*))))
698 (write-string " GROUP BY " *sql-stream*)
700 (do ((order group-by (cdr order)))
702 (let ((item (car order)))
705 (output-sql (car item) database)
706 (format *sql-stream* " ~A" (cadr item)))
708 (output-sql item database)))
710 (write-char #\, *sql-stream*))))
711 (output-sql group-by database)))
713 (write-string " HAVING " *sql-stream*)
714 (output-sql having database))
716 (write-string " ORDER BY " *sql-stream*)
718 (do ((order order-by (cdr order)))
720 (let ((item (car order)))
723 (output-sql (car item) database)
724 (format *sql-stream* " ~A" (cadr item)))
726 (output-sql item database)))
728 (write-char #\, *sql-stream*))))
729 (output-sql order-by database)))
730 (when (and limit (not (eql :mssql (database-underlying-type database))))
731 (write-string " LIMIT " *sql-stream*)
732 (output-sql limit database))
734 (write-string " OFFSET " *sql-stream*)
735 (output-sql offset database))
737 (write-string ")" *sql-stream*))
739 (write-char #\Space *sql-stream*)
740 (output-sql set-operation database)))
743 (defmethod output-sql ((query sql-object-query) database)
744 (declare (ignore database))
745 (with-slots (objects)
748 (format *sql-stream* "(~{~A~^ ~})" objects))))
753 (defclass sql-insert (%sql-expression)
767 "An SQL INSERT statement."))
769 (defmethod output-sql ((ins sql-insert) database)
770 (with-slots (into attributes values query)
772 (write-string "INSERT INTO " *sql-stream*)
775 (string (sql-expression :table into))
779 (write-char #\Space *sql-stream*)
780 (output-sql attributes database))
782 (write-string " VALUES " *sql-stream*)
783 (output-sql values database))
785 (write-char #\Space *sql-stream*)
786 (output-sql query database)))
791 (defclass sql-delete (%sql-expression)
799 "An SQL DELETE statement."))
801 (defmethod output-sql ((stmt sql-delete) database)
802 (with-slots (from where)
804 (write-string "DELETE FROM " *sql-stream*)
806 ((or symbol string) (write-string (sql-escape from) *sql-stream*))
807 (t (output-sql from database)))
809 (write-string " WHERE " *sql-stream*)
810 (output-sql where database)))
815 (defclass sql-update (%sql-expression)
828 (:documentation "An SQL UPDATE statement."))
830 (defmethod output-sql ((expr sql-update) database)
831 (with-slots (table where attributes values)
833 (flet ((update-assignments ()
834 (mapcar #'(lambda (a b)
835 (make-instance 'sql-assignment-exp
837 :sub-expressions (list a b)))
839 (write-string "UPDATE " *sql-stream*)
840 (output-sql table database)
841 (write-string " SET " *sql-stream*)
842 (output-sql (apply #'vector (update-assignments)) database)
844 (write-string " WHERE " *sql-stream*)
845 (output-sql where database))))
850 (defclass sql-create-table (%sql-expression)
861 :initarg :transactions
864 "An SQL CREATE TABLE statement."))
866 ;; Here's a real warhorse of a function!
868 (declaim (inline listify))
874 (defmethod output-sql ((stmt sql-create-table) database)
875 (flet ((output-column (column-spec)
876 (destructuring-bind (name type &optional db-type &rest constraints)
878 (let ((type (listify type)))
879 (output-sql name database)
880 (write-char #\Space *sql-stream*)
882 (if (stringp db-type) db-type ; override definition
883 (database-get-type-specifier (car type) (cdr type) database
884 (database-underlying-type database)))
886 (let ((constraints (database-constraint-statement
887 (if (and db-type (symbolp db-type))
888 (cons db-type constraints)
892 (write-string " " *sql-stream*)
893 (write-string constraints *sql-stream*)))))))
894 (with-slots (name columns modifiers transactions)
896 (write-string "CREATE TABLE " *sql-stream*)
897 (write-string (escaped-database-identifier name database) *sql-stream*)
898 (write-string " (" *sql-stream*)
899 (do ((column columns (cdr column)))
901 (output-column (car column)))
902 (output-column (car column))
903 (write-string ", " *sql-stream*))
905 (do ((modifier (listify modifiers) (cdr modifier)))
907 (write-string ", " *sql-stream*)
908 (write-string (car modifier) *sql-stream*)))
909 (write-char #\) *sql-stream*)
910 (when (and (eq :mysql (database-underlying-type database))
912 (db-type-transaction-capable? :mysql database))
913 (write-string " Type=InnoDB" *sql-stream*))))
919 (defclass sql-create-view (%sql-expression)
920 ((name :initarg :name :initform nil)
921 (column-list :initarg :column-list :initform nil)
922 (query :initarg :query :initform nil)
923 (with-check-option :initarg :with-check-option :initform nil))
924 (:documentation "An SQL CREATE VIEW statement."))
926 (defmethod output-sql ((stmt sql-create-view) database)
927 (with-slots (name column-list query with-check-option) stmt
928 (write-string "CREATE VIEW " *sql-stream*)
929 (output-sql name database)
930 (when column-list (write-string " " *sql-stream*)
931 (output-sql (listify column-list) database))
932 (write-string " AS " *sql-stream*)
933 (output-sql query database)
934 (when with-check-option (write-string " WITH CHECK OPTION" *sql-stream*))))
938 ;; DATABASE-OUTPUT-SQL
941 (defmethod database-output-sql ((str string) database)
942 (declare (optimize (speed 3) (safety 1)
943 #+cmu (extensions:inhibit-warnings 3)))
944 (let ((len (length str)))
945 (declare (type fixnum len))
948 ((and (null (position #\' str))
949 (null (position #\\ str)))
950 (concatenate 'string "'" str "'"))
952 (let ((buf (make-string (+ (* len 2) 2) :initial-element #\')))
953 (declare (simple-string buf))
956 ((= i len) (subseq buf 0 (1+ j)))
957 (declare (type fixnum i j))
958 (let ((char (aref str i)))
959 (declare (character char))
960 (cond ((char= char #\')
961 (setf (aref buf j) #\')
963 (setf (aref buf j) #\'))
964 ((and (char= char #\\)
965 ;; MTP: only escape backslash with pgsql/mysql
966 (member (database-underlying-type database)
967 '(:postgresql :mysql)
969 (setf (aref buf j) #\\)
971 (setf (aref buf j) #\\))
973 (setf (aref buf j) char))))))))))
975 (let ((keyword-package (symbol-package :foo)))
976 (defmethod database-output-sql ((sym symbol) database)
979 (if (equal (symbol-package sym) keyword-package)
980 (concatenate 'string "'" (string sym) "'")
981 (symbol-name sym)))))
983 (defmethod database-output-sql ((tee (eql t)) database)
985 (let ((val (database-output-sql-as-type 'boolean t database (database-type database))))
988 (string (format nil "'~A'" val))
989 (integer (format nil "~A" val)))))
992 #+nil(defmethod database-output-sql ((tee (eql t)) database)
993 (declare (ignore database))
996 (defmethod database-output-sql ((num number) database)
997 (declare (ignore database))
998 (number-to-sql-string num))
1000 (defmethod database-output-sql ((arg list) database)
1003 (format nil "(~{~A~^,~})" (mapcar #'(lambda (val)
1004 (sql-output val database))
1007 (defmethod database-output-sql ((arg vector) database)
1008 (format nil "~{~A~^,~}" (map 'list #'(lambda (val)
1009 (sql-output val database))
1012 (defmethod output-sql-hash-key ((arg vector) database)
1013 (list 'vector (map 'list (lambda (arg)
1014 (or (output-sql-hash-key arg database)
1015 (return-from output-sql-hash-key nil)))
1018 (defmethod database-output-sql ((self wall-time) database)
1019 (declare (ignore database))
1020 (db-timestring self))
1022 (defmethod database-output-sql ((self date) database)
1023 (declare (ignore database))
1024 (db-datestring self))
1026 (defmethod database-output-sql ((self duration) database)
1027 (declare (ignore database))
1028 (format nil "'~a'" (duration-timestring self)))
1031 (defmethod database-output-sql ((self money) database)
1032 (database-output-sql (slot-value self 'odcl::units) database))
1034 (defmethod database-output-sql (thing database)
1035 (if (or (null thing)
1038 (error 'sql-user-error
1041 "No type conversion to SQL for ~A is defined for DB ~A."
1042 (type-of thing) (type-of database)))))
1046 ;; Column constraint types and conversion to SQL
1049 (defparameter *constraint-types*
1051 (cons (symbol-name-default-case "NOT-NULL") "NOT NULL")
1052 (cons (symbol-name-default-case "PRIMARY-KEY") "PRIMARY KEY")
1053 (cons (symbol-name-default-case "NOT") "NOT")
1054 (cons (symbol-name-default-case "NULL") "NULL")
1055 (cons (symbol-name-default-case "PRIMARY") "PRIMARY")
1056 (cons (symbol-name-default-case "KEY") "KEY")
1057 (cons (symbol-name-default-case "UNSIGNED") "UNSIGNED")
1058 (cons (symbol-name-default-case "ZEROFILL") "ZEROFILL")
1059 (cons (symbol-name-default-case "AUTO-INCREMENT") "AUTO_INCREMENT")
1060 (cons (symbol-name-default-case "DEFAULT") "DEFAULT")
1061 (cons (symbol-name-default-case "UNIQUE") "UNIQUE")
1062 (cons (symbol-name-default-case "IDENTITY") "IDENTITY (1,1)") ;; added for sql-server support
1065 (defmethod database-constraint-statement (constraint-list database)
1066 (declare (ignore database))
1067 (make-constraints-description constraint-list))
1069 (defun make-constraints-description (constraint-list)
1072 (do ((constraint constraint-list (cdr constraint)))
1073 ((null constraint) string)
1074 (let ((output (assoc (symbol-name (car constraint))
1078 (error 'sql-user-error
1079 :message (format nil "unsupported column constraint '~A'"
1081 (setq string (concatenate 'string string (cdr output))))
1082 (when (equal (symbol-name (car constraint)) "DEFAULT")
1083 (setq constraint (cdr constraint))
1084 (setq string (concatenate 'string string " " (car constraint))))
1085 (if (< 1 (length constraint))
1086 (setq string (concatenate 'string string " "))))))))
1088 (defmethod database-identifier ( name &optional database find-class-p
1090 "A function that takes whatever you give it, recurively coerces it,
1091 and returns a database-identifier.
1093 (escaped-database-identifiers *any-reasonable-object*) should be called to
1094 produce a string that is safe to splice directly into sql strings.
1096 This function should NOT throw errors when database is nil
1098 find-class-p should be T if we want to search for classes
1099 and check their use their view table. Should be used
1100 on symbols we are sure indicate tables
1103 ;; metaclasses has further typecases of this, so that it will
1104 ;; load less painfully (try-recompiles) in SBCL
1107 (flet ((flatten-id (id)
1108 "if we have multiple pieces that we need to represent as
1109 db-id lets do that by rendering out the id, then creating
1110 a new db-id with that string as escaped"
1111 (let ((s (sql-output id database)))
1112 (make-instance '%database-identifier :escaped s :unescaped s))))
1115 (string (%make-database-identifier name database))
1117 ;; if this is being used as a table, we should check
1118 ;; for a class with this name and use the identifier specified
1120 (if (and find-class-p (setf cls (find-standard-db-class name)))
1121 (database-identifier cls)
1122 (%make-database-identifier name database)))
1123 (%database-identifier name)
1124 ;; we know how to deref this without further escaping
1126 (with-slots ((inner-name name) alias) name
1129 (database-identifier inner-name))))
1130 ;; if this is a single name we can derefence it
1131 (sql-ident-attribute
1132 (with-slots (qualifier (inner-name name)) name
1135 (database-identifier inner-name))))
1137 (with-slots ((inner-name name)) name
1138 (database-identifier inner-name)))
1139 ;; dont know how to handle this really :/
1140 (%sql-expression (flatten-id name))