Adding an oodml read-sql-value case for double-float
[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 (float (read-from-string val)))
643     (float val)))
644
645 (defmethod read-sql-value (val (type (eql 'double-float)) database db-type)
646   (declare (ignore database db-type))
647   ;; writing 1.0 writes 1, so if we *really* want a float, must do (float ...)
648   (etypecase val
649     (string (float
650              (let ((*read-default-float-format* 'double-float))
651                (read-from-string val))
652              1.0d0))
653     (double-float val)
654     (float (coerce val 'double-float))))
655
656 (defmethod read-sql-value (val (type (eql 'boolean)) database db-type)
657   (declare (ignore database db-type))
658   (equal "t" val))
659
660 (defmethod read-sql-value (val (type (eql 'generalized-boolean)) database db-type)
661   (declare (ignore database db-type))
662   (equal "t" val))
663
664 (defmethod read-sql-value (val (type (eql 'number)) database db-type)
665   (declare (ignore database db-type))
666   (etypecase val
667     (string
668      (unless (string-equal "NIL" val)
669        (read-from-string val)))
670     (number val)))
671
672 (defmethod read-sql-value (val (type (eql 'universal-time)) database db-type)
673   (declare (ignore database db-type))
674   (unless (eq 'NULL val)
675     (etypecase val
676       (string
677        (parse-integer val))
678       (number val))))
679
680 (defmethod read-sql-value (val (type (eql 'wall-time)) database db-type)
681   (declare (ignore database db-type))
682   (unless (eq 'NULL val)
683     (parse-timestring val)))
684
685 (defmethod read-sql-value (val (type (eql 'date)) database db-type)
686   (declare (ignore database db-type))
687   (unless (eq 'NULL val)
688     (parse-datestring val)))
689
690 (defmethod read-sql-value (val (type (eql 'duration)) database db-type)
691   (declare (ignore database db-type))
692   (unless (or (eq 'NULL val)
693               (equal "NIL" val))
694     (parse-timestring val)))
695
696 ;; ------------------------------------------------------------
697 ;; Logic for 'faulting in' :join slots
698
699 ;; this works, but is inefficient requiring (+ 1 n-rows)
700 ;; SQL queries
701 #+ignore
702 (defun fault-join-target-slot (class object slot-def)
703   (let* ((res (fault-join-slot-raw class object slot-def))
704          (dbi (view-class-slot-db-info slot-def))
705          (target-name (gethash :target-slot dbi))
706          (target-class (find-class target-name)))
707     (when res
708       (mapcar (lambda (obj)
709                 (list
710                  (car
711                   (fault-join-slot-raw
712                    target-class
713                    obj
714                    (find target-name (class-slots (class-of obj))
715                          :key #'slot-definition-name)))
716                  obj))
717               res)
718       #+ignore ;; this doesn't work when attempting to call slot-value
719       (mapcar (lambda (obj)
720                 (cons obj (slot-value obj ts))) res))))
721
722 (defun fault-join-target-slot (class object slot-def)
723   (let* ((dbi (view-class-slot-db-info slot-def))
724          (ts (gethash :target-slot dbi))
725          (jc  (gethash :join-class dbi))
726          (jc-view-table (view-table (find-class jc)))
727          (tdbi (view-class-slot-db-info
728                 (find ts (class-slots (find-class jc))
729                       :key #'slot-definition-name)))
730          (retrieval (gethash :retrieval tdbi))
731          (tsc (gethash :join-class tdbi))
732          (ts-view-table (view-table (find-class tsc)))
733          (jq (join-qualifier class object slot-def))
734          (key (slot-value object (gethash :home-key dbi))))
735
736     (when jq
737       (ecase retrieval
738         (:immediate
739          (let ((res
740                 (find-all (list tsc)
741                           :inner-join (sql-expression :table jc-view-table)
742                           :on (sql-operation
743                                '==
744                                (sql-expression
745                                 :attribute (gethash :foreign-key tdbi)
746                                 :table ts-view-table)
747                                (sql-expression
748                                 :attribute (gethash :home-key tdbi)
749                                 :table jc-view-table))
750                           :where jq
751                           :result-types :auto
752                           :database (view-database object))))
753            (mapcar #'(lambda (i)
754                        (let* ((instance (car i))
755                               (jcc (make-instance jc :view-database (view-database instance))))
756                          (setf (slot-value jcc (gethash :foreign-key dbi))
757                                key)
758                          (setf (slot-value jcc (gethash :home-key tdbi))
759                                (slot-value instance (gethash :foreign-key tdbi)))
760                          (list instance jcc)))
761                    res)))
762         (:deferred
763          ;; just fill in minimal slots
764          (mapcar
765           #'(lambda (k)
766               (let ((instance (make-instance tsc :view-database (view-database object)))
767                     (jcc (make-instance jc :view-database (view-database object)))
768                     (fk (car k)))
769                 (setf (slot-value instance (gethash :home-key tdbi)) fk)
770                 (setf (slot-value jcc (gethash :foreign-key dbi))
771                       key)
772                 (setf (slot-value jcc (gethash :home-key tdbi))
773                       fk)
774                 (list instance jcc)))
775           (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
776                   :from (sql-expression :table jc-view-table)
777                   :where jq
778                   :database (view-database object))))))))
779
780
781 ;;; Remote Joins
782
783 (defvar *default-update-objects-max-len* nil
784   "The default value to use for the MAX-LEN keyword argument to
785   UPDATE-OBJECT-JOINS.")
786
787 (defun update-objects-joins (objects &key (slots t) (force-p t)
788                              class-name (max-len
789                                          *default-update-objects-max-len*))
790   "Updates from the records of the appropriate database tables
791 the join slots specified by SLOTS in the supplied list of View
792 Class instances OBJECTS.  SLOTS is t by default which means that
793 all join slots with :retrieval :immediate are updated. CLASS-NAME
794 is used to specify the View Class of all instance in OBJECTS and
795 default to nil which means that the class of the first instance
796 in OBJECTS is used. FORCE-P is t by default which means that all
797 join slots are updated whereas a value of nil means that only
798 unbound join slots are updated. MAX-LEN defaults to
799 *DEFAULT-UPDATE-OBJECTS-MAX-LEN* and when non-nil specifies that
800 UPDATE-OBJECT-JOINS may issue multiple database queries with a
801 maximum of MAX-LEN instances updated in each query."
802   (assert (or (null max-len) (plusp max-len)))
803   (when objects
804     (unless class-name
805       (setq class-name (class-name (class-of (first objects)))))
806     (let* ((class (find-class class-name))
807            (class-slots (ordered-class-slots class))
808            (slotdefs
809             (if (eq t slots)
810                 (generate-retrieval-joins-list class :deferred)
811                 (remove-if #'null
812                            (mapcar #'(lambda (name)
813                                        (let ((slotdef (find name class-slots :key #'slot-definition-name)))
814                                          (unless slotdef
815                                            (warn "Unable to find slot named ~S in class ~S." name class))
816                                          slotdef))
817                                    slots)))))
818       (dolist (slotdef slotdefs)
819         (let* ((dbi (view-class-slot-db-info slotdef))
820                (slotdef-name (slot-definition-name slotdef))
821                (foreign-key (gethash :foreign-key dbi))
822                (home-key (gethash :home-key dbi))
823                (object-keys
824                 (remove-duplicates
825                  (if force-p
826                      (mapcar #'(lambda (o) (slot-value o home-key)) objects)
827                      (remove-if #'null
828                                 (mapcar
829                                  #'(lambda (o) (if (slot-boundp o slotdef-name)
830                                                    nil
831                                                    (slot-value o home-key)))
832                                  objects)))))
833                (n-object-keys (length object-keys))
834                (query-len (or max-len n-object-keys)))
835
836           (do ((i 0 (+ i query-len)))
837               ((>= i n-object-keys))
838             (let* ((keys (if max-len
839                              (subseq object-keys i (min (+ i query-len) n-object-keys))
840                              object-keys))
841                    (results (unless (gethash :target-slot dbi)
842                               (find-all (list (gethash :join-class dbi))
843                                         :where (make-instance 'sql-relational-exp
844                                                               :operator 'in
845                                                               :sub-expressions (list (sql-expression :attribute foreign-key)
846                                                                                      keys))
847                                         :result-types :auto
848                                         :flatp t)) ))
849
850               (dolist (object objects)
851                 (when (or force-p (not (slot-boundp object slotdef-name)))
852                   (let ((res (if results
853                                  (remove-if-not #'(lambda (obj)
854                                                     (equal obj (slot-value
855                                                                 object
856                                                                 home-key)))
857                                                 results
858                                                 :key #'(lambda (res)
859                                                          (slot-value res
860                                                                      foreign-key)))
861
862                                  (progn
863                                    (when (gethash :target-slot dbi)
864                                      (fault-join-target-slot class object slotdef))))))
865                     (when res
866                       (setf (slot-value object slotdef-name)
867                             (if (gethash :set dbi) res (car res)))))))))))))
868   (values))
869
870 (defun fault-join-slot-raw (class object slot-def)
871   (let* ((dbi (view-class-slot-db-info slot-def))
872          (jc (gethash :join-class dbi)))
873     (let ((jq (join-qualifier class object slot-def)))
874       (when jq
875         (select jc :where jq :flatp t :result-types nil
876                 :database (view-database object))))))
877
878 (defun fault-join-slot (class object slot-def)
879   (let* ((dbi (view-class-slot-db-info slot-def))
880          (ts (gethash :target-slot dbi)))
881     (if (and ts (gethash :set dbi))
882         (fault-join-target-slot class object slot-def)
883         (let ((res (fault-join-slot-raw class object slot-def)))
884           (when res
885             (cond
886               ((and ts (not (gethash :set dbi)))
887                (mapcar (lambda (obj) (slot-value obj ts)) res))
888               ((and (not ts) (not (gethash :set dbi)))
889                (car res))
890               ((and (not ts) (gethash :set dbi))
891                res)))))))
892
893 ;;;; Should we not return the whole result, instead of only
894 ;;;; the one slot-value? We get all the values from the db
895 ;;;; anyway, so?
896 (defun fault-join-normalized-slot (class object slot-def)
897   (labels ((getsc (this-class)
898              (let ((sc (car (class-direct-superclasses this-class))))
899                (if (key-slots sc)
900                    sc
901                    (getsc sc)))))
902     (let* ((sc (getsc class))
903            (hk (slot-definition-name (car (key-slots class))))
904            (fk (slot-definition-name (car (key-slots sc)))))
905       (let ((jq (sql-operation '==
906                                (typecase fk
907                                  (symbol
908                                   (sql-expression
909                                    :attribute
910                                    (view-class-slot-column
911                                     (slotdef-for-slot-with-class fk sc))
912                                    :table (view-table sc)))
913                                  (t fk))
914                                (typecase hk
915                                  (symbol
916                                   (slot-value object hk))
917                                  (t hk)))))
918
919         ;; Caching nil in next select, because in normalized mode
920         ;; records can be changed through other instances (children,
921         ;; parents) so changes possibly won't be noticed
922         (let ((res (car (select (class-name sc) :where jq
923                                                 :flatp t :result-types nil
924                                                 :caching nil
925                                                 :database (view-database object))))
926               (slot-name (slot-definition-name slot-def)))
927
928           ;; If current class is normalized and wanted slot is not
929           ;; a direct member, recurse up
930           (if (and (normalizedp class)
931                    (not (member slot-name
932                                 (mapcar #'(lambda (esd) (slot-definition-name esd))
933                                         (ordered-class-direct-slots class))))
934                    (not (slot-boundp res slot-name)))
935               (fault-join-normalized-slot sc res slot-def)
936               (slot-value res slot-name)))))) )
937
938 (defun join-qualifier (class object slot-def)
939   (declare (ignore class))
940   (let* ((dbi (view-class-slot-db-info slot-def))
941          (jc (find-class (gethash :join-class dbi)))
942          ;;(ts (gethash :target-slot dbi))
943          ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
944          (foreign-keys (gethash :foreign-key dbi))
945          (home-keys (gethash :home-key dbi)))
946     (when (every #'(lambda (slt)
947                      (and (slot-boundp object slt)
948                           (not (null (slot-value object slt)))))
949                  (if (listp home-keys) home-keys (list home-keys)))
950       (let ((jc
951              (mapcar #'(lambda (hk fk)
952                          (let ((fksd (slotdef-for-slot-with-class fk jc)))
953                            (sql-operation '==
954                                           (typecase fk
955                                             (symbol
956                                              (sql-expression
957                                               :attribute
958                                               (view-class-slot-column fksd)
959                                               :table (view-table jc)))
960                                             (t fk))
961                                           (typecase hk
962                                             (symbol
963                                              (slot-value object hk))
964                                             (t
965                                              hk)))))
966                      (if (listp home-keys)
967                          home-keys
968                          (list home-keys))
969                      (if (listp foreign-keys)
970                          foreign-keys
971                          (list foreign-keys)))))
972         (when jc
973           (if (> (length jc) 1)
974               (apply #'sql-and jc)
975               jc))))))
976
977 ;; FIXME: add retrieval immediate for efficiency
978 ;; For example, for (select 'employee-address) in test suite =>
979 ;; select addr.*,ea_join.* FROM addr,ea_join WHERE ea_join.aaddressid=addr.addressid\g
980
981 (defun build-objects (vals sclasses immediate-join-classes sels immediate-joins database refresh flatp instances)
982   "Used by find-all to build objects."
983   (labels ((build-object (vals vclass jclasses selects immediate-selects instance)
984              (let* ((db-vals (butlast vals (- (list-length vals)
985                                               (list-length selects))))
986                     (obj (if instance instance (make-instance (class-name vclass) :view-database database)))
987                     (join-vals (subseq vals (list-length selects)))
988                     (joins (mapcar #'(lambda (c) (when c (make-instance c :view-database database)))
989                                    jclasses)))
990
991                ;;(format t "joins: ~S~%db-vals: ~S~%join-values: ~S~%selects: ~S~%immediate-selects: ~S~%"
992                ;;joins db-vals join-vals selects immediate-selects)
993
994                ;; use refresh keyword here
995                (setf obj (get-slot-values-from-view obj (mapcar #'car selects) db-vals))
996                (mapc #'(lambda (jo)
997                          ;; find all immediate-select slots and join-vals for this object
998                          (let* ((jo-class (class-of jo))
999                                 (slots
1000                                  (if (normalizedp jo-class)
1001                                      (class-direct-slots jo-class)
1002                                      (class-slots jo-class)))
1003                                 (pos-list (remove-if #'null
1004                                                      (mapcar
1005                                                       #'(lambda (s)
1006                                                           (position s immediate-selects
1007                                                                     :key #'car
1008                                                                     :test #'eq))
1009                                                       slots))))
1010                            (get-slot-values-from-view jo
1011                                                       (mapcar #'car
1012                                                               (mapcar #'(lambda (pos)
1013                                                                           (nth pos immediate-selects))
1014                                                                       pos-list))
1015                                                       (mapcar #'(lambda (pos) (nth pos join-vals))
1016                                                               pos-list))))
1017                      joins)
1018                (mapc
1019                 #'(lambda (jc)
1020                     (let* ((vslots
1021                             (class-slots vclass))
1022                            (slot (find (class-name (class-of jc)) vslots
1023                                        :key #'(lambda (slot)
1024                                                 (when (and (eq :join (view-class-slot-db-kind slot))
1025                                                            (eq (slot-definition-name slot)
1026                                                                (gethash :join-class (view-class-slot-db-info slot))))
1027                                                   (slot-definition-name slot))))))
1028                       (when slot
1029                         (setf (slot-value obj (slot-definition-name slot)) jc))))
1030                 joins)
1031                (when refresh (instance-refreshed obj))
1032                obj)))
1033     (let* ((objects
1034             (mapcar #'(lambda (sclass jclass sel immediate-join instance)
1035                         (prog1
1036                             (build-object vals sclass jclass sel immediate-join instance)
1037                           (setf vals (nthcdr (+ (list-length sel) (list-length immediate-join))
1038                                              vals))))
1039                     sclasses immediate-join-classes sels immediate-joins instances)))
1040       (if (and flatp (= (length sclasses) 1))
1041           (car objects)
1042           objects))))
1043
1044 (defun find-all (view-classes
1045                  &rest args
1046                  &key all set-operation distinct from where group-by having
1047                  order-by offset limit refresh flatp result-types
1048                  inner-join on
1049                  (database *default-database*)
1050                  instances)
1051   "Called by SELECT to generate object query results when the
1052   View Classes VIEW-CLASSES are passed as arguments to SELECT."
1053   (declare (ignore all set-operation group-by having offset limit inner-join on))
1054   (flet ((ref-equal (ref1 ref2)
1055            (string= (sql-output ref1 database)
1056                     (sql-output ref2 database)))
1057          (table-sql-expr (table)
1058            (sql-expression :table (view-table table)))
1059          (tables-equal (table-a table-b)
1060            (when (and table-a table-b)
1061              (string= (string (slot-value table-a 'name))
1062                       (string (slot-value table-b 'name))))))
1063     (remf args :from)
1064     (remf args :where)
1065     (remf args :flatp)
1066     (remf args :additional-fields)
1067     (remf args :result-types)
1068     (remf args :instances)
1069     (let* ((*db-deserializing* t)
1070            (sclasses (mapcar #'find-class view-classes))
1071            (immediate-join-slots
1072             (mapcar #'(lambda (c) (generate-retrieval-joins-list c :immediate)) sclasses))
1073            (immediate-join-classes
1074             (mapcar #'(lambda (jcs)
1075                         (mapcar #'(lambda (slotdef)
1076                                     (find-class (gethash :join-class (view-class-slot-db-info slotdef))))
1077                                 jcs))
1078                     immediate-join-slots))
1079            (immediate-join-sels (mapcar #'generate-immediate-joins-selection-list sclasses))
1080            (sels (mapcar #'generate-selection-list sclasses))
1081            (fullsels (apply #'append (mapcar #'append sels immediate-join-sels)))
1082            (sel-tables (collect-table-refs where))
1083            (tables (remove-if #'null
1084                               (remove-duplicates
1085                                (append (mapcar #'table-sql-expr sclasses)
1086                                        (mapcan #'(lambda (jc-list)
1087                                                    (mapcar
1088                                                     #'(lambda (jc) (when jc (table-sql-expr jc)))
1089                                                     jc-list))
1090                                                immediate-join-classes)
1091                                        sel-tables)
1092                                :test #'tables-equal)))
1093            (order-by-slots (mapcar #'(lambda (ob) (if (atom ob) ob (car ob)))
1094                                    (listify order-by)))
1095            (join-where nil))
1096
1097       ;;(format t "sclasses: ~W~%ijc: ~W~%tables: ~W~%" sclasses immediate-join-classes tables)
1098
1099       (dolist (ob order-by-slots)
1100         (when (and ob (not (member ob (mapcar #'cdr fullsels)
1101                                    :test #'ref-equal)))
1102           (setq fullsels
1103                 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1104                                          order-by-slots)))))
1105       (dolist (ob (listify distinct))
1106         (when (and (typep ob 'sql-ident)
1107                    (not (member ob (mapcar #'cdr fullsels)
1108                                 :test #'ref-equal)))
1109           (setq fullsels
1110                 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1111                                          (listify ob))))))
1112       (mapcar #'(lambda (vclass jclasses jslots)
1113                   (when jclasses
1114                     (mapcar
1115                      #'(lambda (jclass jslot)
1116                          (let ((dbi (view-class-slot-db-info jslot)))
1117                            (setq join-where
1118                                  (append
1119                                   (list (sql-operation '==
1120                                                        (sql-expression
1121                                                         :attribute (gethash :foreign-key dbi)
1122                                                         :table (view-table jclass))
1123                                                        (sql-expression
1124                                                         :attribute (gethash :home-key dbi)
1125                                                         :table (view-table vclass))))
1126                                   (when join-where (listify join-where))))))
1127                      jclasses jslots)))
1128               sclasses immediate-join-classes immediate-join-slots)
1129       ;; Reported buggy on clsql-devel
1130       ;; (when where (setq where (listify where)))
1131       (cond
1132         ((and where join-where)
1133          (setq where (list (apply #'sql-and where join-where))))
1134         ((and (null where) (> (length join-where) 1))
1135          (setq where (list (apply #'sql-and join-where)))))
1136
1137       (let* ((rows (apply #'select
1138                           (append (mapcar #'cdr fullsels)
1139                                   (cons :from
1140                                         (list (append (when from (listify from))
1141                                                       (listify tables))))
1142                                   (list :result-types result-types)
1143                                   (when where
1144                                     (list :where where))
1145                                   args)))
1146              (instances-to-add (- (length rows) (length instances)))
1147              (perhaps-extended-instances
1148               (if (plusp instances-to-add)
1149                   (append instances (do ((i 0 (1+ i))
1150                                          (res nil))
1151                                         ((= i instances-to-add) res)
1152                                       (push (make-list (length sclasses) :initial-element nil) res)))
1153                   instances))
1154              (objects (mapcar
1155                        #'(lambda (row instance)
1156                            (build-objects row sclasses immediate-join-classes sels
1157                                           immediate-join-sels database refresh flatp
1158                                           (if (and flatp (atom instance))
1159                                               (list instance)
1160                                               instance)))
1161                        rows perhaps-extended-instances)))
1162         objects))))
1163
1164 (defmethod instance-refreshed ((instance standard-db-object)))
1165
1166 (defvar *default-caching* t
1167   "Controls whether SELECT caches objects by default. The CommonSQL
1168 specification states caching is on by default.")
1169
1170 (defun select (&rest select-all-args)
1171   "Executes a query on DATABASE, which has a default value of
1172 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
1173 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
1174 argument can be used to generate queries in both functional and
1175 object oriented contexts.
1176
1177 In the functional case, the required arguments specify the
1178 columns selected by the query and may be symbolic SQL expressions
1179 or strings representing attribute identifiers. Type modified
1180 identifiers indicate that the values selected from the specified
1181 column are converted to the specified lisp type. The keyword
1182 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
1183 SET-OPERATION and WHERE are used to specify, using the symbolic
1184 SQL syntax, the corresponding components of the SQL query
1185 generated by the call to SELECT. RESULT-TYPES is a list of
1186 symbols which specifies the lisp type for each field returned by
1187 the query. If RESULT-TYPES is nil all results are returned as
1188 strings whereas the default value of :auto means that the lisp
1189 types are automatically computed for each field. FIELD-NAMES is t
1190 by default which means that the second value returned is a list
1191 of strings representing the columns selected by the query. If
1192 FIELD-NAMES is nil, the list of column names is not returned as a
1193 second value.
1194
1195 In the object oriented case, the required arguments to SELECT are
1196 symbols denoting View Classes which specify the database tables
1197 to query. In this case, SELECT returns a list of View Class
1198 instances whose slots are set from the attribute values of the
1199 records in the specified table. Slot-value is a legal operator
1200 which can be employed as part of the symbolic SQL syntax used in
1201 the WHERE keyword argument to SELECT. REFRESH is nil by default
1202 which means that the View Class instances returned are retrieved
1203 from a cache if an equivalent call to SELECT has previously been
1204 issued. If REFRESH is true, the View Class instances returned are
1205 updated as necessary from the database and the generic function
1206 INSTANCE-REFRESHED is called to perform any necessary operations
1207 on the updated instances.
1208
1209 In both object oriented and functional contexts, FLATP has a
1210 default value of nil which means that the results are returned as
1211 a list of lists. If FLATP is t and only one result is returned
1212 for each record selected in the query, the results are returned
1213 as elements of a list."
1214
1215   (flet ((select-objects (target-args)
1216            (and target-args
1217                 (every #'(lambda (arg)
1218                            (and (symbolp arg)
1219                                 (find-class arg nil)))
1220                        target-args))))
1221     (multiple-value-bind (target-args qualifier-args)
1222         (query-get-selections select-all-args)
1223       (unless (or *default-database* (getf qualifier-args :database))
1224         (signal-no-database-error nil))
1225
1226       (cond
1227         ((select-objects target-args)
1228          (let ((caching (getf qualifier-args :caching *default-caching*))
1229                (result-types (getf qualifier-args :result-types :auto))
1230                (refresh (getf qualifier-args :refresh nil))
1231                (database (or (getf qualifier-args :database) *default-database*))
1232                (order-by (getf qualifier-args :order-by)))
1233            (remf qualifier-args :caching)
1234            (remf qualifier-args :refresh)
1235            (remf qualifier-args :result-types)
1236
1237            ;; Add explicity table name to order-by if not specified and only
1238            ;; one selected table. This is required so FIND-ALL won't duplicate
1239            ;; the field
1240            (when (and order-by (= 1 (length target-args)))
1241              (let ((table-name (view-table (find-class (car target-args))))
1242                    (order-by-list (copy-seq (listify order-by))))
1243
1244                (loop for i from 0 below (length order-by-list)
1245                   do (etypecase (nth i order-by-list)
1246                        (sql-ident-attribute
1247                         (unless (slot-value (nth i order-by-list) 'qualifier)
1248                           (setf (slot-value (nth i order-by-list) 'qualifier) table-name)))
1249                        (cons
1250                         (unless (slot-value (car (nth i order-by-list)) 'qualifier)
1251                           (setf (slot-value (car (nth i order-by-list)) 'qualifier) table-name)))))
1252                (setf (getf qualifier-args :order-by) order-by-list)))
1253
1254            (cond
1255              ((null caching)
1256               (apply #'find-all target-args
1257                      (append qualifier-args
1258                              (list :result-types result-types :refresh refresh))))
1259              (t
1260               (let ((cached (records-cache-results target-args qualifier-args database)))
1261                 (cond
1262                   ((and cached (not refresh))
1263                    cached)
1264                   ((and cached refresh)
1265                    (let ((results (apply #'find-all (append (list target-args) qualifier-args `(:instances ,cached :result-types :auto :refresh ,refresh)))))
1266                      (setf (records-cache-results target-args qualifier-args database) results)
1267                      results))
1268                   (t
1269                    (let ((results (apply #'find-all target-args (append qualifier-args
1270                                                                         `(:result-types :auto :refresh ,refresh)))))
1271                      (setf (records-cache-results target-args qualifier-args database) results)
1272                      results))))))))
1273         (t
1274          (let* ((expr (apply #'make-query select-all-args))
1275                 (specified-types
1276                  (mapcar #'(lambda (attrib)
1277                              (if (typep attrib 'sql-ident-attribute)
1278                                  (let ((type (slot-value attrib 'type)))
1279                                    (if type
1280                                        type
1281                                        t))
1282                                  t))
1283                          (slot-value expr 'selections))))
1284            (destructuring-bind (&key (flatp nil)
1285                                      (result-types :auto)
1286                                      (field-names t)
1287                                      (database *default-database*)
1288                                      &allow-other-keys)
1289                qualifier-args
1290              (query expr :flatp flatp
1291                     :result-types
1292                     ;; specifying a type for an attribute overrides result-types
1293                     (if (some #'(lambda (x) (not (eq t x))) specified-types)
1294                         specified-types
1295                         result-types)
1296                     :field-names field-names
1297                     :database database))))))))
1298
1299 (defun compute-records-cache-key (targets qualifiers)
1300   (list targets
1301         (do ((args *select-arguments* (cdr args))
1302              (results nil))
1303             ((null args) results)
1304           (let* ((arg (car args))
1305                  (value (getf qualifiers arg)))
1306             (when value
1307               (push (list arg
1308                           (typecase value
1309                             (cons (cons (sql (car value)) (cdr value)))
1310                             (%sql-expression (sql value))
1311                             (t value)))
1312                     results))))))
1313
1314 (defun records-cache-results (targets qualifiers database)
1315   (when (record-caches database)
1316     (gethash (compute-records-cache-key targets qualifiers) (record-caches database))))
1317
1318 (defun (setf records-cache-results) (results targets qualifiers database)
1319   (unless (record-caches database)
1320     (setf (record-caches database)
1321           (make-hash-table :test 'equal
1322                            #+allegro   :values    #+allegro :weak
1323                            #+clisp     :weak      #+clisp :value
1324                            #+lispworks :weak-kind #+lispworks :value)))
1325   (setf (gethash (compute-records-cache-key targets qualifiers)
1326                  (record-caches database)) results)
1327   results)
1328
1329
1330
1331 ;;; Serialization functions
1332
1333 (defun write-instance-to-stream (obj stream)
1334   "Writes an instance to a stream where it can be later be read.
1335 NOTE: an error will occur if a slot holds a value which can not be written readably."
1336   (let* ((class (class-of obj))
1337          (alist '()))
1338     (dolist (slot (ordered-class-slots (class-of obj)))
1339       (let ((name (slot-definition-name slot)))
1340         (when (and (not (eq 'view-database name))
1341                    (slot-boundp obj name))
1342           (push (cons name (slot-value obj name)) alist))))
1343     (setq alist (reverse alist))
1344     (write (cons (class-name class) alist) :stream stream :readably t))
1345   obj)
1346
1347 (defun read-instance-from-stream (stream)
1348   (let ((raw (read stream nil nil)))
1349     (when raw
1350       (let ((obj (make-instance (car raw))))
1351         (dolist (pair (cdr raw))
1352           (setf (slot-value obj (car pair)) (cdr pair)))
1353         obj))))