1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
4 ;;;; The CLSQL Object Oriented Data Manipulation Language (OODML).
6 ;;;; This file is part of CLSQL.
8 ;;;; CLSQL users are granted the rights to distribute and use this software
9 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
10 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
11 ;;;; *************************************************************************
13 (in-package #:clsql-sys)
16 (defun key-qualifier-for-instance (obj &key (database *default-database*) this-class)
17 (let* ((obj-class (or this-class (class-of obj)))
18 (tb (view-table obj-class)))
21 (sql-expression :attribute
22 (view-class-slot-column k)
26 (slot-value obj (slot-definition-name k))
28 (let* ((keys (keyslots-for-class obj-class))
29 (keyxprs (mapcar #'qfk (reverse keys))))
31 ((= (length keyxprs) 0) nil)
32 ((= (length keyxprs) 1) (car keyxprs))
33 ((> (length keyxprs) 1) (apply #'sql-operation 'and keyxprs)))))))
36 ;; Function used by 'generate-selection-list'
39 (defun generate-attribute-reference (vclass slotdef)
41 ((eq (view-class-slot-db-kind slotdef) :base)
42 (sql-expression :attribute (view-class-slot-column slotdef)
43 :table (view-table vclass)))
44 ((eq (view-class-slot-db-kind slotdef) :key)
45 (sql-expression :attribute (view-class-slot-column slotdef)
46 :table (view-table vclass)))
50 ;; Function used by 'find-all'
53 (defun generate-selection-list (vclass)
56 (slots (if (normalizedp vclass)
57 (labels ((getdslots ()
58 (let ((sl (ordered-class-direct-slots this-class)))
62 (car (class-direct-superclasses this-class)))
65 (ordered-class-slots this-class))))
66 (dolist (slotdef slots)
67 (let ((res (generate-attribute-reference this-class slotdef)))
69 (push (cons slotdef res) sels))))
72 (error "No slots of type :base in view-class ~A" (class-name vclass)))))
76 (defun generate-retrieval-joins-list (vclass retrieval-method)
77 "Returns list of immediate join slots for a class."
78 (let ((join-slotdefs nil))
79 (dolist (slotdef (ordered-class-slots vclass) join-slotdefs)
80 (when (and (eq :join (view-class-slot-db-kind slotdef))
81 (eq retrieval-method (gethash :retrieval (view-class-slot-db-info slotdef))))
82 (push slotdef join-slotdefs)))))
84 (defun generate-immediate-joins-selection-list (vclass)
85 "Returns list of immediate join slots for a class."
87 (dolist (joined-slot (generate-retrieval-joins-list vclass :immediate) sels)
88 (let* ((join-class-name (gethash :join-class (view-class-slot-db-info joined-slot)))
89 (join-class (when join-class-name (find-class join-class-name))))
90 (dolist (slotdef (ordered-class-slots join-class))
91 (let ((res (generate-attribute-reference join-class slotdef)))
93 (push (cons slotdef res) sels))))))
97 ;; Called by 'get-slot-values-from-view'
100 (defmethod update-slot-from-db ((instance standard-db-object) slotdef value)
101 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
102 (let* ((slot-reader (view-class-slot-db-reader slotdef))
103 (slot-name (slot-definition-name slotdef))
104 (slot-type (specified-type slotdef)))
105 (cond ((and value (null slot-reader))
106 (setf (slot-value instance slot-name)
107 (read-sql-value value (delistify slot-type)
108 (view-database instance)
109 (database-underlying-type
110 (view-database instance)))))
112 (update-slot-with-null instance slot-name slotdef))
113 ((typep slot-reader 'string)
114 (setf (slot-value instance slot-name)
115 (format nil slot-reader value)))
116 ((typep slot-reader '(or symbol function))
117 (setf (slot-value instance slot-name)
118 (apply slot-reader (list value))))
120 (error "Slot reader is of an unusual type.")))))
122 (defmethod key-value-from-db (slotdef value database)
123 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
124 (let ((slot-reader (view-class-slot-db-reader slotdef))
125 (slot-type (specified-type slotdef)))
126 (cond ((and value (null slot-reader))
127 (read-sql-value value (delistify slot-type) database
128 (database-underlying-type database)))
131 ((typep slot-reader 'string)
132 (format nil slot-reader value))
133 ((typep slot-reader '(or symbol function))
134 (apply slot-reader (list value)))
136 (error "Slot reader is of an unusual type.")))))
138 (defun db-value-from-slot (slotdef val database)
139 (let ((dbwriter (view-class-slot-db-writer slotdef))
140 (dbtype (specified-type slotdef)))
142 (string (format nil dbwriter val))
143 ((and (or symbol function) (not null)) (apply dbwriter (list val)))
145 (database-output-sql-as-type
149 val database (database-underlying-type database))))))
151 (defun check-slot-type (slotdef val)
152 (let* ((slot-type (specified-type slotdef))
153 (basetype (if (listp slot-type) (car slot-type) slot-type)))
154 (when (and slot-type val)
155 (unless (typep val basetype)
156 (error 'sql-user-error
158 (format nil "Invalid value ~A in slot ~A, not of type ~A."
159 val (slot-definition-name slotdef) slot-type))))))
162 ;; Called by find-all
165 (defmethod get-slot-values-from-view (obj slotdeflist values)
166 (flet ((update-slot (slot-def values)
167 (update-slot-from-db obj slot-def values)))
168 (mapc #'update-slot slotdeflist values)
171 (defmethod update-record-from-slot ((obj standard-db-object) slot &key
173 (update-record-from-slots obj (list slot) :database database))
175 (defmethod update-record-from-slots ((obj standard-db-object) slots &key
176 (database *default-database*))
177 (let ((database (or database (view-database obj) *default-database*))
180 ((sstoredp (slot) (member (view-class-slot-db-kind slot) '(:base :key)))
181 (sboundp (slot) (slot-boundp obj (slot-definition-name slot)))
182 (slot-value-list (slot)
183 (let ((value (slot-value obj (slot-definition-name slot))))
184 (check-slot-type slot value)
185 (list (sql-expression :attribute (view-class-slot-column slot))
186 (db-value-from-slot slot value database))))
188 (save-slots-for-class (view-class stored-slot-defs)
189 (let ((pk-slot (car (keyslots-for-class view-class)))
190 (table (sql-expression :table (view-table view-class)))
191 (pclass (car (class-direct-superclasses view-class)))
193 direct-slots ; the slots to save on this iteration
194 parent-slots ; slots to handle recursively
196 (if (normalizedp view-class)
197 (let ((cdsn (mapcar #'slot-definition-name
198 (class-direct-slots view-class))))
199 (dolist (s stored-slot-defs)
200 (if (member (slot-definition-name s) cdsn)
201 (push s direct-slots)
202 (push s parent-slots))))
203 ;;not normalized, do everything now.
204 (setf direct-slots stored-slot-defs))
205 '(break "Class:~a ~%direct-slots:~a ~%parent-slots:~a ~%~a"
206 view-class direct-slots parent-slots
207 (class-direct-slots view-class))
209 ;;call recursively, collect primary key if we have it
210 (save-slots-for-class pclass parent-slots)
211 (when (and pk pk-slot)
212 (setf (slot-value obj (slot-definition-name pk-slot)) pk)))
214 ;;we've delayed doing the unbound test till here because
215 ;;the keys are sometimes only bound while updating the pclass
216 (let ((av-pairs (mapcar #'slot-value-list
217 (remove-if-not #'sboundp direct-slots))))
219 ((null av-pairs) nil)
221 (update-records table
223 :where (key-qualifier-for-instance
224 obj :database database
225 :this-class view-class)
227 (when (and pk-slot (not pk))
228 (setf pk (slot-value obj (slot-definition-name pk-slot))))
231 (insert-records :into table
234 (when (and pk-slot (not pk))
235 (setf pk (if (member :auto-increment (listify (view-class-slot-db-constraints pk-slot)))
236 (setf (slot-value obj (slot-definition-name pk-slot))
237 (database-last-auto-increment-id database
245 (save-slots-for-class
247 ;;convert to slot-defs, remove any non-stored.
249 for sd = (etypecase s
250 (symbol (slotdef-for-slot-with-class s (class-of obj)))
254 ;;this may just be a NOP.
255 (setf (slot-value obj 'view-database) database)))
259 (defmethod update-records-from-instance ((obj standard-db-object)
261 (update-record-from-slots obj (class-slots (class-of obj)) :database database))
263 (defmethod delete-instance-records ((instance standard-db-object))
264 (let ((vt (sql-expression :table (view-table (class-of instance))))
265 (vd (view-database instance)))
267 (let ((qualifier (key-qualifier-for-instance instance :database vd)))
268 (delete-records :from vt :where qualifier :database vd)
269 (setf (record-caches vd) nil)
270 (setf (slot-value instance 'view-database) nil)
272 (signal-no-database-error vd))))
274 (defmethod update-instance-from-records ((instance standard-db-object)
275 &key (database *default-database*)
277 (let* ((view-class (or this-class (class-of instance)))
278 (pclass (car (class-direct-superclasses view-class)))
280 (when (normalizedp view-class)
281 (setf pres (update-instance-from-records instance :database database
282 :this-class pclass)))
283 (let* ((view-table (sql-expression :table (view-table view-class)))
284 (vd (or (view-database instance) database))
285 (view-qual (key-qualifier-for-instance instance :database vd
286 :this-class view-class))
287 (sels (generate-selection-list view-class))
290 (setf res (apply #'select (append (mapcar #'cdr sels)
291 (list :from view-table
296 (setf (slot-value instance 'view-database) vd)
297 (get-slot-values-from-view instance (mapcar #'car sels) (car res))))
301 (defmethod update-slot-from-record ((instance standard-db-object)
302 slot &key (database *default-database*))
303 (let* ((view-class (find-class (class-name (class-of instance))))
304 (slot-def (slotdef-for-slot-with-class slot view-class)))
305 (when (normalizedp view-class)
306 ;; If it's normalized, find the class that actually contains
307 ;; the slot that's tied to the db
309 (do ((this-class view-class
310 (car (class-direct-superclasses this-class))))
312 (mapcar #'(lambda (esd) (slot-definition-name esd))
313 (ordered-class-direct-slots this-class)))
315 (let* ((view-table (sql-expression :table (view-table view-class)))
316 (vd (or (view-database instance) database))
317 (view-qual (key-qualifier-for-instance instance :database vd
318 :this-class view-class))
319 (att-ref (generate-attribute-reference view-class slot-def))
320 (res (select att-ref :from view-table :where view-qual
323 (setf (slot-value instance 'view-database) vd)
324 (get-slot-values-from-view instance (list slot-def) (car res))))))
326 (defmethod update-slot-with-null ((object standard-db-object)
329 (setf (slot-value object slotname) (slot-value slotdef 'void-value)))
331 (defvar +no-slot-value+ '+no-slot-value+)
333 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
334 (let* ((class (find-class classname))
335 (sld (slotdef-for-slot-with-class slot class)))
337 (if (eq value +no-slot-value+)
338 (sql-expression :attribute (view-class-slot-column sld)
339 :table (view-table class))
344 (error "Unknown slot ~A for class ~A" slot classname))))
346 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
347 (declare (ignore database))
348 (let* ((class (find-class classname)))
349 (unless (view-table class)
350 (error "No view-table for class ~A" classname))
351 (sql-expression :table (view-table class))))
354 (defmethod database-get-type-specifier (type args database db-type)
355 (declare (ignore type args database db-type))
356 (format nil "VARCHAR(~D)" *default-string-length*))
358 (defmethod database-get-type-specifier ((type (eql 'integer)) args database db-type)
359 (declare (ignore database db-type))
361 (format nil "INT(~A)" (car args))
365 "An 8-bit integer, this width may vary by SQL implementation."
368 (defmethod database-get-type-specifier ((type (eql 'tinyint)) args database db-type)
369 (declare (ignore args database db-type))
373 "An integer smaller than a 32-bit integer. this width may vary by SQL implementation."
376 (defmethod database-get-type-specifier ((type (eql 'smallint)) args database db-type)
377 (declare (ignore args database db-type))
380 (deftype mediumint ()
381 "An integer smaller than a 32-bit integer, but may be larger than a smallint. This width may vary by SQL implementation."
384 (defmethod database-get-type-specifier ((type (eql 'mediumint)) args database db-type)
385 (declare (ignore args database db-type))
389 "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
392 (defmethod database-get-type-specifier ((type (eql 'bigint)) args database db-type)
393 (declare (ignore args database db-type))
396 (deftype varchar (&optional size)
397 "A variable length string for the SQL varchar type."
398 (declare (ignore size))
401 (defmethod database-get-type-specifier ((type (eql 'varchar)) args
403 (declare (ignore database db-type))
405 (format nil "VARCHAR(~A)" (car args))
406 (format nil "VARCHAR(~D)" *default-string-length*)))
408 (defmethod database-get-type-specifier ((type (eql 'string)) args database db-type)
409 (declare (ignore database db-type))
411 (format nil "CHAR(~A)" (car args))
412 (format nil "VARCHAR(~D)" *default-string-length*)))
414 (deftype universal-time ()
415 "A positive integer as returned by GET-UNIVERSAL-TIME."
418 (defmethod database-get-type-specifier ((type (eql 'universal-time)) args database db-type)
419 (declare (ignore args database db-type))
422 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database db-type)
423 (declare (ignore args database db-type))
426 (defmethod database-get-type-specifier ((type (eql 'date)) args database db-type)
427 (declare (ignore args database db-type))
430 (defmethod database-get-type-specifier ((type (eql 'duration)) args database db-type)
431 (declare (ignore database args db-type))
434 (defmethod database-get-type-specifier ((type (eql 'money)) args database db-type)
435 (declare (ignore database args db-type))
439 (deftype char (&optional len)
440 "A lisp type for the SQL CHAR type."
443 (defmethod database-get-type-specifier ((type (eql 'float)) args database db-type)
444 (declare (ignore database db-type))
446 (format nil "FLOAT(~A)" (car args))
449 (defmethod database-get-type-specifier ((type (eql 'long-float)) args database db-type)
450 (declare (ignore database db-type))
452 (format nil "FLOAT(~A)" (car args))
455 (deftype generalized-boolean ()
456 "A type which outputs a SQL boolean value, though any lisp type can be stored in the slot."
459 (defmethod database-get-type-specifier ((type (eql 'boolean)) args database db-type)
460 (declare (ignore args database db-type))
463 (defmethod database-get-type-specifier ((type (eql 'generalized-boolean)) args database db-type)
464 (declare (ignore args database db-type))
467 (defmethod database-get-type-specifier ((type (eql 'number)) args database db-type)
468 (declare (ignore database db-type))
470 ((and (consp args) (= (length args) 2))
471 (format nil "NUMBER(~D,~D)" (first args) (second args)))
472 ((and (consp args) (= (length args) 1))
473 (format nil "NUMBER(~D)" (first args)))
477 (defmethod database-get-type-specifier ((type (eql 'char)) args database db-type)
478 (declare (ignore database db-type))
480 (format nil "CHAR(~D)" (first args))
484 (defmethod database-output-sql-as-type (type val database db-type)
485 (declare (ignore type database db-type))
488 (defmethod database-output-sql-as-type ((type (eql 'list)) val database db-type)
489 (declare (ignore database db-type))
490 (progv '(*print-circle* *print-array*) '(t t)
491 (let ((escaped (prin1-to-string val)))
492 (substitute-char-string
493 escaped #\Null " "))))
495 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database db-type)
496 (declare (ignore database db-type))
499 (package-name (symbol-package val))
504 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database db-type)
505 (declare (ignore database db-type))
510 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database db-type)
511 (declare (ignore database db-type))
512 (progv '(*print-circle* *print-array*) '(t t)
513 (prin1-to-string val)))
515 (defmethod database-output-sql-as-type ((type (eql 'array)) val database db-type)
516 (declare (ignore database db-type))
517 (progv '(*print-circle* *print-array*) '(t t)
518 (prin1-to-string val)))
520 (defmethod database-output-sql-as-type ((type (eql 'boolean)) val database db-type)
521 (declare (ignore database db-type))
524 (defmethod database-output-sql-as-type ((type (eql 'generalized-boolean)) val database db-type)
525 (declare (ignore database db-type))
528 (defmethod database-output-sql-as-type ((type (eql 'string)) val database db-type)
529 (declare (ignore database db-type))
532 (defmethod database-output-sql-as-type ((type (eql 'char)) val database db-type)
533 (declare (ignore database db-type))
535 (character (write-to-string val))
538 (defmethod database-output-sql-as-type ((type (eql 'float)) val database db-type)
539 (declare (ignore database db-type))
540 (if (eq (type-of val) 'null)
542 (let ((*read-default-float-format* (type-of val)))
543 (format nil "~F" val))))
545 (defmethod read-sql-value (val type database db-type)
546 (declare (ignore database db-type))
548 ((null type) val) ;;we have no desired type, just give the value
549 ((typep val type) val) ;;check that it hasn't already been converted.
550 ((typep val 'string) (read-from-string val)) ;;maybe read will just take care of it?
551 (T (error "Unable to read-sql-value ~a as type ~a" val type))))
553 (defmethod read-sql-value (val (type (eql 'string)) database db-type)
554 (declare (ignore database db-type))
557 (defmethod read-sql-value (val (type (eql 'varchar)) database db-type)
558 (declare (ignore database db-type))
561 (defmethod read-sql-value (val (type (eql 'char)) database db-type)
562 (declare (ignore database db-type))
565 (defmethod read-sql-value (val (type (eql 'keyword)) database db-type)
566 (declare (ignore database db-type))
567 (when (< 0 (length val))
568 (intern (symbol-name-default-case val)
569 (find-package '#:keyword))))
571 (defmethod read-sql-value (val (type (eql 'symbol)) database db-type)
572 (declare (ignore database db-type))
573 (when (< 0 (length val))
574 (unless (string= val (symbol-name-default-case "NIL"))
575 (read-from-string val))))
577 (defmethod read-sql-value (val (type (eql 'integer)) database db-type)
578 (declare (ignore database db-type))
581 (unless (string-equal "NIL" val)
582 (parse-integer val)))
585 (defmethod read-sql-value (val (type (eql 'smallint)) database db-type)
586 (declare (ignore database db-type))
589 (unless (string-equal "NIL" val)
590 (parse-integer val)))
593 (defmethod read-sql-value (val (type (eql 'bigint)) database db-type)
594 (declare (ignore database db-type))
597 (unless (string-equal "NIL" val)
598 (parse-integer val)))
601 (defmethod read-sql-value (val (type (eql 'float)) database db-type)
602 (declare (ignore database db-type))
603 ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
605 (string (float (read-from-string val)))
608 (defmethod read-sql-value (val (type (eql 'double-float)) database db-type)
609 (declare (ignore database db-type))
610 ;; writing 1.0 writes 1, so if we *really* want a float, must do (float ...)
613 (let ((*read-default-float-format* 'double-float))
614 (read-from-string val))
617 (float (coerce val 'double-float))))
619 (defmethod read-sql-value (val (type (eql 'boolean)) database db-type)
620 (declare (ignore database db-type))
623 (defmethod read-sql-value (val (type (eql 'generalized-boolean)) database db-type)
624 (declare (ignore database db-type))
627 (defmethod read-sql-value (val (type (eql 'number)) database db-type)
628 (declare (ignore database db-type))
631 (unless (string-equal "NIL" val)
632 (read-from-string val)))
635 (defmethod read-sql-value (val (type (eql 'universal-time)) database db-type)
636 (declare (ignore database db-type))
637 (unless (eq 'NULL val)
643 (defmethod read-sql-value (val (type (eql 'wall-time)) database db-type)
644 (declare (ignore database db-type))
645 (unless (eq 'NULL val)
646 (parse-timestring val)))
648 (defmethod read-sql-value (val (type (eql 'date)) database db-type)
649 (declare (ignore database db-type))
650 (unless (eq 'NULL val)
651 (parse-datestring val)))
653 (defmethod read-sql-value (val (type (eql 'duration)) database db-type)
654 (declare (ignore database db-type))
655 (unless (or (eq 'NULL val)
657 (parse-timestring val)))
659 ;; ------------------------------------------------------------
660 ;; Logic for 'faulting in' :join slots
662 ;; this works, but is inefficient requiring (+ 1 n-rows)
665 (defun fault-join-target-slot (class object slot-def)
666 (let* ((res (fault-join-slot-raw class object slot-def))
667 (dbi (view-class-slot-db-info slot-def))
668 (target-name (gethash :target-slot dbi))
669 (target-class (find-class target-name)))
671 (mapcar (lambda (obj)
677 (find target-name (class-slots (class-of obj))
678 :key #'slot-definition-name)))
681 #+ignore ;; this doesn't work when attempting to call slot-value
682 (mapcar (lambda (obj)
683 (cons obj (slot-value obj ts))) res))))
685 (defun fault-join-target-slot (class object slot-def)
686 (let* ((dbi (view-class-slot-db-info slot-def))
687 (ts (gethash :target-slot dbi))
688 (jc (gethash :join-class dbi))
689 (jc-view-table (view-table (find-class jc)))
690 (tdbi (view-class-slot-db-info
691 (find ts (class-slots (find-class jc))
692 :key #'slot-definition-name)))
693 (retrieval (gethash :retrieval tdbi))
694 (tsc (gethash :join-class tdbi))
695 (ts-view-table (view-table (find-class tsc)))
696 (jq (join-qualifier class object slot-def))
697 (key (slot-value object (gethash :home-key dbi))))
704 :inner-join (sql-expression :table jc-view-table)
708 :attribute (gethash :foreign-key tdbi)
709 :table ts-view-table)
711 :attribute (gethash :home-key tdbi)
712 :table jc-view-table))
715 :database (view-database object))))
716 (mapcar #'(lambda (i)
717 (let* ((instance (car i))
718 (jcc (make-instance jc :view-database (view-database instance))))
719 (setf (slot-value jcc (gethash :foreign-key dbi))
721 (setf (slot-value jcc (gethash :home-key tdbi))
722 (slot-value instance (gethash :foreign-key tdbi)))
723 (list instance jcc)))
726 ;; just fill in minimal slots
729 (let ((instance (make-instance tsc :view-database (view-database object)))
730 (jcc (make-instance jc :view-database (view-database object)))
732 (setf (slot-value instance (gethash :home-key tdbi)) fk)
733 (setf (slot-value jcc (gethash :foreign-key dbi))
735 (setf (slot-value jcc (gethash :home-key tdbi))
737 (list instance jcc)))
738 (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
739 :from (sql-expression :table jc-view-table)
741 :database (view-database object))))))))
746 (defvar *default-update-objects-max-len* nil
747 "The default value to use for the MAX-LEN keyword argument to
748 UPDATE-OBJECT-JOINS.")
750 (defun update-objects-joins (objects &key (slots t) (force-p t)
752 *default-update-objects-max-len*))
753 "Updates from the records of the appropriate database tables
754 the join slots specified by SLOTS in the supplied list of View
755 Class instances OBJECTS. SLOTS is t by default which means that
756 all join slots with :retrieval :immediate are updated. CLASS-NAME
757 is used to specify the View Class of all instance in OBJECTS and
758 default to nil which means that the class of the first instance
759 in OBJECTS is used. FORCE-P is t by default which means that all
760 join slots are updated whereas a value of nil means that only
761 unbound join slots are updated. MAX-LEN defaults to
762 *DEFAULT-UPDATE-OBJECTS-MAX-LEN* and when non-nil specifies that
763 UPDATE-OBJECT-JOINS may issue multiple database queries with a
764 maximum of MAX-LEN instances updated in each query."
765 (assert (or (null max-len) (plusp max-len)))
768 (setq class-name (class-name (class-of (first objects)))))
769 (let* ((class (find-class class-name))
770 (class-slots (ordered-class-slots class))
773 (generate-retrieval-joins-list class :deferred)
775 (mapcar #'(lambda (name)
776 (let ((slotdef (find name class-slots :key #'slot-definition-name)))
778 (warn "Unable to find slot named ~S in class ~S." name class))
781 (dolist (slotdef slotdefs)
782 (let* ((dbi (view-class-slot-db-info slotdef))
783 (slotdef-name (slot-definition-name slotdef))
784 (foreign-key (gethash :foreign-key dbi))
785 (home-key (gethash :home-key dbi))
789 (mapcar #'(lambda (o) (slot-value o home-key)) objects)
792 #'(lambda (o) (if (slot-boundp o slotdef-name)
794 (slot-value o home-key)))
796 (n-object-keys (length object-keys))
797 (query-len (or max-len n-object-keys)))
799 (do ((i 0 (+ i query-len)))
800 ((>= i n-object-keys))
801 (let* ((keys (if max-len
802 (subseq object-keys i (min (+ i query-len) n-object-keys))
804 (results (unless (gethash :target-slot dbi)
805 (find-all (list (gethash :join-class dbi))
806 :where (make-instance 'sql-relational-exp
808 :sub-expressions (list (sql-expression :attribute foreign-key)
813 (dolist (object objects)
814 (when (or force-p (not (slot-boundp object slotdef-name)))
815 (let ((res (if results
816 (remove-if-not #'(lambda (obj)
817 (equal obj (slot-value
826 (when (gethash :target-slot dbi)
827 (fault-join-target-slot class object slotdef))))))
829 (setf (slot-value object slotdef-name)
830 (if (gethash :set dbi) res (car res)))))))))))))
833 (defun fault-join-slot-raw (class object slot-def)
834 (let* ((dbi (view-class-slot-db-info slot-def))
835 (jc (gethash :join-class dbi)))
836 (let ((jq (join-qualifier class object slot-def)))
838 (select jc :where jq :flatp t :result-types nil
839 :database (view-database object))))))
841 (defun fault-join-slot (class object slot-def)
842 (let* ((dbi (view-class-slot-db-info slot-def))
843 (ts (gethash :target-slot dbi)))
844 (if (and ts (gethash :set dbi))
845 (fault-join-target-slot class object slot-def)
846 (let ((res (fault-join-slot-raw class object slot-def)))
849 ((and ts (not (gethash :set dbi)))
850 (mapcar (lambda (obj) (slot-value obj ts)) res))
851 ((and (not ts) (not (gethash :set dbi)))
853 ((and (not ts) (gethash :set dbi))
856 ;;;; Should we not return the whole result, instead of only
857 ;;;; the one slot-value? We get all the values from the db
859 (defun fault-join-normalized-slot (class object slot-def)
860 (labels ((getsc (this-class)
861 (let ((sc (car (class-direct-superclasses this-class))))
865 (let* ((sc (getsc class))
866 (hk (slot-definition-name (car (key-slots class))))
867 (fk (slot-definition-name (car (key-slots sc)))))
868 (let ((jq (sql-operation '==
873 (view-class-slot-column
874 (slotdef-for-slot-with-class fk sc))
875 :table (view-table sc)))
879 (slot-value object hk))
882 ;; Caching nil in next select, because in normalized mode
883 ;; records can be changed through other instances (children,
884 ;; parents) so changes possibly won't be noticed
885 (let ((res (car (select (class-name sc) :where jq
886 :flatp t :result-types nil
888 :database (view-database object))))
889 (slot-name (slot-definition-name slot-def)))
891 ;; If current class is normalized and wanted slot is not
892 ;; a direct member, recurse up
893 (if (and (normalizedp class)
894 (not (member slot-name
895 (mapcar #'(lambda (esd) (slot-definition-name esd))
896 (ordered-class-direct-slots class))))
897 (not (slot-boundp res slot-name)))
898 (fault-join-normalized-slot sc res slot-def)
899 (slot-value res slot-name)))))) )
901 (defun join-qualifier (class object slot-def)
902 (declare (ignore class))
903 (let* ((dbi (view-class-slot-db-info slot-def))
904 (jc (find-class (gethash :join-class dbi)))
905 ;;(ts (gethash :target-slot dbi))
906 ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
907 (foreign-keys (gethash :foreign-key dbi))
908 (home-keys (gethash :home-key dbi)))
909 (when (every #'(lambda (slt)
910 (and (slot-boundp object slt)
911 (not (null (slot-value object slt)))))
912 (if (listp home-keys) home-keys (list home-keys)))
914 (mapcar #'(lambda (hk fk)
915 (let ((fksd (slotdef-for-slot-with-class fk jc)))
921 (view-class-slot-column fksd)
922 :table (view-table jc)))
926 (slot-value object hk))
929 (if (listp home-keys)
932 (if (listp foreign-keys)
934 (list foreign-keys)))))
936 (if (> (length jc) 1)
940 ;; FIXME: add retrieval immediate for efficiency
941 ;; For example, for (select 'employee-address) in test suite =>
942 ;; select addr.*,ea_join.* FROM addr,ea_join WHERE ea_join.aaddressid=addr.addressid\g
944 (defun build-objects (vals sclasses immediate-join-classes sels immediate-joins database refresh flatp instances)
945 "Used by find-all to build objects."
946 (labels ((build-object (vals vclass jclasses selects immediate-selects instance)
947 (let* ((db-vals (butlast vals (- (list-length vals)
948 (list-length selects))))
949 (obj (if instance instance (make-instance (class-name vclass) :view-database database)))
950 (join-vals (subseq vals (list-length selects)))
951 (joins (mapcar #'(lambda (c) (when c (make-instance c :view-database database)))
954 ;;(format t "joins: ~S~%db-vals: ~S~%join-values: ~S~%selects: ~S~%immediate-selects: ~S~%"
955 ;;joins db-vals join-vals selects immediate-selects)
957 ;; use refresh keyword here
958 (setf obj (get-slot-values-from-view obj (mapcar #'car selects) db-vals))
960 ;; find all immediate-select slots and join-vals for this object
961 (let* ((jo-class (class-of jo))
963 (if (normalizedp jo-class)
964 (class-direct-slots jo-class)
965 (class-slots jo-class)))
966 (pos-list (remove-if #'null
969 (position s immediate-selects
973 (get-slot-values-from-view jo
975 (mapcar #'(lambda (pos)
976 (nth pos immediate-selects))
978 (mapcar #'(lambda (pos) (nth pos join-vals))
984 (class-slots vclass))
985 (slot (find (class-name (class-of jc)) vslots
986 :key #'(lambda (slot)
987 (when (and (eq :join (view-class-slot-db-kind slot))
988 (eq (slot-definition-name slot)
989 (gethash :join-class (view-class-slot-db-info slot))))
990 (slot-definition-name slot))))))
992 (setf (slot-value obj (slot-definition-name slot)) jc))))
994 (when refresh (instance-refreshed obj))
997 (mapcar #'(lambda (sclass jclass sel immediate-join instance)
999 (build-object vals sclass jclass sel immediate-join instance)
1000 (setf vals (nthcdr (+ (list-length sel) (list-length immediate-join))
1002 sclasses immediate-join-classes sels immediate-joins instances)))
1003 (if (and flatp (= (length sclasses) 1))
1007 (defun find-all (view-classes
1009 &key all set-operation distinct from where group-by having
1010 order-by offset limit refresh flatp result-types
1012 (database *default-database*)
1014 "Called by SELECT to generate object query results when the
1015 View Classes VIEW-CLASSES are passed as arguments to SELECT."
1016 (declare (ignore all set-operation group-by having offset limit inner-join on))
1017 (flet ((ref-equal (ref1 ref2)
1018 (string= (sql-output ref1 database)
1019 (sql-output ref2 database)))
1020 (table-sql-expr (table)
1021 (sql-expression :table (view-table table)))
1022 (tables-equal (table-a table-b)
1023 (when (and table-a table-b)
1024 (string= (string (slot-value table-a 'name))
1025 (string (slot-value table-b 'name))))))
1029 (remf args :additional-fields)
1030 (remf args :result-types)
1031 (remf args :instances)
1032 (let* ((*db-deserializing* t)
1033 (sclasses (mapcar #'find-class view-classes))
1034 (immediate-join-slots
1035 (mapcar #'(lambda (c) (generate-retrieval-joins-list c :immediate)) sclasses))
1036 (immediate-join-classes
1037 (mapcar #'(lambda (jcs)
1038 (mapcar #'(lambda (slotdef)
1039 (find-class (gethash :join-class (view-class-slot-db-info slotdef))))
1041 immediate-join-slots))
1042 (immediate-join-sels (mapcar #'generate-immediate-joins-selection-list sclasses))
1043 (sels (mapcar #'generate-selection-list sclasses))
1044 (fullsels (apply #'append (mapcar #'append sels immediate-join-sels)))
1045 (sel-tables (collect-table-refs where))
1046 (tables (remove-if #'null
1048 (append (mapcar #'table-sql-expr sclasses)
1049 (mapcan #'(lambda (jc-list)
1051 #'(lambda (jc) (when jc (table-sql-expr jc)))
1053 immediate-join-classes)
1055 :test #'tables-equal)))
1056 (order-by-slots (mapcar #'(lambda (ob) (if (atom ob) ob (car ob)))
1057 (listify order-by)))
1060 ;;(format t "sclasses: ~W~%ijc: ~W~%tables: ~W~%" sclasses immediate-join-classes tables)
1062 (dolist (ob order-by-slots)
1063 (when (and ob (not (member ob (mapcar #'cdr fullsels)
1064 :test #'ref-equal)))
1066 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1068 (dolist (ob (listify distinct))
1069 (when (and (typep ob 'sql-ident)
1070 (not (member ob (mapcar #'cdr fullsels)
1071 :test #'ref-equal)))
1073 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1075 (mapcar #'(lambda (vclass jclasses jslots)
1078 #'(lambda (jclass jslot)
1079 (let ((dbi (view-class-slot-db-info jslot)))
1082 (list (sql-operation '==
1084 :attribute (gethash :foreign-key dbi)
1085 :table (view-table jclass))
1087 :attribute (gethash :home-key dbi)
1088 :table (view-table vclass))))
1089 (when join-where (listify join-where))))))
1091 sclasses immediate-join-classes immediate-join-slots)
1092 ;; Reported buggy on clsql-devel
1093 ;; (when where (setq where (listify where)))
1095 ((and where join-where)
1096 (setq where (list (apply #'sql-and where join-where))))
1097 ((and (null where) (> (length join-where) 1))
1098 (setq where (list (apply #'sql-and join-where)))))
1100 (let* ((rows (apply #'select
1101 (append (mapcar #'cdr fullsels)
1103 (list (append (when from (listify from))
1105 (list :result-types result-types)
1107 (list :where where))
1109 (instances-to-add (- (length rows) (length instances)))
1110 (perhaps-extended-instances
1111 (if (plusp instances-to-add)
1112 (append instances (do ((i 0 (1+ i))
1114 ((= i instances-to-add) res)
1115 (push (make-list (length sclasses) :initial-element nil) res)))
1118 #'(lambda (row instance)
1119 (build-objects row sclasses immediate-join-classes sels
1120 immediate-join-sels database refresh flatp
1121 (if (and flatp (atom instance))
1124 rows perhaps-extended-instances)))
1127 (defmethod instance-refreshed ((instance standard-db-object)))
1129 (defvar *default-caching* t
1130 "Controls whether SELECT caches objects by default. The CommonSQL
1131 specification states caching is on by default.")
1133 (defun select (&rest select-all-args)
1134 "Executes a query on DATABASE, which has a default value of
1135 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
1136 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
1137 argument can be used to generate queries in both functional and
1138 object oriented contexts.
1140 In the functional case, the required arguments specify the
1141 columns selected by the query and may be symbolic SQL expressions
1142 or strings representing attribute identifiers. Type modified
1143 identifiers indicate that the values selected from the specified
1144 column are converted to the specified lisp type. The keyword
1145 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
1146 SET-OPERATION and WHERE are used to specify, using the symbolic
1147 SQL syntax, the corresponding components of the SQL query
1148 generated by the call to SELECT. RESULT-TYPES is a list of
1149 symbols which specifies the lisp type for each field returned by
1150 the query. If RESULT-TYPES is nil all results are returned as
1151 strings whereas the default value of :auto means that the lisp
1152 types are automatically computed for each field. FIELD-NAMES is t
1153 by default which means that the second value returned is a list
1154 of strings representing the columns selected by the query. If
1155 FIELD-NAMES is nil, the list of column names is not returned as a
1158 In the object oriented case, the required arguments to SELECT are
1159 symbols denoting View Classes which specify the database tables
1160 to query. In this case, SELECT returns a list of View Class
1161 instances whose slots are set from the attribute values of the
1162 records in the specified table. Slot-value is a legal operator
1163 which can be employed as part of the symbolic SQL syntax used in
1164 the WHERE keyword argument to SELECT. REFRESH is nil by default
1165 which means that the View Class instances returned are retrieved
1166 from a cache if an equivalent call to SELECT has previously been
1167 issued. If REFRESH is true, the View Class instances returned are
1168 updated as necessary from the database and the generic function
1169 INSTANCE-REFRESHED is called to perform any necessary operations
1170 on the updated instances.
1172 In both object oriented and functional contexts, FLATP has a
1173 default value of nil which means that the results are returned as
1174 a list of lists. If FLATP is t and only one result is returned
1175 for each record selected in the query, the results are returned
1176 as elements of a list."
1178 (flet ((select-objects (target-args)
1180 (every #'(lambda (arg)
1182 (find-class arg nil)))
1184 (multiple-value-bind (target-args qualifier-args)
1185 (query-get-selections select-all-args)
1186 (unless (or *default-database* (getf qualifier-args :database))
1187 (signal-no-database-error nil))
1190 ((select-objects target-args)
1191 (let ((caching (getf qualifier-args :caching *default-caching*))
1192 (result-types (getf qualifier-args :result-types :auto))
1193 (refresh (getf qualifier-args :refresh nil))
1194 (database (or (getf qualifier-args :database) *default-database*))
1195 (order-by (getf qualifier-args :order-by)))
1196 (remf qualifier-args :caching)
1197 (remf qualifier-args :refresh)
1198 (remf qualifier-args :result-types)
1200 ;; Add explicity table name to order-by if not specified and only
1201 ;; one selected table. This is required so FIND-ALL won't duplicate
1203 (when (and order-by (= 1 (length target-args)))
1204 (let ((table-name (view-table (find-class (car target-args))))
1205 (order-by-list (copy-seq (listify order-by))))
1207 (loop for i from 0 below (length order-by-list)
1208 do (etypecase (nth i order-by-list)
1209 (sql-ident-attribute
1210 (unless (slot-value (nth i order-by-list) 'qualifier)
1211 (setf (slot-value (nth i order-by-list) 'qualifier) table-name)))
1213 (unless (slot-value (car (nth i order-by-list)) 'qualifier)
1214 (setf (slot-value (car (nth i order-by-list)) 'qualifier) table-name)))))
1215 (setf (getf qualifier-args :order-by) order-by-list)))
1219 (apply #'find-all target-args
1220 (append qualifier-args
1221 (list :result-types result-types :refresh refresh))))
1223 (let ((cached (records-cache-results target-args qualifier-args database)))
1225 ((and cached (not refresh))
1227 ((and cached refresh)
1228 (let ((results (apply #'find-all (append (list target-args) qualifier-args `(:instances ,cached :result-types :auto :refresh ,refresh)))))
1229 (setf (records-cache-results target-args qualifier-args database) results)
1232 (let ((results (apply #'find-all target-args (append qualifier-args
1233 `(:result-types :auto :refresh ,refresh)))))
1234 (setf (records-cache-results target-args qualifier-args database) results)
1237 (let* ((expr (apply #'make-query select-all-args))
1239 (mapcar #'(lambda (attrib)
1240 (if (typep attrib 'sql-ident-attribute)
1241 (let ((type (slot-value attrib 'type)))
1246 (slot-value expr 'selections))))
1247 (destructuring-bind (&key (flatp nil)
1248 (result-types :auto)
1250 (database *default-database*)
1253 (query expr :flatp flatp
1255 ;; specifying a type for an attribute overrides result-types
1256 (if (some #'(lambda (x) (not (eq t x))) specified-types)
1259 :field-names field-names
1260 :database database))))))))
1262 (defun compute-records-cache-key (targets qualifiers)
1264 (do ((args *select-arguments* (cdr args))
1266 ((null args) results)
1267 (let* ((arg (car args))
1268 (value (getf qualifiers arg)))
1272 (cons (cons (sql (car value)) (cdr value)))
1273 (%sql-expression (sql value))
1277 (defun records-cache-results (targets qualifiers database)
1278 (when (record-caches database)
1279 (gethash (compute-records-cache-key targets qualifiers) (record-caches database))))
1281 (defun (setf records-cache-results) (results targets qualifiers database)
1282 (unless (record-caches database)
1283 (setf (record-caches database)
1284 (make-hash-table :test 'equal
1285 #+allegro :values #+allegro :weak
1286 #+clisp :weak #+clisp :value
1287 #+lispworks :weak-kind #+lispworks :value)))
1288 (setf (gethash (compute-records-cache-key targets qualifiers)
1289 (record-caches database)) results)
1294 ;;; Serialization functions
1296 (defun write-instance-to-stream (obj stream)
1297 "Writes an instance to a stream where it can be later be read.
1298 NOTE: an error will occur if a slot holds a value which can not be written readably."
1299 (let* ((class (class-of obj))
1301 (dolist (slot (ordered-class-slots (class-of obj)))
1302 (let ((name (slot-definition-name slot)))
1303 (when (and (not (eq 'view-database name))
1304 (slot-boundp obj name))
1305 (push (cons name (slot-value obj name)) alist))))
1306 (setq alist (reverse alist))
1307 (write (cons (class-name class) alist) :stream stream :readably t))
1310 (defun read-instance-from-stream (stream)
1311 (let ((raw (read stream nil nil)))
1313 (let ((obj (make-instance (car raw))))
1314 (dolist (pair (cdr raw))
1315 (setf (slot-value obj (car pair)) (cdr pair)))