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