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