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