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