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 list))
254 appending (listify (collect-table-refs i))))
256 (defmethod collect-table-refs ((sql sql-ident-attribute))
257 (let ((qual (slot-value sql 'qualifier)))
259 ;; going to be used as a table, search classes
262 :name (database-identifier qual nil t))))))
264 (defmethod make-load-form ((sql sql-ident-attribute) &optional environment)
265 (declare (ignore environment))
266 (with-slots (qualifier type name)
268 `(make-instance 'sql-ident-attribute :name ',name
269 :qualifier ',qualifier
272 (defmethod output-sql-hash-key ((expr sql-ident-attribute) database)
273 (with-slots (qualifier name type)
275 (list (and database (database-underlying-type database))
277 (unescaped-database-identifier qualifier)
278 (unescaped-database-identifier name) type)))
280 ;; For SQL Identifiers for tables
282 (defclass sql-ident-table (sql-ident)
284 :initarg :table-alias :initform nil))
285 (:documentation "An SQL table identifier."))
287 (defmethod make-load-form ((sql sql-ident-table) &optional environment)
288 (declare (ignore environment))
289 (with-slots (alias name)
291 `(make-instance 'sql-ident-table :name ',name :table-alias ',alias)))
293 (defmethod collect-table-refs ((sql sql-ident-table))
296 (defmethod output-sql ((expr sql-ident-table) database)
297 (with-slots (name alias) expr
298 (flet ((p (s) ;; the etypecase is in sql-escape too
300 (escaped-database-identifier s database)
304 (princ #\space *sql-stream*)
308 (defmethod output-sql ((expr sql-ident-attribute) database)
309 ;;; KMR: The TYPE field is used by CommonSQL for type conversion -- it
310 ;;; should not be output in SQL statements
311 (let ((*print-pretty* nil))
312 (with-slots (qualifier name type) expr
313 (format *sql-stream* "~@[~a.~]~a"
316 (escaped-database-identifier qualifier database T))
317 (escaped-database-identifier name database))
320 (defmethod output-sql-hash-key ((expr sql-ident-table) database)
321 (with-slots (name alias)
323 (list (and database (database-underlying-type database))
325 (unescaped-database-identifier name)
326 (unescaped-database-identifier alias))))
328 (defclass sql-relational-exp (%sql-expression)
333 :initarg :sub-expressions
335 (:documentation "An SQL relational expression."))
337 (defmethod make-load-form ((self sql-relational-exp) &optional environment)
338 (make-load-form-saving-slots self
339 :slot-names '(operator sub-expressions)
340 :environment environment))
342 (defmethod collect-table-refs ((sql sql-relational-exp))
344 (dolist (exp (slot-value sql 'sub-expressions))
345 (let ((refs (collect-table-refs exp)))
346 (if refs (setf tabs (append refs tabs)))))
347 (remove-duplicates tabs :test #'database-identifier-equal)))
352 ;; Write SQL for relational operators (like 'AND' and 'OR').
353 ;; should do arity checking of subexpressions
355 (defun %write-operator (operator database)
357 (string (write-string operator *sql-stream*))
358 (symbol (write-string (symbol-name operator) *sql-stream*))
359 (T (output-sql operator database))))
361 (defmethod output-sql ((expr sql-relational-exp) database)
362 (with-slots (operator sub-expressions) expr
363 ;; we do this as two runs so as not to emit confusing superflous parentheses
364 ;; The first loop renders all the child outputs so that we can skip anding with
365 ;; empty output (which causes sql errors)
366 ;; the next loop simply emits each sub-expression with the appropriate number of
367 ;; parens and operators
369 (string-trim +whitespace-chars+
370 (with-output-to-string (*sql-stream*)
371 (output-sql sub database)))))
372 (let ((str-subs (loop for sub in sub-expressions
373 for str-sub = (trim sub)
374 when (and str-sub (> (length str-sub) 0))
376 (case (length str-subs)
378 (1 (write-string (first str-subs) *sql-stream*))
380 (write-char #\( *sql-stream*)
381 (write-string (first str-subs) *sql-stream*)
382 (loop for str-sub in (rest str-subs)
384 (write-char #\Space *sql-stream*)
385 ;; do this so that symbols can be output as database identifiers
386 ;; rather than allowing symbols to inject sql
387 (%write-operator operator database)
388 (write-char #\Space *sql-stream*)
389 (write-string str-sub *sql-stream*))
390 (write-char #\) *sql-stream*))
394 (defclass sql-upcase-like (sql-relational-exp)
396 (:documentation "An SQL 'like' that upcases its arguments."))
398 (defmethod output-sql ((expr sql-upcase-like) database)
399 (flet ((write-term (term)
400 (write-string "upper(" *sql-stream*)
401 (output-sql term database)
402 (write-char #\) *sql-stream*)))
403 (with-slots (sub-expressions)
405 (let ((subs (if (consp (car sub-expressions))
406 (car sub-expressions)
408 (write-char #\( *sql-stream*)
409 (do ((sub subs (cdr sub)))
410 ((null (cdr sub)) (write-term (car sub)))
411 (write-term (car sub))
412 (write-string " LIKE " *sql-stream*))
413 (write-char #\) *sql-stream*))))
416 (defclass sql-assignment-exp (sql-relational-exp)
418 (:documentation "An SQL Assignment expression."))
421 (defmethod output-sql ((expr sql-assignment-exp) database)
422 (with-slots (operator sub-expressions)
424 (do ((sub sub-expressions (cdr sub)))
425 ((null (cdr sub)) (output-sql (car sub) database))
426 (output-sql (car sub) database)
427 (write-char #\Space *sql-stream*)
428 (%write-operator operator database)
429 (write-char #\Space *sql-stream*)))
432 (defclass sql-value-exp (%sql-expression)
440 "An SQL value expression.")
443 (defmethod collect-table-refs ((sql sql-value-exp))
445 (if (listp (slot-value sql 'components))
447 (dolist (exp (slot-value sql 'components))
448 (let ((refs (collect-table-refs exp)))
449 (if refs (setf tabs (append refs tabs)))))
450 (remove-duplicates tabs :test #'database-identifier-equal))
453 (defmethod output-sql ((expr sql-value-exp) database)
454 (with-slots (modifier components)
458 (write-char #\( *sql-stream*)
460 ((sql-operator modifier)
461 (%write-operator modifier database))
462 ((or (stringp modifier) (symbolp modifier))
464 (escaped-database-identifier modifier)
466 (t (output-sql modifier database)))
467 (write-char #\Space *sql-stream*)
468 (output-sql components database)
469 (write-char #\) *sql-stream*))
470 (output-sql components database))))
472 (defclass sql-typecast-exp (sql-value-exp)
474 (:documentation "An SQL typecast expression."))
476 (defmethod output-sql ((expr sql-typecast-exp) database)
477 (with-slots (components)
479 (output-sql components database)))
481 (defmethod collect-table-refs ((sql sql-typecast-exp))
482 (when (slot-value sql 'components)
483 (collect-table-refs (slot-value sql 'components))))
485 (defclass sql-function-exp (%sql-expression)
493 "An SQL function expression."))
495 (defmethod collect-table-refs ((sql sql-function-exp))
497 (dolist (exp (slot-value sql 'args))
498 (let ((refs (collect-table-refs exp)))
499 (if refs (setf tabs (append refs tabs)))))
500 (remove-duplicates tabs :test #'database-identifier-equal)))
501 (defvar *in-subselect* nil)
503 (defmethod output-sql ((expr sql-function-exp) database)
504 (with-slots (name args)
508 (write-string (escaped-database-identifier name) *sql-stream*))
509 (t (output-sql name database)))
510 (let ((*in-subselect* nil)) ;; aboid double parens
511 (when args (output-sql args database))))
515 (defclass sql-between-exp (sql-function-exp)
517 (:documentation "An SQL between expression."))
519 (defmethod output-sql ((expr sql-between-exp) database)
522 (output-sql (first args) database)
523 (write-string " BETWEEN " *sql-stream*)
524 (output-sql (second args) database)
525 (write-string " AND " *sql-stream*)
526 (output-sql (third args) database))
529 (defclass sql-query-modifier-exp (%sql-expression)
530 ((modifier :initarg :modifier :initform nil)
531 (components :initarg :components :initform nil))
532 (:documentation "An SQL query modifier expression."))
534 (defmethod output-sql ((expr sql-query-modifier-exp) database)
535 (with-slots (modifier components)
537 (%write-operator modifier database)
538 (write-string " " *sql-stream*)
539 (%write-operator (car components) database)
541 (mapc #'(lambda (comp)
542 (write-string ", " *sql-stream*)
543 (output-sql comp database))
547 (defclass sql-set-exp (%sql-expression)
552 :initarg :sub-expressions
554 (:documentation "An SQL set expression."))
556 (defmethod collect-table-refs ((sql sql-set-exp))
558 (dolist (exp (slot-value sql 'sub-expressions))
559 (let ((refs (collect-table-refs exp)))
560 (if refs (setf tabs (append refs tabs)))))
561 (remove-duplicates tabs :test #'database-identifier-equal)))
563 (defmethod output-sql ((expr sql-set-exp) database)
564 (with-slots (operator sub-expressions)
566 (let ((subs (if (consp (car sub-expressions))
567 (car sub-expressions)
569 (when (= (length subs) 1)
570 (%write-operator operator database)
571 (write-char #\Space *sql-stream*))
572 (do ((sub subs (cdr sub)))
573 ((null (cdr sub)) (output-sql (car sub) database))
574 (output-sql (car sub) database)
575 (write-char #\Space *sql-stream*)
576 (%write-operator operator database)
577 (write-char #\Space *sql-stream*))))
580 (defclass sql-query (%sql-expression)
591 :initarg :set-operation
623 (:documentation "An SQL SELECT query."))
625 (defclass sql-object-query (%sql-expression)
639 (defmethod collect-table-refs ((sql sql-query))
641 (collect-table-refs (slot-value sql 'where))
642 :test #'database-identifier-equal))
644 (defvar *select-arguments*
645 '(:all :database :distinct :flatp :from :group-by :having :order-by
646 :set-operation :where :offset :limit :inner-join :on
647 ;; below keywords are not a SQL argument, but these keywords may terminate select
650 (defun query-arg-p (sym)
651 (member sym *select-arguments*))
653 (defun query-get-selections (select-args)
654 "Return two values: the list of select-args up to the first keyword,
655 uninclusive, and the args from that keyword to the end."
656 (let ((first-key-arg (position-if #'query-arg-p select-args)))
658 (values (subseq select-args 0 first-key-arg)
659 (subseq select-args first-key-arg))
662 (defun make-query (&rest args)
663 (flet ((select-objects (target-args)
665 (every #'(lambda (arg)
667 (find-class arg nil)))
669 (multiple-value-bind (selections arglist)
670 (query-get-selections args)
671 (if (select-objects selections)
672 (destructuring-bind (&key flatp refresh &allow-other-keys) arglist
673 (make-instance 'sql-object-query :objects selections
674 :flatp flatp :refresh refresh
676 (destructuring-bind (&key all flatp set-operation distinct from where
677 group-by having order-by
678 offset limit inner-join on &allow-other-keys)
680 (if (null selections)
681 (error "No target columns supplied to select statement."))
683 (error "No source tables supplied to select statement."))
684 (make-instance 'sql-query :selections selections
685 :all all :flatp flatp :set-operation set-operation
686 :distinct distinct :from from :where where
687 :limit limit :offset offset
688 :group-by group-by :having having :order-by order-by
689 :inner-join inner-join :on on))))))
691 (defun output-sql-where-clause (where database)
692 "ensure that we do not output a \"where\" sql keyword when we will
693 not output a clause. Also sets *in-subselect* to use SQL
694 parentheticals as needed."
696 (let ((where-out (string-trim
697 '(#\newline #\space #\tab #\return)
698 (with-output-to-string (*sql-stream*)
699 (let ((*in-subselect* t))
700 (output-sql where database))))))
701 (when (> (length where-out) 0)
702 (write-string " WHERE " *sql-stream*)
703 (write-string where-out *sql-stream*)))))
705 (defmethod output-sql ((query sql-query) database)
706 (with-slots (distinct selections from where group-by having order-by
707 limit offset inner-join on all set-operation)
710 (write-string "(" *sql-stream*))
711 (write-string "SELECT " *sql-stream*)
713 (write-string " ALL " *sql-stream*))
714 (when (and distinct (not all))
715 (write-string " DISTINCT " *sql-stream*)
716 (unless (eql t distinct)
717 (write-string " ON " *sql-stream*)
718 (output-sql distinct database)
719 (write-char #\Space *sql-stream*)))
720 (when (and limit (eql :mssql (database-underlying-type database)))
721 (write-string " TOP " *sql-stream*)
722 (output-sql limit database)
723 (write-string " " *sql-stream*))
724 (let ((*in-subselect* t))
725 (output-sql (apply #'vector selections) database))
727 (write-string " FROM " *sql-stream*)
731 (remove-duplicates from :test #'database-identifier-equal))
733 (string (write-string
734 (escaped-database-identifier from database)
736 (t (let ((*in-subselect* t))
737 (output-sql from database)))))
739 (write-string " INNER JOIN " *sql-stream*)
740 (output-sql inner-join database))
742 (write-string " ON " *sql-stream*)
743 (output-sql on database))
744 (output-sql-where-clause where database)
746 (write-string " GROUP BY " *sql-stream*)
748 (do ((order group-by (cdr order)))
750 (let ((item (car order)))
753 (output-sql (car item) database)
754 (format *sql-stream* " ~A" (cadr item)))
756 (output-sql item database)))
758 (write-char #\, *sql-stream*))))
759 (output-sql group-by database)))
761 (write-string " HAVING " *sql-stream*)
762 (output-sql having database))
764 (write-string " ORDER BY " *sql-stream*)
766 (do ((order order-by (cdr order)))
768 (let ((item (car order)))
771 (output-sql (car item) database)
772 (format *sql-stream* " ~A" (cadr item)))
774 (output-sql item database)))
776 (write-char #\, *sql-stream*))))
777 (output-sql order-by database)))
778 (when (and limit (not (eql :mssql (database-underlying-type database))))
779 (write-string " LIMIT " *sql-stream*)
780 (output-sql limit database))
782 (write-string " OFFSET " *sql-stream*)
783 (output-sql offset database))
785 (write-string ")" *sql-stream*))
787 (write-char #\Space *sql-stream*)
788 (output-sql set-operation database)))
791 (defmethod output-sql ((query sql-object-query) database)
792 (declare (ignore database))
793 (with-slots (objects)
796 (format *sql-stream* "(~{~A~^ ~})" objects))))
801 (defclass sql-insert (%sql-expression)
815 "An SQL INSERT statement."))
817 (defmethod output-sql ((ins sql-insert) database)
818 (with-slots (into attributes values query)
820 (write-string "INSERT INTO " *sql-stream*)
823 (string (sql-expression :table into))
827 (write-char #\Space *sql-stream*)
828 (output-sql attributes database))
830 (write-string " VALUES " *sql-stream*)
831 (let ((clsql-sys::*in-subselect* t))
832 (output-sql values database)))
834 (write-char #\Space *sql-stream*)
835 (output-sql query database)))
840 (defclass sql-delete (%sql-expression)
848 "An SQL DELETE statement."))
850 (defmethod output-sql ((stmt sql-delete) database)
851 (with-slots (from where)
853 (write-string "DELETE FROM " *sql-stream*)
855 ((or symbol string) (write-string (sql-escape from) *sql-stream*))
856 (t (output-sql from database)))
857 (output-sql-where-clause where database))
862 (defclass sql-update (%sql-expression)
875 (:documentation "An SQL UPDATE statement."))
877 (defmethod output-sql ((expr sql-update) database)
878 (with-slots (table where attributes values)
880 (flet ((update-assignments ()
881 (mapcar #'(lambda (a b)
882 (make-instance 'sql-assignment-exp
884 :sub-expressions (list a b)))
886 (write-string "UPDATE " *sql-stream*)
887 (output-sql table database)
888 (write-string " SET " *sql-stream*)
889 (let ((clsql-sys::*in-subselect* t))
890 (output-sql (apply #'vector (update-assignments)) database))
891 (output-sql-where-clause where database)))
896 (defclass sql-create-table (%sql-expression)
907 :initarg :transactions
910 "An SQL CREATE TABLE statement."))
912 ;; Here's a real warhorse of a function!
914 (declaim (inline listify))
920 (defmethod output-sql ((stmt sql-create-table) database)
921 (flet ((output-column (column-spec)
922 (destructuring-bind (name type &optional db-type &rest constraints)
924 (let ((type (listify type)))
925 (output-sql name database)
926 (write-char #\Space *sql-stream*)
928 (if (stringp db-type) db-type ; override definition
929 (database-get-type-specifier (car type) (cdr type) database
930 (database-underlying-type database)))
932 (let ((constraints (database-constraint-statement
933 (if (and db-type (symbolp db-type))
934 (cons db-type constraints)
938 (write-string " " *sql-stream*)
939 (write-string constraints *sql-stream*)))))))
940 (with-slots (name columns modifiers transactions)
942 (write-string "CREATE TABLE " *sql-stream*)
943 (write-string (escaped-database-identifier name database) *sql-stream*)
944 (write-string " (" *sql-stream*)
945 (do ((column columns (cdr column)))
947 (output-column (car column)))
948 (output-column (car column))
949 (write-string ", " *sql-stream*))
951 (do ((modifier (listify modifiers) (cdr modifier)))
953 (write-string ", " *sql-stream*)
954 (write-string (car modifier) *sql-stream*)))
955 (write-char #\) *sql-stream*)
956 (when (and (eq :mysql (database-underlying-type database))
958 (db-type-transaction-capable? :mysql database))
959 (write-string " ENGINE=innodb" *sql-stream*))))
965 (defclass sql-create-view (%sql-expression)
966 ((name :initarg :name :initform nil)
967 (column-list :initarg :column-list :initform nil)
968 (query :initarg :query :initform nil)
969 (with-check-option :initarg :with-check-option :initform nil))
970 (:documentation "An SQL CREATE VIEW statement."))
972 (defmethod output-sql ((stmt sql-create-view) database)
973 (with-slots (name column-list query with-check-option) stmt
974 (write-string "CREATE VIEW " *sql-stream*)
975 (output-sql name database)
976 (when column-list (write-string " " *sql-stream*)
977 (output-sql (listify column-list) database))
978 (write-string " AS " *sql-stream*)
979 (output-sql query database)
980 (when with-check-option (write-string " WITH CHECK OPTION" *sql-stream*))))
984 ;; DATABASE-OUTPUT-SQL
987 (defmethod database-output-sql ((str string) database)
988 (declare (optimize (speed 3) (safety 1)
989 #+cmu (extensions:inhibit-warnings 3)))
990 (let ((len (length str)))
991 (declare (type fixnum len))
994 ((and (null (position #\' str))
995 (null (position #\\ str)))
996 (concatenate 'string "'" str "'"))
998 (let ((buf (make-string (+ (* len 2) 2) :initial-element #\')))
999 (declare (simple-string buf))
1000 (do* ((i 0 (incf i))
1002 ((= i len) (subseq buf 0 (1+ j)))
1003 (declare (type fixnum i j))
1004 (let ((char (aref str i)))
1005 (declare (character char))
1006 (cond ((char= char #\')
1007 (setf (aref buf j) #\')
1009 (setf (aref buf j) #\'))
1010 ((and (char= char #\\)
1011 ;; MTP: only escape backslash with pgsql/mysql
1012 (member (database-underlying-type database)
1013 '(:postgresql :mysql)
1015 (setf (aref buf j) #\\)
1017 (setf (aref buf j) #\\))
1019 (setf (aref buf j) char))))))))))
1021 (let ((keyword-package (symbol-package :foo)))
1022 (defmethod database-output-sql ((sym symbol) database)
1025 (if (equal (symbol-package sym) keyword-package)
1026 (database-output-sql (symbol-name sym) database)
1027 (escaped-database-identifier sym)))))
1029 (defmethod database-output-sql ((tee (eql t)) database)
1031 (let ((val (database-output-sql-as-type 'boolean t database (database-type database))))
1034 (string (format nil "'~A'" val))
1035 (integer (format nil "~A" val)))))
1038 #+nil(defmethod database-output-sql ((tee (eql t)) database)
1039 (declare (ignore database))
1042 (defmethod database-output-sql ((num number) database)
1043 (declare (ignore database))
1044 (number-to-sql-string num))
1046 (defmethod database-output-sql ((arg list) database)
1049 (format nil "(~{~A~^,~})" (mapcar #'(lambda (val)
1050 (sql-output val database))
1053 (defmethod database-output-sql ((arg vector) database)
1054 (format nil "~{~A~^,~}" (map 'list #'(lambda (val)
1055 (sql-output val database))
1058 (defmethod output-sql-hash-key ((arg vector) database)
1059 (list 'vector (map 'list (lambda (arg)
1060 (or (output-sql-hash-key arg database)
1061 (return-from output-sql-hash-key nil)))
1064 (defmethod database-output-sql ((self wall-time) database)
1065 (declare (ignore database))
1066 (db-timestring self))
1068 (defmethod database-output-sql ((self date) database)
1069 (declare (ignore database))
1070 (db-datestring self))
1072 (defmethod database-output-sql ((self duration) database)
1073 (declare (ignore database))
1074 (format nil "'~a'" (duration-timestring self)))
1077 (defmethod database-output-sql ((self money) database)
1078 (database-output-sql (slot-value self 'odcl::units) database))
1080 (defmethod database-output-sql (thing database)
1081 (if (or (null thing)
1084 (error 'sql-user-error
1087 "No type conversion to SQL for ~A is defined for DB ~A."
1088 (type-of thing) (type-of database)))))
1092 ;; Column constraint types and conversion to SQL
1094 (defmethod database-constraint-statement (constraint-list database)
1095 (make-constraints-description constraint-list database))
1097 ;; KEEP THIS SYNCED WITH database-translate-constraint
1098 (defparameter +auto-increment-names+
1099 '(:auto-increment :auto_increment :autoincrement :identity))
1101 (defmethod database-translate-constraint (constraint database)
1103 (:not-null "NOT NULL")
1104 (:primary-key "PRIMARY KEY")
1105 ((:auto-increment :auto_increment :autoincrement :identity)
1106 (ecase (database-underlying-type database)
1107 (:mssql "IDENTITY (1,1)")
1108 ((:sqlite :sqlite3) "PRIMARY KEY AUTOINCREMENT")
1109 (:mysql "AUTO_INCREMENT")
1110 ;; this is modeled as a datatype instead of a constraint
1112 ;; everything else just get the name
1113 (T (string-upcase (symbol-name constraint)))))
1115 (defun make-constraints-description (constraint-list database
1116 &aux (rest constraint-list) constraint)
1117 (when constraint-list
1119 (setf constraint (first rest)
1122 (with-output-to-string (s)
1124 do (unless (keywordp constraint)
1125 (setf constraint (intern (symbol-name constraint) :keyword)))
1126 (write-string (database-translate-constraint constraint database) s)
1127 (when (eql :default constraint) (princ (next) s))
1128 (write-char #\space s)
1131 (defmethod database-identifier ( name &optional database find-class-p
1133 "A function that takes whatever you give it, recursively coerces it,
1134 and returns a database-identifier.
1136 (escaped-database-identifiers *any-reasonable-object*) should be called to
1137 produce a string that is safe to splice directly into sql strings.
1139 This function should NOT throw errors when database is nil
1141 find-class-p should be T if we want to search for classes
1142 and check their use their view table. Should be used
1143 on symbols we are sure indicate tables
1146 ;; metaclasses has further typecases of this, so that it will
1147 ;; load less painfully (try-recompiles) in SBCL
1150 (flet ((flatten-id (id)
1151 "if we have multiple pieces that we need to represent as
1152 db-id lets do that by rendering out the id, then creating
1153 a new db-id with that string as escaped"
1154 (let ((s (sql-output id database)))
1155 (make-instance '%database-identifier :escaped s :unescaped s))))
1156 (setf name (dequote name))
1159 (string (%make-database-identifier name database))
1161 ;; if this is being used as a table, we should check
1162 ;; for a class with this name and use the identifier specified
1164 (if (and find-class-p (setf cls (find-standard-db-class name)))
1165 (database-identifier cls)
1166 (%make-database-identifier name database)))
1167 (%database-identifier name)
1168 ;; we know how to deref this without further escaping
1170 (with-slots ((inner-name name) alias) name
1173 (database-identifier inner-name))))
1174 ;; if this is a single name we can derefence it
1175 (sql-ident-attribute
1176 (with-slots (qualifier (inner-name name)) name
1179 (database-identifier inner-name))))
1181 (with-slots ((inner-name name)) name
1182 (database-identifier inner-name)))
1183 ;; dont know how to handle this really :/
1184 (%sql-expression (flatten-id name))
1187 (defun %clsql-subclauses (clauses)
1188 "a helper for dealing with lists of sql clauses"
1189 (loop for c in clauses
1192 (string (clsql-sys:sql-expression :string c))
1195 (defun clsql-ands (clauses)
1196 "Correctly creates a sql 'and' expression for the clauses
1197 ignores any nil clauses
1198 returns a single child expression if there is only one
1199 returns an 'and' expression if there are many
1200 returns nil if there are no children"
1201 (let ((ex (%clsql-subclauses clauses)))
1205 (t (apply #'clsql-sys:sql-and ex))))))
1207 (defun clsql-and (&rest clauses)
1208 "Correctly creates a sql 'and' expression for the clauses
1209 ignores any nil clauses
1210 returns a single child expression if there is only one
1211 returns an 'and' expression if there are many
1212 returns nil if there are no children"
1213 (clsql-ands clauses))
1215 (defun clsql-ors (clauses)
1216 "Correctly creates a sql 'or' expression for the clauses
1217 ignores any nil clauses
1218 returns a single child expression if there is only one
1219 returns an 'or' expression if there are many
1220 returns nil if there are no children"
1221 (let ((ex (%clsql-subclauses clauses)))
1225 (t (apply #'clsql-sys:sql-or ex))))))
1227 (defun clsql-or (&rest clauses)
1228 "Correctly creates a sql 'or' expression for the clauses
1229 ignores any nil clauses
1230 returns a single child expression if there is only one
1231 returns an 'or' expression if there are many
1232 returns nil if there are no children"
1233 (clsql-ors clauses))
1236 (defclass sql-escape-string-exp (%sql-expression)
1241 "An escaped string string expression (postgresql E'stuff') ."))
1243 (defmethod output-sql ((exp sql-escape-string-exp) database)
1244 (with-slots (string) exp
1246 (write-char #\E *sql-stream*)
1247 (output-sql string database))))