dbd5e6c5d1b2ba9db199d97f3cde08781c108969
[clsql.git] / sql / oodml.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;;
4 ;;;; The CLSQL Object Oriented Data Manipulation Language (OODML).
5 ;;;;
6 ;;;; This file is part of CLSQL.
7 ;;;;
8 ;;;; CLSQL users are granted the rights to distribute and use this software
9 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
10 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
11 ;;;; *************************************************************************
12
13 (in-package #:clsql-sys)
14
15 (defun find-normalized-key (obj)
16   "Find the first / primary key of a normalized object"
17   (find-slot-if obj #'key-slot-p T T))
18
19 (defun normalized-key-value (obj)
20   "Normalized classes share a single key for all their key slots"
21   (when (normalizedp (class-of obj))
22     (easy-slot-value obj (find-normalized-key obj))))
23
24 (defun key-qualifier-for-instance (obj &key (database *default-database*) this-class)
25   "Generate a boolean sql-expression that identifies an object by its keys"
26   (let* ((obj-class (or this-class (class-of obj)))
27          (keys (keyslots-for-class obj-class))
28          (normal-db-value (normalized-key-value obj)))
29     (when keys
30       (labels ((db-value (k)
31                  (or normal-db-value
32                      (db-value-from-slot
33                       k
34                       (easy-slot-value obj k)
35                       database)))
36                (key-equal-exp (k)
37                  (sql-operation '== (generate-attribute-reference obj-class k database)
38                                 (db-value k))))
39         (clsql-ands (mapcar #'key-equal-exp keys))))))
40
41 (defun generate-attribute-reference (vclass slotdef &optional (database *default-database*))
42   "Turns key class and slot-def into a sql-expression representing the
43    table and column it comes from
44
45    used by things like make-select-list, update-slot-from-record"
46   (when (key-or-base-slot-p slotdef)
47     (sql-expression :attribute (database-identifier slotdef database)
48                     :table (database-identifier vclass database))))
49
50 (defun get-join-slots (class &optional retrieval-method)
51   "Returns list of join slots for a class.
52
53    if a retrieval method is specified only return slots of that type
54    if the retrieval method is T, nil or :all return all join slots"
55   (assert (member retrieval-method '(nil t :all :immediate :deferred)))
56   (setf class (to-class class))
57   (let ((all? (member retrieval-method '(nil t :all))))
58     (loop for slot in (ordered-class-slots class)
59           when (and (join-slot-p slot)
60                     (or all? (eql (join-slot-retrieval-method slot) retrieval-method)))
61           collect slot)))
62
63 (defun immediate-join-slots (class)
64   (get-join-slots class :immediate))
65
66 (defmethod choose-database-for-instance ((obj standard-db-object) &optional database)
67   "Determine which database connection to use for a standard-db-object.
68         Errs if none is available."
69   (or (find-if #'(lambda (db)
70                    (and db (is-database-open db)))
71                (list (view-database obj)
72                      database
73                      *default-database*))
74       (signal-no-database-error nil)))
75
76
77
78 (defmethod update-slot-with-null ((object standard-db-object) slotdef)
79   "sets a slot to the void value of the slot-def (usually nil)"
80   (setf (easy-slot-value object slotdef)
81         (slot-value slotdef 'void-value)))
82
83 (defmethod update-slot-from-db-value ((instance standard-db-object) slotdef value)
84   "This gets a value from the database and turns it itno a lisp value
85    based on the slot's slot-db-reader or baring that read-sql-value"
86   (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
87   (let* ((slot-reader (view-class-slot-db-reader slotdef))
88          (slot-type   (specified-type slotdef)))
89     (cond
90       ((null value) (update-slot-with-null instance slotdef))
91       ((null slot-reader)
92        (setf (easy-slot-value instance slotdef)
93              (read-sql-value value (delistify slot-type)
94                              (choose-database-for-instance instance)
95                              (database-underlying-type
96                               (choose-database-for-instance instance)))))
97       (t (etypecase slot-reader
98            ((or symbol function)
99             (setf (easy-slot-value instance slotdef)
100                   (apply slot-reader (list value))))
101            (string
102             (setf (easy-slot-value instance slotdef)
103                   (format nil slot-reader value))))))))
104
105 (defmethod key-value-from-db (slotdef value database)
106   "TODO: is this deprecated? there are no uses anywhere in clsql"
107   (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
108   (let ((slot-reader (view-class-slot-db-reader slotdef))
109         (slot-type (specified-type slotdef)))
110     (cond ((and value (null slot-reader))
111            (read-sql-value value (delistify slot-type) database
112                            (database-underlying-type database)))
113           ((null value)
114            nil)
115           ((typep slot-reader 'string)
116            (format nil slot-reader value))
117           ((typep slot-reader '(or symbol function))
118            (apply slot-reader (list value)))
119           (t
120            (error "Slot reader is of an unusual type.")))))
121
122 (defun db-value-from-slot (slotdef val database)
123   (let ((dbwriter (view-class-slot-db-writer slotdef))
124         (dbtype (specified-type slotdef)))
125     (typecase dbwriter
126       (string (format nil dbwriter val))
127       ((and (or symbol function) (not null)) (apply dbwriter (list val)))
128       (t
129        (database-output-sql-as-type
130         (typecase dbtype
131           (cons (car dbtype))
132           (t dbtype))
133         val database (database-underlying-type database))))))
134
135 (defun check-slot-type (slotdef val)
136   (let* ((slot-type (specified-type slotdef))
137          (basetype (if (listp slot-type) (car slot-type) slot-type)))
138     (when (and slot-type val)
139       (unless (typep val basetype)
140         (error 'sql-user-error
141                :message
142                (format nil "Invalid value ~A in slot ~A, not of type ~A."
143                        val (slot-definition-name slotdef) slot-type))))))
144
145 (defmethod get-slot-values-from-view (obj slotdeflist values)
146   "Used to copy values from the database into the object
147    used by things like find-all and select"
148   (loop for slot in slotdeflist
149         for value in values
150         do (update-slot-from-db-value obj slot value))
151   obj)
152
153 (defclass class-and-slots ()
154   ((view-class :accessor view-class :initarg :view-class :initform nil)
155    (slot-defs :accessor slot-defs :initarg :slot-defs :initform nil))
156   (:documentation "A helper class to keep track of which slot-defs from a
157    table need to be updated, a normalized class might have many of these
158    because each of its parent classes might represent some other table and we
159    need to match which slots came from which parent class/table"))
160
161 (defun make-class-and-slots (c &optional s)
162   "Create a new class-and-slots object"
163   (make-instance 'class-and-slots :view-class c :slot-defs (listify s) ))
164
165 (defmethod view-table ((o class-and-slots))
166   "get the view-table of the view-class of o"
167   (view-table (view-class o)))
168
169 (defmethod view-table-exp ((o class-and-slots))
170   (sql-expression :table (view-table o)))
171
172 (defmethod view-table-exp ((o standard-db-class))
173   (sql-expression :table (view-table o)))
174
175 (defmethod attribute-references ((o class-and-slots))
176   "build sql-ident-attributes for a given class-and-slots"
177   (loop
178     with class = (view-class o)
179     for sd in (slot-defs o)
180     collect (generate-attribute-reference class sd)))
181
182 (defmethod attribute-value-pairs ((def class-and-slots) (o standard-db-object)
183                                   database)
184   "for a given class-and-slots and object, create the sql-expression & value pairs
185    that need to be sent to the database"
186   (loop for s in (slot-defs def)
187         for n = (to-slot-name s)
188         when (slot-boundp o n)
189         collect (make-attribute-value-pair s (slot-value o n) database)))
190
191 (defmethod view-classes-and-slots-by-name ((obj standard-db-object) slots-to-match)
192   "If it's normalized, find the class that actually contains
193    the slot that's tied to the db,
194
195    otherwise just search the current class
196   "
197   (let* ((view-class (class-of obj))
198          (normalizedp (normalizedp view-class))
199          rtns)
200     (labels ((get-c&s-obj (class)
201                (or (find class rtns :key #'view-class)
202                    (first (push (make-class-and-slots class) rtns))))
203              (associate-slot-with-class (class slot)
204                "Find the best class to associate with the slot. If it is
205                 normalized then it needs to be a direct slot otherwise it just
206                 needs to be on the class."
207                (let ((sd (find-slot-by-name class slot normalizedp nil)))
208                  (if sd
209                      ;;we found it directly or it's (not normalized)
210                      (pushnew sd (slot-defs (get-c&s-obj class)))
211                      (when normalizedp
212                        (loop for parent in (class-direct-superclasses class)
213                              until (associate-slot-with-class parent slot))))
214                  sd)))
215       (loop
216         for in-slot in (listify slots-to-match)
217         do (associate-slot-with-class view-class in-slot)))
218     rtns))
219
220 (defun update-auto-increments-keys (class obj database)
221   " handle pulling any autoincrement values into the object
222    if normalized and we now that all the "
223   (let ((pk-slots (keyslots-for-class class))
224         (table (view-table class))
225         new-pk-value)
226     (labels ((do-update (slot)
227                (when (and (null (easy-slot-value obj slot))
228                           (auto-increment-column-p slot database))
229                  (update-slot-from-db-value
230                   obj slot
231                   (or new-pk-value
232                       (setf new-pk-value
233                             (database-last-auto-increment-id
234                              database table slot))))))
235              (chain-primary-keys (in-class)
236                "This seems kindof wrong, but this is mostly how it was working, so
237                   its here to keep the normalized code path working"
238                (when (typep in-class 'standard-db-class)
239                  (loop for slot in (ordered-class-slots in-class)
240                        when (key-slot-p slot)
241                        do (do-update slot)))))
242       (loop for slot in pk-slots do (do-update slot))
243       (let ((direct-class (to-class obj)))
244         (when (and new-pk-value (normalizedp direct-class))
245           (chain-primary-keys direct-class)))
246       new-pk-value)))
247
248 (defmethod %update-instance-helper
249     (class-and-slots obj database
250      &aux (avps (attribute-value-pairs class-and-slots obj database)))
251   "A function to help us update a given table (based on class-and-slots)
252    with values from an object"
253   ;; we dont actually need to update anything on this particular
254   ;; class / parent class
255   (unless avps (return-from %update-instance-helper))
256
257   (let* ((view-class (view-class class-and-slots))
258          (table (view-table view-class))
259          (table-sql (sql-expression :table table)))
260
261     ;; view database is the flag we use to tell it was pulled from a database
262     ;; and thus probably needs an update instead of an insert
263     (cond ((view-database obj)
264            (let ((where (key-qualifier-for-instance
265                          obj :database database :this-class view-class)))
266              (unless where
267                (error "update-record-from-*: could not generate a where clause for ~a using ~A"
268                       obj view-class))
269              (update-records table-sql
270                              :av-pairs avps
271                              :where where
272                              :database database)))
273           (T ;; was not pulled from the db so insert it
274            ;; avps MUST contain any primary key slots set
275            ;; by previous inserts of the same object into different
276            ;; tables (ie: normalized stuff)
277            (insert-records :into table-sql
278                            :av-pairs avps
279                            :database database)
280            (update-auto-increments-keys view-class obj database)
281            ;; we dont set view database here, because there could be
282            ;; N of these for each call to update-record-from-* because
283            ;; of normalized classes
284            ))
285     (update-slot-default-values obj class-and-slots)))
286
287 (defmethod update-record-from-slots ((obj standard-db-object) slots
288                                      &key (database *default-database*))
289   "For a given list of slots, update all records associated with those slots
290    and classes.
291
292    Generally this will update the single record associated with this object,
293    but for normalized classes might update as many records as there are
294    inheritances "
295   (setf slots (listify slots))
296   (let* ((classes-and-slots (view-classes-and-slots-by-name obj slots))
297          (database (choose-database-for-instance obj database)))
298     (loop for class-and-slots in classes-and-slots
299           do (%update-instance-helper class-and-slots obj database))
300     (setf (slot-value obj 'view-database) database))
301   (values))
302
303 (defmethod update-record-from-slot
304     ((obj standard-db-object) slot &key (database *default-database*))
305   "just call update-records-from-slots which now handles this.
306
307    This function is only here to maintain backwards compatibility in
308    the public api"
309   (update-record-from-slots obj slot :database database))
310
311 (defmethod view-classes-and-storable-slots (class &key to-database-p)
312   "Get a list of all the tables we need to update and the slots on them
313
314    for non normalized classes we return the class and all its storable slots
315
316    for normalized classes we return a list of direct slots and the class they
317    came from for each normalized view class
318
319    to-database-p is provided so that we can read / write different data
320    to the database in different circumstances
321    (specifically clsql-helper:dirty-db-slots-mixin which only updates slots
322     that have changed )
323   "
324   (declare (ignore to-database-p))
325   (setf class (to-class class))
326   (let* (rtns)
327     (labels ((storable-slots (class)
328                (loop for sd in (slots-for-possibly-normalized-class class)
329                      when (key-or-base-slot-p sd)
330                      collect sd))
331              (get-classes-and-slots (class &aux (normalizedp (normalizedp class)))
332                (let ((slots (storable-slots class)))
333                  (when slots
334                    (push (make-class-and-slots class slots) rtns)))
335                (when normalizedp
336                  (loop for new-class in (class-direct-superclasses class)
337                        do (when (typep new-class 'standard-db-class)
338                             (get-classes-and-slots new-class))))))
339       (get-classes-and-slots class))
340     rtns))
341
342 (defmethod primary-key-slot-values ((obj standard-db-object)
343                                     &key class slots )
344   "Returns the values of all key-slots for a given class"
345   (defaulting class (class-of obj)
346               slots (keyslots-for-class class))
347   (loop for slot in slots
348         collect (easy-slot-value obj slot)))
349
350 (defmethod update-slot-default-values ((obj standard-db-object)
351                                        classes-and-slots)
352   "Makes sure that if a class has unfilled slots that claim to have a default,
353    that we retrieve those defaults from the database
354
355    TODO: use update-slots-from-record (doesnt exist) instead to batch this!"
356   (loop for class-and-slots in (listify classes-and-slots)
357         do (loop for slot in (slot-defs class-and-slots)
358                  do (when (and (slot-has-default-p slot)
359                                (not (easy-slot-value obj slot)))
360                       (update-slot-from-record obj (to-slot-name slot))))))
361
362 (defmethod update-records-from-instance ((obj standard-db-object)
363                                          &key (database *default-database*))
364   "Updates the records in the database associated with this object if
365    view-database slot on the object is nil then the object is assumed to be
366    new and is inserted"
367   (let ((database (choose-database-for-instance obj database))
368         (classes-and-slots (view-classes-and-storable-slots obj :to-database-p t)))
369     (loop for class-and-slots in classes-and-slots
370           do (%update-instance-helper class-and-slots obj database))
371     (setf (slot-value obj 'view-database) database)
372     (primary-key-slot-values obj)))
373
374 (defmethod delete-instance-records ((instance standard-db-object) &key database)
375   "Removes the records associated with a given instance
376    (as determined by key-qualifier-for-instance)
377
378    TODO: Doesnt handle normalized classes at all afaict"
379   (let ((database (choose-database-for-instance instance database))
380         (vt (sql-expression :table (view-table (class-of instance)))))
381     (if database
382         (let ((qualifier (key-qualifier-for-instance instance :database database)))
383           (delete-records :from vt :where qualifier :database database)
384           (setf (record-caches database) nil)
385           (setf (slot-value instance 'view-database) nil)
386           (values))
387         (signal-no-database-error database))))
388
389 (defmethod update-instance-from-records ((instance standard-db-object)
390                                          &key (database *default-database*))
391   "Updates a database object with the current values stored in the database
392
393    TODO: Should this update immediate join slots similar to build-objects?
394          Can we just call build-objects?, update-objects-joins?
395   "
396
397   (let* ((classes-and-slots (view-classes-and-storable-slots
398                              instance :to-database-p nil))
399          (vd (choose-database-for-instance instance database)))
400     (labels ((do-update (class-and-slots)
401                (let* ((select-list (make-select-list class-and-slots
402                                                      :do-joins-p nil
403                                                      :database database))
404                       (view-table (sql-table select-list))
405                       (view-qual (key-qualifier-for-instance
406                                   instance :database vd
407                                   :this-class (view-class select-list)))
408                       (res (when view-qual
409                              (first
410                               (apply #'select
411                                      (append (full-select-list select-list)
412                                              (list :from view-table
413                                                    :where view-qual
414                                                    :result-types nil
415                                                    :database vd)))))))
416                  (when res
417                    (setf (slot-value instance 'view-database) vd)
418                    (get-slot-values-from-view instance (slot-list select-list) res))
419                  )))
420       (loop for class-and-slots in classes-and-slots
421             do (do-update class-and-slots)))))
422
423
424 (defmethod get-slot-value-from-record ((instance standard-db-object)
425                                        slot &key (database *default-database*))
426   (let* ((class-and-slot
427            (first
428             (view-classes-and-slots-by-name instance slot)))
429          (view-class (view-class class-and-slot))
430          (slot-def (first (slot-defs class-and-slot)))
431          (vd (choose-database-for-instance instance database))
432          (att-ref (first (attribute-references class-and-slot)))
433          (res (first
434                (select att-ref
435                  :from (view-table-exp class-and-slot)
436                  :where (key-qualifier-for-instance
437                          instance
438                          :database vd
439                          :this-class view-class)
440                  :result-types nil
441                  :flatp T))))
442     (values res slot-def)))
443
444 (defmethod update-slot-from-record ((instance standard-db-object)
445                                     slot &key (database *default-database*))
446   "Pulls the value of a given slot form the database and stores that in the
447    appropriate slot on instance"
448   (multiple-value-bind (res slot-def)
449       (get-slot-value-from-record instance slot :database database)
450     (let ((vd (choose-database-for-instance instance database)))
451       (setf (slot-value instance 'view-database) vd)
452       (update-slot-from-db-value instance slot-def res))))
453
454
455 (defvar +no-slot-value+ '+no-slot-value+)
456
457 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
458         (let* ((class (find-class classname))
459                (sld (slotdef-for-slot-with-class slot class)))
460           (if sld
461               (if (eq value +no-slot-value+)
462                   (sql-expression :attribute (database-identifier sld database)
463                                   :table (view-table class))
464                   (db-value-from-slot
465                    sld
466                    value
467                    database))
468               (error "Unknown slot ~A for class ~A" slot classname))))
469
470 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
471         (declare (ignore database))
472         (let* ((class (find-class classname)))
473           (unless (view-table class)
474             (error "No view-table for class ~A"  classname))
475           (sql-expression :table (view-table class))))
476
477 (deftype tinyint ()
478   "An 8-bit integer, this width may vary by SQL implementation."
479   'integer)
480
481 (deftype smallint ()
482   "An integer smaller than a 32-bit integer. this width may vary by SQL implementation."
483   'integer)
484
485 (deftype mediumint ()
486   "An integer smaller than a 32-bit integer, but may be larger than a smallint. This width may vary by SQL implementation."
487   'integer)
488
489 (deftype bigint ()
490   "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
491   'integer)
492
493 (deftype varchar (&optional size)
494   "A variable length string for the SQL varchar type."
495   (declare (ignore size))
496   'string)
497
498 (deftype universal-time ()
499   "A positive integer as returned by GET-UNIVERSAL-TIME."
500   '(integer 1 *))
501
502 (deftype generalized-boolean ()
503   "A type which outputs a SQL boolean value, though any lisp type can be stored in the slot."
504   t)
505
506 #+ignore
507 (deftype char (&optional len)
508   "A lisp type for the SQL CHAR type."
509   `(string ,len))
510
511 (defmethod database-get-type-specifier ((type string) args database (db-type t))
512   "Pass through the literal type as defined in the type string"
513   (declare (ignore args database db-type))
514   type)
515
516
517 (defmethod database-get-type-specifier ((type symbol) args database db-type)
518   (case type
519     (char (if args
520               (format nil "CHAR(~D)" (first args))
521               "CHAR(1)"))
522     ((varchar string)
523      (if args
524          (format nil "VARCHAR(~A)" (car args))
525          (format nil "VARCHAR(~D)" *default-string-length*)))
526     ((longchar text) "text")
527     (integer (if args
528                  (format nil "INT(~A)" (car args))
529                  "INT"))
530     ((tinyint smallint mediumint) "INT")
531     ((long-float float)
532      (if args
533          (format nil "FLOAT(~A)" (car args))
534          "FLOAT"))
535     ((bigint universal-time) "BIGINT")
536     (number
537      (cond
538        ((and (consp args) (= (length args) 2))
539         (format nil "NUMBER(~D,~D)" (first args) (second args)))
540        ((and (consp args) (= (length args) 1))
541         (format nil "NUMBER(~D)" (first args)))
542        (t
543         "NUMBER")))
544     (wall-time "TIMESTAMP")
545     (date "DATE")
546     (duration "VARCHAR")
547     (money "INT8")
548     ((boolean generalized-boolean) "BOOL")
549     (t (warn "Could not determine a valid ~A type specifier for ~A ~A ~A, defaulting to VARCHAR "
550              db-type type args database)
551      (format nil "VARCHAR(~D)" *default-string-length*))))
552
553 (defmethod database-output-sql-as-type (type val database db-type)
554   (declare (ignore type database db-type))
555   val)
556
557 (defmethod database-output-sql-as-type ((type symbol) val database db-type)
558   (declare (ignore database))
559   (case type ;; booleans handle null differently
560     ((boolean generalized-boolean)
561      (case db-type
562        ;; done here so it can be done once
563        ((:mssql :mysql) (if val 1 0))
564        (otherwise (if val "t" "f"))))
565     (otherwise
566      ;; in all other cases if we have nil give everyone else a shot at it,
567      ;; which by default returns nil
568      (if (null val)
569          (call-next-method)
570          (case type
571            (symbol
572             (format nil "~A::~A"
573                     (package-name (symbol-package val))
574                     (symbol-name val)))
575            (keyword (symbol-name val))
576            (string val)
577            (char (etypecase val
578                    (character (write-to-string val))
579                    (string val)))
580            (float (format nil "~F" val))
581            ((list vector array)
582             (let* ((*print-circle* t)
583                    (*print-array* t)
584                    (value (prin1-to-string val)))
585               value))
586            (otherwise (call-next-method)))))))
587
588 (defmethod read-sql-value (val type database db-type
589                            &aux *read-eval*)
590   (declare (ignore database db-type))
591   ;; TODO: All the read-from-strings in here do not check that
592   ;; what we read was of the correct type, should this change?
593
594   ;; TODO: Should this case `(typep val type)=>t` be an around
595   ;; method that short ciruits?
596   (cond
597     ((null type) val) ;;we have no desired type, just give the value
598     ((typep val type) val) ;;check that it hasn't already been converted.
599     ((typep val 'string) (read-from-string val)) ;;maybe read will just take care of it?
600     (T (error "Unable to read-sql-value ~a as type ~a" val type))))
601
602 (defmethod read-sql-value (val (type symbol) database db-type
603                            ;; never eval while reading values
604                            &aux *read-eval*)
605   ;; TODO: All the read-from-strings in here do not check that
606   ;; what we read was of the correct type, should this change?
607   (unless (or (equalp "nil" val) (eql 'null val))
608     (case type
609       ((string varchar) val)
610       (char (etypecase val
611               (string (schar val 0))
612               (character val)))
613       (keyword
614        (when (< 0 (length val))
615          (intern (symbol-name-default-case val) :keyword)))
616       (symbol
617        (when (< 0 (length val))
618          (intern (symbol-name-default-case val))))
619       ((smallint mediumint bigint integer universal-time)
620        (etypecase val
621          (string (parse-integer val))
622          (number val)))
623       ((double-float float)
624        ;; ensure that whatever we got is coerced to a float of the correct
625        ;; type (eg: 1=>1.0d0)
626        (float
627         (etypecase val
628           (string (let ((*read-default-float-format*
629                           (ecase type
630                             (float 'single-float)
631                             (double-float 'double-float))))
632                     (read-from-string val)))
633           (float val))
634         (if (eql type 'double-float) 1.0d0 1.0s0)))
635       (number
636        (etypecase val
637          (string (read-from-string val))
638          (number val)))
639       ((boolean generalized-boolean)
640        (if (member val '(nil t))
641            val
642            (etypecase val
643              (string
644               (when (member val '("1" "t" "true" "y") :test #'string-equal)
645                 t))
646              (number (not (zerop val))))))
647       ((wall-time duration)
648        (parse-timestring val))
649       (date
650        (parse-datestring val))
651       (t (call-next-method)))))
652
653 ;; ------------------------------------------------------------
654 ;; Logic for 'faulting in' :join slots
655
656 ;; this works, but is inefficient requiring (+ 1 n-rows)
657 ;; SQL queries
658 #+ignore
659 (defun fault-join-target-slot (class object slot-def)
660   (let* ((res (fault-join-slot-raw class object slot-def))
661          (dbi (view-class-slot-db-info slot-def))
662          (target-name (gethash :target-slot dbi))
663          (target-class (find-class target-name)))
664     (when res
665       (mapcar (lambda (obj)
666                 (list
667                  (car
668                   (fault-join-slot-raw
669                    target-class
670                    obj
671                    (find target-name (class-slots (class-of obj))
672                          :key #'slot-definition-name)))
673                  obj))
674               res)
675       #+ignore ;; this doesn't work when attempting to call slot-value
676       (mapcar (lambda (obj)
677                 (cons obj (slot-value obj ts))) res))))
678
679 (defun fault-join-target-slot (class object slot-def)
680   (let* ((dbi (view-class-slot-db-info slot-def))
681          (ts (gethash :target-slot dbi))
682          (jc  (gethash :join-class dbi))
683          (jc-view-table (view-table (find-class jc)))
684          (tdbi (view-class-slot-db-info
685                 (find ts (class-slots (find-class jc))
686                       :key #'slot-definition-name)))
687          (retrieval (gethash :retrieval tdbi))
688          (tsc (gethash :join-class tdbi))
689          (ts-view-table (view-table (find-class tsc)))
690          (jq (join-qualifier class object slot-def))
691          (key (slot-value object (gethash :home-key dbi))))
692
693     (when jq
694       (ecase retrieval
695         (:immediate
696          (let ((res
697                 (find-all (list tsc)
698                           :inner-join (sql-expression :table jc-view-table)
699                           :on (sql-operation
700                                '==
701                                (sql-expression
702                                 :attribute (gethash :foreign-key tdbi)
703                                 :table ts-view-table)
704                                (sql-expression
705                                 :attribute (gethash :home-key tdbi)
706                                 :table jc-view-table))
707                           :where jq
708                           :result-types :auto
709                           :database (choose-database-for-instance object))))
710            (mapcar #'(lambda (i)
711                        (let* ((instance (car i))
712                               (jcc (make-instance jc :view-database (choose-database-for-instance instance))))
713                          (setf (slot-value jcc (gethash :foreign-key dbi))
714                                key)
715                          (setf (slot-value jcc (gethash :home-key tdbi))
716                                (slot-value instance (gethash :foreign-key tdbi)))
717                          (list instance jcc)))
718                    res)))
719         (:deferred
720          ;; just fill in minimal slots
721          (mapcar
722           #'(lambda (k)
723               (let ((instance (make-instance tsc :view-database (choose-database-for-instance object)))
724                     (jcc (make-instance jc :view-database (choose-database-for-instance object)))
725                     (fk (car k)))
726                 (setf (slot-value instance (gethash :home-key tdbi)) fk)
727                 (setf (slot-value jcc (gethash :foreign-key dbi))
728                       key)
729                 (setf (slot-value jcc (gethash :home-key tdbi))
730                       fk)
731                 (list instance jcc)))
732           (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
733                   :from (sql-expression :table jc-view-table)
734                   :where jq
735                   :database (choose-database-for-instance object))))))))
736
737
738 ;;; Remote Joins
739
740 (defvar *default-update-objects-max-len* nil
741   "The default value to use for the MAX-LEN keyword argument to
742   UPDATE-OBJECT-JOINS.")
743
744 (defun %update-objects-joins-slot-defs (class slot-names)
745   "Get the slot definitions for the joins slots specified as slot-names
746    if slot-names is :immediate, :deferred or (or :all t) return all of
747    that type of slot definitions"
748   (setf class (to-class class))
749   (when (eq t slot-names) (setf slot-names :all))
750   (etypecase slot-names
751     (null nil)
752     (keyword
753      ;; slot-names is the retrieval type of the join-slot or :all
754      (get-join-slots class slot-names))
755     ((or symbol list)
756      (loop for slot in (listify slot-names)
757            for def = (find-slot-by-name class slot)
758            when (and def (join-slot-p def))
759            collecting def
760            unless (and def (join-slot-p def))
761            do (warn "Unable to find join slot named ~S in class ~S." slot class)))))
762
763 (defun get-joined-objects (objects slotdef &key force-p
764                                            (batch-size *default-update-objects-max-len*))
765   "Given a list of objects and a join slot-def get the objects that need to be
766    joined to the input objects
767
768    we will query in batches as large as batch-size"
769   (when (join-slot-p slotdef)
770     (let* ((slot-name (to-slot-name slotdef))
771            (join-class (join-slot-class-name slotdef))
772            (home-key (join-slot-info-value slotdef :home-key))
773            (foreign-key (join-slot-info-value slotdef :foreign-key))
774            (foreign-key-values
775              (remove-duplicates
776               (loop for object in (listify objects)
777                     for hk = (slot-value object home-key)
778                     when (or force-p
779                              (not (slot-boundp object slot-name)))
780                     collect hk)
781               :test #'equal)))
782       ;; we want to retrieve at most batch-size objects per query
783       (flet ((fetch (keys)
784                (find-all
785                 (list join-class)
786                 :where (make-instance
787                         'sql-relational-exp
788                         :operator 'in
789                         :sub-expressions (list (sql-expression :attribute foreign-key)
790                                                keys))
791                 :result-types :auto
792                 :flatp t)))
793         (if (null batch-size)
794             (fetch foreign-key-values)
795             (loop
796               for keys = (pop-n foreign-key-values batch-size)
797               while keys
798               nconcing (fetch keys)))))))
799
800 (defun %object-joins-from-list (object slot joins force-p )
801   "Given a list of objects that we are trying to join to, pull the correct
802    ones for this object"
803   (when (or force-p (not (slot-boundp object (to-slot-name slot))))
804     (let ((home-key (join-slot-info-value slot :home-key))
805           (foreign-key (join-slot-info-value slot :foreign-key)))
806       (loop for join in joins
807             when (equal (slot-value join foreign-key)
808                         (slot-value object home-key))
809             collect join))))
810
811 (defun update-objects-joins (objects &key (slots :immediate) (force-p t)
812                                      class-name (max-len *default-update-objects-max-len*))
813   "Updates from the records of the appropriate database tables the join slots
814    specified by SLOTS in the supplied list of View Class instances OBJECTS.
815
816    A simpler method of causing a join-slot to be requeried is to set it to
817    unbound, then request it again.  This function has efficiency gains where
818    join-objects are shared among the `objects` (querying all join-objects,
819    then attaching them appropriately to each of the `objects`)
820
821    SLOTS can be one of:
822
823     * :immediate (DEFAULT) - refresh join slots created with :retrieval :immediate
824     * :deferred - refresh join slots created with :retrieval :deferred
825     * :all,t - refresh all join slots regardless of :retrieval
826     * list of symbols - which explicit slots to refresh
827     * a single symobl - what slot to refresh
828
829    CLASS-NAME is used to specify the View Class of all instance in OBJECTS and
830    default to nil which means that the class of the first instance in OBJECTS
831    is used.
832
833    FORCE-P is t by default which means that all join slots are updated whereas
834    a value of nil means that only unbound join slots are updated.
835
836    MAX-LEN defaults to *DEFAULT-UPDATE-OBJECTS-MAX-LEN* When non-nil this is
837    essentially a batch size for the max number of objects to query from the
838    database at a time.  If we need more than max-len we loop till we have all
839    the objects"
840   (assert (or (null max-len) (plusp max-len)))
841   (when objects
842     (defaulting class-name (class-name (class-of (first objects))))
843     (let* ((class (find-class class-name))
844            (slotdefs (%update-objects-joins-slot-defs class slots)))
845       (loop for slotdef in slotdefs
846             ;; all the joins we will need for *all* the objects
847             ;; which then get filtered below for each object
848             for joins = (unless (join-slot-info-value slotdef :target-slot)
849                           (get-joined-objects objects slotdef
850                                               :force-p force-p :batch-size max-len))
851             do (loop for object in objects
852                      for these-joins = ;; the joins just for this object (filtered from above)
853                                        ;; or retrieved via fault-join-target-slot
854                         (or (%object-joins-from-list object slotdef joins force-p)
855                             (when (join-slot-info-value slotdef :target-slot)
856                               (fault-join-target-slot class object slotdef)))
857                      ;; when this object has joined-objects copy them in to the correct slot
858                      do (when these-joins
859                           (setf (easy-slot-value object slotdef)
860                                 (if (join-slot-info-value slotdef :set)
861                                     these-joins
862                                     (first these-joins))))))))
863   (values))
864
865 (defun fault-join-slot-raw (class object slot-def)
866   (let* ((dbi (view-class-slot-db-info slot-def))
867          (jc (gethash :join-class dbi)))
868     (let ((jq (join-qualifier class object slot-def)))
869       (when jq
870         (select jc :where jq :flatp t :result-types nil
871                 :database (choose-database-for-instance object))))))
872
873 (defun fault-join-slot (class object slot-def)
874   (let* ((dbi (view-class-slot-db-info slot-def))
875          (ts (gethash :target-slot dbi))
876          (dbi-set (gethash :set dbi)))
877     (if (and ts dbi-set)
878         (fault-join-target-slot class object slot-def)
879         (let ((res (fault-join-slot-raw class object slot-def)))
880           (when res
881             (cond
882               ((and ts (not dbi-set))
883                (mapcar (lambda (obj) (slot-value obj ts)) res))
884               ((and (not ts) (not dbi-set))
885                (car res))
886               ((and (not ts) dbi-set)
887                res)))))))
888
889 (defun update-fault-join-normalized-slot (class object slot-def)
890   (if (and (normalizedp class) (key-slot-p slot-def))
891       (setf (easy-slot-value object slot-def)
892             (normalized-key-value object))
893       (update-slot-from-record object slot-def)))
894
895 (defun all-home-keys-have-values-p (object slot-def)
896   "Do all of the home-keys have values ?"
897   (let ((home-keys (join-slot-info-value slot-def :home-key)))
898     (loop for key in (listify home-keys)
899           always (easy-slot-value object key))))
900
901 (defun join-qualifier (class object slot-def)
902   "Builds the join where clause based on the keys of the join slot and values
903    of the object"
904   (declare (ignore class))
905   (let* ((jc (join-slot-class slot-def))
906          ;;(ts (gethash :target-slot dbi))
907          ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
908          (foreign-keys (listify (join-slot-info-value slot-def :foreign-key)))
909          (home-keys (listify (join-slot-info-value slot-def :home-key))))
910     (when (all-home-keys-have-values-p object slot-def)
911       (clsql-ands
912        (loop for hk in home-keys
913              for fk in foreign-keys
914              for fksd = (slotdef-for-slot-with-class fk jc)
915              for fk-sql = (typecase fk
916                             (symbol
917                              (sql-expression
918                               :attribute (database-identifier fksd nil)
919                               :table (database-identifier jc nil)))
920                             (t fk))
921              for hk-val = (typecase hk
922                             ((or symbol
923                                  view-class-effective-slot-definition
924                                  view-class-direct-slot-definition)
925                              (easy-slot-value object hk))
926                             (t hk))
927              collect (sql-operation '== fk-sql hk-val))))))
928
929 (defmethod select-table-sql-expr ((table T))
930   "Turns an object representing a table into the :from part of the sql expression that will be executed "
931   (sql-expression :table (view-table table)))
932
933 (defun select-reference-equal (r1 r2)
934   "determines if two sql select references are equal
935    using database identifier equal"
936   (flet ((id-of (r)
937            (etypecase r
938              (cons (cdr r))
939              (sql-ident-attribute r))))
940     (database-identifier-equal (id-of r1) (id-of r2))))
941
942 (defun join-slot-qualifier (class join-slot)
943   "Creates a sql-expression expressing the join between the home-key on the table
944    and its respective key on the joined-to-table"
945   (sql-operation
946    '==
947    (sql-expression
948     :attribute (join-slot-info-value join-slot :foreign-key)
949     :table (view-table (join-slot-class join-slot)))
950    (sql-expression
951     :attribute (join-slot-info-value join-slot :home-key)
952     :table (view-table class))))
953
954 (defun all-immediate-join-classes-for (classes)
955   "returns a list of all join-classes needed for a list of classes"
956   (loop for class in (listify classes)
957         appending (loop for slot in (immediate-join-slots class)
958                         collect (join-slot-class slot))))
959
960 (defun %tables-for-query (classes from where inner-joins)
961   "Given lists of classes froms wheres and inner-join compile a list
962    of tables that should appear in the FROM section of the query.
963
964    This includes any immediate join classes from each of the classes"
965   (let ((inner-join-tables (collect-table-refs (listify inner-joins))))
966     (loop for tbl in (append
967                       (mapcar #'select-table-sql-expr classes)
968                       (mapcar #'select-table-sql-expr
969                               (all-immediate-join-classes-for classes))
970                       (collect-table-refs (listify where))
971                       (collect-table-refs (listify from)))
972           when (and tbl
973                     (not (find tbl rtn :test #'database-identifier-equal))
974                     ;; TODO: inner-join is currently hacky as can be
975                     (not (find tbl inner-join-tables :test #'database-identifier-equal)))
976           collect tbl into rtn
977           finally (return rtn))))
978
979
980 (defclass select-list ()
981   ((view-class :accessor view-class :initarg :view-class :initform nil)
982    (select-list :accessor select-list :initarg :select-list :initform nil)
983    (slot-list :accessor slot-list :initarg :slot-list :initform nil)
984    (joins :accessor joins :initarg :joins :initform nil)
985    (join-slots :accessor join-slots :initarg :join-slots :initform nil))
986   (:documentation
987    "Collects the classes, slots and their respective sql representations
988     so that update-instance-from-recors, find-all, build-objects can share this
989     info and calculate it once.  Joins are select-lists for each immediate join-slot
990     but only if make-select-list is called with do-joins-p"))
991
992 (defmethod view-table ((o select-list))
993   (view-table (view-class o)))
994
995 (defmethod sql-table ((o select-list))
996   (sql-expression :table (view-table o)))
997
998 (defmethod filter-select-list ((c clsql-sys::standard-db-object)
999                                (sl clsql-sys::select-list)
1000                                database)
1001   sl)
1002
1003 (defun make-select-list (class-and-slots &key (do-joins-p nil)
1004                                          (database *default-database*))
1005   "Make a select-list for the current class (or class-and-slots) object."
1006   (let* ((class-and-slots
1007            (etypecase class-and-slots
1008              (class-and-slots class-and-slots)
1009              ((or symbol standard-db-class)
1010               ;; find the first class with slots for us to select (this should be)
1011               ;; the first of its classes / parent-classes with slots
1012               (first (reverse (view-classes-and-storable-slots
1013                                (to-class class-and-slots)
1014                                 :to-database-p nil))))))
1015          (class (view-class class-and-slots))
1016          (join-slots (when do-joins-p (immediate-join-slots class))))
1017     (multiple-value-bind (slots sqls)
1018         (loop for slot in (slot-defs class-and-slots)
1019               for sql = (generate-attribute-reference class slot)
1020               collect slot into slots
1021               collect sql into sqls
1022               finally (return (values slots sqls)))
1023       (unless slots
1024         (error "No slots of type :base in view-class ~A" (class-name class)))
1025       (let ((sl (make-instance
1026                  'select-list
1027                  :view-class class
1028                  :select-list sqls
1029                  :slot-list slots
1030                  :join-slots join-slots
1031                  ;; only do a single layer of join objects
1032                  :joins (when do-joins-p
1033                           (loop for js in join-slots
1034                                 collect (make-select-list
1035                                          (join-slot-class js)
1036                                          :do-joins-p nil
1037                                          :database database))))))
1038         (filter-select-list (make-instance class) sl database)
1039         sl))))
1040
1041 (defun full-select-list ( select-lists )
1042   "Returns a list of sql-ref of things to select for the given classes
1043
1044    THIS NEEDS TO MATCH THE ORDER OF build-objects
1045   "
1046   (loop for s in (listify select-lists)
1047         appending (select-list s)
1048         appending (loop for join in (joins s)
1049                         appending (select-list join))))
1050
1051 (defun build-objects (select-lists row database &optional existing-instances)
1052   "Used by find-all to build objects.
1053
1054    THIS NEEDS TO MATCH THE ORDER OF FULL-SELECT-LIST
1055
1056    TODO: this caching scheme seems bad for a number of reasons
1057     * order is not guaranteed so references being held by one object
1058       might change to represent a different database row (seems HIGHLY
1059       suspect)
1060     * also join objects are overwritten rather than refreshed
1061
1062    TODO: the way we handle immediate joins seems only valid if it is a single
1063       object.  I suspect that making a :set :immediate join column would result
1064       in an invalid number of objects returned from the database, because there
1065       would be multiple rows per object, but we would return an object per row
1066    "
1067   (setf existing-instances (listify existing-instances))
1068   (loop
1069     for select-list in select-lists
1070     for class = (view-class select-list)
1071     for existing = (pop existing-instances)
1072     for object = (or existing
1073                      (make-instance class :view-database database))
1074     do (loop for slot in (slot-list select-list)
1075              do (update-slot-from-db-value object slot (pop row)))
1076     do (loop for join-slot in (join-slots select-list)
1077              for join in (joins select-list)
1078              for join-class = (view-class join)
1079              for join-object =
1080                 (setf (easy-slot-value object join-slot)
1081                       (make-instance join-class))
1082              do (loop for slot in (slot-list join)
1083                       do (update-slot-from-db-value join-object slot (pop row))))
1084     do (when existing (instance-refreshed object))
1085         collect object))
1086
1087 (defun find-all (view-classes
1088                  &rest args
1089                  &key all set-operation distinct from where group-by having
1090                  order-by offset limit refresh flatp result-types
1091                  inner-join on
1092                  (database *default-database*)
1093                  instances parameters)
1094   "Called by SELECT to generate object query results when the
1095   View Classes VIEW-CLASSES are passed as arguments to SELECT.
1096
1097    TODO: the caching scheme of passing in instances and overwriting their
1098          values seems bad for a number of reasons
1099     * order is not guaranteed so references being held by one object
1100       might change to represent a different database row (seems HIGHLY
1101       suspect)
1102
1103    TODO: the way we handle immediate joins seems only valid if it is a single
1104       object.  I suspect that making a :set :immediate join column would result
1105       in an invalid number of objects returned from the database, because there
1106       would be multiple objects returned from the database
1107   "
1108   (declare (ignore all set-operation group-by having offset limit on parameters
1109                    distinct order-by)
1110            (dynamic-extent args))
1111   (let* ((args (filter-plist
1112                 args :from :where :flatp :additional-fields :result-types :instances))
1113          (*db-deserializing* t)
1114          (sclasses (mapcar #'to-class view-classes))
1115          (tables (%tables-for-query sclasses from where inner-join))
1116          (join-where
1117            (loop for class in sclasses
1118                  appending (loop for slot in (immediate-join-slots class)
1119                                  collect (join-slot-qualifier class slot))))
1120          (select-lists (loop for class in sclasses
1121                              collect (make-select-list class :do-joins-p t :database database)))
1122          (full-select-list (full-select-list select-lists))
1123          (where (clsql-ands (append (listify where) (listify join-where))))
1124          #|
1125           (_ (format t "~&sclasses: ~W~%ijc: ~W~%tables: ~W~%"
1126                     sclasses immediate-join-classes tables))
1127          |#
1128          (rows (apply #'select
1129                       (append full-select-list
1130                               (list :from tables
1131                                     :result-types result-types
1132                                     :where where)
1133                               args)))
1134          (return-objects
1135            (loop for row in rows
1136                  for old-objs = (pop instances)
1137                  for objs = (build-objects select-lists row database
1138                                            (when refresh old-objs))
1139                  collecting (if flatp
1140                                 (delist-if-single objs)
1141                                 objs))))
1142     return-objects))
1143
1144 (defmethod instance-refreshed ((instance standard-db-object)))
1145
1146 (defvar *default-caching* t
1147   "Controls whether SELECT caches objects by default. The CommonSQL
1148 specification states caching is on by default.")
1149
1150 (defun select (&rest select-all-args)
1151   "Executes a query on DATABASE, which has a default value of
1152 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
1153 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
1154 argument can be used to generate queries in both functional and
1155 object oriented contexts.
1156
1157 In the functional case, the required arguments specify the
1158 columns selected by the query and may be symbolic SQL expressions
1159 or strings representing attribute identifiers. Type modified
1160 identifiers indicate that the values selected from the specified
1161 column are converted to the specified lisp type. The keyword
1162 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
1163 SET-OPERATION and WHERE are used to specify, using the symbolic
1164 SQL syntax, the corresponding components of the SQL query
1165 generated by the call to SELECT. RESULT-TYPES is a list of
1166 symbols which specifies the lisp type for each field returned by
1167 the query. If RESULT-TYPES is nil all results are returned as
1168 strings whereas the default value of :auto means that the lisp
1169 types are automatically computed for each field. FIELD-NAMES is t
1170 by default which means that the second value returned is a list
1171 of strings representing the columns selected by the query. If
1172 FIELD-NAMES is nil, the list of column names is not returned as a
1173 second value.
1174
1175 In the object oriented case, the required arguments to SELECT are
1176 symbols denoting View Classes which specify the database tables
1177 to query. In this case, SELECT returns a list of View Class
1178 instances whose slots are set from the attribute values of the
1179 records in the specified table. Slot-value is a legal operator
1180 which can be employed as part of the symbolic SQL syntax used in
1181 the WHERE keyword argument to SELECT. REFRESH is nil by default
1182 which means that the View Class instances returned are retrieved
1183 from a cache if an equivalent call to SELECT has previously been
1184 issued. If REFRESH is true, the View Class instances returned are
1185 updated as necessary from the database and the generic function
1186 INSTANCE-REFRESHED is called to perform any necessary operations
1187 on the updated instances.
1188
1189 In both object oriented and functional contexts, FLATP has a
1190 default value of nil which means that the results are returned as
1191 a list of lists. If FLATP is t and only one result is returned
1192 for each record selected in the query, the results are returned
1193 as elements of a list."
1194   (multiple-value-bind (target-args qualifier-args)
1195       (query-get-selections select-all-args)
1196     (unless (or *default-database* (getf qualifier-args :database))
1197       (signal-no-database-error nil))
1198
1199     (let ((caching (getf qualifier-args :caching *default-caching*))
1200           (result-types (getf qualifier-args :result-types :auto))
1201           (refresh (getf qualifier-args :refresh nil))
1202           (database (getf qualifier-args :database *default-database*)))
1203
1204       (cond
1205         ((and target-args
1206               (every #'(lambda (arg)
1207                          (and (symbolp arg)
1208                               (find-class arg nil)))
1209                      target-args))
1210
1211          (setf qualifier-args (filter-plist qualifier-args :caching :refresh :result-types))
1212
1213          ;; Add explicity table name to order-by if not specified and only
1214          ;; one selected table. This is required so FIND-ALL won't duplicate
1215          ;; the field
1216          (let ((order-by (getf qualifier-args :order-by)))
1217            (when (and order-by (= 1 (length target-args)))
1218              (let ((table-name (view-table (find-class (car target-args))))
1219                    (order-by-list (copy-seq (listify order-by))))
1220                (labels ((sv (val name) (ignore-errors (slot-value val name)))
1221                         (set-table-if-needed (val)
1222                           (typecase val
1223                             (sql-ident-attribute
1224                              (handler-case
1225                                  (if (sv val 'qualifier)
1226                                      val
1227                                      (make-instance 'sql-ident-attribute
1228                                                     :name (sv val 'name)
1229                                                     :qualifier table-name))
1230                                (simple-error ()
1231                                  ;; TODO: Check for a specific error we expect
1232                                  )))
1233                             (cons (cons (set-table-if-needed (car val))
1234                                         (cdr val)))
1235                             (t val))))
1236                  (setf order-by-list
1237                        (loop for i from 0 below (length order-by-list)
1238                              for id in order-by-list
1239                              collect (set-table-if-needed id))))
1240                (setf (getf qualifier-args :order-by) order-by-list))))
1241
1242          (cond
1243            ((null caching)
1244             (apply #'find-all target-args :result-types result-types :refresh refresh qualifier-args))
1245            (t
1246             (let ((cached (records-cache-results target-args qualifier-args database)))
1247               (if (and cached (not refresh))
1248                   cached
1249                   (let ((results (apply #'find-all target-args
1250                                         :result-types :auto :refresh refresh
1251                                         :instances cached
1252                                         qualifier-args)))
1253                     (setf (records-cache-results target-args qualifier-args database) results)
1254
1255                     results))))))
1256         (t
1257          (let* ((expr (apply #'make-query select-all-args))
1258                 (parameters (second (member :parameters select-all-args)))
1259                 (specified-types
1260                   (mapcar #'(lambda (attrib)
1261                               (if (typep attrib 'sql-ident-attribute)
1262                                   (let ((type (slot-value attrib 'type)))
1263                                     (if type
1264                                         type
1265                                         t))
1266                                   t))
1267                           (slot-value expr 'selections)))
1268                 (flatp (getf qualifier-args :flatp))
1269                 (field-names (getf qualifier-args :field-names t)))
1270
1271            (when parameters
1272              (setf expr (command-object (sql-output expr database) parameters)))
1273            (query expr :flatp flatp
1274                        :result-types
1275                        ;; specifying a type for an attribute overrides result-types
1276                        (if (some #'(lambda (x) (not (eq t x))) specified-types)
1277                            specified-types
1278                            result-types)
1279                        :field-names field-names
1280                        :database database)))))))
1281
1282 (defun compute-records-cache-key (targets qualifiers)
1283   (list targets
1284         (do ((args *select-arguments* (cdr args))
1285              (results nil))
1286             ((null args) results)
1287           (let* ((arg (car args))
1288                  (value (getf qualifiers arg)))
1289             (when value
1290               (push (list arg
1291                           (typecase value
1292                             (cons (cons (sql (car value)) (cdr value)))
1293                             (%sql-expression (sql value))
1294                             (t value)))
1295                     results))))))
1296
1297 (defun records-cache-results (targets qualifiers database)
1298   (when (record-caches database)
1299     (gethash (compute-records-cache-key targets qualifiers) (record-caches database))))
1300
1301 (defun (setf records-cache-results) (results targets qualifiers database)
1302   (unless (record-caches database)
1303     (setf (record-caches database)
1304           (make-weak-hash-table :test 'equal)))
1305   (setf (gethash (compute-records-cache-key (copy-list targets) qualifiers)
1306                  (record-caches database)) results)
1307   results)
1308
1309
1310
1311 ;;; Serialization functions
1312
1313 (defun write-instance-to-stream (obj stream)
1314   "Writes an instance to a stream where it can be later be read.
1315 NOTE: an error will occur if a slot holds a value which can not be written readably."
1316   (let* ((class (class-of obj))
1317          (alist '()))
1318     (dolist (slot (ordered-class-slots (class-of obj)))
1319       (let ((name (slot-definition-name slot)))
1320         (when (and (not (eq 'view-database name))
1321                    (slot-boundp obj name))
1322           (push (cons name (slot-value obj name)) alist))))
1323     (setq alist (reverse alist))
1324     (write (cons (class-name class) alist) :stream stream :readably t))
1325   obj)
1326
1327 (defun read-instance-from-stream (stream)
1328   (let ((raw (read stream nil nil)))
1329     (when raw
1330       (let ((obj (make-instance (car raw))))
1331         (dolist (pair (cdr raw))
1332           (setf (slot-value obj (car pair)) (cdr pair)))
1333         obj))))