1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
6 ;;;; The CLSQL Object Oriented Data Manipulation Language (OODML).
8 ;;;; This file is part of CLSQL.
10 ;;;; CLSQL users are granted the rights to distribute and use this software
11 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
12 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
13 ;;;; *************************************************************************
15 (in-package #:clsql-sys)
18 (defun key-qualifier-for-instance (obj &key (database *default-database*))
19 (let ((tb (view-table (class-of obj))))
22 (sql-expression :attribute
23 (view-class-slot-column k)
27 (slot-value obj (slot-definition-name k))
29 (let* ((keys (keyslots-for-class (class-of obj)))
30 (keyxprs (mapcar #'qfk (reverse keys))))
32 ((= (length keyxprs) 0) nil)
33 ((= (length keyxprs) 1) (car keyxprs))
34 ((> (length keyxprs) 1) (apply #'sql-operation 'and keyxprs)))))))
37 ;; Function used by 'generate-selection-list'
40 (defun generate-attribute-reference (vclass slotdef)
42 ((eq (view-class-slot-db-kind slotdef) :base)
43 (sql-expression :attribute (view-class-slot-column slotdef)
44 :table (view-table vclass)))
45 ((eq (view-class-slot-db-kind slotdef) :key)
46 (sql-expression :attribute (view-class-slot-column slotdef)
47 :table (view-table vclass)))
51 ;; Function used by 'find-all'
54 (defun generate-selection-list (vclass)
56 (dolist (slotdef (ordered-class-slots vclass))
57 (let ((res (generate-attribute-reference vclass slotdef)))
59 (push (cons slotdef res) sels))))
62 (error "No slots of type :base in view-class ~A" (class-name vclass)))))
66 (defun generate-retrieval-joins-list (vclass retrieval-method)
67 "Returns list of immediate join slots for a class."
68 (let ((join-slotdefs nil))
69 (dolist (slotdef (ordered-class-slots vclass) join-slotdefs)
70 (when (and (eq :join (view-class-slot-db-kind slotdef))
71 (eq retrieval-method (gethash :retrieval (view-class-slot-db-info slotdef))))
72 (push slotdef join-slotdefs)))))
74 (defun generate-immediate-joins-selection-list (vclass)
75 "Returns list of immediate join slots for a class."
77 (dolist (joined-slot (generate-retrieval-joins-list vclass :immediate) sels)
78 (let* ((join-class-name (gethash :join-class (view-class-slot-db-info joined-slot)))
79 (join-class (when join-class-name (find-class join-class-name))))
80 (dolist (slotdef (ordered-class-slots join-class))
81 (let ((res (generate-attribute-reference join-class slotdef)))
83 (push (cons slotdef res) sels))))))
87 ;; Called by 'get-slot-values-from-view'
90 (defmethod update-slot-from-db ((instance standard-db-object) slotdef value)
91 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
92 (let* ((slot-reader (view-class-slot-db-reader slotdef))
93 (slot-name (slot-definition-name slotdef))
94 (slot-type (specified-type slotdef)))
95 (cond ((and value (null slot-reader))
96 (setf (slot-value instance slot-name)
97 (read-sql-value value (delistify slot-type)
98 (view-database instance)
99 (database-underlying-type
100 (view-database instance)))))
102 (update-slot-with-null instance slot-name slotdef))
103 ((typep slot-reader 'string)
104 (setf (slot-value instance slot-name)
105 (format nil slot-reader value)))
106 ((typep slot-reader 'function)
107 (setf (slot-value instance slot-name)
108 (apply slot-reader (list value))))
110 (error "Slot reader is of an unusual type.")))))
112 (defmethod key-value-from-db (slotdef value database)
113 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
114 (let ((slot-reader (view-class-slot-db-reader slotdef))
115 (slot-type (specified-type slotdef)))
116 (cond ((and value (null slot-reader))
117 (read-sql-value value (delistify slot-type) database
118 (database-underlying-type database)))
121 ((typep slot-reader 'string)
122 (format nil slot-reader value))
123 ((typep slot-reader 'function)
124 (apply slot-reader (list value)))
126 (error "Slot reader is of an unusual type.")))))
128 (defun db-value-from-slot (slotdef val database)
129 (let ((dbwriter (view-class-slot-db-writer slotdef))
130 (dbtype (specified-type slotdef)))
132 (string (format nil dbwriter val))
133 (function (apply dbwriter (list val)))
135 (database-output-sql-as-type
139 val database (database-underlying-type database))))))
141 (defun check-slot-type (slotdef val)
142 (let* ((slot-type (specified-type slotdef))
143 (basetype (if (listp slot-type) (car slot-type) slot-type)))
144 (when (and slot-type val)
145 (unless (typep val basetype)
146 (error 'sql-user-error
148 (format nil "Invalid value ~A in slot ~A, not of type ~A."
149 val (slot-definition-name slotdef) slot-type))))))
152 ;; Called by find-all
155 (defmethod get-slot-values-from-view (obj slotdeflist values)
156 (flet ((update-slot (slot-def values)
157 (update-slot-from-db obj slot-def values)))
158 (mapc #'update-slot slotdeflist values)
161 (defmethod update-record-from-slot ((obj standard-db-object) slot &key
162 (database *default-database*))
163 (let* ((database (or (view-database obj) database))
164 (vct (view-table (class-of obj)))
165 (sd (slotdef-for-slot-with-class slot (class-of obj))))
166 (check-slot-type sd (slot-value obj slot))
167 (let* ((att (view-class-slot-column sd))
168 (val (db-value-from-slot sd (slot-value obj slot) database)))
169 (cond ((and vct sd (view-database obj))
170 (update-records (sql-expression :table vct)
171 :attributes (list (sql-expression :attribute att))
173 :where (key-qualifier-for-instance
174 obj :database database)
176 ((and vct sd (not (view-database obj)))
177 (insert-records :into (sql-expression :table vct)
178 :attributes (list (sql-expression :attribute att))
181 (setf (slot-value obj 'view-database) database))
183 (error "Unable to update record.")))))
186 (defmethod update-record-from-slots ((obj standard-db-object) slots &key
187 (database *default-database*))
188 (let* ((database (or (view-database obj) database))
189 (vct (view-table (class-of obj)))
190 (sds (slotdefs-for-slots-with-class slots (class-of obj)))
191 (avps (mapcar #'(lambda (s)
192 (let ((val (slot-value
193 obj (slot-definition-name s))))
194 (check-slot-type s val)
195 (list (sql-expression
196 :attribute (view-class-slot-column s))
197 (db-value-from-slot s val database))))
199 (cond ((and avps (view-database obj))
200 (update-records (sql-expression :table vct)
202 :where (key-qualifier-for-instance
203 obj :database database)
205 ((and avps (not (view-database obj)))
206 (insert-records :into (sql-expression :table vct)
209 (setf (slot-value obj 'view-database) database))
211 (error "Unable to update records"))))
214 (defmethod update-records-from-instance ((obj standard-db-object)
215 &key (database *default-database*))
216 (let ((database (or (view-database obj) database)))
217 (labels ((slot-storedp (slot)
218 (and (member (view-class-slot-db-kind slot) '(:base :key))
219 (slot-boundp obj (slot-definition-name slot))))
220 (slot-value-list (slot)
221 (let ((value (slot-value obj (slot-definition-name slot))))
222 (check-slot-type slot value)
223 (list (sql-expression :attribute (view-class-slot-column slot))
224 (db-value-from-slot slot value database)))))
225 (let* ((view-class (class-of obj))
226 (view-class-table (view-table view-class))
227 (slots (remove-if-not #'slot-storedp
228 (ordered-class-slots view-class)))
229 (record-values (mapcar #'slot-value-list slots)))
230 (unless record-values
231 (error "No settable slots."))
232 (if (view-database obj)
233 (update-records (sql-expression :table view-class-table)
234 :av-pairs record-values
235 :where (key-qualifier-for-instance
236 obj :database database)
239 (insert-records :into (sql-expression :table view-class-table)
240 :av-pairs record-values
242 (setf (slot-value obj 'view-database) database))))))
245 (defmethod delete-instance-records ((instance standard-db-object))
246 (let ((vt (sql-expression :table (view-table (class-of instance))))
247 (vd (view-database instance)))
249 (let ((qualifier (key-qualifier-for-instance instance :database vd)))
250 (delete-records :from vt :where qualifier :database vd)
251 (setf (slot-value instance 'view-database) nil)
253 (signal-no-database-error vd))))
255 (defmethod update-instance-from-records ((instance standard-db-object)
256 &key (database *default-database*))
257 (let* ((view-class (find-class (class-name (class-of instance))))
258 (view-table (sql-expression :table (view-table view-class)))
259 (vd (or (view-database instance) database))
260 (view-qual (key-qualifier-for-instance instance :database vd))
261 (sels (generate-selection-list view-class))
262 (res (apply #'select (append (mapcar #'cdr sels)
263 (list :from view-table
265 (list :result-types nil)))))
267 (get-slot-values-from-view instance (mapcar #'car sels) (car res)))))
269 (defmethod update-slot-from-record ((instance standard-db-object)
270 slot &key (database *default-database*))
271 (let* ((view-class (find-class (class-name (class-of instance))))
272 (view-table (sql-expression :table (view-table view-class)))
273 (vd (or (view-database instance) database))
274 (view-qual (key-qualifier-for-instance instance :database vd))
275 (slot-def (slotdef-for-slot-with-class slot view-class))
276 (att-ref (generate-attribute-reference view-class slot-def))
277 (res (select att-ref :from view-table :where view-qual
280 (get-slot-values-from-view instance (list slot-def) (car res)))))
283 (defmethod update-slot-with-null ((object standard-db-object)
286 (setf (slot-value object slotname) (slot-value slotdef 'void-value)))
288 (defvar +no-slot-value+ '+no-slot-value+)
290 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
291 (let* ((class (find-class classname))
292 (sld (slotdef-for-slot-with-class slot class)))
294 (if (eq value +no-slot-value+)
295 (sql-expression :attribute (view-class-slot-column sld)
296 :table (view-table class))
301 (error "Unknown slot ~A for class ~A" slot classname))))
303 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
304 (declare (ignore database))
305 (let* ((class (find-class classname)))
306 (unless (view-table class)
307 (error "No view-table for class ~A" classname))
308 (sql-expression :table (view-table class))))
311 (defmethod database-get-type-specifier (type args database db-type)
312 (declare (ignore type args database db-type))
313 (format nil "VARCHAR(~D)" *default-string-length*))
315 (defmethod database-get-type-specifier ((type (eql 'integer)) args database db-type)
316 (declare (ignore database db-type))
318 (format nil "INT(~A)" (car args))
322 "An 8-bit integer, this width may vary by SQL implementation."
325 (defmethod database-get-type-specifier ((type (eql 'tinyint)) args database db-type)
326 (declare (ignore args database db-type))
330 "An integer smaller than a 32-bit integer, this width may vary by SQL implementation."
333 (defmethod database-get-type-specifier ((type (eql 'smallint)) args database db-type)
334 (declare (ignore args database db-type))
338 "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
341 (defmethod database-get-type-specifier ((type (eql 'bigint)) args database db-type)
342 (declare (ignore args database db-type))
346 "A variable length string for the SQL varchar type."
349 (defmethod database-get-type-specifier ((type (eql 'varchar)) args
351 (declare (ignore database db-type))
353 (format nil "VARCHAR(~A)" (car args))
354 (format nil "VARCHAR(~D)" *default-string-length*)))
356 (defmethod database-get-type-specifier ((type (eql 'string)) args database db-type)
357 (declare (ignore database db-type))
359 (format nil "CHAR(~A)" (car args))
360 (format nil "VARCHAR(~D)" *default-string-length*)))
362 (deftype universal-time ()
363 "A positive integer as returned by GET-UNIVERSAL-TIME."
366 (defmethod database-get-type-specifier ((type (eql 'universal-time)) args database db-type)
367 (declare (ignore args database db-type))
370 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database db-type)
371 (declare (ignore args database db-type))
374 (defmethod database-get-type-specifier ((type (eql 'duration)) args database db-type)
375 (declare (ignore database args db-type))
378 (defmethod database-get-type-specifier ((type (eql 'money)) args database db-type)
379 (declare (ignore database args db-type))
383 (deftype char (&optional len)
384 "A lisp type for the SQL CHAR type."
387 (defmethod database-get-type-specifier ((type (eql 'float)) args database db-type)
388 (declare (ignore database db-type))
390 (format nil "FLOAT(~A)" (car args))
393 (defmethod database-get-type-specifier ((type (eql 'long-float)) args database db-type)
394 (declare (ignore database db-type))
396 (format nil "FLOAT(~A)" (car args))
399 (deftype generalized-boolean ()
400 "A type which outputs a SQL boolean value, though any lisp type can be stored in the slot."
403 (defmethod database-get-type-specifier ((type (eql 'boolean)) args database db-type)
404 (declare (ignore args database db-type))
407 (defmethod database-get-type-specifier ((type (eql 'generalized-boolean)) args database db-type)
408 (declare (ignore args database db-type))
411 (defmethod database-get-type-specifier ((type (eql 'number)) args database db-type)
412 (declare (ignore database db-type))
414 ((and (consp args) (= (length args) 2))
415 (format nil "NUMBER(~D,~D)" (first args) (second args)))
416 ((and (consp args) (= (length args) 1))
417 (format nil "NUMBER(~D)" (first args)))
421 (defmethod database-get-type-specifier ((type (eql 'char)) args database db-type)
422 (declare (ignore database db-type))
424 (format nil "CHAR(~D)" (first args))
428 (defmethod database-output-sql-as-type (type val database db-type)
429 (declare (ignore type database db-type))
432 (defmethod database-output-sql-as-type ((type (eql 'list)) val database db-type)
433 (declare (ignore database db-type))
434 (progv '(*print-circle* *print-array*) '(t t)
435 (let ((escaped (prin1-to-string val)))
436 (substitute-char-string
437 escaped #\Null " "))))
439 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database db-type)
440 (declare (ignore database db-type))
443 (package-name (symbol-package val))
448 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database db-type)
449 (declare (ignore database db-type))
454 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database db-type)
455 (declare (ignore database db-type))
456 (progv '(*print-circle* *print-array*) '(t t)
457 (prin1-to-string val)))
459 (defmethod database-output-sql-as-type ((type (eql 'array)) val database db-type)
460 (declare (ignore database db-type))
461 (progv '(*print-circle* *print-array*) '(t t)
462 (prin1-to-string val)))
464 (defmethod database-output-sql-as-type ((type (eql 'boolean)) val database db-type)
465 (declare (ignore database db-type))
468 (defmethod database-output-sql-as-type ((type (eql 'generalized-boolean)) val database db-type)
469 (declare (ignore database db-type))
472 (defmethod database-output-sql-as-type ((type (eql 'string)) val database db-type)
473 (declare (ignore database db-type))
476 (defmethod database-output-sql-as-type ((type (eql 'char))
477 val database db-type)
478 (declare (ignore database db-type))
480 (character (write-to-string val))
483 (defmethod read-sql-value (val type database db-type)
484 (declare (ignore type database db-type))
485 (read-from-string val))
487 (defmethod read-sql-value (val (type (eql 'string)) database db-type)
488 (declare (ignore database db-type))
491 (defmethod read-sql-value (val (type (eql 'varchar)) database db-type)
492 (declare (ignore database db-type))
495 (defmethod read-sql-value (val (type (eql 'char)) database db-type)
496 (declare (ignore database db-type))
499 (defmethod read-sql-value (val (type (eql 'keyword)) database db-type)
500 (declare (ignore database db-type))
501 (when (< 0 (length val))
502 (intern (symbol-name-default-case val)
503 (find-package '#:keyword))))
505 (defmethod read-sql-value (val (type (eql 'symbol)) database db-type)
506 (declare (ignore database db-type))
507 (when (< 0 (length val))
508 (unless (string= val (symbol-name-default-case "NIL"))
509 (read-from-string val))))
511 (defmethod read-sql-value (val (type (eql 'integer)) database db-type)
512 (declare (ignore database db-type))
515 (unless (string-equal "NIL" val)
516 (parse-integer val)))
519 (defmethod read-sql-value (val (type (eql 'smallint)) database db-type)
520 (declare (ignore database db-type))
523 (unless (string-equal "NIL" val)
524 (parse-integer val)))
527 (defmethod read-sql-value (val (type (eql 'bigint)) database db-type)
528 (declare (ignore database db-type))
531 (unless (string-equal "NIL" val)
532 (parse-integer val)))
535 (defmethod read-sql-value (val (type (eql 'float)) database db-type)
536 (declare (ignore database db-type))
537 ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
540 (float (read-from-string val)))
544 (defmethod read-sql-value (val (type (eql 'boolean)) database db-type)
545 (declare (ignore database db-type))
548 (defmethod read-sql-value (val (type (eql 'generalized-boolean)) database db-type)
549 (declare (ignore database db-type))
552 (defmethod read-sql-value (val (type (eql 'number)) database db-type)
553 (declare (ignore database db-type))
556 (unless (string-equal "NIL" val)
557 (read-from-string val)))
560 (defmethod read-sql-value (val (type (eql 'universal-time)) database db-type)
561 (declare (ignore database db-type))
562 (unless (eq 'NULL val)
568 (defmethod read-sql-value (val (type (eql 'wall-time)) database db-type)
569 (declare (ignore database db-type))
570 (unless (eq 'NULL val)
571 (parse-timestring val)))
573 (defmethod read-sql-value (val (type (eql 'duration)) database db-type)
574 (declare (ignore database db-type))
575 (unless (or (eq 'NULL val)
577 (parse-timestring val)))
579 ;; ------------------------------------------------------------
580 ;; Logic for 'faulting in' :join slots
582 ;; this works, but is inefficient requiring (+ 1 n-rows)
585 (defun fault-join-target-slot (class object slot-def)
586 (let* ((res (fault-join-slot-raw class object slot-def))
587 (dbi (view-class-slot-db-info slot-def))
588 (target-name (gethash :target-slot dbi))
589 (target-class (find-class target-name)))
591 (mapcar (lambda (obj)
597 (find target-name (class-slots (class-of obj))
598 :key #'slot-definition-name)))
601 #+ignore ;; this doesn't work when attempting to call slot-value
602 (mapcar (lambda (obj)
603 (cons obj (slot-value obj ts))) res))))
605 (defun fault-join-target-slot (class object slot-def)
606 (let* ((dbi (view-class-slot-db-info slot-def))
607 (ts (gethash :target-slot dbi))
608 (jc (gethash :join-class dbi))
609 (ts-view-table (view-table (find-class ts)))
610 (jc-view-table (view-table (find-class jc)))
611 (tdbi (view-class-slot-db-info
612 (find ts (class-slots (find-class jc))
613 :key #'slot-definition-name)))
614 (retrieval (gethash :retrieval tdbi))
615 (jq (join-qualifier class object slot-def))
616 (key (slot-value object (gethash :home-key dbi))))
622 :inner-join (sql-expression :table jc-view-table)
626 :attribute (gethash :foreign-key tdbi)
627 :table ts-view-table)
629 :attribute (gethash :home-key tdbi)
630 :table jc-view-table))
632 :result-types :auto)))
633 (mapcar #'(lambda (i)
634 (let* ((instance (car i))
635 (jcc (make-instance jc :view-database (view-database instance))))
636 (setf (slot-value jcc (gethash :foreign-key dbi))
638 (setf (slot-value jcc (gethash :home-key tdbi))
639 (slot-value instance (gethash :foreign-key tdbi)))
640 (list instance jcc)))
643 ;; just fill in minimal slots
646 (let ((instance (make-instance ts :view-database (view-database object)))
647 (jcc (make-instance jc :view-database (view-database object)))
649 (setf (slot-value instance (gethash :home-key tdbi)) fk)
650 (setf (slot-value jcc (gethash :foreign-key dbi))
652 (setf (slot-value jcc (gethash :home-key tdbi))
654 (list instance jcc)))
655 (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
656 :from (sql-expression :table jc-view-table)
662 (defvar *default-update-objects-max-len* nil
663 "The default value to use for the MAX-LEN keyword argument to
664 UPDATE-OBJECT-JOINS.")
666 (defun update-objects-joins (objects &key (slots t) (force-p t)
668 *default-update-objects-max-len*))
669 "Updates from the records of the appropriate database tables
670 the join slots specified by SLOTS in the supplied list of View
671 Class instances OBJECTS. SLOTS is t by default which means that
672 all join slots with :retrieval :immediate are updated. CLASS-NAME
673 is used to specify the View Class of all instance in OBJECTS and
674 default to nil which means that the class of the first instance
675 in OBJECTS is used. FORCE-P is t by default which means that all
676 join slots are updated whereas a value of nil means that only
677 unbound join slots are updated. MAX-LEN defaults to
678 *DEFAULT-UPDATE-OBJECTS-MAX-LEN* and when non-nil specifies that
679 UPDATE-OBJECT-JOINS may issue multiple database queries with a
680 maximum of MAX-LEN instances updated in each query."
681 (assert (or (null max-len) (plusp max-len)))
684 (setq class-name (class-name (class-of (first objects)))))
685 (let* ((class (find-class class-name))
686 (class-slots (ordered-class-slots class))
689 (generate-retrieval-joins-list class :deferred)
691 (mapcar #'(lambda (name)
692 (let ((slotdef (find name class-slots :key #'slot-definition-name)))
694 (warn "Unable to find slot named ~S in class ~S." name class))
697 (dolist (slotdef slotdefs)
698 (let* ((dbi (view-class-slot-db-info slotdef))
699 (slotdef-name (slot-definition-name slotdef))
700 (foreign-key (gethash :foreign-key dbi))
701 (home-key (gethash :home-key dbi))
705 (mapcar #'(lambda (o) (slot-value o home-key)) objects)
708 #'(lambda (o) (if (slot-boundp o slotdef-name)
710 (slot-value o home-key)))
712 (n-object-keys (length object-keys))
713 (query-len (or max-len n-object-keys)))
715 (do ((i 0 (+ i query-len)))
716 ((>= i n-object-keys))
717 (let* ((keys (if max-len
718 (subseq object-keys i (min (+ i query-len) n-object-keys))
720 (results (find-all (list (gethash :join-class dbi))
721 :where (make-instance 'sql-relational-exp
723 :sub-expressions (list (sql-expression :attribute foreign-key)
727 (dolist (object objects)
728 (when (or force-p (not (slot-boundp object slotdef-name)))
729 (let ((res (find (slot-value object home-key) results
730 :key #'(lambda (res) (slot-value res foreign-key))
733 (setf (slot-value object slotdef-name) res)))))))))))
736 (defun fault-join-slot-raw (class object slot-def)
737 (let* ((dbi (view-class-slot-db-info slot-def))
738 (jc (gethash :join-class dbi)))
739 (let ((jq (join-qualifier class object slot-def)))
741 (select jc :where jq :flatp t :result-types nil)))))
743 (defun fault-join-slot (class object slot-def)
744 (let* ((dbi (view-class-slot-db-info slot-def))
745 (ts (gethash :target-slot dbi)))
746 (if (and ts (gethash :set dbi))
747 (fault-join-target-slot class object slot-def)
748 (let ((res (fault-join-slot-raw class object slot-def)))
751 ((and ts (not (gethash :set dbi)))
752 (mapcar (lambda (obj) (slot-value obj ts)) res))
753 ((and (not ts) (not (gethash :set dbi)))
755 ((and (not ts) (gethash :set dbi))
758 (defun join-qualifier (class object slot-def)
759 (declare (ignore class))
760 (let* ((dbi (view-class-slot-db-info slot-def))
761 (jc (find-class (gethash :join-class dbi)))
762 ;;(ts (gethash :target-slot dbi))
763 ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
764 (foreign-keys (gethash :foreign-key dbi))
765 (home-keys (gethash :home-key dbi)))
766 (when (every #'(lambda (slt)
767 (and (slot-boundp object slt)
768 (not (null (slot-value object slt)))))
769 (if (listp home-keys) home-keys (list home-keys)))
771 (mapcar #'(lambda (hk fk)
772 (let ((fksd (slotdef-for-slot-with-class fk jc)))
778 (view-class-slot-column fksd)
779 :table (view-table jc)))
783 (slot-value object hk))
786 (if (listp home-keys)
789 (if (listp foreign-keys)
791 (list foreign-keys)))))
793 (if (> (length jc) 1)
797 ;; FIXME: add retrieval immediate for efficiency
798 ;; For example, for (select 'employee-address) in test suite =>
799 ;; select addr.*,ea_join.* FROM addr,ea_join WHERE ea_join.aaddressid=addr.addressid\g
801 (defun build-objects (vals sclasses immediate-join-classes sels immediate-joins database refresh flatp instances)
802 "Used by find-all to build objects."
803 (labels ((build-object (vals vclass jclasses selects immediate-selects instance)
804 (let* ((db-vals (butlast vals (- (list-length vals)
805 (list-length selects))))
806 (obj (if instance instance (make-instance (class-name vclass) :view-database database)))
807 (join-vals (subseq vals (list-length selects)))
808 (joins (mapcar #'(lambda (c) (when c (make-instance c :view-database database)))
810 ;;(format t "db-vals: ~S, join-values: ~S~%" db-vals join-vals)
811 ;; use refresh keyword here
812 (setf obj (get-slot-values-from-view obj (mapcar #'car selects) db-vals))
813 (mapc #'(lambda (jc) (get-slot-values-from-view jc (mapcar #'car immediate-selects) join-vals))
817 (let ((slot (find (class-name (class-of jc)) (class-slots vclass)
818 :key #'(lambda (slot)
819 (when (and (eq :join (view-class-slot-db-kind slot))
820 (eq (slot-definition-name slot)
821 (gethash :join-class (view-class-slot-db-info slot))))
822 (slot-definition-name slot))))))
824 (setf (slot-value obj (slot-definition-name slot)) jc))))
826 (when refresh (instance-refreshed obj))
829 (mapcar #'(lambda (sclass jclass sel immediate-join instance)
831 (build-object vals sclass jclass sel immediate-join instance)
832 (setf vals (nthcdr (+ (list-length sel) (list-length immediate-join))
834 sclasses immediate-join-classes sels immediate-joins instances)))
835 (if (and flatp (= (length sclasses) 1))
839 (defun find-all (view-classes
841 &key all set-operation distinct from where group-by having
842 order-by offset limit refresh flatp result-types
844 (database *default-database*)
846 "Called by SELECT to generate object query results when the
847 View Classes VIEW-CLASSES are passed as arguments to SELECT."
848 (declare (ignore all set-operation group-by having offset limit inner-join on)
849 (optimize (debug 3) (speed 1)))
850 (labels ((ref-equal (ref1 ref2)
853 (table-sql-expr (table)
854 (sql-expression :table (view-table table)))
855 (tables-equal (table-a table-b)
856 (when (and table-a table-b)
857 (string= (string (slot-value table-a 'name))
858 (string (slot-value table-b 'name))))))
862 (remf args :additional-fields)
863 (remf args :result-types)
864 (remf args :instances)
865 (let* ((*db-deserializing* t)
866 (sclasses (mapcar #'find-class view-classes))
867 (immediate-join-slots
868 (mapcar #'(lambda (c) (generate-retrieval-joins-list c :immediate)) sclasses))
869 (immediate-join-classes
870 (mapcar #'(lambda (jcs)
871 (mapcar #'(lambda (slotdef)
872 (find-class (gethash :join-class (view-class-slot-db-info slotdef))))
874 immediate-join-slots))
875 (immediate-join-sels (mapcar #'generate-immediate-joins-selection-list sclasses))
876 (sels (mapcar #'generate-selection-list sclasses))
877 (fullsels (apply #'append (mapcar #'append sels immediate-join-sels)))
878 (sel-tables (collect-table-refs where))
879 (tables (remove-if #'null
880 (remove-duplicates (append (mapcar #'table-sql-expr sclasses)
881 (mapcar #'(lambda (jcs)
882 (mapcan #'(lambda (jc)
883 (when jc (table-sql-expr jc)))
885 immediate-join-classes)
887 :test #'tables-equal)))
888 (order-by-slots (mapcar #'(lambda (ob) (if (atom ob) ob (car ob)))
889 (listify order-by))))
891 (dolist (ob order-by-slots)
892 (when (and ob (not (member ob (mapcar #'cdr fullsels)
895 (append fullsels (mapcar #'(lambda (att) (cons nil att))
897 (dolist (ob (listify distinct))
898 (when (and (typep ob 'sql-ident)
899 (not (member ob (mapcar #'cdr fullsels)
902 (append fullsels (mapcar #'(lambda (att) (cons nil att))
904 (mapcar #'(lambda (vclass jclasses jslots)
907 #'(lambda (jclass jslot)
908 (let ((dbi (view-class-slot-db-info jslot)))
911 (list (sql-operation '==
913 :attribute (gethash :foreign-key dbi)
914 :table (view-table jclass))
916 :attribute (gethash :home-key dbi)
917 :table (view-table vclass))))
918 (when where (listify where))))))
920 sclasses immediate-join-classes immediate-join-slots)
921 (let* ((rows (apply #'select
922 (append (mapcar #'cdr fullsels)
924 (list (append (when from (listify from))
926 (list :result-types result-types)
927 (when where (list :where where))
929 (instances-to-add (- (length rows) (length instances)))
930 (perhaps-extended-instances
931 (if (plusp instances-to-add)
932 (append instances (do ((i 0 (1+ i))
934 ((= i instances-to-add) res)
935 (push (make-list (length sclasses) :initial-element nil) res)))
938 #'(lambda (row instance)
939 (build-objects row sclasses immediate-join-classes sels
940 immediate-join-sels database refresh flatp
941 (if (and flatp (atom instance))
944 rows perhaps-extended-instances)))
947 (defmethod instance-refreshed ((instance standard-db-object)))
949 (defun select (&rest select-all-args)
950 "Executes a query on DATABASE, which has a default value of
951 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
952 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
953 argument can be used to generate queries in both functional and
954 object oriented contexts.
956 In the functional case, the required arguments specify the
957 columns selected by the query and may be symbolic SQL expressions
958 or strings representing attribute identifiers. Type modified
959 identifiers indicate that the values selected from the specified
960 column are converted to the specified lisp type. The keyword
961 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
962 SET-OPERATION and WHERE are used to specify, using the symbolic
963 SQL syntax, the corresponding components of the SQL query
964 generated by the call to SELECT. RESULT-TYPES is a list of
965 symbols which specifies the lisp type for each field returned by
966 the query. If RESULT-TYPES is nil all results are returned as
967 strings whereas the default value of :auto means that the lisp
968 types are automatically computed for each field. FIELD-NAMES is t
969 by default which means that the second value returned is a list
970 of strings representing the columns selected by the query. If
971 FIELD-NAMES is nil, the list of column names is not returned as a
974 In the object oriented case, the required arguments to SELECT are
975 symbols denoting View Classes which specify the database tables
976 to query. In this case, SELECT returns a list of View Class
977 instances whose slots are set from the attribute values of the
978 records in the specified table. Slot-value is a legal operator
979 which can be employed as part of the symbolic SQL syntax used in
980 the WHERE keyword argument to SELECT. REFRESH is nil by default
981 which means that the View Class instances returned are retrieved
982 from a cache if an equivalent call to SELECT has previously been
983 issued. If REFRESH is true, the View Class instances returned are
984 updated as necessary from the database and the generic function
985 INSTANCE-REFRESHED is called to perform any necessary operations
986 on the updated instances.
988 In both object oriented and functional contexts, FLATP has a
989 default value of nil which means that the results are returned as
990 a list of lists. If FLATP is t and only one result is returned
991 for each record selected in the query, the results are returned
992 as elements of a list."
994 (flet ((select-objects (target-args)
996 (every #'(lambda (arg)
998 (find-class arg nil)))
1000 (multiple-value-bind (target-args qualifier-args)
1001 (query-get-selections select-all-args)
1002 (unless (or *default-database* (getf qualifier-args :database))
1003 (signal-no-database-error nil))
1006 ((select-objects target-args)
1007 (let ((caching (getf qualifier-args :caching t))
1008 (result-types (getf qualifier-args :result-types :auto))
1009 (refresh (getf qualifier-args :refresh nil))
1010 (database (or (getf qualifier-args :database) *default-database*))
1011 (order-by (getf qualifier-args :order-by)))
1012 (remf qualifier-args :caching)
1013 (remf qualifier-args :refresh)
1014 (remf qualifier-args :result-types)
1016 ;; Add explicity table name to order-by if not specified and only
1017 ;; one selected table. This is required so FIND-ALL won't duplicate
1019 (when (and order-by (= 1 (length target-args)))
1020 (let ((table-name (view-table (find-class (car target-args))))
1021 (order-by-list (copy-seq (listify order-by))))
1023 (loop for i from 0 below (length order-by-list)
1024 do (etypecase (nth i order-by-list)
1025 (sql-ident-attribute
1026 (unless (slot-value (nth i order-by-list) 'qualifier)
1027 (setf (slot-value (nth i order-by-list) 'qualifier) table-name)))
1029 (unless (slot-value (car (nth i order-by-list)) 'qualifier)
1030 (setf (slot-value (car (nth i order-by-list)) 'qualifier) table-name)))))
1031 (setf (getf qualifier-args :order-by) order-by-list)))
1035 (apply #'find-all target-args
1036 (append qualifier-args
1037 (list :result-types result-types :refresh refresh))))
1039 (let ((cached (records-cache-results target-args qualifier-args database)))
1041 ((and cached (not refresh))
1043 ((and cached refresh)
1044 (let ((results (apply #'find-all (append (list target-args) qualifier-args `(:instances ,cached :result-types :auto :refresh ,refresh)))))
1045 (setf (records-cache-results target-args qualifier-args database) results)
1048 (let ((results (apply #'find-all target-args (append qualifier-args
1049 `(:result-types :auto :refresh ,refresh)))))
1050 (setf (records-cache-results target-args qualifier-args database) results)
1053 (let* ((expr (apply #'make-query select-all-args))
1055 (mapcar #'(lambda (attrib)
1056 (if (typep attrib 'sql-ident-attribute)
1057 (let ((type (slot-value attrib 'type)))
1062 (slot-value expr 'selections))))
1063 (destructuring-bind (&key (flatp nil)
1064 (result-types :auto)
1066 (database *default-database*)
1069 (query expr :flatp flatp
1071 ;; specifying a type for an attribute overrides result-types
1072 (if (some #'(lambda (x) (not (eq t x))) specified-types)
1075 :field-names field-names
1076 :database database))))))))
1078 (defun compute-records-cache-key (targets qualifiers)
1080 (do ((args *select-arguments* (cdr args))
1082 ((null args) results)
1083 (let* ((arg (car args))
1084 (value (getf qualifiers arg)))
1088 (cons (cons (sql (car value)) (cdr value)))
1089 (%sql-expression (sql value))
1093 (defun records-cache-results (targets qualifiers database)
1094 (when (record-caches database)
1095 (gethash (compute-records-cache-key targets qualifiers) (record-caches database))))
1097 (defun (setf records-cache-results) (results targets qualifiers database)
1098 (unless (record-caches database)
1099 (setf (record-caches database)
1100 (make-hash-table :test 'equal
1101 #+allegro :values #+allegro :weak
1102 #+lispworks :weak-kind #+lispworks :value)))
1103 (setf (gethash (compute-records-cache-key targets qualifiers)
1104 (record-caches database)) results)
1109 ;;; Serialization functions
1111 (defun write-instance-to-stream (obj stream)
1112 "Writes an instance to a stream where it can be later be read.
1113 NOTE: an error will occur if a slot holds a value which can not be written readably."
1114 (let* ((class (class-of obj))
1116 (dolist (slot (ordered-class-slots (class-of obj)))
1117 (let ((name (slot-definition-name slot)))
1118 (when (and (not (eq 'view-database name))
1119 (slot-boundp obj name))
1120 (push (cons name (slot-value obj name)) alist))))
1121 (setq alist (reverse alist))
1122 (write (cons (class-name class) alist) :stream stream :readably t))
1125 (defun read-instance-from-stream (stream)
1126 (let ((raw (read stream nil nil)))
1128 (let ((obj (make-instance (car raw))))
1129 (dolist (pair (cdr raw))
1130 (setf (slot-value obj (car pair)) (cdr pair)))