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