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