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