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