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 (defvar *update-context* nil)
92 (defmethod update-slot-from-db ((instance standard-db-object) slotdef value)
93 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
94 (let* ((slot-reader (view-class-slot-db-reader slotdef))
95 (slot-name (slot-definition-name slotdef))
96 (slot-type (specified-type slotdef))
97 (*update-context* (cons (type-of instance) slot-name)))
98 (cond ((and value (null slot-reader))
99 (setf (slot-value instance slot-name)
100 (read-sql-value value (delistify slot-type)
101 (view-database instance)
102 (database-underlying-type
103 (view-database instance)))))
105 (update-slot-with-null instance slot-name slotdef))
106 ((typep slot-reader 'string)
107 (setf (slot-value instance slot-name)
108 (format nil slot-reader value)))
109 ((typep slot-reader 'function)
110 (setf (slot-value instance slot-name)
111 (apply slot-reader (list value))))
113 (error "Slot reader is of an unusual type.")))))
115 (defmethod key-value-from-db (slotdef value database)
116 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
117 (let ((slot-reader (view-class-slot-db-reader slotdef))
118 (slot-type (specified-type slotdef)))
119 (cond ((and value (null slot-reader))
120 (read-sql-value value (delistify slot-type) database
121 (database-underlying-type database)))
124 ((typep slot-reader 'string)
125 (format nil slot-reader value))
126 ((typep slot-reader 'function)
127 (apply slot-reader (list value)))
129 (error "Slot reader is of an unusual type.")))))
131 (defun db-value-from-slot (slotdef val database)
132 (let ((dbwriter (view-class-slot-db-writer slotdef))
133 (dbtype (specified-type slotdef)))
135 (string (format nil dbwriter val))
136 (function (apply dbwriter (list val)))
138 (database-output-sql-as-type
142 val database (database-underlying-type database))))))
144 (defun check-slot-type (slotdef val)
145 (let* ((slot-type (specified-type slotdef))
146 (basetype (if (listp slot-type) (car slot-type) slot-type)))
147 (when (and slot-type val)
148 (unless (typep val basetype)
149 (error 'sql-user-error
151 (format nil "Invalid value ~A in slot ~A, not of type ~A."
152 val (slot-definition-name slotdef) slot-type))))))
155 ;; Called by find-all
158 (defmethod get-slot-values-from-view (obj slotdeflist values)
159 (flet ((update-slot (slot-def values)
160 (update-slot-from-db obj slot-def values)))
161 (mapc #'update-slot slotdeflist values)
164 (defmethod update-record-from-slot ((obj standard-db-object) slot &key
165 (database *default-database*))
166 (let* ((database (or (view-database obj) database))
167 (vct (view-table (class-of obj)))
168 (sd (slotdef-for-slot-with-class slot (class-of obj))))
169 (check-slot-type sd (slot-value obj slot))
170 (let* ((att (view-class-slot-column sd))
171 (val (db-value-from-slot sd (slot-value obj slot) database)))
172 (cond ((and vct sd (view-database obj))
173 (update-records (sql-expression :table vct)
174 :attributes (list (sql-expression :attribute att))
176 :where (key-qualifier-for-instance
177 obj :database database)
179 ((and vct sd (not (view-database obj)))
180 (insert-records :into (sql-expression :table vct)
181 :attributes (list (sql-expression :attribute att))
184 (setf (slot-value obj 'view-database) database))
186 (error "Unable to update record.")))))
189 (defmethod update-record-from-slots ((obj standard-db-object) slots &key
190 (database *default-database*))
191 (let* ((database (or (view-database obj) database))
192 (vct (view-table (class-of obj)))
193 (sds (slotdefs-for-slots-with-class slots (class-of obj)))
194 (avps (mapcar #'(lambda (s)
195 (let ((val (slot-value
196 obj (slot-definition-name s))))
197 (check-slot-type s val)
198 (list (sql-expression
199 :attribute (view-class-slot-column s))
200 (db-value-from-slot s val database))))
202 (cond ((and avps (view-database obj))
203 (update-records (sql-expression :table vct)
205 :where (key-qualifier-for-instance
206 obj :database database)
208 ((and avps (not (view-database obj)))
209 (insert-records :into (sql-expression :table vct)
212 (setf (slot-value obj 'view-database) database))
214 (error "Unable to update records"))))
217 (defmethod update-records-from-instance ((obj standard-db-object)
218 &key (database *default-database*))
219 (let ((database (or (view-database obj) database)))
220 (labels ((slot-storedp (slot)
221 (and (member (view-class-slot-db-kind slot) '(:base :key))
222 (slot-boundp obj (slot-definition-name slot))))
223 (slot-value-list (slot)
224 (let ((value (slot-value obj (slot-definition-name slot))))
225 (check-slot-type slot value)
226 (list (sql-expression :attribute (view-class-slot-column slot))
227 (db-value-from-slot slot value database)))))
228 (let* ((view-class (class-of obj))
229 (view-class-table (view-table view-class))
230 (slots (remove-if-not #'slot-storedp
231 (ordered-class-slots view-class)))
232 (record-values (mapcar #'slot-value-list slots)))
233 (unless record-values
234 (error "No settable slots."))
235 (if (view-database obj)
236 (update-records (sql-expression :table view-class-table)
237 :av-pairs record-values
238 :where (key-qualifier-for-instance
239 obj :database database)
242 (insert-records :into (sql-expression :table view-class-table)
243 :av-pairs record-values
245 (setf (slot-value obj 'view-database) database))))))
248 (defmethod delete-instance-records ((instance standard-db-object))
249 (let ((vt (sql-expression :table (view-table (class-of instance))))
250 (vd (view-database instance)))
252 (let ((qualifier (key-qualifier-for-instance instance :database vd)))
253 (delete-records :from vt :where qualifier :database vd)
254 (setf (slot-value instance 'view-database) nil))
255 (signal-no-database-error vd))))
257 (defmethod update-instance-from-records ((instance standard-db-object)
258 &key (database *default-database*))
259 (let* ((view-class (find-class (class-name (class-of instance))))
260 (view-table (sql-expression :table (view-table view-class)))
261 (vd (or (view-database instance) database))
262 (view-qual (key-qualifier-for-instance instance :database vd))
263 (sels (generate-selection-list view-class))
264 (res (apply #'select (append (mapcar #'cdr sels)
265 (list :from view-table
267 (list :result-types nil)))))
269 (get-slot-values-from-view instance (mapcar #'car sels) (car res)))))
271 (defmethod update-slot-from-record ((instance standard-db-object)
272 slot &key (database *default-database*))
273 (let* ((view-class (find-class (class-name (class-of instance))))
274 (view-table (sql-expression :table (view-table view-class)))
275 (vd (or (view-database instance) database))
276 (view-qual (key-qualifier-for-instance instance :database vd))
277 (slot-def (slotdef-for-slot-with-class slot view-class))
278 (att-ref (generate-attribute-reference view-class slot-def))
279 (res (select att-ref :from view-table :where view-qual
282 (get-slot-values-from-view instance (list slot-def) (car res)))))
285 (defmethod update-slot-with-null ((object standard-db-object)
288 (setf (slot-value object slotname) (slot-value slotdef 'void-value)))
290 (defvar +no-slot-value+ '+no-slot-value+)
292 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
293 (let* ((class (find-class classname))
294 (sld (slotdef-for-slot-with-class slot class)))
296 (if (eq value +no-slot-value+)
297 (sql-expression :attribute (view-class-slot-column sld)
298 :table (view-table class))
303 (error "Unknown slot ~A for class ~A" slot classname))))
305 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
306 (declare (ignore database))
307 (let* ((class (find-class classname)))
308 (unless (view-table class)
309 (error "No view-table for class ~A" classname))
310 (sql-expression :table (view-table class))))
312 (defmethod database-get-type-specifier (type args database db-type)
313 (declare (ignore type args database db-type))
316 (defmethod database-get-type-specifier ((type (eql 'integer)) args database db-type)
317 (declare (ignore database db-type))
319 (format nil "INT(~A)" (car args))
323 "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
326 (defmethod database-get-type-specifier ((type (eql 'bigint)) args database db-type)
327 (declare (ignore args database db-type))
330 (defmethod database-get-type-specifier ((type (eql 'simple-base-string)) args
332 (declare (ignore database db-type))
334 (format nil "VARCHAR(~A)" (car args))
337 (defmethod database-get-type-specifier ((type (eql 'simple-string)) args
339 (declare (ignore database db-type))
341 (format nil "VARCHAR(~A)" (car args))
344 (defmethod database-get-type-specifier ((type (eql 'string)) args database db-type)
345 (declare (ignore database db-type))
347 (format nil "VARCHAR(~A)" (car args))
350 (deftype universal-time ()
351 "A positive integer as returned by GET-UNIVERSAL-TIME."
354 (defmethod database-get-type-specifier ((type (eql 'universal-time)) args database db-type)
355 (declare (ignore args database db-type))
358 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database db-type)
359 (declare (ignore args database db-type))
362 (defmethod database-get-type-specifier ((type (eql 'duration)) args database db-type)
363 (declare (ignore database args db-type))
366 (defmethod database-get-type-specifier ((type (eql 'money)) args database db-type)
367 (declare (ignore database args db-type))
370 (deftype raw-string (&optional len)
371 "A string which is not trimmed when retrieved from the database"
374 (defmethod database-get-type-specifier ((type (eql 'raw-string)) args database db-type)
375 (declare (ignore database db-type))
377 (format nil "VARCHAR(~A)" (car args))
380 (defmethod database-get-type-specifier ((type (eql 'float)) args database db-type)
381 (declare (ignore database db-type))
383 (format nil "FLOAT(~A)" (car args))
386 (defmethod database-get-type-specifier ((type (eql 'long-float)) args database db-type)
387 (declare (ignore database db-type))
389 (format nil "FLOAT(~A)" (car args))
392 (defmethod database-get-type-specifier ((type (eql 'boolean)) args database db-type)
393 (declare (ignore args database db-type))
396 (defmethod database-output-sql-as-type (type val database db-type)
397 (declare (ignore type database db-type))
400 (defmethod database-output-sql-as-type ((type (eql 'list)) val database db-type)
401 (declare (ignore database db-type))
402 (progv '(*print-circle* *print-array*) '(t t)
403 (let ((escaped (prin1-to-string val)))
404 (substitute-char-string
405 escaped #\Null " "))))
407 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database db-type)
408 (declare (ignore database db-type))
413 (package-name (symbol-package val))
418 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database db-type)
419 (declare (ignore database db-type))
424 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database db-type)
425 (declare (ignore database db-type))
426 (progv '(*print-circle* *print-array*) '(t t)
427 (prin1-to-string val)))
429 (defmethod database-output-sql-as-type ((type (eql 'array)) val database db-type)
430 (declare (ignore database db-type))
431 (progv '(*print-circle* *print-array*) '(t t)
432 (prin1-to-string val)))
434 (defmethod database-output-sql-as-type ((type (eql 'boolean)) val database db-type)
435 (declare (ignore database db-type))
438 (defmethod database-output-sql-as-type ((type (eql 'string)) val database db-type)
439 (declare (ignore database db-type))
442 (defmethod database-output-sql-as-type ((type (eql 'simple-string))
443 val database db-type)
444 (declare (ignore database db-type))
447 (defmethod database-output-sql-as-type ((type (eql 'simple-base-string))
448 val database db-type)
449 (declare (ignore database db-type))
452 (defmethod read-sql-value (val type database db-type)
453 (declare (ignore type database db-type))
454 (read-from-string val))
456 (defmethod read-sql-value (val (type (eql 'string)) database db-type)
457 (declare (ignore database db-type))
460 (defmethod read-sql-value (val (type (eql 'simple-string)) database db-type)
461 (declare (ignore database db-type))
464 (defmethod read-sql-value (val (type (eql 'simple-base-string)) database db-type)
465 (declare (ignore database db-type))
468 (defmethod read-sql-value (val (type (eql 'raw-string)) database db-type)
469 (declare (ignore database db-type))
472 (defmethod read-sql-value (val (type (eql 'keyword)) database db-type)
473 (declare (ignore database db-type))
474 (when (< 0 (length val))
475 (intern (symbol-name-default-case val)
476 (find-package '#:keyword))))
478 (defmethod read-sql-value (val (type (eql 'symbol)) database db-type)
479 (declare (ignore database db-type))
480 (when (< 0 (length val))
481 (unless (string= val (symbol-name-default-case "NIL"))
482 (intern (symbol-name-default-case val)
483 (symbol-package *update-context*)))))
485 (defmethod read-sql-value (val (type (eql 'integer)) database db-type)
486 (declare (ignore database db-type))
489 (unless (string-equal "NIL" val)
490 (parse-integer val)))
493 (defmethod read-sql-value (val (type (eql 'bigint)) database db-type)
494 (declare (ignore database db-type))
497 (unless (string-equal "NIL" val)
498 (parse-integer val)))
501 (defmethod read-sql-value (val (type (eql 'float)) database db-type)
502 (declare (ignore database db-type))
503 ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
506 (float (read-from-string val)))
510 (defmethod read-sql-value (val (type (eql 'boolean)) database db-type)
511 (declare (ignore database db-type))
514 (defmethod read-sql-value (val (type (eql 'univeral-time)) database db-type)
515 (declare (ignore database db-type))
516 (unless (eq 'NULL val)
522 (defmethod read-sql-value (val (type (eql 'wall-time)) database db-type)
523 (declare (ignore database db-type))
524 (unless (eq 'NULL val)
525 (parse-timestring val)))
527 (defmethod read-sql-value (val (type (eql 'duration)) database db-type)
528 (declare (ignore database db-type))
529 (unless (or (eq 'NULL val)
531 (parse-timestring val)))
533 ;; ------------------------------------------------------------
534 ;; Logic for 'faulting in' :join slots
536 ;; this works, but is inefficient requiring (+ 1 n-rows)
539 (defun fault-join-target-slot (class object slot-def)
540 (let* ((res (fault-join-slot-raw class object slot-def))
541 (dbi (view-class-slot-db-info slot-def))
542 (target-name (gethash :target-slot dbi))
543 (target-class (find-class target-name)))
545 (mapcar (lambda (obj)
551 (find target-name (class-slots (class-of obj))
552 :key #'slot-definition-name)))
555 #+ignore ;; this doesn't work when attempting to call slot-value
556 (mapcar (lambda (obj)
557 (cons obj (slot-value obj ts))) res))))
559 (defun fault-join-target-slot (class object slot-def)
560 (let* ((dbi (view-class-slot-db-info slot-def))
561 (ts (gethash :target-slot dbi))
562 (jc (gethash :join-class dbi))
563 (ts-view-table (view-table (find-class ts)))
564 (jc-view-table (view-table (find-class jc)))
565 (tdbi (view-class-slot-db-info
566 (find ts (class-slots (find-class jc))
567 :key #'slot-definition-name)))
568 (retrieval (gethash :retrieval tdbi))
569 (jq (join-qualifier class object slot-def))
570 (key (slot-value object (gethash :home-key dbi))))
576 :inner-join (sql-expression :table jc-view-table)
580 :attribute (gethash :foreign-key tdbi)
581 :table ts-view-table)
583 :attribute (gethash :home-key tdbi)
584 :table jc-view-table))
586 :result-types :auto)))
587 (mapcar #'(lambda (i)
588 (let* ((instance (car i))
589 (jcc (make-instance jc :view-database (view-database instance))))
590 (setf (slot-value jcc (gethash :foreign-key dbi))
592 (setf (slot-value jcc (gethash :home-key tdbi))
593 (slot-value instance (gethash :foreign-key tdbi)))
594 (list instance jcc)))
597 ;; just fill in minimal slots
600 (let ((instance (make-instance ts :view-database (view-database object)))
601 (jcc (make-instance jc :view-database (view-database object)))
603 (setf (slot-value instance (gethash :home-key tdbi)) fk)
604 (setf (slot-value jcc (gethash :foreign-key dbi))
606 (setf (slot-value jcc (gethash :home-key tdbi))
608 (list instance jcc)))
609 (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
610 :from (sql-expression :table jc-view-table)
616 (defvar *default-update-objects-max-len* nil
617 "The default value to use for the MAX-LEN keyword argument to
618 UPDATE-OBJECT-JOINS.")
620 (defun update-objects-joins (objects &key (slots t) (force-p t)
622 *default-update-objects-max-len*))
623 "Updates from the records of the appropriate database tables
624 the join slots specified by SLOTS in the supplied list of View
625 Class instances OBJECTS. SLOTS is t by default which means that
626 all join slots with :retrieval :immediate are updated. CLASS-NAME
627 is used to specify the View Class of all instance in OBJECTS and
628 default to nil which means that the class of the first instance
629 in OBJECTS is used. FORCE-P is t by default which means that all
630 join slots are updated whereas a value of nil means that only
631 unbound join slots are updated. MAX-LEN defaults to
632 *DEFAULT-UPDATE-OBJECTS-MAX-LEN* and when non-nil specifies that
633 UPDATE-OBJECT-JOINS may issue multiple database queries with a
634 maximum of MAX-LEN instances updated in each query."
635 (assert (or (null max-len) (plusp max-len)))
638 (setq class-name (class-name (class-of (first objects)))))
639 (let* ((class (find-class class-name))
640 (class-slots (ordered-class-slots class))
643 (generate-retrieval-joins-list class :deferred)
645 (mapcar #'(lambda (name)
646 (let ((slotdef (find name class-slots :key #'slot-definition-name)))
648 (warn "Unable to find slot named ~S in class ~S." name class))
651 (dolist (slotdef slotdefs)
652 (let* ((dbi (view-class-slot-db-info slotdef))
653 (slotdef-name (slot-definition-name slotdef))
654 (foreign-key (gethash :foreign-key dbi))
655 (home-key (gethash :home-key dbi))
659 (mapcar #'(lambda (o) (slot-value o home-key)) objects)
662 #'(lambda (o) (if (slot-boundp o slotdef-name)
664 (slot-value o home-key)))
666 (n-object-keys (length object-keys))
667 (query-len (or max-len n-object-keys)))
669 (do ((i 0 (+ i query-len)))
670 ((>= i n-object-keys))
671 (let* ((keys (if max-len
672 (subseq object-keys i (min (+ i query-len) n-object-keys))
674 (results (find-all (list (gethash :join-class dbi))
675 :where (make-instance 'sql-relational-exp
677 :sub-expressions (list (sql-expression :attribute foreign-key)
681 (dolist (object objects)
682 (when (or force-p (not (slot-boundp object slotdef-name)))
683 (let ((res (find (slot-value object home-key) results
684 :key #'(lambda (res) (slot-value res foreign-key))
687 (setf (slot-value object slotdef-name) res)))))))))))
690 (defun fault-join-slot-raw (class object slot-def)
691 (let* ((dbi (view-class-slot-db-info slot-def))
692 (jc (gethash :join-class dbi)))
693 (let ((jq (join-qualifier class object slot-def)))
695 (select jc :where jq :flatp t :result-types nil)))))
697 (defun fault-join-slot (class object slot-def)
698 (let* ((dbi (view-class-slot-db-info slot-def))
699 (ts (gethash :target-slot dbi)))
700 (if (and ts (gethash :set dbi))
701 (fault-join-target-slot class object slot-def)
702 (let ((res (fault-join-slot-raw class object slot-def)))
705 ((and ts (not (gethash :set dbi)))
706 (mapcar (lambda (obj) (slot-value obj ts)) res))
707 ((and (not ts) (not (gethash :set dbi)))
709 ((and (not ts) (gethash :set dbi))
712 (defun join-qualifier (class object slot-def)
713 (declare (ignore class))
714 (let* ((dbi (view-class-slot-db-info slot-def))
715 (jc (find-class (gethash :join-class dbi)))
716 ;;(ts (gethash :target-slot dbi))
717 ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
718 (foreign-keys (gethash :foreign-key dbi))
719 (home-keys (gethash :home-key dbi)))
720 (when (every #'(lambda (slt)
721 (and (slot-boundp object slt)
722 (not (null (slot-value object slt)))))
723 (if (listp home-keys) home-keys (list home-keys)))
725 (mapcar #'(lambda (hk fk)
726 (let ((fksd (slotdef-for-slot-with-class fk jc)))
732 (view-class-slot-column fksd)
733 :table (view-table jc)))
737 (slot-value object hk))
740 (if (listp home-keys)
743 (if (listp foreign-keys)
745 (list foreign-keys)))))
747 (if (> (length jc) 1)
751 ;; FIXME: add retrieval immediate for efficiency
752 ;; For example, for (select 'employee-address) in test suite =>
753 ;; select addr.*,ea_join.* FROM addr,ea_join WHERE ea_join.aaddressid=addr.addressid\g
755 (defun build-objects (vals sclasses immediate-join-classes sels immediate-joins database refresh flatp instances)
756 "Used by find-all to build objects."
757 (labels ((build-object (vals vclass jclasses selects immediate-selects instance)
758 (let* ((db-vals (butlast vals (- (list-length vals)
759 (list-length selects))))
760 (obj (if instance instance (make-instance (class-name vclass) :view-database database)))
761 (join-vals (subseq vals (list-length selects)))
762 (joins (mapcar #'(lambda (c) (when c (make-instance c :view-database database)))
764 ;;(format t "db-vals: ~S, join-values: ~S~%" db-vals join-vals)
765 ;; use refresh keyword here
766 (setf obj (get-slot-values-from-view obj (mapcar #'car selects) db-vals))
767 (mapc #'(lambda (jc) (get-slot-values-from-view jc (mapcar #'car immediate-selects) join-vals))
771 (let ((slot (find (class-name (class-of jc)) (class-slots vclass)
772 :key #'(lambda (slot)
773 (when (and (eq :join (view-class-slot-db-kind slot))
774 (eq (slot-definition-name slot)
775 (gethash :join-class (view-class-slot-db-info slot))))
776 (slot-definition-name slot))))))
778 (setf (slot-value obj (slot-definition-name slot)) jc))))
780 (when refresh (instance-refreshed obj))
783 (mapcar #'(lambda (sclass jclass sel immediate-join instance)
785 (build-object vals sclass jclass sel immediate-join instance)
786 (setf vals (nthcdr (+ (list-length sel) (list-length immediate-join))
788 sclasses immediate-join-classes sels immediate-joins instances)))
789 (if (and flatp (= (length sclasses) 1))
793 (defun find-all (view-classes
795 &key all set-operation distinct from where group-by having
796 order-by offset limit refresh flatp result-types
798 (database *default-database*)
800 "Called by SELECT to generate object query results when the
801 View Classes VIEW-CLASSES are passed as arguments to SELECT."
802 (declare (ignore all set-operation group-by having offset limit inner-join on)
803 (optimize (debug 3) (speed 1)))
804 (labels ((ref-equal (ref1 ref2)
807 (table-sql-expr (table)
808 (sql-expression :table (view-table table)))
809 (tables-equal (table-a table-b)
810 (when (and table-a table-b)
811 (string= (string (slot-value table-a 'name))
812 (string (slot-value table-b 'name))))))
816 (remf args :additional-fields)
817 (remf args :result-types)
818 (remf args :instances)
819 (let* ((*db-deserializing* t)
820 (sclasses (mapcar #'find-class view-classes))
821 (immediate-join-slots
822 (mapcar #'(lambda (c) (generate-retrieval-joins-list c :immediate)) sclasses))
823 (immediate-join-classes
824 (mapcar #'(lambda (jcs)
825 (mapcar #'(lambda (slotdef)
826 (find-class (gethash :join-class (view-class-slot-db-info slotdef))))
828 immediate-join-slots))
829 (immediate-join-sels (mapcar #'generate-immediate-joins-selection-list sclasses))
830 (sels (mapcar #'generate-selection-list sclasses))
831 (fullsels (apply #'append (mapcar #'append sels immediate-join-sels)))
832 (sel-tables (collect-table-refs where))
833 (tables (remove-if #'null
834 (remove-duplicates (append (mapcar #'table-sql-expr sclasses)
835 (mapcar #'(lambda (jcs)
836 (mapcan #'(lambda (jc)
837 (when jc (table-sql-expr jc)))
839 immediate-join-classes)
841 :test #'tables-equal)))
842 (order-by-slots (mapcar #'(lambda (ob) (if (atom ob) ob (car ob)))
843 (listify order-by))))
845 (dolist (ob order-by-slots)
846 (when (and ob (not (member ob (mapcar #'cdr fullsels)
849 (append fullsels (mapcar #'(lambda (att) (cons nil att))
851 (dolist (ob (listify distinct))
852 (when (and (typep ob 'sql-ident)
853 (not (member ob (mapcar #'cdr fullsels)
856 (append fullsels (mapcar #'(lambda (att) (cons nil att))
858 (mapcar #'(lambda (vclass jclasses jslots)
861 #'(lambda (jclass jslot)
862 (let ((dbi (view-class-slot-db-info jslot)))
865 (list (sql-operation '==
867 :attribute (gethash :foreign-key dbi)
868 :table (view-table jclass))
870 :attribute (gethash :home-key dbi)
871 :table (view-table vclass))))
872 (when where (listify where))))))
874 sclasses immediate-join-classes immediate-join-slots)
875 (let* ((rows (apply #'select
876 (append (mapcar #'cdr fullsels)
878 (list (append (when from (listify from))
880 (list :result-types result-types)
881 (when where (list :where where))
883 (instances-to-add (- (length rows) (length instances)))
884 (perhaps-extended-instances
885 (if (plusp instances-to-add)
886 (append instances (do ((i 0 (1+ i))
888 ((= i instances-to-add) res)
889 (push (make-list (length sclasses) :initial-element nil) res)))
892 #'(lambda (row instance)
893 (build-objects row sclasses immediate-join-classes sels
894 immediate-join-sels database refresh flatp
895 (if (and flatp (atom instance))
898 rows perhaps-extended-instances)))
901 (defmethod instance-refreshed ((instance standard-db-object)))
903 (defun select (&rest select-all-args)
904 "Executes a query on DATABASE, which has a default value of
905 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
906 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
907 argument can be used to generate queries in both functional and
908 object oriented contexts.
910 In the functional case, the required arguments specify the
911 columns selected by the query and may be symbolic SQL expressions
912 or strings representing attribute identifiers. Type modified
913 identifiers indicate that the values selected from the specified
914 column are converted to the specified lisp type. The keyword
915 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
916 SET-OPERATION and WHERE are used to specify, using the symbolic
917 SQL syntax, the corresponding components of the SQL query
918 generated by the call to SELECT. RESULT-TYPES is a list of
919 symbols which specifies the lisp type for each field returned by
920 the query. If RESULT-TYPES is nil all results are returned as
921 strings whereas the default value of :auto means that the lisp
922 types are automatically computed for each field. FIELD-NAMES is t
923 by default which means that the second value returned is a list
924 of strings representing the columns selected by the query. If
925 FIELD-NAMES is nil, the list of column names is not returned as a
928 In the object oriented case, the required arguments to SELECT are
929 symbols denoting View Classes which specify the database tables
930 to query. In this case, SELECT returns a list of View Class
931 instances whose slots are set from the attribute values of the
932 records in the specified table. Slot-value is a legal operator
933 which can be employed as part of the symbolic SQL syntax used in
934 the WHERE keyword argument to SELECT. REFRESH is nil by default
935 which means that the View Class instances returned are retrieved
936 from a cache if an equivalent call to SELECT has previously been
937 issued. If REFRESH is true, the View Class instances returned are
938 updated as necessary from the database and the generic function
939 INSTANCE-REFRESHED is called to perform any necessary operations
940 on the updated instances.
942 In both object oriented and functional contexts, FLATP has a
943 default value of nil which means that the results are returned as
944 a list of lists. If FLATP is t and only one result is returned
945 for each record selected in the query, the results are returned
946 as elements of a list."
948 (flet ((select-objects (target-args)
950 (every #'(lambda (arg)
952 (find-class arg nil)))
954 (multiple-value-bind (target-args qualifier-args)
955 (query-get-selections select-all-args)
956 (unless (or *default-database* (getf qualifier-args :database))
957 (signal-no-database-error nil))
960 ((select-objects target-args)
961 (let ((caching (getf qualifier-args :caching t))
962 (result-types (getf qualifier-args :result-types :auto))
963 (refresh (getf qualifier-args :refresh nil))
964 (database (or (getf qualifier-args :database) *default-database*))
965 (order-by (getf qualifier-args :order-by)))
966 (remf qualifier-args :caching)
967 (remf qualifier-args :refresh)
968 (remf qualifier-args :result-types)
971 ;; Add explicity table name to order-by if not specified and only
972 ;; one selected table. This is required so FIND-ALL won't duplicate
974 (when (and order-by (= 1 (length target-args)))
975 (let ((table-name (view-table (find-class (car target-args))))
976 (order-by-list (copy-seq (listify order-by))))
978 (loop for i from 0 below (length order-by-list)
979 do (etypecase (nth i order-by-list)
981 (unless (slot-value (nth i order-by-list) 'qualifier)
982 (setf (slot-value (nth i order-by-list) 'qualifier) table-name)))
984 (unless (slot-value (car (nth i order-by-list)) 'qualifier)
985 (setf (slot-value (car (nth i order-by-list)) 'qualifier) table-name)))))
986 (setf (getf qualifier-args :order-by) order-by-list)))
990 (apply #'find-all target-args
991 (append qualifier-args (list :result-types result-types))))
993 (let ((cached (records-cache-results target-args qualifier-args database)))
995 ((and cached (not refresh))
997 ((and cached refresh)
998 (let ((results (apply #'find-all (append (list target-args) qualifier-args `(:instances ,cached :result-types :auto)))))
999 (setf (records-cache-results target-args qualifier-args database) results)
1002 (let ((results (apply #'find-all target-args (append qualifier-args
1003 '(:result-types :auto)))))
1004 (setf (records-cache-results target-args qualifier-args database) results)
1007 (let* ((expr (apply #'make-query select-all-args))
1009 (mapcar #'(lambda (attrib)
1010 (if (typep attrib 'sql-ident-attribute)
1011 (let ((type (slot-value attrib 'type)))
1016 (slot-value expr 'selections))))
1017 (destructuring-bind (&key (flatp nil)
1018 (result-types :auto)
1020 (database *default-database*)
1023 (query expr :flatp flatp
1025 ;; specifying a type for an attribute overrides result-types
1026 (if (some #'(lambda (x) (not (eq t x))) specified-types)
1029 :field-names field-names
1030 :database database))))))))
1032 (defun compute-records-cache-key (targets qualifiers)
1034 (do ((args *select-arguments* (cdr args))
1036 ((null args) results)
1037 (let* ((arg (car args))
1038 (value (getf qualifiers arg)))
1042 (cons (cons (sql (car value)) (cdr value)))
1043 (%sql-expression (sql value))
1047 (defun records-cache-results (targets qualifiers database)
1048 (when (record-caches database)
1049 (gethash (compute-records-cache-key targets qualifiers) (record-caches database))))
1051 (defun (setf records-cache-results) (results targets qualifiers database)
1052 (unless (record-caches database)
1053 (setf (record-caches database)
1054 (make-hash-table :test 'equal
1055 #+allegro :values #+allegro :weak)))
1056 (setf (gethash (compute-records-cache-key targets qualifiers)
1057 (record-caches database)) results)