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