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