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