made select accept a parameters argument. If parameters are supplied, it builds
[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 database db-type))
477   (cond
478     ((null type) val) ;;we have no desired type, just give the value
479     ((typep val type) val) ;;check that it hasn't already been converted.
480     ((typep val 'string) (read-from-string val)) ;;maybe read will just take care of it?
481     (T (error "Unable to read-sql-value ~a as type ~a" val type))))
482
483 (defmethod read-sql-value (val (type (eql 'string)) database db-type)
484   (declare (ignore database db-type))
485   val)
486
487 (defmethod read-sql-value (val (type (eql 'varchar)) database db-type)
488   (declare (ignore database db-type))
489   val)
490
491 (defmethod read-sql-value (val (type (eql 'char)) database db-type)
492   (declare (ignore database db-type))
493   (schar val 0))
494
495 (defmethod read-sql-value (val (type (eql 'keyword)) database db-type)
496   (declare (ignore database db-type))
497   (when (< 0 (length val))
498     (intern (symbol-name-default-case val)
499             (find-package '#:keyword))))
500
501 (defmethod read-sql-value (val (type (eql 'symbol)) database db-type)
502   (declare (ignore database db-type))
503   (when (< 0 (length val))
504     (unless (string= val (symbol-name-default-case "NIL"))
505       (read-from-string val))))
506
507 (defmethod read-sql-value (val (type (eql 'integer)) database db-type)
508   (declare (ignore database db-type))
509   (etypecase val
510     (string
511      (unless (string-equal "NIL" val)
512        (parse-integer val)))
513     (number val)))
514
515 (defmethod read-sql-value (val (type (eql 'smallint)) database db-type)
516   (declare (ignore database db-type))
517   (etypecase val
518     (string
519      (unless (string-equal "NIL" val)
520        (parse-integer val)))
521     (number val)))
522
523 (defmethod read-sql-value (val (type (eql 'bigint)) database db-type)
524   (declare (ignore database db-type))
525   (etypecase val
526     (string
527      (unless (string-equal "NIL" val)
528        (parse-integer val)))
529     (number val)))
530
531 (defmethod read-sql-value (val (type (eql 'float)) database db-type)
532   (declare (ignore database db-type))
533   ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
534   (etypecase val
535     (string
536      (float (read-from-string val)))
537     (float
538      val)))
539
540 (defmethod read-sql-value (val (type (eql 'boolean)) database db-type)
541   (declare (ignore database db-type))
542   (equal "t" val))
543
544 (defmethod read-sql-value (val (type (eql 'generalized-boolean)) database db-type)
545   (declare (ignore database db-type))
546   (equal "t" val))
547
548 (defmethod read-sql-value (val (type (eql 'number)) database db-type)
549   (declare (ignore database db-type))
550   (etypecase val
551     (string
552      (unless (string-equal "NIL" val)
553        (read-from-string val)))
554     (number val)))
555
556 (defmethod read-sql-value (val (type (eql 'universal-time)) database db-type)
557   (declare (ignore database db-type))
558   (unless (eq 'NULL val)
559     (etypecase val
560       (string
561        (parse-integer val))
562       (number val))))
563
564 (defmethod read-sql-value (val (type (eql 'wall-time)) database db-type)
565   (declare (ignore database db-type))
566   (unless (eq 'NULL val)
567     (parse-timestring val)))
568
569 (defmethod read-sql-value (val (type (eql 'date)) database db-type)
570   (declare (ignore database db-type))
571   (unless (eq 'NULL val)
572     (parse-datestring val)))
573
574 (defmethod read-sql-value (val (type (eql 'duration)) database db-type)
575   (declare (ignore database db-type))
576   (unless (or (eq 'NULL val)
577               (equal "NIL" val))
578     (parse-timestring val)))
579
580 ;; ------------------------------------------------------------
581 ;; Logic for 'faulting in' :join slots
582
583 ;; this works, but is inefficient requiring (+ 1 n-rows)
584 ;; SQL queries
585 #+ignore
586 (defun fault-join-target-slot (class object slot-def)
587   (let* ((res (fault-join-slot-raw class object slot-def))
588          (dbi (view-class-slot-db-info slot-def))
589          (target-name (gethash :target-slot dbi))
590          (target-class (find-class target-name)))
591     (when res
592       (mapcar (lambda (obj)
593                 (list
594                  (car
595                   (fault-join-slot-raw
596                    target-class
597                    obj
598                    (find target-name (class-slots (class-of obj))
599                          :key #'slot-definition-name)))
600                  obj))
601               res)
602       #+ignore ;; this doesn't work when attempting to call slot-value
603       (mapcar (lambda (obj)
604                 (cons obj (slot-value obj ts))) res))))
605
606 (defun fault-join-target-slot (class object slot-def)
607   (let* ((dbi (view-class-slot-db-info slot-def))
608          (ts (gethash :target-slot dbi))
609          (jc  (gethash :join-class dbi))
610          (jc-view-table (view-table (find-class jc)))
611          (tdbi (view-class-slot-db-info
612                 (find ts (class-slots (find-class jc))
613                       :key #'slot-definition-name)))
614          (retrieval (gethash :retrieval tdbi))
615          (tsc (gethash :join-class tdbi))
616          (ts-view-table (view-table (find-class tsc)))
617          (jq (join-qualifier class object slot-def))
618          (key (slot-value object (gethash :home-key dbi))))
619
620     (when jq
621       (ecase retrieval
622         (:immediate
623          (let ((res
624                 (find-all (list tsc)
625                           :inner-join (sql-expression :table jc-view-table)
626                           :on (sql-operation
627                                '==
628                                (sql-expression
629                                 :attribute (gethash :foreign-key tdbi)
630                                 :table ts-view-table)
631                                (sql-expression
632                                 :attribute (gethash :home-key tdbi)
633                                 :table jc-view-table))
634                           :where jq
635                           :result-types :auto
636                           :database (choose-database-for-instance object))))
637            (mapcar #'(lambda (i)
638                        (let* ((instance (car i))
639                               (jcc (make-instance jc :view-database (choose-database-for-instance object))))
640                          (setf (slot-value jcc (gethash :foreign-key dbi))
641                                key)
642                          (setf (slot-value jcc (gethash :home-key tdbi))
643                                (slot-value instance (gethash :foreign-key tdbi)))
644                       (list instance jcc)))
645                    res)))
646         (:deferred
647             ;; just fill in minimal slots
648             (mapcar
649              #'(lambda (k)
650                  (let ((instance (make-instance tsc :view-database (choose-database-for-instance object)))
651                        (jcc (make-instance jc :view-database (choose-database-for-instance object)))
652                        (fk (car k)))
653                    (setf (slot-value instance (gethash :home-key tdbi)) fk)
654                    (setf (slot-value jcc (gethash :foreign-key dbi))
655                          key)
656                    (setf (slot-value jcc (gethash :home-key tdbi))
657                          fk)
658                    (list instance jcc)))
659              (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
660                      :from (sql-expression :table jc-view-table)
661                      :where jq
662                      :database (choose-database-for-instance object))))))))
663
664
665 ;;; Remote Joins
666
667 (defvar *default-update-objects-max-len* nil
668   "The default value to use for the MAX-LEN keyword argument to
669   UPDATE-OBJECT-JOINS.")
670
671 (defun update-objects-joins (objects &key (slots t) (force-p t)
672                             class-name (max-len
673                             *default-update-objects-max-len*))
674   "Updates from the records of the appropriate database tables
675 the join slots specified by SLOTS in the supplied list of View
676 Class instances OBJECTS.  SLOTS is t by default which means that
677 all join slots with :retrieval :immediate are updated. CLASS-NAME
678 is used to specify the View Class of all instance in OBJECTS and
679 default to nil which means that the class of the first instance
680 in OBJECTS is used. FORCE-P is t by default which means that all
681 join slots are updated whereas a value of nil means that only
682 unbound join slots are updated. MAX-LEN defaults to
683 *DEFAULT-UPDATE-OBJECTS-MAX-LEN* and when non-nil specifies that
684 UPDATE-OBJECT-JOINS may issue multiple database queries with a
685 maximum of MAX-LEN instances updated in each query."
686   (assert (or (null max-len) (plusp max-len)))
687   (when objects
688     (unless class-name
689       (setq class-name (class-name (class-of (first objects)))))
690     (let* ((class (find-class class-name))
691            (class-slots (ordered-class-slots class))
692            (slotdefs
693             (if (eq t slots)
694                 (generate-retrieval-joins-list class :deferred)
695               (remove-if #'null
696                          (mapcar #'(lambda (name)
697                                      (let ((slotdef (find name class-slots :key #'slot-definition-name)))
698                                        (unless slotdef
699                                          (warn "Unable to find slot named ~S in class ~S." name class))
700                                        slotdef))
701                                  slots)))))
702       (dolist (slotdef slotdefs)
703         (let* ((dbi (view-class-slot-db-info slotdef))
704                (slotdef-name (slot-definition-name slotdef))
705                (foreign-key (gethash :foreign-key dbi))
706                (home-key (gethash :home-key dbi))
707                (object-keys
708                 (remove-duplicates
709                  (if force-p
710                      (mapcar #'(lambda (o) (slot-value o home-key)) objects)
711                    (remove-if #'null
712                               (mapcar
713                                #'(lambda (o) (if (slot-boundp o slotdef-name)
714                                                  nil
715                                                (slot-value o home-key)))
716                                objects)))))
717                (n-object-keys (length object-keys))
718                (query-len (or max-len n-object-keys)))
719
720           (do ((i 0 (+ i query-len)))
721               ((>= i n-object-keys))
722             (let* ((keys (if max-len
723                              (subseq object-keys i (min (+ i query-len) n-object-keys))
724                            object-keys))
725                    (results (unless (gethash :target-slot dbi)
726                                 (find-all (list (gethash :join-class dbi))
727                               :where (make-instance 'sql-relational-exp
728                                                     :operator 'in
729                                                     :sub-expressions (list (sql-expression :attribute foreign-key)
730                                                                            keys))
731                               :result-types :auto
732                               :flatp t)) ))
733
734               (dolist (object objects)
735                 (when (or force-p (not (slot-boundp object slotdef-name)))
736                   (let ((res (if results
737                                  (remove-if-not #'(lambda (obj)
738                                                     (equal obj (slot-value
739                                                                 object
740                                                                 home-key)))
741                                                 results
742                                                 :key #'(lambda (res)
743                                                          (slot-value res
744                                                                      foreign-key)))
745
746                                  (progn
747                                    (when (gethash :target-slot dbi)
748                                      (fault-join-target-slot class object slotdef))))))
749                     (when res
750                       (setf (slot-value object slotdef-name)
751                             (if (gethash :set dbi) res (car res)))))))))))))
752   (values))
753
754 (defun fault-join-slot-raw (class object slot-def)
755   (let* ((dbi (view-class-slot-db-info slot-def))
756          (jc (gethash :join-class dbi)))
757     (let ((jq (join-qualifier class object slot-def)))
758       (when jq
759         (select jc :where jq :flatp t :result-types nil
760                 :database (choose-database-for-instance object))))))
761
762 (defun fault-join-slot (class object slot-def)
763   (let* ((dbi (view-class-slot-db-info slot-def))
764          (ts (gethash :target-slot dbi)))
765     (if (and ts (gethash :set dbi))
766         (fault-join-target-slot class object slot-def)
767         (let ((res (fault-join-slot-raw class object slot-def)))
768           (when res
769             (cond
770               ((and ts (not (gethash :set dbi)))
771                (mapcar (lambda (obj) (slot-value obj ts)) res))
772               ((and (not ts) (not (gethash :set dbi)))
773                (car res))
774               ((and (not ts) (gethash :set dbi))
775                res)))))))
776
777 (defun join-qualifier (class object slot-def)
778     (declare (ignore class))
779     (let* ((dbi (view-class-slot-db-info slot-def))
780            (jc (find-class (gethash :join-class dbi)))
781            ;;(ts (gethash :target-slot dbi))
782            ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
783            (foreign-keys (gethash :foreign-key dbi))
784            (home-keys (gethash :home-key dbi)))
785       (when (every #'(lambda (slt)
786                        (and (slot-boundp object slt)
787                             (not (null (slot-value object slt)))))
788                    (if (listp home-keys) home-keys (list home-keys)))
789         (let ((jc
790                (mapcar #'(lambda (hk fk)
791                            (let ((fksd (slotdef-for-slot-with-class fk jc)))
792                              (sql-operation '==
793                                             (typecase fk
794                                               (symbol
795                                                (sql-expression
796                                                 :attribute
797                                                 (view-class-slot-column fksd)
798                                                 :table (view-table jc)))
799                                               (t fk))
800                                             (typecase hk
801                                               (symbol
802                                                (slot-value object hk))
803                                               (t
804                                                hk)))))
805                        (if (listp home-keys)
806                            home-keys
807                            (list home-keys))
808                        (if (listp foreign-keys)
809                            foreign-keys
810                            (list foreign-keys)))))
811           (when jc
812             (if (> (length jc) 1)
813                 (apply #'sql-and jc)
814                 jc))))))
815
816 ;; FIXME: add retrieval immediate for efficiency
817 ;; For example, for (select 'employee-address) in test suite =>
818 ;; select addr.*,ea_join.* FROM addr,ea_join WHERE ea_join.aaddressid=addr.addressid\g
819
820 (defun build-objects (vals sclasses immediate-join-classes sels immediate-joins database refresh flatp instances)
821   "Used by find-all to build objects."
822   (labels ((build-object (vals vclass jclasses selects immediate-selects instance)
823              (let* ((db-vals (butlast vals (- (list-length vals)
824                                               (list-length selects))))
825                     (obj (if instance instance (make-instance (class-name vclass) :view-database database)))
826                     (join-vals (subseq vals (list-length selects)))
827                     (joins (mapcar #'(lambda (c) (when c (make-instance c :view-database database)))
828                                    jclasses)))
829
830                ;;(format t "joins: ~S~%db-vals: ~S~%join-values: ~S~%selects: ~S~%immediate-selects: ~S~%"
831                ;;joins db-vals join-vals selects immediate-selects)
832
833                ;; use refresh keyword here
834                (setf obj (get-slot-values-from-view obj (mapcar #'car selects) db-vals))
835                (mapc #'(lambda (jo)
836                          ;; find all immediate-select slots and join-vals for this object
837                          (let* ((slots (class-slots (class-of jo)))
838                                 (pos-list (remove-if #'null
839                                                      (mapcar
840                                                       #'(lambda (s)
841                                                           (position s immediate-selects
842                                                                     :key #'car
843                                                                     :test #'eq))
844                                                       slots))))
845                            (get-slot-values-from-view jo
846                                                       (mapcar #'car
847                                                               (mapcar #'(lambda (pos)
848                                                                           (nth pos immediate-selects))
849                                                                       pos-list))
850                                                       (mapcar #'(lambda (pos) (nth pos join-vals))
851                                                               pos-list))))
852                      joins)
853                (mapc
854                 #'(lambda (jc)
855                     (let ((slot (find (class-name (class-of jc)) (class-slots vclass)
856                                       :key #'(lambda (slot)
857                                                (when (and (eq :join (view-class-slot-db-kind slot))
858                                                           (eq (slot-definition-name slot)
859                                                               (gethash :join-class (view-class-slot-db-info slot))))
860                                                  (slot-definition-name slot))))))
861                       (when slot
862                         (setf (slot-value obj (slot-definition-name slot)) jc))))
863                 joins)
864                (when refresh (instance-refreshed obj))
865                obj)))
866     (let* ((objects
867             (mapcar #'(lambda (sclass jclass sel immediate-join instance)
868                         (prog1
869                             (build-object vals sclass jclass sel immediate-join instance)
870                           (setf vals (nthcdr (+ (list-length sel) (list-length immediate-join))
871                                              vals))))
872                     sclasses immediate-join-classes sels immediate-joins instances)))
873       (if (and flatp (= (length sclasses) 1))
874           (car objects)
875         objects))))
876
877 (defmethod select-table-sql-expr ((table T))
878   "Turns an object representing a table into the :from part of the sql expression that will be executed "
879   (sql-expression :table (view-table table)))
880
881 (defun find-all (view-classes
882                  &rest args
883                  &key all set-operation distinct from where group-by having
884                       order-by offset limit refresh flatp result-types
885                       inner-join on
886                       (database *default-database*)
887                       instances parameters)
888   "Called by SELECT to generate object query results when the
889   View Classes VIEW-CLASSES are passed as arguments to SELECT."
890   (declare (ignore all set-operation group-by having offset limit inner-join on))
891   (flet ((ref-equal (ref1 ref2)
892            (string= (sql-output ref1 database)
893                     (sql-output ref2 database)))
894          (tables-equal (table-a table-b)
895            (when (and table-a table-b)
896              (string= (string (slot-value table-a 'name))
897                       (string (slot-value table-b 'name))))))
898     (remf args :from)
899     (remf args :where)
900     (remf args :flatp)
901     (remf args :additional-fields)
902     (remf args :result-types)
903     (remf args :instances)
904     (let* ((*db-deserializing* t)
905            (sclasses (mapcar #'find-class view-classes))
906            (immediate-join-slots
907             (mapcar #'(lambda (c) (generate-retrieval-joins-list c :immediate)) sclasses))
908            (immediate-join-classes
909             (mapcar #'(lambda (jcs)
910                         (mapcar #'(lambda (slotdef)
911                                     (find-class (gethash :join-class (view-class-slot-db-info slotdef))))
912                                 jcs))
913                     immediate-join-slots))
914            (immediate-join-sels (mapcar #'generate-immediate-joins-selection-list sclasses))
915            (sels (mapcar #'generate-selection-list sclasses))
916            (fullsels (apply #'append (mapcar #'append sels immediate-join-sels)))
917            (sel-tables (collect-table-refs where))
918            (tables (remove-if #'null
919                               (remove-duplicates
920                                (append (mapcar #'select-table-sql-expr sclasses)
921                                        (mapcan #'(lambda (jc-list)
922                                                    (mapcar
923                                                     #'(lambda (jc) (when jc (select-table-sql-expr jc)))
924                                                     jc-list))
925                                                immediate-join-classes)
926                                        sel-tables)
927                                :test #'tables-equal)))
928            (order-by-slots (mapcar #'(lambda (ob) (if (atom ob) ob (car ob)))
929                                    (listify order-by)))
930            (join-where nil))
931
932       ;;(format t "sclasses: ~W~%ijc: ~W~%tables: ~W~%" sclasses immediate-join-classes tables)
933
934       (dolist (ob order-by-slots)
935         (when (and ob (not (member ob (mapcar #'cdr fullsels)
936                                    :test #'ref-equal)))
937           (setq fullsels
938             (append fullsels (mapcar #'(lambda (att) (cons nil att))
939                                      order-by-slots)))))
940       (dolist (ob (listify distinct))
941         (when (and (typep ob 'sql-ident)
942                    (not (member ob (mapcar #'cdr fullsels)
943                                 :test #'ref-equal)))
944           (setq fullsels
945               (append fullsels (mapcar #'(lambda (att) (cons nil att))
946                                        (listify ob))))))
947       (mapcar #'(lambda (vclass jclasses jslots)
948                   (when jclasses
949                     (mapcar
950                      #'(lambda (jclass jslot)
951                          (let ((dbi (view-class-slot-db-info jslot)))
952                            (setq join-where
953                              (append
954                               (list (sql-operation '==
955                                                    (sql-expression
956                                                     :attribute (gethash :foreign-key dbi)
957                                                     :table (view-table jclass))
958                                                    (sql-expression
959                                                     :attribute (gethash :home-key dbi)
960                                                     :table (view-table vclass))))
961                               (when join-where (listify join-where))))))
962                      jclasses jslots)))
963               sclasses immediate-join-classes immediate-join-slots)
964       ;; Reported buggy on clsql-devel
965       ;; (when where (setq where (listify where)))
966       (cond
967        ((and where join-where)
968         (setq where (list (apply #'sql-and where join-where))))
969        ((and (null where) (> (length join-where) 1))
970         (setq where (list (apply #'sql-and join-where)))))
971
972       (let* ((rows (apply #'select
973                           (append (mapcar #'cdr fullsels)
974                                   (cons :from
975                                         (list (append (when from (listify from))
976                                                       (listify tables))))
977                                   (list :result-types result-types)
978                                   (when where
979                                     (list :where where))
980                                   args)))
981              (instances-to-add (- (length rows) (length instances)))
982              (perhaps-extended-instances
983               (if (plusp instances-to-add)
984                   (append instances (do ((i 0 (1+ i))
985                                          (res nil))
986                                         ((= i instances-to-add) res)
987                                       (push (make-list (length sclasses) :initial-element nil) res)))
988                 instances))
989              (objects (mapcar
990                        #'(lambda (row instance)
991                            (build-objects row sclasses immediate-join-classes sels
992                                           immediate-join-sels database refresh flatp
993                                           (if (and flatp (atom instance))
994                                               (list instance)
995                                             instance)))
996                        rows perhaps-extended-instances)))
997         objects))))
998
999 (defmethod instance-refreshed ((instance standard-db-object)))
1000
1001 (defvar *default-caching* t
1002   "Controls whether SELECT caches objects by default. The CommonSQL
1003 specification states caching is on by default.")
1004
1005 (defun select (&rest select-all-args)
1006    "Executes a query on DATABASE, which has a default value of
1007 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
1008 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
1009 argument can be used to generate queries in both functional and
1010 object oriented contexts.
1011
1012 In the functional case, the required arguments specify the
1013 columns selected by the query and may be symbolic SQL expressions
1014 or strings representing attribute identifiers. Type modified
1015 identifiers indicate that the values selected from the specified
1016 column are converted to the specified lisp type. The keyword
1017 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
1018 SET-OPERATION and WHERE are used to specify, using the symbolic
1019 SQL syntax, the corresponding components of the SQL query
1020 generated by the call to SELECT. RESULT-TYPES is a list of
1021 symbols which specifies the lisp type for each field returned by
1022 the query. If RESULT-TYPES is nil all results are returned as
1023 strings whereas the default value of :auto means that the lisp
1024 types are automatically computed for each field. FIELD-NAMES is t
1025 by default which means that the second value returned is a list
1026 of strings representing the columns selected by the query. If
1027 FIELD-NAMES is nil, the list of column names is not returned as a
1028 second value.
1029
1030 In the object oriented case, the required arguments to SELECT are
1031 symbols denoting View Classes which specify the database tables
1032 to query. In this case, SELECT returns a list of View Class
1033 instances whose slots are set from the attribute values of the
1034 records in the specified table. Slot-value is a legal operator
1035 which can be employed as part of the symbolic SQL syntax used in
1036 the WHERE keyword argument to SELECT. REFRESH is nil by default
1037 which means that the View Class instances returned are retrieved
1038 from a cache if an equivalent call to SELECT has previously been
1039 issued. If REFRESH is true, the View Class instances returned are
1040 updated as necessary from the database and the generic function
1041 INSTANCE-REFRESHED is called to perform any necessary operations
1042 on the updated instances.
1043
1044 In both object oriented and functional contexts, FLATP has a
1045 default value of nil which means that the results are returned as
1046 a list of lists. If FLATP is t and only one result is returned
1047 for each record selected in the query, the results are returned
1048 as elements of a list."
1049
1050    (flet ((select-objects (target-args)
1051             (and target-args
1052                  (every #'(lambda (arg)
1053                             (and (symbolp arg)
1054                                  (find-class arg nil)))
1055                         target-args))))
1056      (multiple-value-bind (target-args qualifier-args)
1057          (query-get-selections select-all-args)
1058        (unless (or *default-database* (getf qualifier-args :database))
1059          (signal-no-database-error nil))
1060
1061        (cond
1062          ((select-objects target-args)
1063           (let ((caching (getf qualifier-args :caching *default-caching*))
1064                 (result-types (getf qualifier-args :result-types :auto))
1065                 (refresh (getf qualifier-args :refresh nil))
1066                 (database (or (getf qualifier-args :database) *default-database*))
1067                 (order-by (getf qualifier-args :order-by)))
1068             (remf qualifier-args :caching)
1069             (remf qualifier-args :refresh)
1070             (remf qualifier-args :result-types)
1071
1072             ;; Add explicity table name to order-by if not specified and only
1073             ;; one selected table. This is required so FIND-ALL won't duplicate
1074             ;; the field
1075             (when (and order-by (= 1 (length target-args)))
1076               (let ((table-name (view-table (find-class (car target-args))))
1077                     (order-by-list (copy-seq (listify order-by))))
1078
1079                 (loop for i from 0 below (length order-by-list)
1080                    do (typecase (nth i order-by-list)
1081                            (sql-ident-attribute
1082                             (handler-case
1083                                 (unless (slot-value (nth i order-by-list) 'qualifier)
1084                                   (setf (slot-value (nth i order-by-list) 'qualifier) table-name))
1085                               (simple-error ())))
1086                            (cons
1087                             (handler-case
1088                              (unless (slot-value (car (nth i order-by-list)) 'qualifier)
1089                                (setf (slot-value (car (nth i order-by-list)) 'qualifier) table-name))
1090                               (simple-error ())))
1091                            (clsql-sys:sql-function-exp)))
1092                 (setf (getf qualifier-args :order-by) order-by-list)))
1093
1094             (cond
1095               ((null caching)
1096                (apply #'find-all target-args
1097                       (append qualifier-args
1098                               (list :result-types result-types :refresh refresh))))
1099               (t
1100                (let ((cached (records-cache-results target-args qualifier-args database)))
1101                  (cond
1102                    ((and cached (not refresh))
1103                     cached)
1104                    ((and cached refresh)
1105                     (let ((results (apply #'find-all (append (list target-args) qualifier-args `(:instances ,cached :result-types :auto :refresh ,refresh)))))
1106                       (setf (records-cache-results target-args qualifier-args database) results)
1107                       results))
1108                    (t
1109                     (let ((results (apply #'find-all target-args (append qualifier-args
1110                                                                          `(:result-types :auto :refresh ,refresh)))))
1111                       (setf (records-cache-results target-args qualifier-args database) results)
1112                       results))))))))
1113          (t
1114           (let* ((expr (apply #'make-query select-all-args))
1115                  (parameters (second (member :parameters select-all-args)))
1116                  (specified-types
1117                   (mapcar #'(lambda (attrib)
1118                               (if (typep attrib 'sql-ident-attribute)
1119                                   (let ((type (slot-value attrib 'type)))
1120                                     (if type
1121                                         type
1122                                         t))
1123                                   t))
1124                           (slot-value expr 'selections))))
1125             
1126             (destructuring-bind (&key (flatp nil)
1127                                  (result-types :auto)
1128                                  (field-names t)
1129                                  (database *default-database*)
1130                                  &allow-other-keys)
1131                 qualifier-args
1132               (when parameters
1133                 (setf expr (make-instance 'command-object
1134                                           :expression (sql-output expr database)
1135                                           :parameters parameters)))
1136               (query expr :flatp flatp
1137                      :result-types
1138                      ;; specifying a type for an attribute overrides result-types
1139                      (if (some #'(lambda (x) (not (eq t x))) specified-types)
1140                          specified-types
1141                          result-types)
1142                      :field-names field-names
1143                      :database database))))))))
1144
1145 (defun compute-records-cache-key (targets qualifiers)
1146   (list targets
1147         (do ((args *select-arguments* (cdr args))
1148              (results nil))
1149             ((null args) results)
1150           (let* ((arg (car args))
1151                  (value (getf qualifiers arg)))
1152             (when value
1153               (push (list arg
1154                           (typecase value
1155                             (cons (cons (sql (car value)) (cdr value)))
1156                             (%sql-expression (sql value))
1157                             (t value)))
1158                     results))))))
1159
1160 (defun records-cache-results (targets qualifiers database)
1161   (when (record-caches database)
1162     (gethash (compute-records-cache-key targets qualifiers) (record-caches database))))
1163
1164 (defun (setf records-cache-results) (results targets qualifiers database)
1165   (unless (record-caches database)
1166     (setf (record-caches database)
1167           (make-hash-table :test 'equal
1168                            #+allegro   :values    #+allegro :weak
1169                            #+clisp     :weak      #+clisp :value
1170                            #+lispworks :weak-kind #+lispworks :value)))
1171   (setf (gethash (compute-records-cache-key targets qualifiers)
1172                  (record-caches database)) results)
1173   results)
1174
1175
1176
1177 ;;; Serialization functions
1178
1179 (defun write-instance-to-stream (obj stream)
1180   "Writes an instance to a stream where it can be later be read.
1181 NOTE: an error will occur if a slot holds a value which can not be written readably."
1182   (let* ((class (class-of obj))
1183          (alist '()))
1184     (dolist (slot (ordered-class-slots (class-of obj)))
1185       (let ((name (slot-definition-name slot)))
1186         (when (and (not (eq 'view-database name))
1187                    (slot-boundp obj name))
1188           (push (cons name (slot-value obj name)) alist))))
1189     (setq alist (reverse alist))
1190     (write (cons (class-name class) alist) :stream stream :readably t))
1191   obj)
1192
1193 (defun read-instance-from-stream (stream)
1194   (let ((raw (read stream nil nil)))
1195     (when raw
1196       (let ((obj (make-instance (car raw))))
1197         (dolist (pair (cdr raw))
1198           (setf (slot-value obj (car pair)) (cdr pair)))
1199         obj))))