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