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