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