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