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