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