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