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 (or (member :auto-increment (listify (view-class-slot-db-constraints pk-slot)))
236 (not (null (view-class-slot-autoincrement-sequence pk-slot))))
237 (setf (slot-value obj (slot-definition-name pk-slot))
238 (database-last-auto-increment-id database
246 (save-slots-for-class
248 ;;convert to slot-defs, remove any non-stored.
250 for sd = (etypecase s
251 (symbol (slotdef-for-slot-with-class s (class-of obj)))
255 ;; handle slots with defaults
257 (when (and (slot-exists-p slot 'db-constraints)
258 (listp (view-class-slot-db-constraints slot))
259 (member :default (view-class-slot-db-constraints slot)))
260 (unless (and (slot-boundp obj (slot-definition-name slot))
261 (slot-value obj (slot-definition-name slot)))
262 (update-slot-from-record obj (slot-definition-name slot)))))
263 ;;this may just be a NOP.
264 (setf (slot-value obj 'view-database) database)))
268 (defmethod update-records-from-instance ((obj standard-db-object)
270 (update-record-from-slots obj (class-slots (class-of obj)) :database database))
272 (defmethod delete-instance-records ((instance standard-db-object))
273 (let ((vt (sql-expression :table (view-table (class-of instance))))
274 (vd (view-database instance)))
276 (let ((qualifier (key-qualifier-for-instance instance :database vd)))
277 (delete-records :from vt :where qualifier :database vd)
278 (setf (record-caches vd) nil)
279 (setf (slot-value instance 'view-database) nil)
281 (signal-no-database-error vd))))
283 (defmethod update-instance-from-records ((instance standard-db-object)
284 &key (database *default-database*)
286 (let* ((view-class (or this-class (class-of instance)))
287 (pclass (car (class-direct-superclasses view-class)))
289 (when (normalizedp view-class)
290 (setf pres (update-instance-from-records instance :database database
291 :this-class pclass)))
292 (let* ((view-table (sql-expression :table (view-table view-class)))
293 (vd (or (view-database instance) database))
294 (view-qual (key-qualifier-for-instance instance :database vd
295 :this-class view-class))
296 (sels (generate-selection-list view-class))
299 (setf res (apply #'select (append (mapcar #'cdr sels)
300 (list :from view-table
305 (setf (slot-value instance 'view-database) vd)
306 (get-slot-values-from-view instance (mapcar #'car sels) (car res))))
310 (defmethod update-slot-from-record ((instance standard-db-object)
311 slot &key (database *default-database*))
312 (let* ((view-class (find-class (class-name (class-of instance))))
313 (slot-def (slotdef-for-slot-with-class slot view-class)))
314 (when (normalizedp view-class)
315 ;; If it's normalized, find the class that actually contains
316 ;; the slot that's tied to the db
318 (do ((this-class view-class
319 (car (class-direct-superclasses this-class))))
321 (mapcar #'(lambda (esd) (slot-definition-name esd))
322 (ordered-class-direct-slots this-class)))
324 (let* ((view-table (sql-expression :table (view-table view-class)))
325 (vd (or (view-database instance) database))
326 (view-qual (key-qualifier-for-instance instance :database vd
327 :this-class view-class))
328 (att-ref (generate-attribute-reference view-class slot-def))
329 (res (select att-ref :from view-table :where view-qual
332 (setf (slot-value instance 'view-database) vd)
333 (get-slot-values-from-view instance (list slot-def) (car res))))))
335 (defmethod update-slot-with-null ((object standard-db-object)
338 (setf (slot-value object slotname) (slot-value slotdef 'void-value)))
340 (defvar +no-slot-value+ '+no-slot-value+)
342 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
343 (let* ((class (find-class classname))
344 (sld (slotdef-for-slot-with-class slot class)))
346 (if (eq value +no-slot-value+)
347 (sql-expression :attribute (view-class-slot-column sld)
348 :table (view-table class))
353 (error "Unknown slot ~A for class ~A" slot classname))))
355 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
356 (declare (ignore database))
357 (let* ((class (find-class classname)))
358 (unless (view-table class)
359 (error "No view-table for class ~A" classname))
360 (sql-expression :table (view-table class))))
363 (defmethod database-get-type-specifier (type args database db-type)
364 (declare (ignore type args database db-type))
365 (format nil "VARCHAR(~D)" *default-string-length*))
367 (defmethod database-get-type-specifier ((type (eql 'integer)) args database db-type)
368 (declare (ignore database db-type))
370 (format nil "INT(~A)" (car args))
374 "An 8-bit integer, this width may vary by SQL implementation."
377 (defmethod database-get-type-specifier ((type (eql 'tinyint)) args database db-type)
378 (declare (ignore args database db-type))
382 "An integer smaller than a 32-bit integer. this width may vary by SQL implementation."
385 (defmethod database-get-type-specifier ((type (eql 'smallint)) args database db-type)
386 (declare (ignore args database db-type))
389 (deftype mediumint ()
390 "An integer smaller than a 32-bit integer, but may be larger than a smallint. This width may vary by SQL implementation."
393 (defmethod database-get-type-specifier ((type (eql 'mediumint)) args database db-type)
394 (declare (ignore args database db-type))
398 "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
401 (defmethod database-get-type-specifier ((type (eql 'bigint)) args database db-type)
402 (declare (ignore args database db-type))
405 (deftype varchar (&optional size)
406 "A variable length string for the SQL varchar type."
407 (declare (ignore size))
410 (defmethod database-get-type-specifier ((type (eql 'varchar)) args
412 (declare (ignore database db-type))
414 (format nil "VARCHAR(~A)" (car args))
415 (format nil "VARCHAR(~D)" *default-string-length*)))
417 (defmethod database-get-type-specifier ((type (eql 'string)) args database db-type)
418 (declare (ignore database db-type))
420 (format nil "CHAR(~A)" (car args))
421 (format nil "VARCHAR(~D)" *default-string-length*)))
423 (deftype universal-time ()
424 "A positive integer as returned by GET-UNIVERSAL-TIME."
427 (defmethod database-get-type-specifier ((type (eql 'universal-time)) args database db-type)
428 (declare (ignore args database db-type))
431 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database db-type)
432 (declare (ignore args database db-type))
435 (defmethod database-get-type-specifier ((type (eql 'date)) args database db-type)
436 (declare (ignore args database db-type))
439 (defmethod database-get-type-specifier ((type (eql 'duration)) args database db-type)
440 (declare (ignore database args db-type))
443 (defmethod database-get-type-specifier ((type (eql 'money)) args database db-type)
444 (declare (ignore database args db-type))
448 (deftype char (&optional len)
449 "A lisp type for the SQL CHAR type."
452 (defmethod database-get-type-specifier ((type (eql 'float)) args database db-type)
453 (declare (ignore database db-type))
455 (format nil "FLOAT(~A)" (car args))
458 (defmethod database-get-type-specifier ((type (eql 'long-float)) args database db-type)
459 (declare (ignore database db-type))
461 (format nil "FLOAT(~A)" (car args))
464 (deftype generalized-boolean ()
465 "A type which outputs a SQL boolean value, though any lisp type can be stored in the slot."
468 (defmethod database-get-type-specifier ((type (eql 'boolean)) args database db-type)
469 (declare (ignore args database db-type))
472 (defmethod database-get-type-specifier ((type (eql 'generalized-boolean)) args database db-type)
473 (declare (ignore args database db-type))
476 (defmethod database-get-type-specifier ((type (eql 'number)) args database db-type)
477 (declare (ignore database db-type))
479 ((and (consp args) (= (length args) 2))
480 (format nil "NUMBER(~D,~D)" (first args) (second args)))
481 ((and (consp args) (= (length args) 1))
482 (format nil "NUMBER(~D)" (first args)))
486 (defmethod database-get-type-specifier ((type (eql 'char)) args database db-type)
487 (declare (ignore database db-type))
489 (format nil "CHAR(~D)" (first args))
493 (defmethod database-output-sql-as-type (type val database db-type)
494 (declare (ignore type database db-type))
497 (defmethod database-output-sql-as-type ((type (eql 'list)) val database db-type)
498 (declare (ignore database db-type))
499 (progv '(*print-circle* *print-array*) '(t t)
500 (let ((escaped (prin1-to-string val)))
501 (substitute-char-string
502 escaped #\Null " "))))
504 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database db-type)
505 (declare (ignore database db-type))
508 (package-name (symbol-package val))
513 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database db-type)
514 (declare (ignore database db-type))
519 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database db-type)
520 (declare (ignore database db-type))
521 (progv '(*print-circle* *print-array*) '(t t)
522 (prin1-to-string val)))
524 (defmethod database-output-sql-as-type ((type (eql 'array)) val database db-type)
525 (declare (ignore database db-type))
526 (progv '(*print-circle* *print-array*) '(t t)
527 (prin1-to-string val)))
529 (defmethod database-output-sql-as-type ((type (eql 'boolean)) val database db-type)
530 (declare (ignore database db-type))
533 (defmethod database-output-sql-as-type ((type (eql 'generalized-boolean)) val database db-type)
534 (declare (ignore database db-type))
537 (defmethod database-output-sql-as-type ((type (eql 'string)) val database db-type)
538 (declare (ignore database db-type))
541 (defmethod database-output-sql-as-type ((type (eql 'char)) val database db-type)
542 (declare (ignore database db-type))
544 (character (write-to-string val))
547 (defmethod database-output-sql-as-type ((type (eql 'float)) val database db-type)
548 (declare (ignore database db-type))
549 (if (eq (type-of val) 'null)
551 (let ((*read-default-float-format* (type-of val)))
552 (format nil "~F" val))))
554 (defmethod read-sql-value (val type database db-type)
555 (declare (ignore database db-type))
557 ((null type) val) ;;we have no desired type, just give the value
558 ((typep val type) val) ;;check that it hasn't already been converted.
559 ((typep val 'string) (read-from-string val)) ;;maybe read will just take care of it?
560 (T (error "Unable to read-sql-value ~a as type ~a" val type))))
562 (defmethod read-sql-value (val (type (eql 'string)) database db-type)
563 (declare (ignore database db-type))
566 (defmethod read-sql-value (val (type (eql 'varchar)) database db-type)
567 (declare (ignore database db-type))
570 (defmethod read-sql-value (val (type (eql 'char)) database db-type)
571 (declare (ignore database db-type))
574 (defmethod read-sql-value (val (type (eql 'keyword)) database db-type)
575 (declare (ignore database db-type))
576 (when (< 0 (length val))
577 (intern (symbol-name-default-case val)
578 (find-package '#:keyword))))
580 (defmethod read-sql-value (val (type (eql 'symbol)) database db-type)
581 (declare (ignore database db-type))
582 (when (< 0 (length val))
583 (unless (string= val (symbol-name-default-case "NIL"))
584 (read-from-string val))))
586 (defmethod read-sql-value (val (type (eql 'integer)) database db-type)
587 (declare (ignore database db-type))
590 (unless (string-equal "NIL" val)
591 (parse-integer val)))
594 (defmethod read-sql-value (val (type (eql 'smallint)) database db-type)
595 (declare (ignore database db-type))
598 (unless (string-equal "NIL" val)
599 (parse-integer val)))
602 (defmethod read-sql-value (val (type (eql 'bigint)) database db-type)
603 (declare (ignore database db-type))
606 (unless (string-equal "NIL" val)
607 (parse-integer val)))
610 (defmethod read-sql-value (val (type (eql 'float)) database db-type)
611 (declare (ignore database db-type))
612 ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
614 (string (float (read-from-string val)))
617 (defmethod read-sql-value (val (type (eql 'double-float)) database db-type)
618 (declare (ignore database db-type))
619 ;; writing 1.0 writes 1, so if we *really* want a float, must do (float ...)
622 (let ((*read-default-float-format* 'double-float))
623 (read-from-string val))
626 (float (coerce val 'double-float))))
628 (defmethod read-sql-value (val (type (eql 'boolean)) database db-type)
629 (declare (ignore database db-type))
632 (defmethod read-sql-value (val (type (eql 'generalized-boolean)) database db-type)
633 (declare (ignore database db-type))
636 (defmethod read-sql-value (val (type (eql 'number)) database db-type)
637 (declare (ignore database db-type))
640 (unless (string-equal "NIL" val)
641 (read-from-string val)))
644 (defmethod read-sql-value (val (type (eql 'universal-time)) database db-type)
645 (declare (ignore database db-type))
646 (unless (eq 'NULL val)
652 (defmethod read-sql-value (val (type (eql 'wall-time)) database db-type)
653 (declare (ignore database db-type))
654 (unless (eq 'NULL val)
655 (parse-timestring val)))
657 (defmethod read-sql-value (val (type (eql 'date)) database db-type)
658 (declare (ignore database db-type))
659 (unless (eq 'NULL val)
660 (parse-datestring val)))
662 (defmethod read-sql-value (val (type (eql 'duration)) database db-type)
663 (declare (ignore database db-type))
664 (unless (or (eq 'NULL val)
666 (parse-timestring val)))
668 ;; ------------------------------------------------------------
669 ;; Logic for 'faulting in' :join slots
671 ;; this works, but is inefficient requiring (+ 1 n-rows)
674 (defun fault-join-target-slot (class object slot-def)
675 (let* ((res (fault-join-slot-raw class object slot-def))
676 (dbi (view-class-slot-db-info slot-def))
677 (target-name (gethash :target-slot dbi))
678 (target-class (find-class target-name)))
680 (mapcar (lambda (obj)
686 (find target-name (class-slots (class-of obj))
687 :key #'slot-definition-name)))
690 #+ignore ;; this doesn't work when attempting to call slot-value
691 (mapcar (lambda (obj)
692 (cons obj (slot-value obj ts))) res))))
694 (defun fault-join-target-slot (class object slot-def)
695 (let* ((dbi (view-class-slot-db-info slot-def))
696 (ts (gethash :target-slot dbi))
697 (jc (gethash :join-class dbi))
698 (jc-view-table (view-table (find-class jc)))
699 (tdbi (view-class-slot-db-info
700 (find ts (class-slots (find-class jc))
701 :key #'slot-definition-name)))
702 (retrieval (gethash :retrieval tdbi))
703 (tsc (gethash :join-class tdbi))
704 (ts-view-table (view-table (find-class tsc)))
705 (jq (join-qualifier class object slot-def))
706 (key (slot-value object (gethash :home-key dbi))))
713 :inner-join (sql-expression :table jc-view-table)
717 :attribute (gethash :foreign-key tdbi)
718 :table ts-view-table)
720 :attribute (gethash :home-key tdbi)
721 :table jc-view-table))
724 :database (view-database object))))
725 (mapcar #'(lambda (i)
726 (let* ((instance (car i))
727 (jcc (make-instance jc :view-database (view-database instance))))
728 (setf (slot-value jcc (gethash :foreign-key dbi))
730 (setf (slot-value jcc (gethash :home-key tdbi))
731 (slot-value instance (gethash :foreign-key tdbi)))
732 (list instance jcc)))
735 ;; just fill in minimal slots
738 (let ((instance (make-instance tsc :view-database (view-database object)))
739 (jcc (make-instance jc :view-database (view-database object)))
741 (setf (slot-value instance (gethash :home-key tdbi)) fk)
742 (setf (slot-value jcc (gethash :foreign-key dbi))
744 (setf (slot-value jcc (gethash :home-key tdbi))
746 (list instance jcc)))
747 (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
748 :from (sql-expression :table jc-view-table)
750 :database (view-database object))))))))
755 (defvar *default-update-objects-max-len* nil
756 "The default value to use for the MAX-LEN keyword argument to
757 UPDATE-OBJECT-JOINS.")
759 (defun update-objects-joins (objects &key (slots t) (force-p t)
761 *default-update-objects-max-len*))
762 "Updates from the records of the appropriate database tables
763 the join slots specified by SLOTS in the supplied list of View
764 Class instances OBJECTS. SLOTS is t by default which means that
765 all join slots with :retrieval :immediate are updated. CLASS-NAME
766 is used to specify the View Class of all instance in OBJECTS and
767 default to nil which means that the class of the first instance
768 in OBJECTS is used. FORCE-P is t by default which means that all
769 join slots are updated whereas a value of nil means that only
770 unbound join slots are updated. MAX-LEN defaults to
771 *DEFAULT-UPDATE-OBJECTS-MAX-LEN* and when non-nil specifies that
772 UPDATE-OBJECT-JOINS may issue multiple database queries with a
773 maximum of MAX-LEN instances updated in each query."
774 (assert (or (null max-len) (plusp max-len)))
777 (setq class-name (class-name (class-of (first objects)))))
778 (let* ((class (find-class class-name))
779 (class-slots (ordered-class-slots class))
782 (generate-retrieval-joins-list class :deferred)
784 (mapcar #'(lambda (name)
785 (let ((slotdef (find name class-slots :key #'slot-definition-name)))
787 (warn "Unable to find slot named ~S in class ~S." name class))
790 (dolist (slotdef slotdefs)
791 (let* ((dbi (view-class-slot-db-info slotdef))
792 (slotdef-name (slot-definition-name slotdef))
793 (foreign-key (gethash :foreign-key dbi))
794 (home-key (gethash :home-key dbi))
798 (mapcar #'(lambda (o) (slot-value o home-key)) objects)
801 #'(lambda (o) (if (slot-boundp o slotdef-name)
803 (slot-value o home-key)))
805 (n-object-keys (length object-keys))
806 (query-len (or max-len n-object-keys)))
808 (do ((i 0 (+ i query-len)))
809 ((>= i n-object-keys))
810 (let* ((keys (if max-len
811 (subseq object-keys i (min (+ i query-len) n-object-keys))
813 (results (unless (gethash :target-slot dbi)
814 (find-all (list (gethash :join-class dbi))
815 :where (make-instance 'sql-relational-exp
817 :sub-expressions (list (sql-expression :attribute foreign-key)
822 (dolist (object objects)
823 (when (or force-p (not (slot-boundp object slotdef-name)))
824 (let ((res (if results
825 (remove-if-not #'(lambda (obj)
826 (equal obj (slot-value
835 (when (gethash :target-slot dbi)
836 (fault-join-target-slot class object slotdef))))))
838 (setf (slot-value object slotdef-name)
839 (if (gethash :set dbi) res (car res)))))))))))))
842 (defun fault-join-slot-raw (class object slot-def)
843 (let* ((dbi (view-class-slot-db-info slot-def))
844 (jc (gethash :join-class dbi)))
845 (let ((jq (join-qualifier class object slot-def)))
847 (select jc :where jq :flatp t :result-types nil
848 :database (view-database object))))))
850 (defun fault-join-slot (class object slot-def)
851 (let* ((dbi (view-class-slot-db-info slot-def))
852 (ts (gethash :target-slot dbi)))
853 (if (and ts (gethash :set dbi))
854 (fault-join-target-slot class object slot-def)
855 (let ((res (fault-join-slot-raw class object slot-def)))
858 ((and ts (not (gethash :set dbi)))
859 (mapcar (lambda (obj) (slot-value obj ts)) res))
860 ((and (not ts) (not (gethash :set dbi)))
862 ((and (not ts) (gethash :set dbi))
865 ;;;; Should we not return the whole result, instead of only
866 ;;;; the one slot-value? We get all the values from the db
868 (defun fault-join-normalized-slot (class object slot-def)
869 (labels ((getsc (this-class)
870 (let ((sc (car (class-direct-superclasses this-class))))
874 (let* ((sc (getsc class))
875 (hk (slot-definition-name (car (key-slots class))))
876 (fk (slot-definition-name (car (key-slots sc)))))
877 (let ((jq (sql-operation '==
882 (view-class-slot-column
883 (slotdef-for-slot-with-class fk sc))
884 :table (view-table sc)))
888 (slot-value object hk))
891 ;; Caching nil in next select, because in normalized mode
892 ;; records can be changed through other instances (children,
893 ;; parents) so changes possibly won't be noticed
894 (let ((res (car (select (class-name sc) :where jq
895 :flatp t :result-types nil
897 :database (view-database object))))
898 (slot-name (slot-definition-name slot-def)))
900 ;; If current class is normalized and wanted slot is not
901 ;; a direct member, recurse up
902 (if (and (normalizedp class)
903 (not (member slot-name
904 (mapcar #'(lambda (esd) (slot-definition-name esd))
905 (ordered-class-direct-slots class))))
906 (not (slot-boundp res slot-name)))
907 (fault-join-normalized-slot sc res slot-def)
908 (slot-value res slot-name)))))) )
910 (defun join-qualifier (class object slot-def)
911 (declare (ignore class))
912 (let* ((dbi (view-class-slot-db-info slot-def))
913 (jc (find-class (gethash :join-class dbi)))
914 ;;(ts (gethash :target-slot dbi))
915 ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
916 (foreign-keys (gethash :foreign-key dbi))
917 (home-keys (gethash :home-key dbi)))
918 (when (every #'(lambda (slt)
919 (and (slot-boundp object slt)
920 (not (null (slot-value object slt)))))
921 (if (listp home-keys) home-keys (list home-keys)))
923 (mapcar #'(lambda (hk fk)
924 (let ((fksd (slotdef-for-slot-with-class fk jc)))
930 (view-class-slot-column fksd)
931 :table (view-table jc)))
935 (slot-value object hk))
938 (if (listp home-keys)
941 (if (listp foreign-keys)
943 (list foreign-keys)))))
945 (if (> (length jc) 1)
949 ;; FIXME: add retrieval immediate for efficiency
950 ;; For example, for (select 'employee-address) in test suite =>
951 ;; select addr.*,ea_join.* FROM addr,ea_join WHERE ea_join.aaddressid=addr.addressid\g
953 (defun build-objects (vals sclasses immediate-join-classes sels immediate-joins database refresh flatp instances)
954 "Used by find-all to build objects."
955 (labels ((build-object (vals vclass jclasses selects immediate-selects instance)
956 (let* ((db-vals (butlast vals (- (list-length vals)
957 (list-length selects))))
958 (obj (if instance instance (make-instance (class-name vclass) :view-database database)))
959 (join-vals (subseq vals (list-length selects)))
960 (joins (mapcar #'(lambda (c) (when c (make-instance c :view-database database)))
963 ;;(format t "joins: ~S~%db-vals: ~S~%join-values: ~S~%selects: ~S~%immediate-selects: ~S~%"
964 ;;joins db-vals join-vals selects immediate-selects)
966 ;; use refresh keyword here
967 (setf obj (get-slot-values-from-view obj (mapcar #'car selects) db-vals))
969 ;; find all immediate-select slots and join-vals for this object
970 (let* ((jo-class (class-of jo))
972 (if (normalizedp jo-class)
973 (class-direct-slots jo-class)
974 (class-slots jo-class)))
975 (pos-list (remove-if #'null
978 (position s immediate-selects
982 (get-slot-values-from-view jo
984 (mapcar #'(lambda (pos)
985 (nth pos immediate-selects))
987 (mapcar #'(lambda (pos) (nth pos join-vals))
993 (class-slots vclass))
994 (slot (find (class-name (class-of jc)) vslots
995 :key #'(lambda (slot)
996 (when (and (eq :join (view-class-slot-db-kind slot))
997 (eq (slot-definition-name slot)
998 (gethash :join-class (view-class-slot-db-info slot))))
999 (slot-definition-name slot))))))
1001 (setf (slot-value obj (slot-definition-name slot)) jc))))
1003 (when refresh (instance-refreshed obj))
1006 (mapcar #'(lambda (sclass jclass sel immediate-join instance)
1008 (build-object vals sclass jclass sel immediate-join instance)
1009 (setf vals (nthcdr (+ (list-length sel) (list-length immediate-join))
1011 sclasses immediate-join-classes sels immediate-joins instances)))
1012 (if (and flatp (= (length sclasses) 1))
1016 (defun find-all (view-classes
1018 &key all set-operation distinct from where group-by having
1019 order-by offset limit refresh flatp result-types
1021 (database *default-database*)
1023 "Called by SELECT to generate object query results when the
1024 View Classes VIEW-CLASSES are passed as arguments to SELECT."
1025 (declare (ignore all set-operation group-by having offset limit inner-join on))
1026 (flet ((ref-equal (ref1 ref2)
1027 (string= (sql-output ref1 database)
1028 (sql-output ref2 database)))
1029 (table-sql-expr (table)
1030 (sql-expression :table (view-table table)))
1031 (tables-equal (table-a table-b)
1032 (when (and table-a table-b)
1033 (string= (string (slot-value table-a 'name))
1034 (string (slot-value table-b 'name))))))
1038 (remf args :additional-fields)
1039 (remf args :result-types)
1040 (remf args :instances)
1041 (let* ((*db-deserializing* t)
1042 (sclasses (mapcar #'find-class view-classes))
1043 (immediate-join-slots
1044 (mapcar #'(lambda (c) (generate-retrieval-joins-list c :immediate)) sclasses))
1045 (immediate-join-classes
1046 (mapcar #'(lambda (jcs)
1047 (mapcar #'(lambda (slotdef)
1048 (find-class (gethash :join-class (view-class-slot-db-info slotdef))))
1050 immediate-join-slots))
1051 (immediate-join-sels (mapcar #'generate-immediate-joins-selection-list sclasses))
1052 (sels (mapcar #'generate-selection-list sclasses))
1053 (fullsels (apply #'append (mapcar #'append sels immediate-join-sels)))
1054 (sel-tables (collect-table-refs where))
1055 (tables (remove-if #'null
1057 (append (mapcar #'table-sql-expr sclasses)
1058 (mapcan #'(lambda (jc-list)
1060 #'(lambda (jc) (when jc (table-sql-expr jc)))
1062 immediate-join-classes)
1064 :test #'tables-equal)))
1065 (order-by-slots (mapcar #'(lambda (ob) (if (atom ob) ob (car ob)))
1066 (listify order-by)))
1069 ;;(format t "sclasses: ~W~%ijc: ~W~%tables: ~W~%" sclasses immediate-join-classes tables)
1071 (dolist (ob order-by-slots)
1072 (when (and ob (not (member ob (mapcar #'cdr fullsels)
1073 :test #'ref-equal)))
1075 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1077 (dolist (ob (listify distinct))
1078 (when (and (typep ob 'sql-ident)
1079 (not (member ob (mapcar #'cdr fullsels)
1080 :test #'ref-equal)))
1082 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1084 (mapcar #'(lambda (vclass jclasses jslots)
1087 #'(lambda (jclass jslot)
1088 (let ((dbi (view-class-slot-db-info jslot)))
1091 (list (sql-operation '==
1093 :attribute (gethash :foreign-key dbi)
1094 :table (view-table jclass))
1096 :attribute (gethash :home-key dbi)
1097 :table (view-table vclass))))
1098 (when join-where (listify join-where))))))
1100 sclasses immediate-join-classes immediate-join-slots)
1101 ;; Reported buggy on clsql-devel
1102 ;; (when where (setq where (listify where)))
1104 ((and where join-where)
1105 (setq where (list (apply #'sql-and where join-where))))
1106 ((and (null where) (> (length join-where) 1))
1107 (setq where (list (apply #'sql-and join-where)))))
1109 (let* ((rows (apply #'select
1110 (append (mapcar #'cdr fullsels)
1112 (list (append (when from (listify from))
1114 (list :result-types result-types)
1116 (list :where where))
1118 (instances-to-add (- (length rows) (length instances)))
1119 (perhaps-extended-instances
1120 (if (plusp instances-to-add)
1121 (append instances (do ((i 0 (1+ i))
1123 ((= i instances-to-add) res)
1124 (push (make-list (length sclasses) :initial-element nil) res)))
1127 #'(lambda (row instance)
1128 (build-objects row sclasses immediate-join-classes sels
1129 immediate-join-sels database refresh flatp
1130 (if (and flatp (atom instance))
1133 rows perhaps-extended-instances)))
1136 (defmethod instance-refreshed ((instance standard-db-object)))
1138 (defvar *default-caching* t
1139 "Controls whether SELECT caches objects by default. The CommonSQL
1140 specification states caching is on by default.")
1142 (defun select (&rest select-all-args)
1143 "Executes a query on DATABASE, which has a default value of
1144 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
1145 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
1146 argument can be used to generate queries in both functional and
1147 object oriented contexts.
1149 In the functional case, the required arguments specify the
1150 columns selected by the query and may be symbolic SQL expressions
1151 or strings representing attribute identifiers. Type modified
1152 identifiers indicate that the values selected from the specified
1153 column are converted to the specified lisp type. The keyword
1154 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
1155 SET-OPERATION and WHERE are used to specify, using the symbolic
1156 SQL syntax, the corresponding components of the SQL query
1157 generated by the call to SELECT. RESULT-TYPES is a list of
1158 symbols which specifies the lisp type for each field returned by
1159 the query. If RESULT-TYPES is nil all results are returned as
1160 strings whereas the default value of :auto means that the lisp
1161 types are automatically computed for each field. FIELD-NAMES is t
1162 by default which means that the second value returned is a list
1163 of strings representing the columns selected by the query. If
1164 FIELD-NAMES is nil, the list of column names is not returned as a
1167 In the object oriented case, the required arguments to SELECT are
1168 symbols denoting View Classes which specify the database tables
1169 to query. In this case, SELECT returns a list of View Class
1170 instances whose slots are set from the attribute values of the
1171 records in the specified table. Slot-value is a legal operator
1172 which can be employed as part of the symbolic SQL syntax used in
1173 the WHERE keyword argument to SELECT. REFRESH is nil by default
1174 which means that the View Class instances returned are retrieved
1175 from a cache if an equivalent call to SELECT has previously been
1176 issued. If REFRESH is true, the View Class instances returned are
1177 updated as necessary from the database and the generic function
1178 INSTANCE-REFRESHED is called to perform any necessary operations
1179 on the updated instances.
1181 In both object oriented and functional contexts, FLATP has a
1182 default value of nil which means that the results are returned as
1183 a list of lists. If FLATP is t and only one result is returned
1184 for each record selected in the query, the results are returned
1185 as elements of a list."
1187 (flet ((select-objects (target-args)
1189 (every #'(lambda (arg)
1191 (find-class arg nil)))
1193 (multiple-value-bind (target-args qualifier-args)
1194 (query-get-selections select-all-args)
1195 (unless (or *default-database* (getf qualifier-args :database))
1196 (signal-no-database-error nil))
1199 ((select-objects target-args)
1200 (let ((caching (getf qualifier-args :caching *default-caching*))
1201 (result-types (getf qualifier-args :result-types :auto))
1202 (refresh (getf qualifier-args :refresh nil))
1203 (database (or (getf qualifier-args :database) *default-database*))
1204 (order-by (getf qualifier-args :order-by)))
1205 (remf qualifier-args :caching)
1206 (remf qualifier-args :refresh)
1207 (remf qualifier-args :result-types)
1209 ;; Add explicity table name to order-by if not specified and only
1210 ;; one selected table. This is required so FIND-ALL won't duplicate
1212 (when (and order-by (= 1 (length target-args)))
1213 (let ((table-name (view-table (find-class (car target-args))))
1214 (order-by-list (copy-seq (listify order-by))))
1216 (loop for i from 0 below (length order-by-list)
1217 do (etypecase (nth i order-by-list)
1218 (sql-ident-attribute
1219 (unless (slot-value (nth i order-by-list) 'qualifier)
1220 (setf (slot-value (nth i order-by-list) 'qualifier) table-name)))
1222 (unless (slot-value (car (nth i order-by-list)) 'qualifier)
1223 (setf (slot-value (car (nth i order-by-list)) 'qualifier) table-name)))))
1224 (setf (getf qualifier-args :order-by) order-by-list)))
1228 (apply #'find-all target-args
1229 (append qualifier-args
1230 (list :result-types result-types :refresh refresh))))
1232 (let ((cached (records-cache-results target-args qualifier-args database)))
1234 ((and cached (not refresh))
1236 ((and cached refresh)
1237 (let ((results (apply #'find-all (append (list target-args) qualifier-args `(:instances ,cached :result-types :auto :refresh ,refresh)))))
1238 (setf (records-cache-results target-args qualifier-args database) results)
1241 (let ((results (apply #'find-all target-args (append qualifier-args
1242 `(:result-types :auto :refresh ,refresh)))))
1243 (setf (records-cache-results target-args qualifier-args database) results)
1246 (let* ((expr (apply #'make-query select-all-args))
1248 (mapcar #'(lambda (attrib)
1249 (if (typep attrib 'sql-ident-attribute)
1250 (let ((type (slot-value attrib 'type)))
1255 (slot-value expr 'selections))))
1256 (destructuring-bind (&key (flatp nil)
1257 (result-types :auto)
1259 (database *default-database*)
1262 (query expr :flatp flatp
1264 ;; specifying a type for an attribute overrides result-types
1265 (if (some #'(lambda (x) (not (eq t x))) specified-types)
1268 :field-names field-names
1269 :database database))))))))
1271 (defun compute-records-cache-key (targets qualifiers)
1273 (do ((args *select-arguments* (cdr args))
1275 ((null args) results)
1276 (let* ((arg (car args))
1277 (value (getf qualifiers arg)))
1281 (cons (cons (sql (car value)) (cdr value)))
1282 (%sql-expression (sql value))
1286 (defun records-cache-results (targets qualifiers database)
1287 (when (record-caches database)
1288 (gethash (compute-records-cache-key targets qualifiers) (record-caches database))))
1290 (defun (setf records-cache-results) (results targets qualifiers database)
1291 (unless (record-caches database)
1292 (setf (record-caches database)
1293 (make-hash-table :test 'equal
1294 #+allegro :values #+allegro :weak
1295 #+clisp :weak #+clisp :value
1296 #+lispworks :weak-kind #+lispworks :value)))
1297 (setf (gethash (compute-records-cache-key targets qualifiers)
1298 (record-caches database)) results)
1303 ;;; Serialization functions
1305 (defun write-instance-to-stream (obj stream)
1306 "Writes an instance to a stream where it can be later be read.
1307 NOTE: an error will occur if a slot holds a value which can not be written readably."
1308 (let* ((class (class-of obj))
1310 (dolist (slot (ordered-class-slots (class-of obj)))
1311 (let ((name (slot-definition-name slot)))
1312 (when (and (not (eq 'view-database name))
1313 (slot-boundp obj name))
1314 (push (cons name (slot-value obj name)) alist))))
1315 (setq alist (reverse alist))
1316 (write (cons (class-name class) alist) :stream stream :readably t))
1319 (defun read-instance-from-stream (stream)
1320 (let ((raw (read stream nil nil)))
1322 (let ((obj (make-instance (car raw))))
1323 (dolist (pair (cdr raw))
1324 (setf (slot-value obj (car pair)) (cdr pair)))