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