r9451: 23 May 2004 Kevin Rosenberg
[clsql.git] / sql / objects.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;;
4 ;;;; $Id$
5 ;;;;
6 ;;;; The CLSQL Object Oriented Data Definitional Language (OODDL)
7 ;;;; and Object Oriented Data Manipulation Language (OODML).
8 ;;;;
9 ;;;; This file is part of CLSQL.
10 ;;;;
11 ;;;; CLSQL users are granted the rights to distribute and use this software
12 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
13 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
14 ;;;; *************************************************************************
15
16 (in-package #:clsql-sys)
17
18 (defclass standard-db-object ()
19   ((view-database :initform nil :initarg :view-database :reader view-database
20     :db-kind :virtual))
21   (:metaclass standard-db-class)
22   (:documentation "Superclass for all CLSQL View Classes."))
23
24 (defvar *db-auto-sync* nil 
25   "A non-nil value means that creating View Class instances or
26   setting their slots automatically creates/updates the
27   corresponding records in the underlying database.")
28
29 (defvar *db-deserializing* nil)
30 (defvar *db-initializing* nil)
31
32 (defmethod slot-value-using-class ((class standard-db-class) instance slot-def)
33   (declare (optimize (speed 3)))
34   (unless *db-deserializing*
35     (let* ((slot-name (%svuc-slot-name slot-def))
36            (slot-object (%svuc-slot-object slot-def class))
37            (slot-kind (view-class-slot-db-kind slot-object)))
38       (when (and (eql slot-kind :join)
39                  (not (slot-boundp instance slot-name)))
40         (let ((*db-deserializing* t))
41           (if (view-database instance)
42               (setf (slot-value instance slot-name)
43                     (fault-join-slot class instance slot-object))
44               (setf (slot-value instance slot-name) nil))))))
45   (call-next-method))
46
47 (defmethod (setf slot-value-using-class) (new-value (class standard-db-class)
48                                           instance slot-def)
49   (declare (ignore new-value))
50   (let* ((slot-name (%svuc-slot-name slot-def))
51          (slot-object (%svuc-slot-object slot-def class))
52          (slot-kind (view-class-slot-db-kind slot-object)))
53     (call-next-method)
54     (when (and *db-auto-sync* 
55                (not *db-initializing*)
56                (not *db-deserializing*)
57                (not (eql slot-kind :virtual)))
58       (update-record-from-slot instance slot-name))))
59
60 (defmethod initialize-instance ((object standard-db-object)
61                                         &rest all-keys &key &allow-other-keys)
62   (declare (ignore all-keys))
63   (let ((*db-initializing* t))
64     (call-next-method)
65     (when (and *db-auto-sync*
66                (not *db-deserializing*))
67       (update-records-from-instance object))))
68
69 ;;
70 ;; Build the database tables required to store the given view class
71 ;;
72
73 (defun create-view-from-class (view-class-name
74                                &key (database *default-database*))
75   "Creates a table as defined by the View Class VIEW-CLASS-NAME
76 in DATABASE which defaults to *DEFAULT-DATABASE*."
77   (let ((tclass (find-class view-class-name)))
78     (if tclass
79         (let ((*default-database* database))
80           (%install-class tclass database))
81         (error "Class ~s not found." view-class-name)))
82   (values))
83
84 (defmethod %install-class ((self standard-db-class) database &aux schemadef)
85   (dolist (slotdef (ordered-class-slots self))
86     (let ((res (database-generate-column-definition (class-name self)
87                                                     slotdef database)))
88       (when res 
89         (push res schemadef))))
90   (unless schemadef
91     (error "Class ~s has no :base slots" self))
92   (create-table (sql-expression :table (view-table self)) (nreverse schemadef)
93                 :database database
94                 :constraints (database-pkey-constraint self database))
95   (push self (database-view-classes database))
96   t)
97
98 (defmethod database-pkey-constraint ((class standard-db-class) database)
99   (let ((keylist (mapcar #'view-class-slot-column (keyslots-for-class class))))
100     (when keylist 
101       (convert-to-db-default-case
102        (format nil "CONSTRAINT ~APK PRIMARY KEY~A"
103                (database-output-sql (view-table class) database)
104                (database-output-sql keylist database))
105        database))))
106
107 (defmethod database-generate-column-definition (class slotdef database)
108   (declare (ignore database class))
109   (when (member (view-class-slot-db-kind slotdef) '(:base :key))
110     (let ((cdef
111            (list (sql-expression :attribute (view-class-slot-column slotdef))
112                  (specified-type slotdef))))
113       (setf cdef (append cdef (list (view-class-slot-db-type slotdef))))
114       (let ((const (view-class-slot-db-constraints slotdef)))
115         (when const 
116           (setq cdef (append cdef (list const)))))
117       cdef)))
118
119
120 ;;
121 ;; Drop the tables which store the given view class
122 ;;
123
124 (defun drop-view-from-class (view-class-name &key (database *default-database*))
125   "Removes a table defined by the View Class VIEW-CLASS-NAME from
126 DATABASE which defaults to *DEFAULT-DATABASE*."
127   (let ((tclass (find-class view-class-name)))
128     (if tclass
129         (let ((*default-database* database))
130           (%uninstall-class tclass))
131         (error "Class ~s not found." view-class-name)))
132   (values))
133
134 (defun %uninstall-class (self &key (database *default-database*))
135   (drop-table (sql-expression :table (view-table self))
136               :if-does-not-exist :ignore
137               :database database)
138   (setf (database-view-classes database)
139         (remove self (database-view-classes database))))
140
141
142 ;;
143 ;; List all known view classes
144 ;;
145
146 (defun list-classes (&key (test #'identity)
147                      (root-class (find-class 'standard-db-object))
148                      (database *default-database*))
149   "Returns a list of all the View Classes which are connected to
150 DATABASE, which defaults to *DEFAULT-DATABASE*, and which descend
151 from the class ROOT-CLASS and which satisfy the function TEST. By
152 default ROOT-CLASS is STANDARD-DB-OBJECT and TEST is IDENTITY."
153   (flet ((find-superclass (class) 
154            (member root-class (class-precedence-list class))))
155     (let ((view-classes (and database (database-view-classes database))))
156       (when view-classes
157         (remove-if #'(lambda (c) (or (not (funcall test c))
158                                      (not (find-superclass c))))
159                    view-classes)))))
160
161 ;;
162 ;; Define a new view class
163 ;;
164
165 (defmacro def-view-class (class supers slots &rest cl-options)
166   "Creates a View Class called CLASS whose slots SLOTS can map
167 onto the attributes of a table in a database. If SUPERS is nil
168 then the superclass of CLASS will be STANDARD-DB-OBJECT,
169 otherwise SUPERS is a list of superclasses for CLASS which must
170 include STANDARD-DB-OBJECT or a descendent of this class. The
171 syntax of DEFCLASS is extended through the addition of a class
172 option :base-table which defines the database table onto which
173 the View Class maps and which defaults to CLASS. The DEFCLASS
174 syntax is also extended through additional slot
175 options. The :db-kind slot option specifies the kind of DB
176 mapping which is performed for this slot and defaults to :base
177 which indicates that the slot maps to an ordinary column of the
178 database table. A :db-kind value of :key indicates that this slot
179 is a special kind of :base slot which maps onto a column which is
180 one of the unique keys for the database table, the value :join
181 indicates this slot represents a join onto another View Class
182 which contains View Class objects, and the value :virtual
183 indicates a standard CLOS slot which does not map onto columns of
184 the database table. If a slot is specified with :db-kind :join,
185 the slot option :db-info contains a list which specifies the
186 nature of the join. For slots of :db-kind :base or :key,
187 the :type slot option has a special interpretation such that Lisp
188 types, such as string, integer and float are automatically
189 converted into appropriate SQL types for the column onto which
190 the slot maps. This behaviour may be over-ridden using
191 the :db-type slot option which is a string specifying the
192 vendor-specific database type for this slot's column definition
193 in the database. The :column slot option specifies the name of
194 the SQL column which the slot maps onto, if :db-kind is
195 not :virtual, and defaults to the slot name. The :void-value slot
196 option specifies the value to store if the SQL value is NULL and
197 defaults to NIL. The :db-constraints slot option is a string
198 representing an SQL table constraint expression or a list of such
199 strings."
200   `(progn
201     (defclass ,class ,supers ,slots 
202       ,@(if (find :metaclass `,cl-options :key #'car)
203             `,cl-options
204             (cons '(:metaclass clsql-sys::standard-db-class) `,cl-options)))
205     (finalize-inheritance (find-class ',class))
206     (find-class ',class)))
207
208 (defun keyslots-for-class (class)
209   (slot-value class 'key-slots))
210
211 (defun key-qualifier-for-instance (obj &key (database *default-database*))
212   (let ((tb (view-table (class-of obj))))
213     (flet ((qfk (k)
214              (sql-operation '==
215                             (sql-expression :attribute
216                                             (view-class-slot-column k)
217                                             :table tb)
218                             (db-value-from-slot
219                              k
220                              (slot-value obj (slot-definition-name k))
221                              database))))
222       (let* ((keys (keyslots-for-class (class-of obj)))
223              (keyxprs (mapcar #'qfk (reverse keys))))
224         (cond
225           ((= (length keyxprs) 0) nil)
226           ((= (length keyxprs) 1) (car keyxprs))
227           ((> (length keyxprs) 1) (apply #'sql-operation 'and keyxprs)))))))
228
229 ;;
230 ;; Function used by 'generate-selection-list'
231 ;;
232
233 (defun generate-attribute-reference (vclass slotdef)
234   (cond
235    ((eq (view-class-slot-db-kind slotdef) :base)
236     (sql-expression :attribute (view-class-slot-column slotdef)
237                     :table (view-table vclass)))
238    ((eq (view-class-slot-db-kind slotdef) :key)
239     (sql-expression :attribute (view-class-slot-column slotdef)
240                     :table (view-table vclass)))
241    (t nil)))
242
243 ;;
244 ;; Function used by 'find-all'
245 ;;
246
247 (defun generate-selection-list (vclass)
248   (let ((sels nil))
249     (dolist (slotdef (ordered-class-slots vclass))
250       (let ((res (generate-attribute-reference vclass slotdef)))
251         (when res
252           (push (cons slotdef res) sels))))
253     (if sels
254         sels
255         (error "No slots of type :base in view-class ~A" (class-name vclass)))))
256
257
258
259 (defun generate-retrieval-joins-list (vclass retrieval-method)
260   "Returns list of immediate join slots for a class."
261   (let ((join-slotdefs nil))
262     (dolist (slotdef (ordered-class-slots vclass) join-slotdefs)
263       (when (and (eq :join (view-class-slot-db-kind slotdef))
264                  (eq retrieval-method (gethash :retrieval (view-class-slot-db-info slotdef))))
265         (push slotdef join-slotdefs)))))
266
267 (defun generate-immediate-joins-selection-list (vclass)
268   "Returns list of immediate join slots for a class."
269   (let (sels)
270     (dolist (joined-slot (generate-retrieval-joins-list vclass :immediate) sels)
271       (let* ((join-class-name (gethash :join-class (view-class-slot-db-info joined-slot)))
272              (join-class (when join-class-name (find-class join-class-name))))
273         (dolist (slotdef (ordered-class-slots join-class))
274           (let ((res (generate-attribute-reference join-class slotdef)))
275             (when res
276               (push (cons slotdef res) sels))))))
277     sels))
278
279
280 ;; Called by 'get-slot-values-from-view'
281 ;;
282
283 (defvar *update-context* nil)
284
285 (defmethod update-slot-from-db ((instance standard-db-object) slotdef value)
286   (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
287   (let* ((slot-reader (view-class-slot-db-reader slotdef))
288          (slot-name   (slot-definition-name slotdef))
289          (slot-type   (specified-type slotdef))
290          (*update-context* (cons (type-of instance) slot-name)))
291     (cond ((and value (null slot-reader))
292            (setf (slot-value instance slot-name)
293                  (read-sql-value value (delistify slot-type)
294                                  (view-database instance)
295                                  (database-underlying-type
296                                   (view-database instance)))))
297           ((null value)
298            (update-slot-with-null instance slot-name slotdef))
299           ((typep slot-reader 'string)
300            (setf (slot-value instance slot-name)
301                  (format nil slot-reader value)))
302           ((typep slot-reader 'function)
303            (setf (slot-value instance slot-name)
304                  (apply slot-reader (list value))))
305           (t
306            (error "Slot reader is of an unusual type.")))))
307
308 (defmethod key-value-from-db (slotdef value database) 
309   (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
310   (let ((slot-reader (view-class-slot-db-reader slotdef))
311         (slot-type (specified-type slotdef)))
312     (cond ((and value (null slot-reader))
313            (read-sql-value value (delistify slot-type) database
314                            (database-underlying-type database)))
315           ((null value)
316            nil)
317           ((typep slot-reader 'string)
318            (format nil slot-reader value))
319           ((typep slot-reader 'function)
320            (apply slot-reader (list value)))
321           (t
322            (error "Slot reader is of an unusual type.")))))
323
324 (defun db-value-from-slot (slotdef val database)
325   (let ((dbwriter (view-class-slot-db-writer slotdef))
326         (dbtype (specified-type slotdef)))
327     (typecase dbwriter
328       (string (format nil dbwriter val))
329       (function (apply dbwriter (list val)))
330       (t
331        (database-output-sql-as-type
332         (typecase dbtype
333           (cons (car dbtype))
334           (t dbtype))
335         val database (database-underlying-type database))))))
336
337 (defun check-slot-type (slotdef val)
338   (let* ((slot-type (specified-type slotdef))
339          (basetype (if (listp slot-type) (car slot-type) slot-type)))
340     (when (and slot-type val)
341       (unless (typep val basetype)
342         (error 'sql-user-error
343                :message
344                (format nil "Invalid value ~A in slot ~A, not of type ~A."
345                        val (slot-definition-name slotdef) slot-type))))))
346
347 ;;
348 ;; Called by find-all
349 ;;
350
351 (defmethod get-slot-values-from-view (obj slotdeflist values)
352     (flet ((update-slot (slot-def values)
353              (update-slot-from-db obj slot-def values)))
354       (mapc #'update-slot slotdeflist values)
355       obj))
356
357 (defmethod update-record-from-slot ((obj standard-db-object) slot &key
358                                     (database *default-database*))
359   (let* ((database (or (view-database obj) database))
360          (vct (view-table (class-of obj)))
361          (sd (slotdef-for-slot-with-class slot (class-of obj))))
362     (check-slot-type sd (slot-value obj slot))
363     (let* ((att (view-class-slot-column sd))
364            (val (db-value-from-slot sd (slot-value obj slot) database)))
365       (cond ((and vct sd (view-database obj))
366              (update-records (sql-expression :table vct)
367                              :attributes (list (sql-expression :attribute att))
368                              :values (list val)
369                              :where (key-qualifier-for-instance
370                                      obj :database database)
371                              :database database))
372             ((and vct sd (not (view-database obj)))
373              (insert-records :into (sql-expression :table vct)
374                              :attributes (list (sql-expression :attribute att))
375                              :values (list val)
376                              :database database)
377              (setf (slot-value obj 'view-database) database))
378             (t
379              (error "Unable to update record.")))))
380   (values))
381
382 (defmethod update-record-from-slots ((obj standard-db-object) slots &key
383                                      (database *default-database*))
384   (let* ((database (or (view-database obj) database))
385          (vct (view-table (class-of obj)))
386          (sds (slotdefs-for-slots-with-class slots (class-of obj)))
387          (avps (mapcar #'(lambda (s)
388                            (let ((val (slot-value
389                                        obj (slot-definition-name s))))
390                              (check-slot-type s val)
391                              (list (sql-expression
392                                     :attribute (view-class-slot-column s))
393                                    (db-value-from-slot s val database))))
394                        sds)))
395     (cond ((and avps (view-database obj))
396            (update-records (sql-expression :table vct)
397                            :av-pairs avps
398                            :where (key-qualifier-for-instance
399                                    obj :database database)
400                            :database database))
401           ((and avps (not (view-database obj)))
402            (insert-records :into (sql-expression :table vct)
403                            :av-pairs avps
404                            :database database)
405            (setf (slot-value obj 'view-database) database))
406           (t
407            (error "Unable to update records"))))
408   (values))
409
410 (defmethod update-records-from-instance ((obj standard-db-object)
411                                          &key (database *default-database*))
412   (let ((database (or (view-database obj) database)))
413     (labels ((slot-storedp (slot)
414                (and (member (view-class-slot-db-kind slot) '(:base :key))
415                     (slot-boundp obj (slot-definition-name slot))))
416              (slot-value-list (slot)
417                (let ((value (slot-value obj (slot-definition-name slot))))
418                  (check-slot-type slot value)
419                  (list (sql-expression :attribute (view-class-slot-column slot))
420                        (db-value-from-slot slot value database)))))
421       (let* ((view-class (class-of obj))
422              (view-class-table (view-table view-class))
423              (slots (remove-if-not #'slot-storedp 
424                                    (ordered-class-slots view-class)))
425              (record-values (mapcar #'slot-value-list slots)))
426         (unless record-values
427           (error "No settable slots."))
428         (if (view-database obj)
429             (update-records (sql-expression :table view-class-table)
430                             :av-pairs record-values
431                             :where (key-qualifier-for-instance
432                                     obj :database database)
433                             :database database)
434             (progn
435               (insert-records :into (sql-expression :table view-class-table)
436                               :av-pairs record-values
437                               :database database)
438               (setf (slot-value obj 'view-database) database))))))
439   (values))
440
441 (defmethod delete-instance-records ((instance standard-db-object))
442   (let ((vt (sql-expression :table (view-table (class-of instance))))
443         (vd (view-database instance)))
444     (if vd
445         (let ((qualifier (key-qualifier-for-instance instance :database vd)))
446           (delete-records :from vt :where qualifier :database vd)
447           (setf (slot-value instance 'view-database) nil))
448         (signal-no-database-error vd))))
449
450 (defmethod update-instance-from-records ((instance standard-db-object)
451                                          &key (database *default-database*))
452   (let* ((view-class (find-class (class-name (class-of instance))))
453          (view-table (sql-expression :table (view-table view-class)))
454          (vd (or (view-database instance) database))
455          (view-qual (key-qualifier-for-instance instance :database vd))
456          (sels (generate-selection-list view-class))
457          (res (apply #'select (append (mapcar #'cdr sels)
458                                       (list :from  view-table
459                                             :where view-qual)
460                                       (list :result-types nil)))))
461     (when res
462       (get-slot-values-from-view instance (mapcar #'car sels) (car res)))))
463
464 (defmethod update-slot-from-record ((instance standard-db-object)
465                                     slot &key (database *default-database*))
466   (let* ((view-class (find-class (class-name (class-of instance))))
467          (view-table (sql-expression :table (view-table view-class)))
468          (vd (or (view-database instance) database))
469          (view-qual (key-qualifier-for-instance instance :database vd))
470          (slot-def (slotdef-for-slot-with-class slot view-class))
471          (att-ref (generate-attribute-reference view-class slot-def))
472          (res (select att-ref :from  view-table :where view-qual
473                       :result-types nil)))
474     (when res 
475       (get-slot-values-from-view instance (list slot-def) (car res)))))
476
477
478 (defmethod update-slot-with-null ((object standard-db-object)
479                                   slotname
480                                   slotdef)
481   (setf (slot-value object slotname) (slot-value slotdef 'void-value)))
482
483 (defvar +no-slot-value+ '+no-slot-value+)
484
485 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
486   (let* ((class (find-class classname))
487          (sld (slotdef-for-slot-with-class slot class)))
488     (if sld
489         (if (eq value +no-slot-value+)
490             (sql-expression :attribute (view-class-slot-column sld)
491                             :table (view-table class))
492             (db-value-from-slot
493              sld
494              value
495              database))
496         (error "Unknown slot ~A for class ~A" slot classname))))
497
498 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
499         (declare (ignore database))
500         (let* ((class (find-class classname)))
501           (unless (view-table class)
502             (error "No view-table for class ~A"  classname))
503           (sql-expression :table (view-table class))))
504
505 (defmethod database-get-type-specifier (type args database db-type)
506   (declare (ignore type args database db-type))
507   "VARCHAR(255)")
508
509 (defmethod database-get-type-specifier ((type (eql 'integer)) args database db-type)
510   (declare (ignore database db-type))
511   (if args
512       (format nil "INT(~A)" (car args))
513       "INT"))
514
515 (deftype bigint () 
516   "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
517   'integer)
518
519 (defmethod database-get-type-specifier ((type (eql 'bigint)) args database db-type)
520   (declare (ignore args database db-type))
521   "BIGINT")
522               
523 (defmethod database-get-type-specifier ((type (eql 'simple-base-string)) args
524                                         database db-type)
525   (declare (ignore database db-type))
526   (if args
527       (format nil "VARCHAR(~A)" (car args))
528       "VARCHAR(255)"))
529
530 (defmethod database-get-type-specifier ((type (eql 'simple-string)) args
531                                         database db-type)
532   (declare (ignore database db-type))
533   (if args
534       (format nil "VARCHAR(~A)" (car args))
535       "VARCHAR(255)"))
536
537 (defmethod database-get-type-specifier ((type (eql 'string)) args database db-type)
538   (declare (ignore database db-type))
539   (if args
540       (format nil "VARCHAR(~A)" (car args))
541       "VARCHAR(255)"))
542
543 (deftype universal-time () 
544   "A positive integer as returned by GET-UNIVERSAL-TIME."
545   '(integer 1 *))
546
547 (defmethod database-get-type-specifier ((type (eql 'universal-time)) args database db-type)
548   (declare (ignore args database db-type))
549   "BIGINT")
550
551 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database db-type)
552   (declare (ignore args database db-type))
553   "TIMESTAMP")
554
555 (defmethod database-get-type-specifier ((type (eql 'duration)) args database db-type)
556   (declare (ignore database args db-type))
557   "VARCHAR")
558
559 (defmethod database-get-type-specifier ((type (eql 'money)) args database db-type)
560   (declare (ignore database args db-type))
561   "INT8")
562
563 (deftype raw-string (&optional len)
564   "A string which is not trimmed when retrieved from the database"
565   `(string ,len))
566
567 (defmethod database-get-type-specifier ((type (eql 'raw-string)) args database db-type)
568   (declare (ignore database db-type))
569   (if args
570       (format nil "VARCHAR(~A)" (car args))
571       "VARCHAR"))
572
573 (defmethod database-get-type-specifier ((type (eql 'float)) args database db-type)
574   (declare (ignore database db-type))
575   (if args
576       (format nil "FLOAT(~A)" (car args))
577       "FLOAT"))
578
579 (defmethod database-get-type-specifier ((type (eql 'long-float)) args database db-type)
580   (declare (ignore database db-type))
581   (if args
582       (format nil "FLOAT(~A)" (car args))
583       "FLOAT"))
584
585 (defmethod database-get-type-specifier ((type (eql 'boolean)) args database db-type)
586   (declare (ignore args database db-type))
587   "BOOL")
588
589 (defmethod database-output-sql-as-type (type val database db-type)
590   (declare (ignore type database db-type))
591   val)
592
593 (defmethod database-output-sql-as-type ((type (eql 'list)) val database db-type)
594   (declare (ignore database db-type))
595   (progv '(*print-circle* *print-array*) '(t t)
596     (let ((escaped (prin1-to-string val)))
597       (substitute-char-string
598        escaped #\Null " "))))
599
600 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database db-type)
601   (declare (ignore database db-type))
602   (if (keywordp val)
603       (symbol-name val)
604       (if val
605           (concatenate 'string
606                        (package-name (symbol-package val))
607                        "::"
608                        (symbol-name val))
609           "")))
610
611 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database db-type)
612   (declare (ignore database db-type))
613   (if val
614       (symbol-name val)
615       ""))
616
617 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database db-type)
618   (declare (ignore database db-type))
619   (progv '(*print-circle* *print-array*) '(t t)
620     (prin1-to-string val)))
621
622 (defmethod database-output-sql-as-type ((type (eql 'array)) val database db-type)
623   (declare (ignore database db-type))
624   (progv '(*print-circle* *print-array*) '(t t)
625     (prin1-to-string val)))
626
627 (defmethod database-output-sql-as-type ((type (eql 'boolean)) val database db-type)
628   (declare (ignore database db-type))
629   (if val "t" "f"))
630
631 (defmethod database-output-sql-as-type ((type (eql 'string)) val database db-type)
632   (declare (ignore database db-type))
633   val)
634
635 (defmethod database-output-sql-as-type ((type (eql 'simple-string))
636                                         val database db-type)
637   (declare (ignore database db-type))
638   val)
639
640 (defmethod database-output-sql-as-type ((type (eql 'simple-base-string))
641                                         val database db-type)
642   (declare (ignore database db-type))
643   val)
644
645 (defmethod read-sql-value (val type database db-type)
646   (declare (ignore type database db-type))
647   (read-from-string val))
648
649 (defmethod read-sql-value (val (type (eql 'string)) database db-type)
650   (declare (ignore database db-type))
651   val)
652
653 (defmethod read-sql-value (val (type (eql 'simple-string)) database db-type)
654   (declare (ignore database db-type))
655   val)
656
657 (defmethod read-sql-value (val (type (eql 'simple-base-string)) database db-type)
658   (declare (ignore database db-type))
659   val)
660
661 (defmethod read-sql-value (val (type (eql 'raw-string)) database db-type)
662   (declare (ignore database db-type))
663   val)
664
665 (defmethod read-sql-value (val (type (eql 'keyword)) database db-type)
666   (declare (ignore database db-type))
667   (when (< 0 (length val))
668     (intern (symbol-name-default-case val) 
669             (find-package '#:keyword))))
670
671 (defmethod read-sql-value (val (type (eql 'symbol)) database db-type)
672   (declare (ignore database db-type))
673   (when (< 0 (length val))
674     (unless (string= val (symbol-name-default-case "NIL"))
675       (intern (symbol-name-default-case val)
676               (symbol-package *update-context*)))))
677
678 (defmethod read-sql-value (val (type (eql 'integer)) database db-type)
679   (declare (ignore database db-type))
680   (etypecase val
681     (string
682      (unless (string-equal "NIL" val)
683        (parse-integer val)))
684     (number val)))
685
686 (defmethod read-sql-value (val (type (eql 'bigint)) database db-type)
687   (declare (ignore database db-type))
688   (etypecase val
689     (string
690      (unless (string-equal "NIL" val)
691        (parse-integer val)))
692     (number val)))
693
694 (defmethod read-sql-value (val (type (eql 'float)) database db-type)
695   (declare (ignore database db-type))
696   ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
697   (etypecase val
698     (string
699      (float (read-from-string val)))
700     (float
701      val)))
702
703 (defmethod read-sql-value (val (type (eql 'boolean)) database db-type)
704   (declare (ignore database db-type))
705   (equal "t" val))
706
707 (defmethod read-sql-value (val (type (eql 'univeral-time)) database db-type)
708   (declare (ignore database db-type))
709   (unless (eq 'NULL val)
710     (etypecase val
711       (string
712        (parse-integer val))
713       (number val))))
714
715 (defmethod read-sql-value (val (type (eql 'wall-time)) database db-type)
716   (declare (ignore database db-type))
717   (unless (eq 'NULL val)
718     (parse-timestring val)))
719
720 (defmethod read-sql-value (val (type (eql 'duration)) database db-type)
721   (declare (ignore database db-type))
722   (unless (or (eq 'NULL val)
723               (equal "NIL" val))
724     (parse-timestring val)))
725
726 ;; ------------------------------------------------------------
727 ;; Logic for 'faulting in' :join slots
728
729 ;; this works, but is inefficient requiring (+ 1 n-rows)
730 ;; SQL queries
731 #+ignore
732 (defun fault-join-target-slot (class object slot-def)
733   (let* ((res (fault-join-slot-raw class object slot-def))
734          (dbi (view-class-slot-db-info slot-def))
735          (target-name (gethash :target-slot dbi))
736          (target-class (find-class target-name)))
737     (when res
738       (mapcar (lambda (obj)
739                 (list 
740                  (car
741                   (fault-join-slot-raw 
742                    target-class
743                    obj
744                    (find target-name (class-slots (class-of obj))
745                          :key #'slot-definition-name)))
746                  obj))
747               res)
748       #+ignore ;; this doesn't work when attempting to call slot-value
749       (mapcar (lambda (obj)
750                 (cons obj (slot-value obj ts))) res))))
751
752 (defun fault-join-target-slot (class object slot-def)
753   (let* ((dbi (view-class-slot-db-info slot-def))
754          (ts (gethash :target-slot dbi))
755          (jc (gethash :join-class dbi))
756          (ts-view-table (view-table (find-class ts)))
757          (jc-view-table (view-table (find-class jc)))
758          (tdbi (view-class-slot-db-info 
759                 (find ts (class-slots (find-class jc))
760                       :key #'slot-definition-name)))
761          (retrieval (gethash :retrieval tdbi))
762          (jq (join-qualifier class object slot-def))
763          (key (slot-value object (gethash :home-key dbi))))
764     (when jq
765       (ecase retrieval
766         (:immediate
767          (let ((res
768                 (find-all (list ts) 
769                           :inner-join (sql-expression :table jc-view-table)
770                           :on (sql-operation 
771                                '==
772                                (sql-expression 
773                                 :attribute (gethash :foreign-key tdbi) 
774                                 :table ts-view-table)
775                                (sql-expression 
776                                 :attribute (gethash :home-key tdbi) 
777                                 :table jc-view-table))
778                           :where jq
779                           :result-types :auto)))
780            (mapcar #'(lambda (i)
781                        (let* ((instance (car i))
782                               (jcc (make-instance jc :view-database (view-database instance))))
783                          (setf (slot-value jcc (gethash :foreign-key dbi)) 
784                                key)
785                          (setf (slot-value jcc (gethash :home-key tdbi)) 
786                                (slot-value instance (gethash :foreign-key tdbi)))
787                       (list instance jcc)))
788                    res)))
789         (:deferred
790             ;; just fill in minimal slots
791             (mapcar
792              #'(lambda (k)
793                  (let ((instance (make-instance ts :view-database (view-database object)))
794                        (jcc (make-instance jc :view-database (view-database object)))
795                        (fk (car k)))
796                    (setf (slot-value instance (gethash :home-key tdbi)) fk)
797                    (setf (slot-value jcc (gethash :foreign-key dbi)) 
798                          key)
799                    (setf (slot-value jcc (gethash :home-key tdbi)) 
800                          fk)
801                    (list instance jcc)))
802              (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
803                      :from (sql-expression :table jc-view-table)
804                      :where jq)))))))
805
806
807 ;;; Remote Joins
808
809 (defvar *default-update-objects-max-len* nil
810   "The default value to use for the MAX-LEN keyword argument to
811   UPDATE-OBJECT-JOINS.")
812
813 (defun update-objects-joins (objects &key (slots t) (force-p t)
814                             class-name (max-len
815                             *default-update-objects-max-len*))
816   "Updates from the records of the appropriate database tables
817 the join slots specified by SLOTS in the supplied list of View
818 Class instances OBJECTS.  SLOTS is t by default which means that
819 all join slots with :retrieval :immediate are updated. CLASS-NAME
820 is used to specify the View Class of all instance in OBJECTS and
821 default to nil which means that the class of the first instance
822 in OBJECTS is used. FORCE-P is t by default which means that all
823 join slots are updated whereas a value of nil means that only
824 unbound join slots are updated. MAX-LEN defaults to
825 *DEFAULT-UPDATE-OBJECTS-MAX-LEN* and when non-nil specifies that
826 UPDATE-OBJECT-JOINS may issue multiple database queries with a
827 maximum of MAX-LEN instances updated in each query."
828   (assert (or (null max-len) (plusp max-len)))
829   (when objects
830     (unless class-name
831       (setq class-name (class-name (class-of (first objects)))))
832     (let* ((class (find-class class-name))
833            (class-slots (ordered-class-slots class))
834            (slotdefs 
835             (if (eq t slots)
836                 (generate-retrieval-joins-list class :deferred)
837               (remove-if #'null
838                          (mapcar #'(lambda (name)
839                                      (let ((slotdef (find name class-slots :key #'slot-definition-name)))
840                                        (unless slotdef
841                                          (warn "Unable to find slot named ~S in class ~S." name class))
842                                        slotdef))
843                                  slots)))))
844       (dolist (slotdef slotdefs)
845         (let* ((dbi (view-class-slot-db-info slotdef))
846                (slotdef-name (slot-definition-name slotdef))
847                (foreign-key (gethash :foreign-key dbi))
848                (home-key (gethash :home-key dbi))
849                (object-keys
850                 (remove-duplicates
851                  (if force-p
852                      (mapcar #'(lambda (o) (slot-value o home-key)) objects)
853                    (remove-if #'null
854                               (mapcar
855                                #'(lambda (o) (if (slot-boundp o slotdef-name)
856                                                  nil
857                                                (slot-value o home-key)))
858                                objects)))))
859                (n-object-keys (length object-keys))
860                (query-len (or max-len n-object-keys)))
861           
862           (do ((i 0 (+ i query-len)))
863               ((>= i n-object-keys))
864             (let* ((keys (if max-len
865                              (subseq object-keys i (min (+ i query-len) n-object-keys))
866                            object-keys))
867                    (results (find-all (list (gethash :join-class dbi))
868                                       :where (make-instance 'sql-relational-exp
869                                                :operator 'in
870                                                :sub-expressions (list (sql-expression :attribute foreign-key)
871                                                                       keys))
872                                       :result-types :auto
873                                       :flatp t)))
874               (dolist (object objects)
875                 (when (or force-p (not (slot-boundp object slotdef-name)))
876                   (let ((res (find (slot-value object home-key) results 
877                                    :key #'(lambda (res) (slot-value res foreign-key))
878                                    :test #'equal)))
879                     (when res
880                       (setf (slot-value object slotdef-name) res)))))))))))
881   (values))
882   
883 (defun fault-join-slot-raw (class object slot-def)
884   (let* ((dbi (view-class-slot-db-info slot-def))
885          (jc (gethash :join-class dbi)))
886     (let ((jq (join-qualifier class object slot-def)))
887       (when jq 
888         (select jc :where jq :flatp t :result-types nil)))))
889
890 (defun fault-join-slot (class object slot-def)
891   (let* ((dbi (view-class-slot-db-info slot-def))
892          (ts (gethash :target-slot dbi)))
893     (if (and ts (gethash :set dbi))
894         (fault-join-target-slot class object slot-def)
895         (let ((res (fault-join-slot-raw class object slot-def)))
896           (when res
897             (cond
898               ((and ts (not (gethash :set dbi)))
899                (mapcar (lambda (obj) (slot-value obj ts)) res))
900               ((and (not ts) (not (gethash :set dbi)))
901                (car res))
902               ((and (not ts) (gethash :set dbi))
903                res)))))))
904
905 (defun join-qualifier (class object slot-def)
906     (declare (ignore class))
907     (let* ((dbi (view-class-slot-db-info slot-def))
908            (jc (find-class (gethash :join-class dbi)))
909            ;;(ts (gethash :target-slot dbi))
910            ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
911            (foreign-keys (gethash :foreign-key dbi))
912            (home-keys (gethash :home-key dbi)))
913       (when (every #'(lambda (slt)
914                        (and (slot-boundp object slt)
915                             (not (null (slot-value object slt)))))
916                    (if (listp home-keys) home-keys (list home-keys)))
917         (let ((jc
918                (mapcar #'(lambda (hk fk)
919                            (let ((fksd (slotdef-for-slot-with-class fk jc)))
920                              (sql-operation '==
921                                             (typecase fk
922                                               (symbol
923                                                (sql-expression
924                                                 :attribute
925                                                 (view-class-slot-column fksd)
926                                                 :table (view-table jc)))
927                                               (t fk))
928                                             (typecase hk
929                                               (symbol
930                                                (slot-value object hk))
931                                               (t
932                                                hk)))))
933                        (if (listp home-keys)
934                            home-keys
935                            (list home-keys))
936                        (if (listp foreign-keys)
937                            foreign-keys
938                            (list foreign-keys)))))
939           (when jc
940             (if (> (length jc) 1)
941                 (apply #'sql-and jc)
942                 jc))))))
943
944 ;; FIXME: add retrieval immediate for efficiency
945 ;; For example, for (select 'employee-address) in test suite =>
946 ;; select addr.*,ea_join.* FROM addr,ea_join WHERE ea_join.aaddressid=addr.addressid\g
947
948 (defun build-objects (vals sclasses immediate-join-classes sels immediate-joins database refresh flatp instances)
949   "Used by find-all to build objects."
950   (labels ((build-object (vals vclass jclasses selects immediate-selects instance)
951              (let* ((db-vals (butlast vals (- (list-length vals)
952                                               (list-length selects))))
953                     (obj (if instance instance (make-instance (class-name vclass) :view-database database)))
954                     (join-vals (subseq vals (list-length selects)))
955                     (joins (mapcar #'(lambda (c) (when c (make-instance c :view-database database)))
956                                    jclasses)))
957                ;;(format t "db-vals: ~S, join-values: ~S~%" db-vals join-vals)
958                ;; use refresh keyword here 
959                (setf obj (get-slot-values-from-view obj (mapcar #'car selects) db-vals))
960                (mapc #'(lambda (jc) (get-slot-values-from-view jc (mapcar #'car immediate-selects) join-vals))
961                      joins)
962                (mapc
963                 #'(lambda (jc) 
964                     (let ((slot (find (class-name (class-of jc)) (class-slots vclass) 
965                                       :key #'(lambda (slot) 
966                                                (when (and (eq :join (view-class-slot-db-kind slot))
967                                                           (eq (slot-definition-name slot)
968                                                               (gethash :join-class (view-class-slot-db-info slot))))
969                                                  (slot-definition-name slot))))))
970                       (when slot
971                         (setf (slot-value obj (slot-definition-name slot)) jc))))
972                 joins)
973                (when refresh (instance-refreshed obj))
974                obj)))
975     (let* ((objects
976             (mapcar #'(lambda (sclass jclass sel immediate-join instance) 
977                         (prog1
978                             (build-object vals sclass jclass sel immediate-join instance)
979                           (setf vals (nthcdr (+ (list-length sel) (list-length immediate-join))
980                                              vals))))
981                     sclasses immediate-join-classes sels immediate-joins instances)))
982       (if (and flatp (= (length sclasses) 1))
983           (car objects)
984         objects))))
985
986 (defun find-all (view-classes 
987                  &rest args
988                  &key all set-operation distinct from where group-by having 
989                       order-by offset limit refresh flatp result-types 
990                       inner-join on 
991                       (database *default-database*)
992                       instances)
993   "Called by SELECT to generate object query results when the
994   View Classes VIEW-CLASSES are passed as arguments to SELECT."
995   (declare (ignore all set-operation group-by having offset limit inner-join on)
996            (optimize (debug 3) (speed 1)))
997   (labels ((ref-equal (ref1 ref2)
998              (equal (sql ref1)
999                     (sql ref2)))
1000            (table-sql-expr (table)
1001              (sql-expression :table (view-table table)))
1002            (tables-equal (table-a table-b)
1003              (when (and table-a table-b)
1004                (string= (string (slot-value table-a 'name))
1005                         (string (slot-value table-b 'name))))))
1006     (remf args :from)
1007     (remf args :where)
1008     (remf args :flatp)
1009     (remf args :additional-fields)
1010     (remf args :result-types)
1011     (remf args :instances)
1012     (let* ((*db-deserializing* t)
1013            (sclasses (mapcar #'find-class view-classes))
1014            (immediate-join-slots 
1015             (mapcar #'(lambda (c) (generate-retrieval-joins-list c :immediate)) sclasses))
1016            (immediate-join-classes
1017             (mapcar #'(lambda (jcs)
1018                         (mapcar #'(lambda (slotdef)
1019                                     (find-class (gethash :join-class (view-class-slot-db-info slotdef))))
1020                                 jcs))
1021                     immediate-join-slots))
1022            (immediate-join-sels (mapcar #'generate-immediate-joins-selection-list sclasses))
1023            (sels (mapcar #'generate-selection-list sclasses))
1024            (fullsels (apply #'append (mapcar #'append sels immediate-join-sels)))
1025            (sel-tables (collect-table-refs where))
1026            (tables (remove-if #'null
1027                               (remove-duplicates (append (mapcar #'table-sql-expr sclasses)
1028                                                          (mapcar #'(lambda (jcs)
1029                                                                      (mapcan #'(lambda (jc)
1030                                                                                  (when jc (table-sql-expr jc)))
1031                                                                              jcs))
1032                                                                  immediate-join-classes)
1033                                                          sel-tables)
1034                                                  :test #'tables-equal)))
1035            (order-by-slots (mapcar #'(lambda (ob) (if (atom ob) ob (car ob)))
1036                                    (listify order-by))))
1037                                  
1038       (dolist (ob order-by-slots)
1039         (when (and ob (not (member ob (mapcar #'cdr fullsels)
1040                                    :test #'ref-equal)))
1041           (setq fullsels 
1042             (append fullsels (mapcar #'(lambda (att) (cons nil att))
1043                                      order-by-slots)))))
1044       (dolist (ob (listify distinct))
1045         (when (and (typep ob 'sql-ident) 
1046                    (not (member ob (mapcar #'cdr fullsels) 
1047                                 :test #'ref-equal)))
1048           (setq fullsels 
1049               (append fullsels (mapcar #'(lambda (att) (cons nil att))
1050                                        (listify ob))))))
1051       (mapcar #'(lambda (vclass jclasses jslots)
1052                   (when jclasses
1053                     (mapcar
1054                      #'(lambda (jclass jslot)
1055                          (let ((dbi (view-class-slot-db-info jslot)))
1056                            (setq where
1057                                  (append
1058                                   (list (sql-operation '==
1059                                                       (sql-expression
1060                                                        :attribute (gethash :foreign-key dbi)
1061                                                        :table (view-table jclass))
1062                                                       (sql-expression
1063                                                        :attribute (gethash :home-key dbi)
1064                                                        :table (view-table vclass))))
1065                                   (when where (listify where))))))
1066                      jclasses jslots)))
1067               sclasses immediate-join-classes immediate-join-slots)
1068       (let* ((rows (apply #'select 
1069                           (append (mapcar #'cdr fullsels)
1070                                   (cons :from 
1071                                         (list (append (when from (listify from)) 
1072                                                       (listify tables)))) 
1073                                   (list :result-types result-types)
1074                                   (when where (list :where where))
1075                                   args)))
1076              (instances-to-add (- (length rows) (length instances)))
1077              (perhaps-extended-instances
1078               (if (plusp instances-to-add)
1079                   (append instances (do ((i 0 (1+ i))
1080                                          (res nil))
1081                                         ((= i instances-to-add) res)
1082                                       (push (make-list (length sclasses) :initial-element nil) res)))
1083                 instances))
1084              (objects (mapcar 
1085                        #'(lambda (row instance)
1086                            (build-objects row sclasses immediate-join-classes sels
1087                                           immediate-join-sels database refresh flatp 
1088                                           (if (and flatp (atom instance))
1089                                               (list instance)
1090                                             instance)))
1091                        rows perhaps-extended-instances)))
1092         objects))))
1093
1094 (defmethod instance-refreshed ((instance standard-db-object)))
1095
1096 (defun select (&rest select-all-args) 
1097    "Executes a query on DATABASE, which has a default value of
1098 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
1099 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
1100 argument can be used to generate queries in both functional and
1101 object oriented contexts. 
1102
1103 In the functional case, the required arguments specify the
1104 columns selected by the query and may be symbolic SQL expressions
1105 or strings representing attribute identifiers. Type modified
1106 identifiers indicate that the values selected from the specified
1107 column are converted to the specified lisp type. The keyword
1108 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
1109 SET-OPERATION and WHERE are used to specify, using the symbolic
1110 SQL syntax, the corresponding components of the SQL query
1111 generated by the call to SELECT. RESULT-TYPES is a list of
1112 symbols which specifies the lisp type for each field returned by
1113 the query. If RESULT-TYPES is nil all results are returned as
1114 strings whereas the default value of :auto means that the lisp
1115 types are automatically computed for each field. FIELD-NAMES is t
1116 by default which means that the second value returned is a list
1117 of strings representing the columns selected by the query. If
1118 FIELD-NAMES is nil, the list of column names is not returned as a
1119 second value. 
1120
1121 In the object oriented case, the required arguments to SELECT are
1122 symbols denoting View Classes which specify the database tables
1123 to query. In this case, SELECT returns a list of View Class
1124 instances whose slots are set from the attribute values of the
1125 records in the specified table. Slot-value is a legal operator
1126 which can be employed as part of the symbolic SQL syntax used in
1127 the WHERE keyword argument to SELECT. REFRESH is nil by default
1128 which means that the View Class instances returned are retrieved
1129 from a cache if an equivalent call to SELECT has previously been
1130 issued. If REFRESH is true, the View Class instances returned are
1131 updated as necessary from the database and the generic function
1132 INSTANCE-REFRESHED is called to perform any necessary operations
1133 on the updated instances.
1134
1135 In both object oriented and functional contexts, FLATP has a
1136 default value of nil which means that the results are returned as
1137 a list of lists. If FLATP is t and only one result is returned
1138 for each record selected in the query, the results are returned
1139 as elements of a list."
1140
1141   (flet ((select-objects (target-args)
1142            (and target-args
1143                 (every #'(lambda (arg)
1144                            (and (symbolp arg)
1145                                 (find-class arg nil)))
1146                        target-args))))
1147     (multiple-value-bind (target-args qualifier-args)
1148         (query-get-selections select-all-args)
1149       (unless (or *default-database* (getf qualifier-args :database))
1150         (signal-no-database-error nil))
1151    
1152         (cond
1153           ((select-objects target-args)
1154            (let ((caching (getf qualifier-args :caching t))
1155                  (result-types (getf qualifier-args :result-types :auto))
1156                  (refresh (getf qualifier-args :refresh nil))
1157                  (database (or (getf qualifier-args :database) *default-database*))
1158                  (order-by (getf qualifier-args :order-by)))
1159              (remf qualifier-args :caching)
1160              (remf qualifier-args :refresh)
1161              (remf qualifier-args :result-types)
1162              
1163              
1164              ;; Add explicity table name to order-by if not specified and only
1165              ;; one selected table. This is required so FIND-ALL won't duplicate
1166              ;; the field
1167              (when (and order-by (= 1 (length target-args)))
1168                (let ((table-name  (view-table (find-class (car target-args))))
1169                      (order-by-list (copy-seq (listify order-by))))
1170                  
1171                  (loop for i from 0 below (length order-by-list)
1172                      do (etypecase (nth i order-by-list)
1173                           (sql-ident-attribute
1174                            (unless (slot-value (nth i order-by-list) 'qualifier)
1175                              (setf (slot-value (nth i order-by-list) 'qualifier) table-name)))
1176                           (cons
1177                            (unless (slot-value (car (nth i order-by-list)) 'qualifier)
1178                              (setf (slot-value (car (nth i order-by-list)) 'qualifier) table-name)))))
1179                  (setf (getf qualifier-args :order-by) order-by-list)))
1180         
1181              (cond
1182                ((null caching)
1183                 (apply #'find-all target-args
1184                        (append qualifier-args (list :result-types result-types))))
1185                (t
1186                 (let ((cached (records-cache-results target-args qualifier-args database)))
1187                   (cond
1188                     ((and cached (not refresh))
1189                      cached)
1190                     ((and cached refresh)
1191                      (let ((results (apply #'find-all (append (list target-args) qualifier-args `(:instances ,cached :result-types :auto)))))
1192                        (setf (records-cache-results target-args qualifier-args database) results)
1193                        results))
1194                     (t
1195                      (let ((results (apply #'find-all target-args (append qualifier-args
1196                                                                           '(:result-types :auto)))))
1197                        (setf (records-cache-results target-args qualifier-args database) results)
1198                        results))))))))
1199           (t
1200            (let* ((expr (apply #'make-query select-all-args))
1201                   (specified-types
1202                    (mapcar #'(lambda (attrib)
1203                                (if (typep attrib 'sql-ident-attribute)
1204                                    (let ((type (slot-value attrib 'type)))
1205                                      (if type
1206                                          type
1207                                          t))
1208                                    t))
1209                            (slot-value expr 'selections))))
1210              (destructuring-bind (&key (flatp nil)
1211                                        (result-types :auto)
1212                                        (field-names t) 
1213                                        (database *default-database*)
1214                                        &allow-other-keys)
1215                  qualifier-args
1216                (query expr :flatp flatp 
1217                       :result-types 
1218                       ;; specifying a type for an attribute overrides result-types
1219                       (if (some #'(lambda (x) (not (eq t x))) specified-types) 
1220                           specified-types
1221                           result-types)
1222                       :field-names field-names
1223                       :database database))))))))
1224
1225 (defun compute-records-cache-key (targets qualifiers)
1226   (list targets
1227         (do ((args *select-arguments* (cdr args))
1228              (results nil))
1229             ((null args) results)
1230           (let* ((arg (car args))
1231                  (value (getf qualifiers arg)))
1232             (when value
1233               (push (list arg
1234                           (typecase value
1235                             (cons (cons (sql (car value)) (cdr value)))
1236                             (%sql-expression (sql value))
1237                             (t value)))
1238                     results))))))
1239
1240 (defun records-cache-results (targets qualifiers database)
1241   (when (record-caches database)
1242     (gethash (compute-records-cache-key targets qualifiers) (record-caches database)))) 
1243
1244 (defun (setf records-cache-results) (results targets qualifiers database)
1245   (unless (record-caches database)
1246     (setf (record-caches database)
1247           (make-hash-table :test 'equal
1248                            #+allegro :values #+allegro :weak)))
1249   (setf (gethash (compute-records-cache-key targets qualifiers)
1250                  (record-caches database)) results)
1251   results)
1252
1253 (defun update-cached-results (targets qualifiers database)
1254   ;; FIXME: this routine will need to update slots in cached objects, perhaps adding or removing objects from cached
1255   ;; for now, dump cache entry and perform fresh search
1256   (let ((res (apply #'find-all targets qualifiers)))
1257     (setf (gethash (compute-records-cache-key targets qualifiers)
1258                    (record-caches database)) res)
1259     res))
1260