3a005ad0990ac8b19d82c95fbcca018e7b55f590
[clsql.git] / sql / oodml.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;;
4 ;;;; $Id: $
5 ;;;;
6 ;;;; The CLSQL Object Oriented Data Manipulation Language (OODML).
7 ;;;;
8 ;;;; This file is part of CLSQL.
9 ;;;;
10 ;;;; CLSQL users are granted the rights to distribute and use this software
11 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
12 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
13 ;;;; *************************************************************************
14
15 (in-package #:clsql-sys)
16
17
18 (defun key-qualifier-for-instance (obj &key (database *default-database*))
19   (let ((tb (view-table (class-of obj))))
20     (flet ((qfk (k)
21              (sql-operation '==
22                             (sql-expression :attribute
23                                             (view-class-slot-column k)
24                                             :table tb)
25                             (db-value-from-slot
26                              k
27                              (slot-value obj (slot-definition-name k))
28                              database))))
29       (let* ((keys (keyslots-for-class (class-of obj)))
30              (keyxprs (mapcar #'qfk (reverse keys))))
31         (cond
32           ((= (length keyxprs) 0) nil)
33           ((= (length keyxprs) 1) (car keyxprs))
34           ((> (length keyxprs) 1) (apply #'sql-operation 'and keyxprs)))))))
35
36 ;;
37 ;; Function used by 'generate-selection-list'
38 ;;
39
40 (defun generate-attribute-reference (vclass slotdef)
41   (cond
42    ((eq (view-class-slot-db-kind slotdef) :base)
43     (sql-expression :attribute (view-class-slot-column slotdef)
44                     :table (view-table vclass)))
45    ((eq (view-class-slot-db-kind slotdef) :key)
46     (sql-expression :attribute (view-class-slot-column slotdef)
47                     :table (view-table vclass)))
48    (t nil)))
49
50 ;;
51 ;; Function used by 'find-all'
52 ;;
53
54 (defun generate-selection-list (vclass)
55   (let ((sels nil))
56     (dolist (slotdef (ordered-class-slots vclass))
57       (let ((res (generate-attribute-reference vclass slotdef)))
58         (when res
59           (push (cons slotdef res) sels))))
60     (if sels
61         sels
62         (error "No slots of type :base in view-class ~A" (class-name vclass)))))
63
64
65
66 (defun generate-retrieval-joins-list (vclass retrieval-method)
67   "Returns list of immediate join slots for a class."
68   (let ((join-slotdefs nil))
69     (dolist (slotdef (ordered-class-slots vclass) join-slotdefs)
70       (when (and (eq :join (view-class-slot-db-kind slotdef))
71                  (eq retrieval-method (gethash :retrieval (view-class-slot-db-info slotdef))))
72         (push slotdef join-slotdefs)))))
73
74 (defun generate-immediate-joins-selection-list (vclass)
75   "Returns list of immediate join slots for a class."
76   (let (sels)
77     (dolist (joined-slot (generate-retrieval-joins-list vclass :immediate) sels)
78       (let* ((join-class-name (gethash :join-class (view-class-slot-db-info joined-slot)))
79              (join-class (when join-class-name (find-class join-class-name))))
80         (dolist (slotdef (ordered-class-slots join-class))
81           (let ((res (generate-attribute-reference join-class slotdef)))
82             (when res
83               (push (cons slotdef res) sels))))))
84     sels))
85
86
87 ;; Called by 'get-slot-values-from-view'
88 ;;
89
90 (defvar *update-context* nil)
91
92 (defmethod update-slot-from-db ((instance standard-db-object) slotdef value)
93   (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
94   (let* ((slot-reader (view-class-slot-db-reader slotdef))
95          (slot-name   (slot-definition-name slotdef))
96          (slot-type   (specified-type slotdef))
97          (*update-context* (cons (type-of instance) slot-name)))
98     (cond ((and value (null slot-reader))
99            (setf (slot-value instance slot-name)
100                  (read-sql-value value (delistify slot-type)
101                                  (view-database instance)
102                                  (database-underlying-type
103                                   (view-database instance)))))
104           ((null value)
105            (update-slot-with-null instance slot-name slotdef))
106           ((typep slot-reader 'string)
107            (setf (slot-value instance slot-name)
108                  (format nil slot-reader value)))
109           ((typep slot-reader 'function)
110            (setf (slot-value instance slot-name)
111                  (apply slot-reader (list value))))
112           (t
113            (error "Slot reader is of an unusual type.")))))
114
115 (defmethod key-value-from-db (slotdef value database) 
116   (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
117   (let ((slot-reader (view-class-slot-db-reader slotdef))
118         (slot-type (specified-type slotdef)))
119     (cond ((and value (null slot-reader))
120            (read-sql-value value (delistify slot-type) database
121                            (database-underlying-type database)))
122           ((null value)
123            nil)
124           ((typep slot-reader 'string)
125            (format nil slot-reader value))
126           ((typep slot-reader 'function)
127            (apply slot-reader (list value)))
128           (t
129            (error "Slot reader is of an unusual type.")))))
130
131 (defun db-value-from-slot (slotdef val database)
132   (let ((dbwriter (view-class-slot-db-writer slotdef))
133         (dbtype (specified-type slotdef)))
134     (typecase dbwriter
135       (string (format nil dbwriter val))
136       (function (apply dbwriter (list val)))
137       (t
138        (database-output-sql-as-type
139         (typecase dbtype
140           (cons (car dbtype))
141           (t dbtype))
142         val database (database-underlying-type database))))))
143
144 (defun check-slot-type (slotdef val)
145   (let* ((slot-type (specified-type slotdef))
146          (basetype (if (listp slot-type) (car slot-type) slot-type)))
147     (when (and slot-type val)
148       (unless (typep val basetype)
149         (error 'sql-user-error
150                :message
151                (format nil "Invalid value ~A in slot ~A, not of type ~A."
152                        val (slot-definition-name slotdef) slot-type))))))
153
154 ;;
155 ;; Called by find-all
156 ;;
157
158 (defmethod get-slot-values-from-view (obj slotdeflist values)
159     (flet ((update-slot (slot-def values)
160              (update-slot-from-db obj slot-def values)))
161       (mapc #'update-slot slotdeflist values)
162       obj))
163
164 (defmethod update-record-from-slot ((obj standard-db-object) slot &key
165                                     (database *default-database*))
166   (let* ((database (or (view-database obj) database))
167          (vct (view-table (class-of obj)))
168          (sd (slotdef-for-slot-with-class slot (class-of obj))))
169     (check-slot-type sd (slot-value obj slot))
170     (let* ((att (view-class-slot-column sd))
171            (val (db-value-from-slot sd (slot-value obj slot) database)))
172       (cond ((and vct sd (view-database obj))
173              (update-records (sql-expression :table vct)
174                              :attributes (list (sql-expression :attribute att))
175                              :values (list val)
176                              :where (key-qualifier-for-instance
177                                      obj :database database)
178                              :database database))
179             ((and vct sd (not (view-database obj)))
180              (insert-records :into (sql-expression :table vct)
181                              :attributes (list (sql-expression :attribute att))
182                              :values (list val)
183                              :database database)
184              (setf (slot-value obj 'view-database) database))
185             (t
186              (error "Unable to update record.")))))
187   (values))
188
189 (defmethod update-record-from-slots ((obj standard-db-object) slots &key
190                                      (database *default-database*))
191   (let* ((database (or (view-database obj) database))
192          (vct (view-table (class-of obj)))
193          (sds (slotdefs-for-slots-with-class slots (class-of obj)))
194          (avps (mapcar #'(lambda (s)
195                            (let ((val (slot-value
196                                        obj (slot-definition-name s))))
197                              (check-slot-type s val)
198                              (list (sql-expression
199                                     :attribute (view-class-slot-column s))
200                                    (db-value-from-slot s val database))))
201                        sds)))
202     (cond ((and avps (view-database obj))
203            (update-records (sql-expression :table vct)
204                            :av-pairs avps
205                            :where (key-qualifier-for-instance
206                                    obj :database database)
207                            :database database))
208           ((and avps (not (view-database obj)))
209            (insert-records :into (sql-expression :table vct)
210                            :av-pairs avps
211                            :database database)
212            (setf (slot-value obj 'view-database) database))
213           (t
214            (error "Unable to update records"))))
215   (values))
216
217 (defmethod update-records-from-instance ((obj standard-db-object)
218                                          &key (database *default-database*))
219   (let ((database (or (view-database obj) database)))
220     (labels ((slot-storedp (slot)
221                (and (member (view-class-slot-db-kind slot) '(:base :key))
222                     (slot-boundp obj (slot-definition-name slot))))
223              (slot-value-list (slot)
224                (let ((value (slot-value obj (slot-definition-name slot))))
225                  (check-slot-type slot value)
226                  (list (sql-expression :attribute (view-class-slot-column slot))
227                        (db-value-from-slot slot value database)))))
228       (let* ((view-class (class-of obj))
229              (view-class-table (view-table view-class))
230              (slots (remove-if-not #'slot-storedp 
231                                    (ordered-class-slots view-class)))
232              (record-values (mapcar #'slot-value-list slots)))
233         (unless record-values
234           (error "No settable slots."))
235         (if (view-database obj)
236             (update-records (sql-expression :table view-class-table)
237                             :av-pairs record-values
238                             :where (key-qualifier-for-instance
239                                     obj :database database)
240                             :database database)
241             (progn
242               (insert-records :into (sql-expression :table view-class-table)
243                               :av-pairs record-values
244                               :database database)
245               (setf (slot-value obj 'view-database) database))))))
246   (values))
247
248 (defmethod delete-instance-records ((instance standard-db-object))
249   (let ((vt (sql-expression :table (view-table (class-of instance))))
250         (vd (view-database instance)))
251     (if vd
252         (let ((qualifier (key-qualifier-for-instance instance :database vd)))
253           (delete-records :from vt :where qualifier :database vd)
254           (setf (slot-value instance 'view-database) nil))
255         (signal-no-database-error vd))))
256
257 (defmethod update-instance-from-records ((instance standard-db-object)
258                                          &key (database *default-database*))
259   (let* ((view-class (find-class (class-name (class-of instance))))
260          (view-table (sql-expression :table (view-table view-class)))
261          (vd (or (view-database instance) database))
262          (view-qual (key-qualifier-for-instance instance :database vd))
263          (sels (generate-selection-list view-class))
264          (res (apply #'select (append (mapcar #'cdr sels)
265                                       (list :from  view-table
266                                             :where view-qual)
267                                       (list :result-types nil)))))
268     (when res
269       (get-slot-values-from-view instance (mapcar #'car sels) (car res)))))
270
271 (defmethod update-slot-from-record ((instance standard-db-object)
272                                     slot &key (database *default-database*))
273   (let* ((view-class (find-class (class-name (class-of instance))))
274          (view-table (sql-expression :table (view-table view-class)))
275          (vd (or (view-database instance) database))
276          (view-qual (key-qualifier-for-instance instance :database vd))
277          (slot-def (slotdef-for-slot-with-class slot view-class))
278          (att-ref (generate-attribute-reference view-class slot-def))
279          (res (select att-ref :from  view-table :where view-qual
280                       :result-types nil)))
281     (when res 
282       (get-slot-values-from-view instance (list slot-def) (car res)))))
283
284
285 (defmethod update-slot-with-null ((object standard-db-object)
286                                   slotname
287                                   slotdef)
288   (setf (slot-value object slotname) (slot-value slotdef 'void-value)))
289
290 (defvar +no-slot-value+ '+no-slot-value+)
291
292 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
293   (let* ((class (find-class classname))
294          (sld (slotdef-for-slot-with-class slot class)))
295     (if sld
296         (if (eq value +no-slot-value+)
297             (sql-expression :attribute (view-class-slot-column sld)
298                             :table (view-table class))
299             (db-value-from-slot
300              sld
301              value
302              database))
303         (error "Unknown slot ~A for class ~A" slot classname))))
304
305 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
306         (declare (ignore database))
307         (let* ((class (find-class classname)))
308           (unless (view-table class)
309             (error "No view-table for class ~A"  classname))
310           (sql-expression :table (view-table class))))
311
312 (defmethod database-get-type-specifier (type args database db-type)
313   (declare (ignore type args database db-type))
314   "VARCHAR(255)")
315
316 (defmethod database-get-type-specifier ((type (eql 'integer)) args database db-type)
317   (declare (ignore database db-type))
318   (if args
319       (format nil "INT(~A)" (car args))
320       "INT"))
321
322 (deftype bigint () 
323   "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
324   'integer)
325
326 (defmethod database-get-type-specifier ((type (eql 'bigint)) args database db-type)
327   (declare (ignore args database db-type))
328   "BIGINT")
329               
330 (defmethod database-get-type-specifier ((type (eql 'simple-base-string)) args
331                                         database db-type)
332   (declare (ignore database db-type))
333   (if args
334       (format nil "VARCHAR(~A)" (car args))
335       "VARCHAR(255)"))
336
337 (defmethod database-get-type-specifier ((type (eql 'simple-string)) args
338                                         database db-type)
339   (declare (ignore database db-type))
340   (if args
341       (format nil "VARCHAR(~A)" (car args))
342       "VARCHAR(255)"))
343
344 (defmethod database-get-type-specifier ((type (eql 'string)) args database db-type)
345   (declare (ignore database db-type))
346   (if args
347       (format nil "VARCHAR(~A)" (car args))
348       "VARCHAR(255)"))
349
350 (deftype universal-time () 
351   "A positive integer as returned by GET-UNIVERSAL-TIME."
352   '(integer 1 *))
353
354 (defmethod database-get-type-specifier ((type (eql 'universal-time)) args database db-type)
355   (declare (ignore args database db-type))
356   "BIGINT")
357
358 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database db-type)
359   (declare (ignore args database db-type))
360   "TIMESTAMP")
361
362 (defmethod database-get-type-specifier ((type (eql 'duration)) args database db-type)
363   (declare (ignore database args db-type))
364   "VARCHAR")
365
366 (defmethod database-get-type-specifier ((type (eql 'money)) args database db-type)
367   (declare (ignore database args db-type))
368   "INT8")
369
370 (deftype raw-string (&optional len)
371   "A string which is not trimmed when retrieved from the database"
372   `(string ,len))
373
374 (defmethod database-get-type-specifier ((type (eql 'raw-string)) args database db-type)
375   (declare (ignore database db-type))
376   (if args
377       (format nil "VARCHAR(~A)" (car args))
378       "VARCHAR"))
379
380 (defmethod database-get-type-specifier ((type (eql 'float)) args database db-type)
381   (declare (ignore database db-type))
382   (if args
383       (format nil "FLOAT(~A)" (car args))
384       "FLOAT"))
385
386 (defmethod database-get-type-specifier ((type (eql 'long-float)) args database db-type)
387   (declare (ignore database db-type))
388   (if args
389       (format nil "FLOAT(~A)" (car args))
390       "FLOAT"))
391
392 (defmethod database-get-type-specifier ((type (eql 'boolean)) args database db-type)
393   (declare (ignore args database db-type))
394   "BOOL")
395
396 (defmethod database-output-sql-as-type (type val database db-type)
397   (declare (ignore type database db-type))
398   val)
399
400 (defmethod database-output-sql-as-type ((type (eql 'list)) val database db-type)
401   (declare (ignore database db-type))
402   (progv '(*print-circle* *print-array*) '(t t)
403     (let ((escaped (prin1-to-string val)))
404       (substitute-char-string
405        escaped #\Null " "))))
406
407 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database db-type)
408   (declare (ignore database db-type))
409   (if (keywordp val)
410       (symbol-name val)
411       (if val
412           (concatenate 'string
413                        (package-name (symbol-package val))
414                        "::"
415                        (symbol-name val))
416           "")))
417
418 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database db-type)
419   (declare (ignore database db-type))
420   (if val
421       (symbol-name val)
422       ""))
423
424 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database db-type)
425   (declare (ignore database db-type))
426   (progv '(*print-circle* *print-array*) '(t t)
427     (prin1-to-string val)))
428
429 (defmethod database-output-sql-as-type ((type (eql 'array)) val database db-type)
430   (declare (ignore database db-type))
431   (progv '(*print-circle* *print-array*) '(t t)
432     (prin1-to-string val)))
433
434 (defmethod database-output-sql-as-type ((type (eql 'boolean)) val database db-type)
435   (declare (ignore database db-type))
436   (if val "t" "f"))
437
438 (defmethod database-output-sql-as-type ((type (eql 'string)) val database db-type)
439   (declare (ignore database db-type))
440   val)
441
442 (defmethod database-output-sql-as-type ((type (eql 'simple-string))
443                                         val database db-type)
444   (declare (ignore database db-type))
445   val)
446
447 (defmethod database-output-sql-as-type ((type (eql 'simple-base-string))
448                                         val database db-type)
449   (declare (ignore database db-type))
450   val)
451
452 (defmethod read-sql-value (val type database db-type)
453   (declare (ignore type database db-type))
454   (read-from-string val))
455
456 (defmethod read-sql-value (val (type (eql 'string)) database db-type)
457   (declare (ignore database db-type))
458   val)
459
460 (defmethod read-sql-value (val (type (eql 'simple-string)) database db-type)
461   (declare (ignore database db-type))
462   val)
463
464 (defmethod read-sql-value (val (type (eql 'simple-base-string)) database db-type)
465   (declare (ignore database db-type))
466   val)
467
468 (defmethod read-sql-value (val (type (eql 'raw-string)) database db-type)
469   (declare (ignore database db-type))
470   val)
471
472 (defmethod read-sql-value (val (type (eql 'keyword)) database db-type)
473   (declare (ignore database db-type))
474   (when (< 0 (length val))
475     (intern (symbol-name-default-case val) 
476             (find-package '#:keyword))))
477
478 (defmethod read-sql-value (val (type (eql 'symbol)) database db-type)
479   (declare (ignore database db-type))
480   (when (< 0 (length val))
481     (unless (string= val (symbol-name-default-case "NIL"))
482       (intern (symbol-name-default-case val)
483               (symbol-package *update-context*)))))
484
485 (defmethod read-sql-value (val (type (eql 'integer)) database db-type)
486   (declare (ignore database db-type))
487   (etypecase val
488     (string
489      (unless (string-equal "NIL" val)
490        (parse-integer val)))
491     (number val)))
492
493 (defmethod read-sql-value (val (type (eql 'bigint)) database db-type)
494   (declare (ignore database db-type))
495   (etypecase val
496     (string
497      (unless (string-equal "NIL" val)
498        (parse-integer val)))
499     (number val)))
500
501 (defmethod read-sql-value (val (type (eql 'float)) database db-type)
502   (declare (ignore database db-type))
503   ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
504   (etypecase val
505     (string
506      (float (read-from-string val)))
507     (float
508      val)))
509
510 (defmethod read-sql-value (val (type (eql 'boolean)) database db-type)
511   (declare (ignore database db-type))
512   (equal "t" val))
513
514 (defmethod read-sql-value (val (type (eql 'univeral-time)) database db-type)
515   (declare (ignore database db-type))
516   (unless (eq 'NULL val)
517     (etypecase val
518       (string
519        (parse-integer val))
520       (number val))))
521
522 (defmethod read-sql-value (val (type (eql 'wall-time)) database db-type)
523   (declare (ignore database db-type))
524   (unless (eq 'NULL val)
525     (parse-timestring val)))
526
527 (defmethod read-sql-value (val (type (eql 'duration)) database db-type)
528   (declare (ignore database db-type))
529   (unless (or (eq 'NULL val)
530               (equal "NIL" val))
531     (parse-timestring val)))
532
533 ;; ------------------------------------------------------------
534 ;; Logic for 'faulting in' :join slots
535
536 ;; this works, but is inefficient requiring (+ 1 n-rows)
537 ;; SQL queries
538 #+ignore
539 (defun fault-join-target-slot (class object slot-def)
540   (let* ((res (fault-join-slot-raw class object slot-def))
541          (dbi (view-class-slot-db-info slot-def))
542          (target-name (gethash :target-slot dbi))
543          (target-class (find-class target-name)))
544     (when res
545       (mapcar (lambda (obj)
546                 (list 
547                  (car
548                   (fault-join-slot-raw 
549                    target-class
550                    obj
551                    (find target-name (class-slots (class-of obj))
552                          :key #'slot-definition-name)))
553                  obj))
554               res)
555       #+ignore ;; this doesn't work when attempting to call slot-value
556       (mapcar (lambda (obj)
557                 (cons obj (slot-value obj ts))) res))))
558
559 (defun fault-join-target-slot (class object slot-def)
560   (let* ((dbi (view-class-slot-db-info slot-def))
561          (ts (gethash :target-slot dbi))
562          (jc (gethash :join-class dbi))
563          (ts-view-table (view-table (find-class ts)))
564          (jc-view-table (view-table (find-class jc)))
565          (tdbi (view-class-slot-db-info 
566                 (find ts (class-slots (find-class jc))
567                       :key #'slot-definition-name)))
568          (retrieval (gethash :retrieval tdbi))
569          (jq (join-qualifier class object slot-def))
570          (key (slot-value object (gethash :home-key dbi))))
571     (when jq
572       (ecase retrieval
573         (:immediate
574          (let ((res
575                 (find-all (list ts) 
576                           :inner-join (sql-expression :table jc-view-table)
577                           :on (sql-operation 
578                                '==
579                                (sql-expression 
580                                 :attribute (gethash :foreign-key tdbi) 
581                                 :table ts-view-table)
582                                (sql-expression 
583                                 :attribute (gethash :home-key tdbi) 
584                                 :table jc-view-table))
585                           :where jq
586                           :result-types :auto)))
587            (mapcar #'(lambda (i)
588                        (let* ((instance (car i))
589                               (jcc (make-instance jc :view-database (view-database instance))))
590                          (setf (slot-value jcc (gethash :foreign-key dbi)) 
591                                key)
592                          (setf (slot-value jcc (gethash :home-key tdbi)) 
593                                (slot-value instance (gethash :foreign-key tdbi)))
594                       (list instance jcc)))
595                    res)))
596         (:deferred
597             ;; just fill in minimal slots
598             (mapcar
599              #'(lambda (k)
600                  (let ((instance (make-instance ts :view-database (view-database object)))
601                        (jcc (make-instance jc :view-database (view-database object)))
602                        (fk (car k)))
603                    (setf (slot-value instance (gethash :home-key tdbi)) fk)
604                    (setf (slot-value jcc (gethash :foreign-key dbi)) 
605                          key)
606                    (setf (slot-value jcc (gethash :home-key tdbi)) 
607                          fk)
608                    (list instance jcc)))
609              (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
610                      :from (sql-expression :table jc-view-table)
611                      :where jq)))))))
612
613
614 ;;; Remote Joins
615
616 (defvar *default-update-objects-max-len* nil
617   "The default value to use for the MAX-LEN keyword argument to
618   UPDATE-OBJECT-JOINS.")
619
620 (defun update-objects-joins (objects &key (slots t) (force-p t)
621                             class-name (max-len
622                             *default-update-objects-max-len*))
623   "Updates from the records of the appropriate database tables
624 the join slots specified by SLOTS in the supplied list of View
625 Class instances OBJECTS.  SLOTS is t by default which means that
626 all join slots with :retrieval :immediate are updated. CLASS-NAME
627 is used to specify the View Class of all instance in OBJECTS and
628 default to nil which means that the class of the first instance
629 in OBJECTS is used. FORCE-P is t by default which means that all
630 join slots are updated whereas a value of nil means that only
631 unbound join slots are updated. MAX-LEN defaults to
632 *DEFAULT-UPDATE-OBJECTS-MAX-LEN* and when non-nil specifies that
633 UPDATE-OBJECT-JOINS may issue multiple database queries with a
634 maximum of MAX-LEN instances updated in each query."
635   (assert (or (null max-len) (plusp max-len)))
636   (when objects
637     (unless class-name
638       (setq class-name (class-name (class-of (first objects)))))
639     (let* ((class (find-class class-name))
640            (class-slots (ordered-class-slots class))
641            (slotdefs 
642             (if (eq t slots)
643                 (generate-retrieval-joins-list class :deferred)
644               (remove-if #'null
645                          (mapcar #'(lambda (name)
646                                      (let ((slotdef (find name class-slots :key #'slot-definition-name)))
647                                        (unless slotdef
648                                          (warn "Unable to find slot named ~S in class ~S." name class))
649                                        slotdef))
650                                  slots)))))
651       (dolist (slotdef slotdefs)
652         (let* ((dbi (view-class-slot-db-info slotdef))
653                (slotdef-name (slot-definition-name slotdef))
654                (foreign-key (gethash :foreign-key dbi))
655                (home-key (gethash :home-key dbi))
656                (object-keys
657                 (remove-duplicates
658                  (if force-p
659                      (mapcar #'(lambda (o) (slot-value o home-key)) objects)
660                    (remove-if #'null
661                               (mapcar
662                                #'(lambda (o) (if (slot-boundp o slotdef-name)
663                                                  nil
664                                                (slot-value o home-key)))
665                                objects)))))
666                (n-object-keys (length object-keys))
667                (query-len (or max-len n-object-keys)))
668           
669           (do ((i 0 (+ i query-len)))
670               ((>= i n-object-keys))
671             (let* ((keys (if max-len
672                              (subseq object-keys i (min (+ i query-len) n-object-keys))
673                            object-keys))
674                    (results (find-all (list (gethash :join-class dbi))
675                                       :where (make-instance 'sql-relational-exp
676                                                :operator 'in
677                                                :sub-expressions (list (sql-expression :attribute foreign-key)
678                                                                       keys))
679                                       :result-types :auto
680                                       :flatp t)))
681               (dolist (object objects)
682                 (when (or force-p (not (slot-boundp object slotdef-name)))
683                   (let ((res (find (slot-value object home-key) results 
684                                    :key #'(lambda (res) (slot-value res foreign-key))
685                                    :test #'equal)))
686                     (when res
687                       (setf (slot-value object slotdef-name) res)))))))))))
688   (values))
689   
690 (defun fault-join-slot-raw (class object slot-def)
691   (let* ((dbi (view-class-slot-db-info slot-def))
692          (jc (gethash :join-class dbi)))
693     (let ((jq (join-qualifier class object slot-def)))
694       (when jq 
695         (select jc :where jq :flatp t :result-types nil)))))
696
697 (defun fault-join-slot (class object slot-def)
698   (let* ((dbi (view-class-slot-db-info slot-def))
699          (ts (gethash :target-slot dbi)))
700     (if (and ts (gethash :set dbi))
701         (fault-join-target-slot class object slot-def)
702         (let ((res (fault-join-slot-raw class object slot-def)))
703           (when res
704             (cond
705               ((and ts (not (gethash :set dbi)))
706                (mapcar (lambda (obj) (slot-value obj ts)) res))
707               ((and (not ts) (not (gethash :set dbi)))
708                (car res))
709               ((and (not ts) (gethash :set dbi))
710                res)))))))
711
712 (defun join-qualifier (class object slot-def)
713     (declare (ignore class))
714     (let* ((dbi (view-class-slot-db-info slot-def))
715            (jc (find-class (gethash :join-class dbi)))
716            ;;(ts (gethash :target-slot dbi))
717            ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
718            (foreign-keys (gethash :foreign-key dbi))
719            (home-keys (gethash :home-key dbi)))
720       (when (every #'(lambda (slt)
721                        (and (slot-boundp object slt)
722                             (not (null (slot-value object slt)))))
723                    (if (listp home-keys) home-keys (list home-keys)))
724         (let ((jc
725                (mapcar #'(lambda (hk fk)
726                            (let ((fksd (slotdef-for-slot-with-class fk jc)))
727                              (sql-operation '==
728                                             (typecase fk
729                                               (symbol
730                                                (sql-expression
731                                                 :attribute
732                                                 (view-class-slot-column fksd)
733                                                 :table (view-table jc)))
734                                               (t fk))
735                                             (typecase hk
736                                               (symbol
737                                                (slot-value object hk))
738                                               (t
739                                                hk)))))
740                        (if (listp home-keys)
741                            home-keys
742                            (list home-keys))
743                        (if (listp foreign-keys)
744                            foreign-keys
745                            (list foreign-keys)))))
746           (when jc
747             (if (> (length jc) 1)
748                 (apply #'sql-and jc)
749                 jc))))))
750
751 ;; FIXME: add retrieval immediate for efficiency
752 ;; For example, for (select 'employee-address) in test suite =>
753 ;; select addr.*,ea_join.* FROM addr,ea_join WHERE ea_join.aaddressid=addr.addressid\g
754
755 (defun build-objects (vals sclasses immediate-join-classes sels immediate-joins database refresh flatp instances)
756   "Used by find-all to build objects."
757   (labels ((build-object (vals vclass jclasses selects immediate-selects instance)
758              (let* ((db-vals (butlast vals (- (list-length vals)
759                                               (list-length selects))))
760                     (obj (if instance instance (make-instance (class-name vclass) :view-database database)))
761                     (join-vals (subseq vals (list-length selects)))
762                     (joins (mapcar #'(lambda (c) (when c (make-instance c :view-database database)))
763                                    jclasses)))
764                ;;(format t "db-vals: ~S, join-values: ~S~%" db-vals join-vals)
765                ;; use refresh keyword here 
766                (setf obj (get-slot-values-from-view obj (mapcar #'car selects) db-vals))
767                (mapc #'(lambda (jc) (get-slot-values-from-view jc (mapcar #'car immediate-selects) join-vals))
768                      joins)
769                (mapc
770                 #'(lambda (jc) 
771                     (let ((slot (find (class-name (class-of jc)) (class-slots vclass) 
772                                       :key #'(lambda (slot) 
773                                                (when (and (eq :join (view-class-slot-db-kind slot))
774                                                           (eq (slot-definition-name slot)
775                                                               (gethash :join-class (view-class-slot-db-info slot))))
776                                                  (slot-definition-name slot))))))
777                       (when slot
778                         (setf (slot-value obj (slot-definition-name slot)) jc))))
779                 joins)
780                (when refresh (instance-refreshed obj))
781                obj)))
782     (let* ((objects
783             (mapcar #'(lambda (sclass jclass sel immediate-join instance) 
784                         (prog1
785                             (build-object vals sclass jclass sel immediate-join instance)
786                           (setf vals (nthcdr (+ (list-length sel) (list-length immediate-join))
787                                              vals))))
788                     sclasses immediate-join-classes sels immediate-joins instances)))
789       (if (and flatp (= (length sclasses) 1))
790           (car objects)
791         objects))))
792
793 (defun find-all (view-classes 
794                  &rest args
795                  &key all set-operation distinct from where group-by having 
796                       order-by offset limit refresh flatp result-types 
797                       inner-join on 
798                       (database *default-database*)
799                       instances)
800   "Called by SELECT to generate object query results when the
801   View Classes VIEW-CLASSES are passed as arguments to SELECT."
802   (declare (ignore all set-operation group-by having offset limit inner-join on)
803            (optimize (debug 3) (speed 1)))
804   (labels ((ref-equal (ref1 ref2)
805              (equal (sql ref1)
806                     (sql ref2)))
807            (table-sql-expr (table)
808              (sql-expression :table (view-table table)))
809            (tables-equal (table-a table-b)
810              (when (and table-a table-b)
811                (string= (string (slot-value table-a 'name))
812                         (string (slot-value table-b 'name))))))
813     (remf args :from)
814     (remf args :where)
815     (remf args :flatp)
816     (remf args :additional-fields)
817     (remf args :result-types)
818     (remf args :instances)
819     (let* ((*db-deserializing* t)
820            (sclasses (mapcar #'find-class view-classes))
821            (immediate-join-slots 
822             (mapcar #'(lambda (c) (generate-retrieval-joins-list c :immediate)) sclasses))
823            (immediate-join-classes
824             (mapcar #'(lambda (jcs)
825                         (mapcar #'(lambda (slotdef)
826                                     (find-class (gethash :join-class (view-class-slot-db-info slotdef))))
827                                 jcs))
828                     immediate-join-slots))
829            (immediate-join-sels (mapcar #'generate-immediate-joins-selection-list sclasses))
830            (sels (mapcar #'generate-selection-list sclasses))
831            (fullsels (apply #'append (mapcar #'append sels immediate-join-sels)))
832            (sel-tables (collect-table-refs where))
833            (tables (remove-if #'null
834                               (remove-duplicates (append (mapcar #'table-sql-expr sclasses)
835                                                          (mapcar #'(lambda (jcs)
836                                                                      (mapcan #'(lambda (jc)
837                                                                                  (when jc (table-sql-expr jc)))
838                                                                              jcs))
839                                                                  immediate-join-classes)
840                                                          sel-tables)
841                                                  :test #'tables-equal)))
842            (order-by-slots (mapcar #'(lambda (ob) (if (atom ob) ob (car ob)))
843                                    (listify order-by))))
844                                  
845       (dolist (ob order-by-slots)
846         (when (and ob (not (member ob (mapcar #'cdr fullsels)
847                                    :test #'ref-equal)))
848           (setq fullsels 
849             (append fullsels (mapcar #'(lambda (att) (cons nil att))
850                                      order-by-slots)))))
851       (dolist (ob (listify distinct))
852         (when (and (typep ob 'sql-ident) 
853                    (not (member ob (mapcar #'cdr fullsels) 
854                                 :test #'ref-equal)))
855           (setq fullsels 
856               (append fullsels (mapcar #'(lambda (att) (cons nil att))
857                                        (listify ob))))))
858       (mapcar #'(lambda (vclass jclasses jslots)
859                   (when jclasses
860                     (mapcar
861                      #'(lambda (jclass jslot)
862                          (let ((dbi (view-class-slot-db-info jslot)))
863                            (setq where
864                                  (append
865                                   (list (sql-operation '==
866                                                       (sql-expression
867                                                        :attribute (gethash :foreign-key dbi)
868                                                        :table (view-table jclass))
869                                                       (sql-expression
870                                                        :attribute (gethash :home-key dbi)
871                                                        :table (view-table vclass))))
872                                   (when where (listify where))))))
873                      jclasses jslots)))
874               sclasses immediate-join-classes immediate-join-slots)
875       (let* ((rows (apply #'select 
876                           (append (mapcar #'cdr fullsels)
877                                   (cons :from 
878                                         (list (append (when from (listify from)) 
879                                                       (listify tables)))) 
880                                   (list :result-types result-types)
881                                   (when where (list :where where))
882                                   args)))
883              (instances-to-add (- (length rows) (length instances)))
884              (perhaps-extended-instances
885               (if (plusp instances-to-add)
886                   (append instances (do ((i 0 (1+ i))
887                                          (res nil))
888                                         ((= i instances-to-add) res)
889                                       (push (make-list (length sclasses) :initial-element nil) res)))
890                 instances))
891              (objects (mapcar 
892                        #'(lambda (row instance)
893                            (build-objects row sclasses immediate-join-classes sels
894                                           immediate-join-sels database refresh flatp 
895                                           (if (and flatp (atom instance))
896                                               (list instance)
897                                             instance)))
898                        rows perhaps-extended-instances)))
899         objects))))
900
901 (defmethod instance-refreshed ((instance standard-db-object)))
902
903 (defun select (&rest select-all-args) 
904    "Executes a query on DATABASE, which has a default value of
905 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
906 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
907 argument can be used to generate queries in both functional and
908 object oriented contexts. 
909
910 In the functional case, the required arguments specify the
911 columns selected by the query and may be symbolic SQL expressions
912 or strings representing attribute identifiers. Type modified
913 identifiers indicate that the values selected from the specified
914 column are converted to the specified lisp type. The keyword
915 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
916 SET-OPERATION and WHERE are used to specify, using the symbolic
917 SQL syntax, the corresponding components of the SQL query
918 generated by the call to SELECT. RESULT-TYPES is a list of
919 symbols which specifies the lisp type for each field returned by
920 the query. If RESULT-TYPES is nil all results are returned as
921 strings whereas the default value of :auto means that the lisp
922 types are automatically computed for each field. FIELD-NAMES is t
923 by default which means that the second value returned is a list
924 of strings representing the columns selected by the query. If
925 FIELD-NAMES is nil, the list of column names is not returned as a
926 second value. 
927
928 In the object oriented case, the required arguments to SELECT are
929 symbols denoting View Classes which specify the database tables
930 to query. In this case, SELECT returns a list of View Class
931 instances whose slots are set from the attribute values of the
932 records in the specified table. Slot-value is a legal operator
933 which can be employed as part of the symbolic SQL syntax used in
934 the WHERE keyword argument to SELECT. REFRESH is nil by default
935 which means that the View Class instances returned are retrieved
936 from a cache if an equivalent call to SELECT has previously been
937 issued. If REFRESH is true, the View Class instances returned are
938 updated as necessary from the database and the generic function
939 INSTANCE-REFRESHED is called to perform any necessary operations
940 on the updated instances.
941
942 In both object oriented and functional contexts, FLATP has a
943 default value of nil which means that the results are returned as
944 a list of lists. If FLATP is t and only one result is returned
945 for each record selected in the query, the results are returned
946 as elements of a list."
947
948   (flet ((select-objects (target-args)
949            (and target-args
950                 (every #'(lambda (arg)
951                            (and (symbolp arg)
952                                 (find-class arg nil)))
953                        target-args))))
954     (multiple-value-bind (target-args qualifier-args)
955         (query-get-selections select-all-args)
956       (unless (or *default-database* (getf qualifier-args :database))
957         (signal-no-database-error nil))
958    
959         (cond
960           ((select-objects target-args)
961            (let ((caching (getf qualifier-args :caching t))
962                  (result-types (getf qualifier-args :result-types :auto))
963                  (refresh (getf qualifier-args :refresh nil))
964                  (database (or (getf qualifier-args :database) *default-database*))
965                  (order-by (getf qualifier-args :order-by)))
966              (remf qualifier-args :caching)
967              (remf qualifier-args :refresh)
968              (remf qualifier-args :result-types)
969              
970              
971              ;; Add explicity table name to order-by if not specified and only
972              ;; one selected table. This is required so FIND-ALL won't duplicate
973              ;; the field
974              (when (and order-by (= 1 (length target-args)))
975                (let ((table-name  (view-table (find-class (car target-args))))
976                      (order-by-list (copy-seq (listify order-by))))
977                  
978                  (loop for i from 0 below (length order-by-list)
979                      do (etypecase (nth i order-by-list)
980                           (sql-ident-attribute
981                            (unless (slot-value (nth i order-by-list) 'qualifier)
982                              (setf (slot-value (nth i order-by-list) 'qualifier) table-name)))
983                           (cons
984                            (unless (slot-value (car (nth i order-by-list)) 'qualifier)
985                              (setf (slot-value (car (nth i order-by-list)) 'qualifier) table-name)))))
986                  (setf (getf qualifier-args :order-by) order-by-list)))
987         
988              (cond
989                ((null caching)
990                 (apply #'find-all target-args
991                        (append qualifier-args (list :result-types result-types))))
992                (t
993                 (let ((cached (records-cache-results target-args qualifier-args database)))
994                   (cond
995                     ((and cached (not refresh))
996                      cached)
997                     ((and cached refresh)
998                      (let ((results (apply #'find-all (append (list target-args) qualifier-args `(:instances ,cached :result-types :auto)))))
999                        (setf (records-cache-results target-args qualifier-args database) results)
1000                        results))
1001                     (t
1002                      (let ((results (apply #'find-all target-args (append qualifier-args
1003                                                                           '(:result-types :auto)))))
1004                        (setf (records-cache-results target-args qualifier-args database) results)
1005                        results))))))))
1006           (t
1007            (let* ((expr (apply #'make-query select-all-args))
1008                   (specified-types
1009                    (mapcar #'(lambda (attrib)
1010                                (if (typep attrib 'sql-ident-attribute)
1011                                    (let ((type (slot-value attrib 'type)))
1012                                      (if type
1013                                          type
1014                                          t))
1015                                    t))
1016                            (slot-value expr 'selections))))
1017              (destructuring-bind (&key (flatp nil)
1018                                        (result-types :auto)
1019                                        (field-names t) 
1020                                        (database *default-database*)
1021                                        &allow-other-keys)
1022                  qualifier-args
1023                (query expr :flatp flatp 
1024                       :result-types 
1025                       ;; specifying a type for an attribute overrides result-types
1026                       (if (some #'(lambda (x) (not (eq t x))) specified-types) 
1027                           specified-types
1028                           result-types)
1029                       :field-names field-names
1030                       :database database))))))))
1031
1032 (defun compute-records-cache-key (targets qualifiers)
1033   (list targets
1034         (do ((args *select-arguments* (cdr args))
1035              (results nil))
1036             ((null args) results)
1037           (let* ((arg (car args))
1038                  (value (getf qualifiers arg)))
1039             (when value
1040               (push (list arg
1041                           (typecase value
1042                             (cons (cons (sql (car value)) (cdr value)))
1043                             (%sql-expression (sql value))
1044                             (t value)))
1045                     results))))))
1046
1047 (defun records-cache-results (targets qualifiers database)
1048   (when (record-caches database)
1049     (gethash (compute-records-cache-key targets qualifiers) (record-caches database)))) 
1050
1051 (defun (setf records-cache-results) (results targets qualifiers database)
1052   (unless (record-caches database)
1053     (setf (record-caches database)
1054           (make-hash-table :test 'equal
1055                            #+allegro :values #+allegro :weak)))
1056   (setf (gethash (compute-records-cache-key targets qualifiers)
1057                  (record-caches database)) results)
1058   results)
1059
1060 (defun update-cached-results (targets qualifiers database)
1061   ;; FIXME: this routine will need to update slots in cached objects, perhaps adding or removing objects from cached
1062   ;; for now, dump cache entry and perform fresh search
1063   (let ((res (apply #'find-all targets qualifiers)))
1064     (setf (gethash (compute-records-cache-key targets qualifiers)
1065                    (record-caches database)) res)
1066     res))
1067