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