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