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