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