r9442: * sql/objects.lisp: Add database type to default database-get-type...
[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)) 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           ((null value)
296            (update-slot-with-null instance slot-name slotdef))
297           ((typep slot-reader 'string)
298            (setf (slot-value instance slot-name)
299                  (format nil slot-reader value)))
300           ((typep slot-reader 'function)
301            (setf (slot-value instance slot-name)
302                  (apply slot-reader (list value))))
303           (t
304            (error "Slot reader is of an unusual type.")))))
305
306 (defmethod key-value-from-db (slotdef value database) 
307   (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
308   (let ((slot-reader (view-class-slot-db-reader slotdef))
309         (slot-type (specified-type slotdef)))
310     (cond ((and value (null slot-reader))
311            (read-sql-value value (delistify slot-type) database))
312           ((null value)
313            nil)
314           ((typep slot-reader 'string)
315            (format nil slot-reader value))
316           ((typep slot-reader 'function)
317            (apply slot-reader (list value)))
318           (t
319            (error "Slot reader is of an unusual type.")))))
320
321 (defun db-value-from-slot (slotdef val database)
322   (let ((dbwriter (view-class-slot-db-writer slotdef))
323         (dbtype (specified-type slotdef)))
324     (typecase dbwriter
325       (string (format nil dbwriter val))
326       (function (apply dbwriter (list val)))
327       (t
328        (typecase dbtype
329          (cons
330           (database-output-sql-as-type (car dbtype) val database))
331          (t
332           (database-output-sql-as-type dbtype val database)))))))
333
334 (defun check-slot-type (slotdef val)
335   (let* ((slot-type (specified-type slotdef))
336          (basetype (if (listp slot-type) (car slot-type) slot-type)))
337     (when (and slot-type val)
338       (unless (typep val basetype)
339         (error 'sql-user-error
340                :message
341                (format nil "Invalid value ~A in slot ~A, not of type ~A."
342                        val (slot-definition-name slotdef) slot-type))))))
343
344 ;;
345 ;; Called by find-all
346 ;;
347
348 (defmethod get-slot-values-from-view (obj slotdeflist values)
349     (flet ((update-slot (slot-def values)
350              (update-slot-from-db obj slot-def values)))
351       (mapc #'update-slot slotdeflist values)
352       obj))
353
354 (defmethod update-record-from-slot ((obj standard-db-object) slot &key
355                                     (database *default-database*))
356   (let* ((database (or (view-database obj) database))
357          (vct (view-table (class-of obj)))
358          (sd (slotdef-for-slot-with-class slot (class-of obj))))
359     (check-slot-type sd (slot-value obj slot))
360     (let* ((att (view-class-slot-column sd))
361            (val (db-value-from-slot sd (slot-value obj slot) database)))
362       (cond ((and vct sd (view-database obj))
363              (update-records (sql-expression :table vct)
364                              :attributes (list (sql-expression :attribute att))
365                              :values (list val)
366                              :where (key-qualifier-for-instance
367                                      obj :database database)
368                              :database database))
369             ((and vct sd (not (view-database obj)))
370              (insert-records :into (sql-expression :table vct)
371                              :attributes (list (sql-expression :attribute att))
372                              :values (list val)
373                              :database database)
374              (setf (slot-value obj 'view-database) database))
375             (t
376              (error "Unable to update record.")))))
377   (values))
378
379 (defmethod update-record-from-slots ((obj standard-db-object) slots &key
380                                      (database *default-database*))
381   (let* ((database (or (view-database obj) database))
382          (vct (view-table (class-of obj)))
383          (sds (slotdefs-for-slots-with-class slots (class-of obj)))
384          (avps (mapcar #'(lambda (s)
385                            (let ((val (slot-value
386                                        obj (slot-definition-name s))))
387                              (check-slot-type s val)
388                              (list (sql-expression
389                                     :attribute (view-class-slot-column s))
390                                    (db-value-from-slot s val database))))
391                        sds)))
392     (cond ((and avps (view-database obj))
393            (update-records (sql-expression :table vct)
394                            :av-pairs avps
395                            :where (key-qualifier-for-instance
396                                    obj :database database)
397                            :database database))
398           ((and avps (not (view-database obj)))
399            (insert-records :into (sql-expression :table vct)
400                            :av-pairs avps
401                            :database database)
402            (setf (slot-value obj 'view-database) database))
403           (t
404            (error "Unable to update records"))))
405   (values))
406
407 (defmethod update-records-from-instance ((obj standard-db-object)
408                                          &key (database *default-database*))
409   (let ((database (or (view-database obj) database)))
410     (labels ((slot-storedp (slot)
411                (and (member (view-class-slot-db-kind slot) '(:base :key))
412                     (slot-boundp obj (slot-definition-name slot))))
413              (slot-value-list (slot)
414                (let ((value (slot-value obj (slot-definition-name slot))))
415                  (check-slot-type slot value)
416                  (list (sql-expression :attribute (view-class-slot-column slot))
417                        (db-value-from-slot slot value database)))))
418       (let* ((view-class (class-of obj))
419              (view-class-table (view-table view-class))
420              (slots (remove-if-not #'slot-storedp 
421                                    (ordered-class-slots view-class)))
422              (record-values (mapcar #'slot-value-list slots)))
423         (unless record-values
424           (error "No settable slots."))
425         (if (view-database obj)
426             (update-records (sql-expression :table view-class-table)
427                             :av-pairs record-values
428                             :where (key-qualifier-for-instance
429                                     obj :database database)
430                             :database database)
431             (progn
432               (insert-records :into (sql-expression :table view-class-table)
433                               :av-pairs record-values
434                               :database database)
435               (setf (slot-value obj 'view-database) database))))))
436   (values))
437
438 (defmethod delete-instance-records ((instance standard-db-object))
439   (let ((vt (sql-expression :table (view-table (class-of instance))))
440         (vd (view-database instance)))
441     (if vd
442         (let ((qualifier (key-qualifier-for-instance instance :database vd)))
443           (delete-records :from vt :where qualifier :database vd)
444           (setf (slot-value instance 'view-database) nil))
445         (signal-no-database-error vd))))
446
447 (defmethod update-instance-from-records ((instance standard-db-object)
448                                          &key (database *default-database*))
449   (let* ((view-class (find-class (class-name (class-of instance))))
450          (view-table (sql-expression :table (view-table view-class)))
451          (vd (or (view-database instance) database))
452          (view-qual (key-qualifier-for-instance instance :database vd))
453          (sels (generate-selection-list view-class))
454          (res (apply #'select (append (mapcar #'cdr sels)
455                                       (list :from  view-table
456                                             :where view-qual)
457                                       (list :result-types nil)))))
458     (when res
459       (get-slot-values-from-view instance (mapcar #'car sels) (car res)))))
460
461 (defmethod update-slot-from-record ((instance standard-db-object)
462                                     slot &key (database *default-database*))
463   (let* ((view-class (find-class (class-name (class-of instance))))
464          (view-table (sql-expression :table (view-table view-class)))
465          (vd (or (view-database instance) database))
466          (view-qual (key-qualifier-for-instance instance :database vd))
467          (slot-def (slotdef-for-slot-with-class slot view-class))
468          (att-ref (generate-attribute-reference view-class slot-def))
469          (res (select att-ref :from  view-table :where view-qual
470                       :result-types nil)))
471     (when res 
472       (get-slot-values-from-view instance (list slot-def) (car res)))))
473
474
475 (defmethod update-slot-with-null ((object standard-db-object)
476                                   slotname
477                                   slotdef)
478   (setf (slot-value object slotname) (slot-value slotdef 'void-value)))
479
480 (defvar +no-slot-value+ '+no-slot-value+)
481
482 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
483   (let* ((class (find-class classname))
484          (sld (slotdef-for-slot-with-class slot class)))
485     (if sld
486         (if (eq value +no-slot-value+)
487             (sql-expression :attribute (view-class-slot-column sld)
488                             :table (view-table class))
489             (db-value-from-slot
490              sld
491              value
492              database))
493         (error "Unknown slot ~A for class ~A" slot classname))))
494
495 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
496         (declare (ignore database))
497         (let* ((class (find-class classname)))
498           (unless (view-table class)
499             (error "No view-table for class ~A"  classname))
500           (sql-expression :table (view-table class))))
501
502 (defmethod database-get-type-specifier (type args (database database))
503   (declare (ignore type args))
504   (if (in (database-underlying-type database)
505                           :postgresql :postgresql-socket)
506           "VARCHAR"
507           "VARCHAR(255)"))
508
509 (defmethod database-get-type-specifier ((type (eql 'integer)) args database)
510   (declare (ignore database))
511   ;;"INT8")
512   (if args
513       (format nil "INT(~A)" (car args))
514       "INT"))
515
516 (deftype bigint () 
517   "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
518   'integer)
519
520 (defmethod database-get-type-specifier ((type (eql 'bigint)) args database)
521   (declare (ignore args database))
522   "BIGINT")
523               
524 (defmethod database-get-type-specifier ((type (eql 'simple-base-string)) args
525                                         database)
526   (if args
527       (format nil "VARCHAR(~A)" (car args))
528     (if (in (database-underlying-type database) 
529                             :postgresql :postgresql-socket)
530         "VARCHAR"
531       "VARCHAR(255)")))
532
533 (defmethod database-get-type-specifier ((type (eql 'simple-string)) args
534                                         database)
535   (if args
536       (format nil "VARCHAR(~A)" (car args))
537     (if (in (database-underlying-type database) 
538                             :postgresql :postgresql-socket)
539         "VARCHAR"
540       "VARCHAR(255)")))
541
542 (defmethod database-get-type-specifier ((type (eql 'string)) args database)
543   (if args
544       (format nil "VARCHAR(~A)" (car args))
545     (if (in (database-underlying-type database) 
546                             :postgresql :postgresql-socket)
547         "VARCHAR"
548       "VARCHAR(255)")))
549
550 (deftype universal-time () 
551   "A positive integer as returned by GET-UNIVERSAL-TIME."
552   '(integer 1 *))
553
554 (defmethod database-get-type-specifier ((type (eql 'universal-time)) args database)
555   (declare (ignore args database))
556   "BIGINT")
557
558 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database)
559   (declare (ignore args))
560   (case (database-underlying-type database)
561     ((:postgresql :postgresql-socket)
562      "TIMESTAMP WITHOUT TIME ZONE")
563     (:mysql
564      "DATETIME")
565     (t "TIMESTAMP")))
566
567 (defmethod database-get-type-specifier ((type (eql 'duration)) args database)
568   (declare (ignore database args))
569   "VARCHAR")
570
571 (defmethod database-get-type-specifier ((type (eql 'money)) args database)
572   (declare (ignore database args))
573   "INT8")
574
575 (deftype raw-string (&optional len)
576   "A string which is not trimmed when retrieved from the database"
577   `(string ,len))
578
579 (defmethod database-get-type-specifier ((type (eql 'raw-string)) args database)
580   (declare (ignore database))
581   (if args
582       (format nil "VARCHAR(~A)" (car args))
583       "VARCHAR"))
584
585 (defmethod database-get-type-specifier ((type (eql 'float)) args database)
586   (declare (ignore database))
587   (if args
588       (format nil "FLOAT(~A)" (car args))
589       "FLOAT"))
590
591 (defmethod database-get-type-specifier ((type (eql 'long-float)) args database)
592   (declare (ignore database))
593   (if args
594       (format nil "FLOAT(~A)" (car args))
595       "FLOAT"))
596
597 (defmethod database-get-type-specifier ((type (eql 'boolean)) args database)
598   (declare (ignore args database))
599   "BOOL")
600
601 (defmethod database-output-sql-as-type (type val database)
602   (declare (ignore type database))
603   val)
604
605 (defmethod database-output-sql-as-type ((type (eql 'list)) val database)
606   (declare (ignore database))
607   (progv '(*print-circle* *print-array*) '(t t)
608     (let ((escaped (prin1-to-string val)))
609       (substitute-char-string
610        escaped #\Null " "))))
611
612 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database)
613   (declare (ignore database))
614   (if (keywordp val)
615       (symbol-name val)
616       (if val
617           (concatenate 'string
618                        (package-name (symbol-package val))
619                        "::"
620                        (symbol-name val))
621           "")))
622
623 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database)
624   (declare (ignore database))
625   (if val
626       (symbol-name val)
627       ""))
628
629 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database)
630   (declare (ignore database))
631   (progv '(*print-circle* *print-array*) '(t t)
632     (prin1-to-string val)))
633
634 (defmethod database-output-sql-as-type ((type (eql 'array)) val database)
635   (declare (ignore database))
636   (progv '(*print-circle* *print-array*) '(t t)
637     (prin1-to-string val)))
638
639 (defmethod database-output-sql-as-type ((type (eql 'boolean)) val database)
640   (case (database-underlying-type database)
641     (:mysql
642      (if val 1 0))
643     (t
644      (if val "t" "f"))))
645
646 (defmethod database-output-sql-as-type ((type (eql 'string)) val database)
647   (declare (ignore database))
648   val)
649
650 (defmethod database-output-sql-as-type ((type (eql 'simple-string))
651                                         val database)
652   (declare (ignore database))
653   val)
654
655 (defmethod database-output-sql-as-type ((type (eql 'simple-base-string))
656                                         val database)
657   (declare (ignore database))
658   val)
659
660 (defmethod read-sql-value (val type database)
661   (declare (ignore type database))
662   (read-from-string val))
663
664 (defmethod read-sql-value (val (type (eql 'string)) database)
665   (declare (ignore database))
666   val)
667
668 (defmethod read-sql-value (val (type (eql 'simple-string)) database)
669   (declare (ignore database))
670   val)
671
672 (defmethod read-sql-value (val (type (eql 'simple-base-string)) database)
673   (declare (ignore database))
674   val)
675
676 (defmethod read-sql-value (val (type (eql 'raw-string)) database)
677   (declare (ignore database))
678   val)
679
680 (defmethod read-sql-value (val (type (eql 'keyword)) database)
681   (declare (ignore database))
682   (when (< 0 (length val))
683     (intern (symbol-name-default-case val) 
684             (find-package '#:keyword))))
685
686 (defmethod read-sql-value (val (type (eql 'symbol)) database)
687   (declare (ignore database))
688   (when (< 0 (length val))
689     (unless (string= val (symbol-name-default-case "NIL"))
690       (intern (symbol-name-default-case val)
691               (symbol-package *update-context*)))))
692
693 (defmethod read-sql-value (val (type (eql 'integer)) database)
694   (declare (ignore database))
695   (etypecase val
696     (string
697      (unless (string-equal "NIL" val)
698        (parse-integer val)))
699     (number val)))
700
701 (defmethod read-sql-value (val (type (eql 'bigint)) database)
702   (declare (ignore database))
703   (etypecase val
704     (string
705      (unless (string-equal "NIL" val)
706        (parse-integer val)))
707     (number val)))
708
709 (defmethod read-sql-value (val (type (eql 'float)) database)
710   (declare (ignore database))
711   ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
712   (etypecase val
713     (string
714      (float (read-from-string val)))
715     (float
716      val)))
717
718 (defmethod read-sql-value (val (type (eql 'boolean)) database)
719   (case (database-underlying-type database)
720     (:mysql
721      (etypecase val
722        (string (if (string= "0" val) nil t))
723        (integer (if (zerop val) nil t))))
724     (:postgresql
725      (if (eq :odbc (database-type database))
726          (if (string= "0" val) nil t)
727        (equal "t" val)))
728     (t
729      (equal "t" val))))
730
731 (defmethod read-sql-value (val (type (eql 'univeral-time)) database)
732   (declare (ignore database))
733   (unless (eq 'NULL val)
734     (etypecase val
735       (string
736        (parse-integer val))
737       (number val))))
738
739 (defmethod read-sql-value (val (type (eql 'wall-time)) database)
740   (declare (ignore database))
741   (unless (eq 'NULL val)
742     (parse-timestring val)))
743
744 (defmethod read-sql-value (val (type (eql 'duration)) database)
745   (declare (ignore database))
746   (unless (or (eq 'NULL val)
747               (equal "NIL" val))
748     (parse-timestring val)))
749
750 ;; ------------------------------------------------------------
751 ;; Logic for 'faulting in' :join slots
752
753 ;; this works, but is inefficient requiring (+ 1 n-rows)
754 ;; SQL queries
755 #+ignore
756 (defun fault-join-target-slot (class object slot-def)
757   (let* ((res (fault-join-slot-raw class object slot-def))
758          (dbi (view-class-slot-db-info slot-def))
759          (target-name (gethash :target-slot dbi))
760          (target-class (find-class target-name)))
761     (when res
762       (mapcar (lambda (obj)
763                 (list 
764                  (car
765                   (fault-join-slot-raw 
766                    target-class
767                    obj
768                    (find target-name (class-slots (class-of obj))
769                          :key #'slot-definition-name)))
770                  obj))
771               res)
772       #+ignore ;; this doesn't work when attempting to call slot-value
773       (mapcar (lambda (obj)
774                 (cons obj (slot-value obj ts))) res))))
775
776 (defun fault-join-target-slot (class object slot-def)
777   (let* ((dbi (view-class-slot-db-info slot-def))
778          (ts (gethash :target-slot dbi))
779          (jc (gethash :join-class dbi))
780          (ts-view-table (view-table (find-class ts)))
781          (jc-view-table (view-table (find-class jc)))
782          (tdbi (view-class-slot-db-info 
783                 (find ts (class-slots (find-class jc))
784                       :key #'slot-definition-name)))
785          (retrieval (gethash :retrieval tdbi))
786          (jq (join-qualifier class object slot-def))
787          (key (slot-value object (gethash :home-key dbi))))
788     (when jq
789       (ecase retrieval
790         (:immediate
791          (let ((res
792                 (find-all (list ts) 
793                           :inner-join (sql-expression :table jc-view-table)
794                           :on (sql-operation 
795                                '==
796                                (sql-expression 
797                                 :attribute (gethash :foreign-key tdbi) 
798                                 :table ts-view-table)
799                                (sql-expression 
800                                 :attribute (gethash :home-key tdbi) 
801                                 :table jc-view-table))
802                           :where jq
803                           :result-types :auto)))
804            (mapcar #'(lambda (i)
805                        (let* ((instance (car i))
806                               (jcc (make-instance jc :view-database (view-database instance))))
807                          (setf (slot-value jcc (gethash :foreign-key dbi)) 
808                                key)
809                          (setf (slot-value jcc (gethash :home-key tdbi)) 
810                                (slot-value instance (gethash :foreign-key tdbi)))
811                       (list instance jcc)))
812                    res)))
813         (:deferred
814             ;; just fill in minimal slots
815             (mapcar
816              #'(lambda (k)
817                  (let ((instance (make-instance ts :view-database (view-database object)))
818                        (jcc (make-instance jc :view-database (view-database object)))
819                        (fk (car k)))
820                    (setf (slot-value instance (gethash :home-key tdbi)) fk)
821                    (setf (slot-value jcc (gethash :foreign-key dbi)) 
822                          key)
823                    (setf (slot-value jcc (gethash :home-key tdbi)) 
824                          fk)
825                    (list instance jcc)))
826              (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
827                      :from (sql-expression :table jc-view-table)
828                      :where jq)))))))
829
830
831 ;;; Remote Joins
832
833 (defvar *default-update-objects-max-len* nil
834   "The default value to use for the MAX-LEN keyword argument to
835   UPDATE-OBJECT-JOINS.")
836
837 (defun update-objects-joins (objects &key (slots t) (force-p t)
838                             class-name (max-len
839                             *default-update-objects-max-len*))
840   "Updates from the records of the appropriate database tables
841 the join slots specified by SLOTS in the supplied list of View
842 Class instances OBJECTS.  SLOTS is t by default which means that
843 all join slots with :retrieval :immediate are updated. CLASS-NAME
844 is used to specify the View Class of all instance in OBJECTS and
845 default to nil which means that the class of the first instance
846 in OBJECTS is used. FORCE-P is t by default which means that all
847 join slots are updated whereas a value of nil means that only
848 unbound join slots are updated. MAX-LEN defaults to
849 *DEFAULT-UPDATE-OBJECTS-MAX-LEN* and when non-nil specifies that
850 UPDATE-OBJECT-JOINS may issue multiple database queries with a
851 maximum of MAX-LEN instances updated in each query."
852   (assert (or (null max-len) (plusp max-len)))
853   (when objects
854     (unless class-name
855       (setq class-name (class-name (class-of (first objects)))))
856     (let* ((class (find-class class-name))
857            (class-slots (ordered-class-slots class))
858            (slotdefs 
859             (if (eq t slots)
860                 (generate-retrieval-joins-list class :deferred)
861               (remove-if #'null
862                          (mapcar #'(lambda (name)
863                                      (let ((slotdef (find name class-slots :key #'slot-definition-name)))
864                                        (unless slotdef
865                                          (warn "Unable to find slot named ~S in class ~S." name class))
866                                        slotdef))
867                                  slots)))))
868       (dolist (slotdef slotdefs)
869         (let* ((dbi (view-class-slot-db-info slotdef))
870                (slotdef-name (slot-definition-name slotdef))
871                (foreign-key (gethash :foreign-key dbi))
872                (home-key (gethash :home-key dbi))
873                (object-keys
874                 (remove-duplicates
875                  (if force-p
876                      (mapcar #'(lambda (o) (slot-value o home-key)) objects)
877                    (remove-if #'null
878                               (mapcar
879                                #'(lambda (o) (if (slot-boundp o slotdef-name)
880                                                  nil
881                                                (slot-value o home-key)))
882                                objects)))))
883                (n-object-keys (length object-keys))
884                (query-len (or max-len n-object-keys)))
885           
886           (do ((i 0 (+ i query-len)))
887               ((>= i n-object-keys))
888             (let* ((keys (if max-len
889                              (subseq object-keys i (min (+ i query-len) n-object-keys))
890                            object-keys))
891                    (results (find-all (list (gethash :join-class dbi))
892                                       :where (make-instance 'sql-relational-exp
893                                                :operator 'in
894                                                :sub-expressions (list (sql-expression :attribute foreign-key)
895                                                                       keys))
896                                       :result-types :auto
897                                       :flatp t)))
898               (dolist (object objects)
899                 (when (or force-p (not (slot-boundp object slotdef-name)))
900                   (let ((res (find (slot-value object home-key) results 
901                                    :key #'(lambda (res) (slot-value res foreign-key))
902                                    :test #'equal)))
903                     (when res
904                       (setf (slot-value object slotdef-name) res)))))))))))
905   (values))
906   
907 (defun fault-join-slot-raw (class object slot-def)
908   (let* ((dbi (view-class-slot-db-info slot-def))
909          (jc (gethash :join-class dbi)))
910     (let ((jq (join-qualifier class object slot-def)))
911       (when jq 
912         (select jc :where jq :flatp t :result-types nil)))))
913
914 (defun fault-join-slot (class object slot-def)
915   (let* ((dbi (view-class-slot-db-info slot-def))
916          (ts (gethash :target-slot dbi)))
917     (if (and ts (gethash :set dbi))
918         (fault-join-target-slot class object slot-def)
919         (let ((res (fault-join-slot-raw class object slot-def)))
920           (when res
921             (cond
922               ((and ts (not (gethash :set dbi)))
923                (mapcar (lambda (obj) (slot-value obj ts)) res))
924               ((and (not ts) (not (gethash :set dbi)))
925                (car res))
926               ((and (not ts) (gethash :set dbi))
927                res)))))))
928
929 (defun join-qualifier (class object slot-def)
930     (declare (ignore class))
931     (let* ((dbi (view-class-slot-db-info slot-def))
932            (jc (find-class (gethash :join-class dbi)))
933            ;;(ts (gethash :target-slot dbi))
934            ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
935            (foreign-keys (gethash :foreign-key dbi))
936            (home-keys (gethash :home-key dbi)))
937       (when (every #'(lambda (slt)
938                        (and (slot-boundp object slt)
939                             (not (null (slot-value object slt)))))
940                    (if (listp home-keys) home-keys (list home-keys)))
941         (let ((jc
942                (mapcar #'(lambda (hk fk)
943                            (let ((fksd (slotdef-for-slot-with-class fk jc)))
944                              (sql-operation '==
945                                             (typecase fk
946                                               (symbol
947                                                (sql-expression
948                                                 :attribute
949                                                 (view-class-slot-column fksd)
950                                                 :table (view-table jc)))
951                                               (t fk))
952                                             (typecase hk
953                                               (symbol
954                                                (slot-value object hk))
955                                               (t
956                                                hk)))))
957                        (if (listp home-keys)
958                            home-keys
959                            (list home-keys))
960                        (if (listp foreign-keys)
961                            foreign-keys
962                            (list foreign-keys)))))
963           (when jc
964             (if (> (length jc) 1)
965                 (apply #'sql-and jc)
966                 jc))))))
967
968 ;; FIXME: add retrieval immediate for efficiency
969 ;; For example, for (select 'employee-address) in test suite =>
970 ;; select addr.*,ea_join.* FROM addr,ea_join WHERE ea_join.aaddressid=addr.addressid\g
971
972 (defun build-objects (vals sclasses immediate-join-classes sels immediate-joins database refresh flatp instances)
973   "Used by find-all to build objects."
974   (labels ((build-object (vals vclass jclasses selects immediate-selects instance)
975              (let* ((db-vals (butlast vals (- (list-length vals)
976                                               (list-length selects))))
977                     (obj (if instance instance (make-instance (class-name vclass) :view-database database)))
978                     (join-vals (subseq vals (list-length selects)))
979                     (joins (mapcar #'(lambda (c) (when c (make-instance c :view-database database)))
980                                    jclasses)))
981                ;;(format t "db-vals: ~S, join-values: ~S~%" db-vals join-vals)
982                ;; use refresh keyword here 
983                (setf obj (get-slot-values-from-view obj (mapcar #'car selects) db-vals))
984                (mapc #'(lambda (jc) (get-slot-values-from-view jc (mapcar #'car immediate-selects) join-vals))
985                      joins)
986                (mapc
987                 #'(lambda (jc) 
988                     (let ((slot (find (class-name (class-of jc)) (class-slots vclass) 
989                                       :key #'(lambda (slot) 
990                                                (when (and (eq :join (view-class-slot-db-kind slot))
991                                                           (eq (slot-definition-name slot)
992                                                               (gethash :join-class (view-class-slot-db-info slot))))
993                                                  (slot-definition-name slot))))))
994                       (when slot
995                         (setf (slot-value obj (slot-definition-name slot)) jc))))
996                 joins)
997                (when refresh (instance-refreshed obj))
998                obj)))
999     (let* ((objects
1000             (mapcar #'(lambda (sclass jclass sel immediate-join instance) 
1001                         (prog1
1002                             (build-object vals sclass jclass sel immediate-join instance)
1003                           (setf vals (nthcdr (+ (list-length sel) (list-length immediate-join))
1004                                              vals))))
1005                     sclasses immediate-join-classes sels immediate-joins instances)))
1006       (if (and flatp (= (length sclasses) 1))
1007           (car objects)
1008         objects))))
1009
1010 (defun find-all (view-classes 
1011                  &rest args
1012                  &key all set-operation distinct from where group-by having 
1013                       order-by offset limit refresh flatp result-types 
1014                       inner-join on 
1015                       (database *default-database*)
1016                       instances)
1017   "Called by SELECT to generate object query results when the
1018   View Classes VIEW-CLASSES are passed as arguments to SELECT."
1019   (declare (ignore all set-operation group-by having offset limit inner-join on)
1020            (optimize (debug 3) (speed 1)))
1021   (labels ((ref-equal (ref1 ref2)
1022              (equal (sql ref1)
1023                     (sql ref2)))
1024            (table-sql-expr (table)
1025              (sql-expression :table (view-table table)))
1026            (tables-equal (table-a table-b)
1027              (when (and table-a table-b)
1028                (string= (string (slot-value table-a 'name))
1029                         (string (slot-value table-b 'name))))))
1030     (remf args :from)
1031     (remf args :where)
1032     (remf args :flatp)
1033     (remf args :additional-fields)
1034     (remf args :result-types)
1035     (remf args :instances)
1036     (let* ((*db-deserializing* t)
1037            (sclasses (mapcar #'find-class view-classes))
1038            (immediate-join-slots 
1039             (mapcar #'(lambda (c) (generate-retrieval-joins-list c :immediate)) sclasses))
1040            (immediate-join-classes
1041             (mapcar #'(lambda (jcs)
1042                         (mapcar #'(lambda (slotdef)
1043                                     (find-class (gethash :join-class (view-class-slot-db-info slotdef))))
1044                                 jcs))
1045                     immediate-join-slots))
1046            (immediate-join-sels (mapcar #'generate-immediate-joins-selection-list sclasses))
1047            (sels (mapcar #'generate-selection-list sclasses))
1048            (fullsels (apply #'append (mapcar #'append sels immediate-join-sels)))
1049            (sel-tables (collect-table-refs where))
1050            (tables (remove-if #'null
1051                               (remove-duplicates (append (mapcar #'table-sql-expr sclasses)
1052                                                          (mapcar #'(lambda (jcs)
1053                                                                      (mapcan #'(lambda (jc)
1054                                                                                  (when jc (table-sql-expr jc)))
1055                                                                              jcs))
1056                                                                  immediate-join-classes)
1057                                                          sel-tables)
1058                                                  :test #'tables-equal)))
1059            (order-by-slots (mapcar #'(lambda (ob) (if (atom ob) ob (car ob)))
1060                                    (listify order-by))))
1061                                  
1062       (dolist (ob order-by-slots)
1063         (when (and ob (not (member ob (mapcar #'cdr fullsels)
1064                                    :test #'ref-equal)))
1065           (setq fullsels 
1066             (append fullsels (mapcar #'(lambda (att) (cons nil att))
1067                                      order-by-slots)))))
1068       (dolist (ob (listify distinct))
1069         (when (and (typep ob 'sql-ident) 
1070                    (not (member ob (mapcar #'cdr fullsels) 
1071                                 :test #'ref-equal)))
1072           (setq fullsels 
1073               (append fullsels (mapcar #'(lambda (att) (cons nil att))
1074                                        (listify ob))))))
1075       (mapcar #'(lambda (vclass jclasses jslots)
1076                   (when jclasses
1077                     (mapcar
1078                      #'(lambda (jclass jslot)
1079                          (let ((dbi (view-class-slot-db-info jslot)))
1080                            (setq where
1081                                  (append
1082                                   (list (sql-operation '==
1083                                                       (sql-expression
1084                                                        :attribute (gethash :foreign-key dbi)
1085                                                        :table (view-table jclass))
1086                                                       (sql-expression
1087                                                        :attribute (gethash :home-key dbi)
1088                                                        :table (view-table vclass))))
1089                                   (when where (listify where))))))
1090                      jclasses jslots)))
1091               sclasses immediate-join-classes immediate-join-slots)
1092       (let* ((rows (apply #'select 
1093                           (append (mapcar #'cdr fullsels)
1094                                   (cons :from 
1095                                         (list (append (when from (listify from)) 
1096                                                       (listify tables)))) 
1097                                   (list :result-types result-types)
1098                                   (when where (list :where where))
1099                                   args)))
1100              (instances-to-add (- (length rows) (length instances)))
1101              (perhaps-extended-instances
1102               (if (plusp instances-to-add)
1103                   (append instances (do ((i 0 (1+ i))
1104                                          (res nil))
1105                                         ((= i instances-to-add) res)
1106                                       (push (make-list (length sclasses) :initial-element nil) res)))
1107                 instances))
1108              (objects (mapcar 
1109                        #'(lambda (row instance)
1110                            (build-objects row sclasses immediate-join-classes sels
1111                                           immediate-join-sels database refresh flatp 
1112                                           (if (and flatp (atom instance))
1113                                               (list instance)
1114                                             instance)))
1115                        rows perhaps-extended-instances)))
1116         objects))))
1117
1118 (defmethod instance-refreshed ((instance standard-db-object)))
1119
1120 (defun select (&rest select-all-args) 
1121    "Executes a query on DATABASE, which has a default value of
1122 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
1123 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
1124 argument can be used to generate queries in both functional and
1125 object oriented contexts. 
1126
1127 In the functional case, the required arguments specify the
1128 columns selected by the query and may be symbolic SQL expressions
1129 or strings representing attribute identifiers. Type modified
1130 identifiers indicate that the values selected from the specified
1131 column are converted to the specified lisp type. The keyword
1132 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
1133 SET-OPERATION and WHERE are used to specify, using the symbolic
1134 SQL syntax, the corresponding components of the SQL query
1135 generated by the call to SELECT. RESULT-TYPES is a list of
1136 symbols which specifies the lisp type for each field returned by
1137 the query. If RESULT-TYPES is nil all results are returned as
1138 strings whereas the default value of :auto means that the lisp
1139 types are automatically computed for each field. FIELD-NAMES is t
1140 by default which means that the second value returned is a list
1141 of strings representing the columns selected by the query. If
1142 FIELD-NAMES is nil, the list of column names is not returned as a
1143 second value. 
1144
1145 In the object oriented case, the required arguments to SELECT are
1146 symbols denoting View Classes which specify the database tables
1147 to query. In this case, SELECT returns a list of View Class
1148 instances whose slots are set from the attribute values of the
1149 records in the specified table. Slot-value is a legal operator
1150 which can be employed as part of the symbolic SQL syntax used in
1151 the WHERE keyword argument to SELECT. REFRESH is nil by default
1152 which means that the View Class instances returned are retrieved
1153 from a cache if an equivalent call to SELECT has previously been
1154 issued. If REFRESH is true, the View Class instances returned are
1155 updated as necessary from the database and the generic function
1156 INSTANCE-REFRESHED is called to perform any necessary operations
1157 on the updated instances.
1158
1159 In both object oriented and functional contexts, FLATP has a
1160 default value of nil which means that the results are returned as
1161 a list of lists. If FLATP is t and only one result is returned
1162 for each record selected in the query, the results are returned
1163 as elements of a list."
1164
1165   (flet ((select-objects (target-args)
1166            (and target-args
1167                 (every #'(lambda (arg)
1168                            (and (symbolp arg)
1169                                 (find-class arg nil)))
1170                        target-args))))
1171     (multiple-value-bind (target-args qualifier-args)
1172         (query-get-selections select-all-args)
1173       (unless (or *default-database* (getf qualifier-args :database))
1174         (signal-no-database-error nil))
1175    
1176         (cond
1177           ((select-objects target-args)
1178            (let ((caching (getf qualifier-args :caching t))
1179                  (result-types (getf qualifier-args :result-types :auto))
1180                  (refresh (getf qualifier-args :refresh nil))
1181                  (database (or (getf qualifier-args :database) *default-database*))
1182                  (order-by (getf qualifier-args :order-by)))
1183              (remf qualifier-args :caching)
1184              (remf qualifier-args :refresh)
1185              (remf qualifier-args :result-types)
1186              
1187              
1188              ;; Add explicity table name to order-by if not specified and only
1189              ;; one selected table. This is required so FIND-ALL won't duplicate
1190              ;; the field
1191              (when (and order-by (= 1 (length target-args)))
1192                (let ((table-name  (view-table (find-class (car target-args))))
1193                      (order-by-list (copy-seq (listify order-by))))
1194                  
1195                  (loop for i from 0 below (length order-by-list)
1196                      do (etypecase (nth i order-by-list)
1197                           (sql-ident-attribute
1198                            (unless (slot-value (nth i order-by-list) 'qualifier)
1199                              (setf (slot-value (nth i order-by-list) 'qualifier) table-name)))
1200                           (cons
1201                            (unless (slot-value (car (nth i order-by-list)) 'qualifier)
1202                              (setf (slot-value (car (nth i order-by-list)) 'qualifier) table-name)))))
1203                  (setf (getf qualifier-args :order-by) order-by-list)))
1204         
1205              (cond
1206                ((null caching)
1207                 (apply #'find-all target-args
1208                        (append qualifier-args (list :result-types result-types))))
1209                (t
1210                 (let ((cached (records-cache-results target-args qualifier-args database)))
1211                   (cond
1212                     ((and cached (not refresh))
1213                      cached)
1214                     ((and cached refresh)
1215                      (let ((results (apply #'find-all (append (list target-args) qualifier-args `(:instances ,cached :result-types :auto)))))
1216                        (setf (records-cache-results target-args qualifier-args database) results)
1217                        results))
1218                     (t
1219                      (let ((results (apply #'find-all target-args (append qualifier-args
1220                                                                           '(:result-types :auto)))))
1221                        (setf (records-cache-results target-args qualifier-args database) results)
1222                        results))))))))
1223           (t
1224            (let* ((expr (apply #'make-query select-all-args))
1225                   (specified-types
1226                    (mapcar #'(lambda (attrib)
1227                                (if (typep attrib 'sql-ident-attribute)
1228                                    (let ((type (slot-value attrib 'type)))
1229                                      (if type
1230                                          type
1231                                          t))
1232                                    t))
1233                            (slot-value expr 'selections))))
1234              (destructuring-bind (&key (flatp nil)
1235                                        (result-types :auto)
1236                                        (field-names t) 
1237                                        (database *default-database*)
1238                                        &allow-other-keys)
1239                  qualifier-args
1240                (query expr :flatp flatp 
1241                       :result-types 
1242                       ;; specifying a type for an attribute overrides result-types
1243                       (if (some #'(lambda (x) (not (eq t x))) specified-types) 
1244                           specified-types
1245                           result-types)
1246                       :field-names field-names
1247                       :database database))))))))
1248
1249 (defun compute-records-cache-key (targets qualifiers)
1250   (list targets
1251         (do ((args *select-arguments* (cdr args))
1252              (results nil))
1253             ((null args) results)
1254           (let* ((arg (car args))
1255                  (value (getf qualifiers arg)))
1256             (when value
1257               (push (list arg
1258                           (typecase value
1259                             (cons (cons (sql (car value)) (cdr value)))
1260                             (%sql-expression (sql value))
1261                             (t value)))
1262                     results))))))
1263
1264 (defun records-cache-results (targets qualifiers database)
1265   (when (record-caches database)
1266     (gethash (compute-records-cache-key targets qualifiers) (record-caches database)))) 
1267
1268 (defun (setf records-cache-results) (results targets qualifiers database)
1269   (unless (record-caches database)
1270     (setf (record-caches database)
1271           (make-hash-table :test 'equal
1272                            #+allegro :values #+allegro :weak)))
1273   (setf (gethash (compute-records-cache-key targets qualifiers)
1274                  (record-caches database)) results)
1275   results)
1276
1277 (defun update-cached-results (targets qualifiers database)
1278   ;; FIXME: this routine will need to update slots in cached objects, perhaps adding or removing objects from cached
1279   ;; for now, dump cache entry and perform fresh search
1280   (let ((res (apply #'find-all targets qualifiers)))
1281     (setf (gethash (compute-records-cache-key targets qualifiers)
1282                    (record-caches database)) res)
1283     res))
1284