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