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