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