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