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