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