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