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