Version 4.0.6
[clsql/s11.git] / sql / oodml.lisp
blobf797be0b02b36d611021bdffa4e9d3afc9477fea
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;;
4 ;;;; $Id$
5 ;;;;
6 ;;;; The CLSQL Object Oriented Data Manipulation Language (OODML).
7 ;;;;
8 ;;;; This file is part of CLSQL.
9 ;;;;
10 ;;;; CLSQL users are granted the rights to distribute and use this software
11 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
12 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
13 ;;;; *************************************************************************
15 (in-package #:clsql-sys)
18 (defun key-qualifier-for-instance (obj &key (database *default-database*))
19 (let ((tb (view-table (class-of obj))))
20 (flet ((qfk (k)
21 (sql-operation '==
22 (sql-expression :attribute
23 (view-class-slot-column k)
24 :table tb)
25 (db-value-from-slot
27 (slot-value obj (slot-definition-name k))
28 database))))
29 (let* ((keys (keyslots-for-class (class-of obj)))
30 (keyxprs (mapcar #'qfk (reverse keys))))
31 (cond
32 ((= (length keyxprs) 0) nil)
33 ((= (length keyxprs) 1) (car keyxprs))
34 ((> (length keyxprs) 1) (apply #'sql-operation 'and keyxprs)))))))
37 ;; Function used by 'generate-selection-list'
40 (defun generate-attribute-reference (vclass slotdef)
41 (cond
42 ((eq (view-class-slot-db-kind slotdef) :base)
43 (sql-expression :attribute (view-class-slot-column slotdef)
44 :table (view-table vclass)))
45 ((eq (view-class-slot-db-kind slotdef) :key)
46 (sql-expression :attribute (view-class-slot-column slotdef)
47 :table (view-table vclass)))
48 (t nil)))
51 ;; Function used by 'find-all'
54 (defun generate-selection-list (vclass)
55 (let ((sels nil))
56 (dolist (slotdef (ordered-class-slots vclass))
57 (let ((res (generate-attribute-reference vclass slotdef)))
58 (when res
59 (push (cons slotdef res) sels))))
60 (if sels
61 sels
62 (error "No slots of type :base in view-class ~A" (class-name vclass)))))
66 (defun generate-retrieval-joins-list (vclass retrieval-method)
67 "Returns list of immediate join slots for a class."
68 (let ((join-slotdefs nil))
69 (dolist (slotdef (ordered-class-slots vclass) join-slotdefs)
70 (when (and (eq :join (view-class-slot-db-kind slotdef))
71 (eq retrieval-method (gethash :retrieval (view-class-slot-db-info slotdef))))
72 (push slotdef join-slotdefs)))))
74 (defun generate-immediate-joins-selection-list (vclass)
75 "Returns list of immediate join slots for a class."
76 (let (sels)
77 (dolist (joined-slot (generate-retrieval-joins-list vclass :immediate) sels)
78 (let* ((join-class-name (gethash :join-class (view-class-slot-db-info joined-slot)))
79 (join-class (when join-class-name (find-class join-class-name))))
80 (dolist (slotdef (ordered-class-slots join-class))
81 (let ((res (generate-attribute-reference join-class slotdef)))
82 (when res
83 (push (cons slotdef res) sels))))))
84 sels))
87 ;; Called by 'get-slot-values-from-view'
90 (defmethod update-slot-from-db ((instance standard-db-object) slotdef value)
91 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
92 (let* ((slot-reader (view-class-slot-db-reader slotdef))
93 (slot-name (slot-definition-name slotdef))
94 (slot-type (specified-type slotdef)))
95 (cond ((and value (null slot-reader))
96 (setf (slot-value instance slot-name)
97 (read-sql-value value (delistify slot-type)
98 (view-database instance)
99 (database-underlying-type
100 (view-database instance)))))
101 ((null value)
102 (update-slot-with-null instance slot-name slotdef))
103 ((typep slot-reader 'string)
104 (setf (slot-value instance slot-name)
105 (format nil slot-reader value)))
106 ((typep slot-reader '(or symbol function))
107 (setf (slot-value instance slot-name)
108 (apply slot-reader (list value))))
110 (error "Slot reader is of an unusual type.")))))
112 (defmethod key-value-from-db (slotdef value database)
113 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
114 (let ((slot-reader (view-class-slot-db-reader slotdef))
115 (slot-type (specified-type slotdef)))
116 (cond ((and value (null slot-reader))
117 (read-sql-value value (delistify slot-type) database
118 (database-underlying-type database)))
119 ((null value)
120 nil)
121 ((typep slot-reader 'string)
122 (format nil slot-reader value))
123 ((typep slot-reader '(or symbol function))
124 (apply slot-reader (list value)))
126 (error "Slot reader is of an unusual type.")))))
128 (defun db-value-from-slot (slotdef val database)
129 (let ((dbwriter (view-class-slot-db-writer slotdef))
130 (dbtype (specified-type slotdef)))
131 (typecase dbwriter
132 (string (format nil dbwriter val))
133 ((and (or symbol function) (not null)) (apply dbwriter (list val)))
135 (database-output-sql-as-type
136 (typecase dbtype
137 (cons (car dbtype))
138 (t dbtype))
139 val database (database-underlying-type database))))))
141 (defun check-slot-type (slotdef val)
142 (let* ((slot-type (specified-type slotdef))
143 (basetype (if (listp slot-type) (car slot-type) slot-type)))
144 (when (and slot-type val)
145 (unless (typep val basetype)
146 (error 'sql-user-error
147 :message
148 (format nil "Invalid value ~A in slot ~A, not of type ~A."
149 val (slot-definition-name slotdef) slot-type))))))
152 ;; Called by find-all
155 (defmethod get-slot-values-from-view (obj slotdeflist values)
156 (flet ((update-slot (slot-def values)
157 (update-slot-from-db obj slot-def values)))
158 (mapc #'update-slot slotdeflist values)
159 obj))
161 (defmethod update-record-from-slot ((obj standard-db-object) slot &key
162 (database *default-database*))
163 (let* ((database (or (view-database obj) database))
164 (vct (view-table (class-of obj)))
165 (sd (slotdef-for-slot-with-class slot (class-of obj))))
166 (check-slot-type sd (slot-value obj slot))
167 (let* ((att (view-class-slot-column sd))
168 (val (db-value-from-slot sd (slot-value obj slot) database)))
169 (cond ((and vct sd (view-database obj))
170 (update-records (sql-expression :table vct)
171 :attributes (list (sql-expression :attribute att))
172 :values (list val)
173 :where (key-qualifier-for-instance
174 obj :database database)
175 :database database))
176 ((and vct sd (not (view-database obj)))
177 (insert-records :into (sql-expression :table vct)
178 :attributes (list (sql-expression :attribute att))
179 :values (list val)
180 :database database)
181 (setf (slot-value obj 'view-database) database))
183 (error "Unable to update record.")))))
184 (values))
186 (defmethod update-record-from-slots ((obj standard-db-object) slots &key
187 (database *default-database*))
188 (let* ((database (or (view-database obj) database))
189 (vct (view-table (class-of obj)))
190 (sds (slotdefs-for-slots-with-class slots (class-of obj)))
191 (avps (mapcar #'(lambda (s)
192 (let ((val (slot-value
193 obj (slot-definition-name s))))
194 (check-slot-type s val)
195 (list (sql-expression
196 :attribute (view-class-slot-column s))
197 (db-value-from-slot s val database))))
198 sds)))
199 (cond ((and avps (view-database obj))
200 (update-records (sql-expression :table vct)
201 :av-pairs avps
202 :where (key-qualifier-for-instance
203 obj :database database)
204 :database database))
205 ((and avps (not (view-database obj)))
206 (insert-records :into (sql-expression :table vct)
207 :av-pairs avps
208 :database database)
209 (setf (slot-value obj 'view-database) database))
211 (error "Unable to update records"))))
212 (values))
214 (defmethod update-records-from-instance ((obj standard-db-object) &key database)
215 (let ((database (or database (view-database obj) *default-database*)))
216 (labels ((slot-storedp (slot)
217 (and (member (view-class-slot-db-kind slot) '(:base :key))
218 (slot-boundp obj (slot-definition-name slot))))
219 (slot-value-list (slot)
220 (let ((value (slot-value obj (slot-definition-name slot))))
221 (check-slot-type slot value)
222 (list (sql-expression :attribute (view-class-slot-column slot))
223 (db-value-from-slot slot value database)))))
224 (let* ((view-class (class-of obj))
225 (view-class-table (view-table view-class))
226 (slots (remove-if-not #'slot-storedp
227 (ordered-class-slots view-class)))
228 (record-values (mapcar #'slot-value-list slots)))
229 (unless record-values
230 (error "No settable slots."))
231 (if (view-database obj)
232 (update-records (sql-expression :table view-class-table)
233 :av-pairs record-values
234 :where (key-qualifier-for-instance
235 obj :database database)
236 :database database)
237 (progn
238 (insert-records :into (sql-expression :table view-class-table)
239 :av-pairs record-values
240 :database database)
241 (setf (slot-value obj 'view-database) database))))))
242 (values))
244 (defmethod delete-instance-records ((instance standard-db-object))
245 (let ((vt (sql-expression :table (view-table (class-of instance))))
246 (vd (view-database instance)))
247 (if vd
248 (let ((qualifier (key-qualifier-for-instance instance :database vd)))
249 (delete-records :from vt :where qualifier :database vd)
250 (setf (record-caches vd) nil)
251 (setf (slot-value instance 'view-database) nil)
252 (values))
253 (signal-no-database-error vd))))
255 (defmethod update-instance-from-records ((instance standard-db-object)
256 &key (database *default-database*))
257 (let* ((view-class (find-class (class-name (class-of instance))))
258 (view-table (sql-expression :table (view-table view-class)))
259 (vd (or (view-database instance) database))
260 (view-qual (key-qualifier-for-instance instance :database vd))
261 (sels (generate-selection-list view-class))
262 (res (apply #'select (append (mapcar #'cdr sels)
263 (list :from view-table
264 :where view-qual
265 :result-types nil
266 :database vd)))))
267 (when res
268 (get-slot-values-from-view instance (mapcar #'car sels) (car res)))))
270 (defmethod update-slot-from-record ((instance standard-db-object)
271 slot &key (database *default-database*))
272 (let* ((view-class (find-class (class-name (class-of instance))))
273 (view-table (sql-expression :table (view-table view-class)))
274 (vd (or (view-database instance) database))
275 (view-qual (key-qualifier-for-instance instance :database vd))
276 (slot-def (slotdef-for-slot-with-class slot view-class))
277 (att-ref (generate-attribute-reference view-class slot-def))
278 (res (select att-ref :from view-table :where view-qual
279 :result-types nil)))
280 (when res
281 (get-slot-values-from-view instance (list slot-def) (car res)))))
284 (defmethod update-slot-with-null ((object standard-db-object)
285 slotname
286 slotdef)
287 (setf (slot-value object slotname) (slot-value slotdef 'void-value)))
289 (defvar +no-slot-value+ '+no-slot-value+)
291 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
292 (let* ((class (find-class classname))
293 (sld (slotdef-for-slot-with-class slot class)))
294 (if sld
295 (if (eq value +no-slot-value+)
296 (sql-expression :attribute (view-class-slot-column sld)
297 :table (view-table class))
298 (db-value-from-slot
300 value
301 database))
302 (error "Unknown slot ~A for class ~A" slot classname))))
304 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
305 (declare (ignore database))
306 (let* ((class (find-class classname)))
307 (unless (view-table class)
308 (error "No view-table for class ~A" classname))
309 (sql-expression :table (view-table class))))
312 (defmethod database-get-type-specifier (type args database db-type)
313 (declare (ignore type args database db-type))
314 (format nil "VARCHAR(~D)" *default-string-length*))
316 (defmethod database-get-type-specifier ((type (eql 'integer)) args database db-type)
317 (declare (ignore database db-type))
318 (if args
319 (format nil "INT(~A)" (car args))
320 "INT"))
322 (deftype tinyint ()
323 "An 8-bit integer, this width may vary by SQL implementation."
324 'integer)
326 (defmethod database-get-type-specifier ((type (eql 'tinyint)) args database db-type)
327 (declare (ignore args database db-type))
328 "INT")
330 (deftype smallint ()
331 "An integer smaller than a 32-bit integer. this width may vary by SQL implementation."
332 'integer)
334 (defmethod database-get-type-specifier ((type (eql 'smallint)) args database db-type)
335 (declare (ignore args database db-type))
336 "INT")
338 (deftype mediumint ()
339 "An integer smaller than a 32-bit integer, but may be larger than a smallint. This width may vary by SQL implementation."
340 'integer)
342 (defmethod database-get-type-specifier ((type (eql 'mediumint)) args database db-type)
343 (declare (ignore args database db-type))
344 "INT")
346 (deftype bigint ()
347 "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
348 'integer)
350 (defmethod database-get-type-specifier ((type (eql 'bigint)) args database db-type)
351 (declare (ignore args database db-type))
352 "BIGINT")
354 (deftype varchar (&optional size)
355 "A variable length string for the SQL varchar type."
356 (declare (ignore size))
357 'string)
359 (defmethod database-get-type-specifier ((type (eql 'varchar)) args
360 database db-type)
361 (declare (ignore database db-type))
362 (if args
363 (format nil "VARCHAR(~A)" (car args))
364 (format nil "VARCHAR(~D)" *default-string-length*)))
366 (defmethod database-get-type-specifier ((type (eql 'string)) args database db-type)
367 (declare (ignore database db-type))
368 (if args
369 (format nil "CHAR(~A)" (car args))
370 (format nil "VARCHAR(~D)" *default-string-length*)))
372 (deftype universal-time ()
373 "A positive integer as returned by GET-UNIVERSAL-TIME."
374 '(integer 1 *))
376 (defmethod database-get-type-specifier ((type (eql 'universal-time)) args database db-type)
377 (declare (ignore args database db-type))
378 "BIGINT")
380 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database db-type)
381 (declare (ignore args database db-type))
382 "TIMESTAMP")
384 (defmethod database-get-type-specifier ((type (eql 'date)) args database db-type)
385 (declare (ignore args database db-type))
386 "DATE")
388 (defmethod database-get-type-specifier ((type (eql 'duration)) args database db-type)
389 (declare (ignore database args db-type))
390 "VARCHAR")
392 (defmethod database-get-type-specifier ((type (eql 'money)) args database db-type)
393 (declare (ignore database args db-type))
394 "INT8")
396 #+ignore
397 (deftype char (&optional len)
398 "A lisp type for the SQL CHAR type."
399 `(string ,len))
401 (defmethod database-get-type-specifier ((type (eql 'float)) args database db-type)
402 (declare (ignore database db-type))
403 (if args
404 (format nil "FLOAT(~A)" (car args))
405 "FLOAT"))
407 (defmethod database-get-type-specifier ((type (eql 'long-float)) args database db-type)
408 (declare (ignore database db-type))
409 (if args
410 (format nil "FLOAT(~A)" (car args))
411 "FLOAT"))
413 (deftype generalized-boolean ()
414 "A type which outputs a SQL boolean value, though any lisp type can be stored in the slot."
417 (defmethod database-get-type-specifier ((type (eql 'boolean)) args database db-type)
418 (declare (ignore args database db-type))
419 "BOOL")
421 (defmethod database-get-type-specifier ((type (eql 'generalized-boolean)) args database db-type)
422 (declare (ignore args database db-type))
423 "BOOL")
425 (defmethod database-get-type-specifier ((type (eql 'number)) args database db-type)
426 (declare (ignore database db-type))
427 (cond
428 ((and (consp args) (= (length args) 2))
429 (format nil "NUMBER(~D,~D)" (first args) (second args)))
430 ((and (consp args) (= (length args) 1))
431 (format nil "NUMBER(~D)" (first args)))
433 "NUMBER")))
435 (defmethod database-get-type-specifier ((type (eql 'char)) args database db-type)
436 (declare (ignore database db-type))
437 (if args
438 (format nil "CHAR(~D)" (first args))
439 "CHAR(1)"))
442 (defmethod database-output-sql-as-type (type val database db-type)
443 (declare (ignore type database db-type))
444 val)
446 (defmethod database-output-sql-as-type ((type (eql 'list)) val database db-type)
447 (declare (ignore database db-type))
448 (progv '(*print-circle* *print-array*) '(t t)
449 (let ((escaped (prin1-to-string val)))
450 (substitute-char-string
451 escaped #\Null " "))))
453 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database db-type)
454 (declare (ignore database db-type))
455 (if val
456 (concatenate 'string
457 (package-name (symbol-package val))
458 "::"
459 (symbol-name val))
460 ""))
462 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database db-type)
463 (declare (ignore database db-type))
464 (if val
465 (symbol-name val)
466 ""))
468 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database db-type)
469 (declare (ignore database db-type))
470 (progv '(*print-circle* *print-array*) '(t t)
471 (prin1-to-string val)))
473 (defmethod database-output-sql-as-type ((type (eql 'array)) val database db-type)
474 (declare (ignore database db-type))
475 (progv '(*print-circle* *print-array*) '(t t)
476 (prin1-to-string val)))
478 (defmethod database-output-sql-as-type ((type (eql 'boolean)) val database db-type)
479 (declare (ignore database db-type))
480 (if val "t" "f"))
482 (defmethod database-output-sql-as-type ((type (eql 'generalized-boolean)) val database db-type)
483 (declare (ignore database db-type))
484 (if val "t" "f"))
486 (defmethod database-output-sql-as-type ((type (eql 'string)) val database db-type)
487 (declare (ignore database db-type))
488 val)
490 (defmethod database-output-sql-as-type ((type (eql 'char)) val database db-type)
491 (declare (ignore database db-type))
492 (etypecase val
493 (character (write-to-string val))
494 (string val)))
496 (defmethod database-output-sql-as-type ((type (eql 'float)) val database db-type)
497 (declare (ignore database db-type))
498 (if (eq (type-of val) 'null)
500 (let ((*read-default-float-format* (type-of val)))
501 (format nil "~F" val))))
503 (defmethod read-sql-value (val type database db-type)
504 (declare (ignore type database db-type))
505 (read-from-string val))
507 (defmethod read-sql-value (val (type (eql 'string)) database db-type)
508 (declare (ignore database db-type))
509 val)
511 (defmethod read-sql-value (val (type (eql 'varchar)) database db-type)
512 (declare (ignore database db-type))
513 val)
515 (defmethod read-sql-value (val (type (eql 'char)) database db-type)
516 (declare (ignore database db-type))
517 (schar val 0))
519 (defmethod read-sql-value (val (type (eql 'keyword)) database db-type)
520 (declare (ignore database db-type))
521 (when (< 0 (length val))
522 (intern (symbol-name-default-case val)
523 (find-package '#:keyword))))
525 (defmethod read-sql-value (val (type (eql 'symbol)) database db-type)
526 (declare (ignore database db-type))
527 (when (< 0 (length val))
528 (unless (string= val (symbol-name-default-case "NIL"))
529 (read-from-string val))))
531 (defmethod read-sql-value (val (type (eql 'integer)) database db-type)
532 (declare (ignore database db-type))
533 (etypecase val
534 (string
535 (unless (string-equal "NIL" val)
536 (parse-integer val)))
537 (number val)))
539 (defmethod read-sql-value (val (type (eql 'smallint)) database db-type)
540 (declare (ignore database db-type))
541 (etypecase val
542 (string
543 (unless (string-equal "NIL" val)
544 (parse-integer val)))
545 (number val)))
547 (defmethod read-sql-value (val (type (eql 'bigint)) database db-type)
548 (declare (ignore database db-type))
549 (etypecase val
550 (string
551 (unless (string-equal "NIL" val)
552 (parse-integer val)))
553 (number val)))
555 (defmethod read-sql-value (val (type (eql 'float)) database db-type)
556 (declare (ignore database db-type))
557 ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
558 (etypecase val
559 (string
560 (float (read-from-string val)))
561 (float
562 val)))
564 (defmethod read-sql-value (val (type (eql 'boolean)) database db-type)
565 (declare (ignore database db-type))
566 (equal "t" val))
568 (defmethod read-sql-value (val (type (eql 'generalized-boolean)) database db-type)
569 (declare (ignore database db-type))
570 (equal "t" val))
572 (defmethod read-sql-value (val (type (eql 'number)) database db-type)
573 (declare (ignore database db-type))
574 (etypecase val
575 (string
576 (unless (string-equal "NIL" val)
577 (read-from-string val)))
578 (number val)))
580 (defmethod read-sql-value (val (type (eql 'universal-time)) database db-type)
581 (declare (ignore database db-type))
582 (unless (eq 'NULL val)
583 (etypecase val
584 (string
585 (parse-integer val))
586 (number val))))
588 (defmethod read-sql-value (val (type (eql 'wall-time)) database db-type)
589 (declare (ignore database db-type))
590 (unless (eq 'NULL val)
591 (parse-timestring val)))
593 (defmethod read-sql-value (val (type (eql 'date)) database db-type)
594 (declare (ignore database db-type))
595 (unless (eq 'NULL val)
596 (parse-datestring val)))
598 (defmethod read-sql-value (val (type (eql 'duration)) database db-type)
599 (declare (ignore database db-type))
600 (unless (or (eq 'NULL val)
601 (equal "NIL" val))
602 (parse-timestring val)))
604 ;; ------------------------------------------------------------
605 ;; Logic for 'faulting in' :join slots
607 ;; this works, but is inefficient requiring (+ 1 n-rows)
608 ;; SQL queries
609 #+ignore
610 (defun fault-join-target-slot (class object slot-def)
611 (let* ((res (fault-join-slot-raw class object slot-def))
612 (dbi (view-class-slot-db-info slot-def))
613 (target-name (gethash :target-slot dbi))
614 (target-class (find-class target-name)))
615 (when res
616 (mapcar (lambda (obj)
617 (list
618 (car
619 (fault-join-slot-raw
620 target-class
622 (find target-name (class-slots (class-of obj))
623 :key #'slot-definition-name)))
624 obj))
625 res)
626 #+ignore ;; this doesn't work when attempting to call slot-value
627 (mapcar (lambda (obj)
628 (cons obj (slot-value obj ts))) res))))
630 (defun fault-join-target-slot (class object slot-def)
631 (let* ((dbi (view-class-slot-db-info slot-def))
632 (ts (gethash :target-slot dbi))
633 (jc (gethash :join-class dbi))
634 (jc-view-table (view-table (find-class jc)))
635 (tdbi (view-class-slot-db-info
636 (find ts (class-slots (find-class jc))
637 :key #'slot-definition-name)))
638 (retrieval (gethash :retrieval tdbi))
639 (tsc (gethash :join-class tdbi))
640 (ts-view-table (view-table (find-class tsc)))
641 (jq (join-qualifier class object slot-def))
642 (key (slot-value object (gethash :home-key dbi))))
644 (when jq
645 (ecase retrieval
646 (:immediate
647 (let ((res
648 (find-all (list tsc)
649 :inner-join (sql-expression :table jc-view-table)
650 :on (sql-operation
652 (sql-expression
653 :attribute (gethash :foreign-key tdbi)
654 :table ts-view-table)
655 (sql-expression
656 :attribute (gethash :home-key tdbi)
657 :table jc-view-table))
658 :where jq
659 :result-types :auto
660 :database (view-database object))))
661 (mapcar #'(lambda (i)
662 (let* ((instance (car i))
663 (jcc (make-instance jc :view-database (view-database instance))))
664 (setf (slot-value jcc (gethash :foreign-key dbi))
665 key)
666 (setf (slot-value jcc (gethash :home-key tdbi))
667 (slot-value instance (gethash :foreign-key tdbi)))
668 (list instance jcc)))
669 res)))
670 (:deferred
671 ;; just fill in minimal slots
672 (mapcar
673 #'(lambda (k)
674 (let ((instance (make-instance tsc :view-database (view-database object)))
675 (jcc (make-instance jc :view-database (view-database object)))
676 (fk (car k)))
677 (setf (slot-value instance (gethash :home-key tdbi)) fk)
678 (setf (slot-value jcc (gethash :foreign-key dbi))
679 key)
680 (setf (slot-value jcc (gethash :home-key tdbi))
682 (list instance jcc)))
683 (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
684 :from (sql-expression :table jc-view-table)
685 :where jq
686 :database (view-database object))))))))
689 ;;; Remote Joins
691 (defvar *default-update-objects-max-len* nil
692 "The default value to use for the MAX-LEN keyword argument to
693 UPDATE-OBJECT-JOINS.")
695 (defun update-objects-joins (objects &key (slots t) (force-p t)
696 class-name (max-len
697 *default-update-objects-max-len*))
698 "Updates from the records of the appropriate database tables
699 the join slots specified by SLOTS in the supplied list of View
700 Class instances OBJECTS. SLOTS is t by default which means that
701 all join slots with :retrieval :immediate are updated. CLASS-NAME
702 is used to specify the View Class of all instance in OBJECTS and
703 default to nil which means that the class of the first instance
704 in OBJECTS is used. FORCE-P is t by default which means that all
705 join slots are updated whereas a value of nil means that only
706 unbound join slots are updated. MAX-LEN defaults to
707 *DEFAULT-UPDATE-OBJECTS-MAX-LEN* and when non-nil specifies that
708 UPDATE-OBJECT-JOINS may issue multiple database queries with a
709 maximum of MAX-LEN instances updated in each query."
710 (assert (or (null max-len) (plusp max-len)))
711 (when objects
712 (unless class-name
713 (setq class-name (class-name (class-of (first objects)))))
714 (let* ((class (find-class class-name))
715 (class-slots (ordered-class-slots class))
716 (slotdefs
717 (if (eq t slots)
718 (generate-retrieval-joins-list class :deferred)
719 (remove-if #'null
720 (mapcar #'(lambda (name)
721 (let ((slotdef (find name class-slots :key #'slot-definition-name)))
722 (unless slotdef
723 (warn "Unable to find slot named ~S in class ~S." name class))
724 slotdef))
725 slots)))))
726 (dolist (slotdef slotdefs)
727 (let* ((dbi (view-class-slot-db-info slotdef))
728 (slotdef-name (slot-definition-name slotdef))
729 (foreign-key (gethash :foreign-key dbi))
730 (home-key (gethash :home-key dbi))
731 (object-keys
732 (remove-duplicates
733 (if force-p
734 (mapcar #'(lambda (o) (slot-value o home-key)) objects)
735 (remove-if #'null
736 (mapcar
737 #'(lambda (o) (if (slot-boundp o slotdef-name)
739 (slot-value o home-key)))
740 objects)))))
741 (n-object-keys (length object-keys))
742 (query-len (or max-len n-object-keys)))
744 (do ((i 0 (+ i query-len)))
745 ((>= i n-object-keys))
746 (let* ((keys (if max-len
747 (subseq object-keys i (min (+ i query-len) n-object-keys))
748 object-keys))
749 (results (unless (gethash :target-slot dbi)
750 (find-all (list (gethash :join-class dbi))
751 :where (make-instance 'sql-relational-exp
752 :operator 'in
753 :sub-expressions (list (sql-expression :attribute foreign-key)
754 keys))
755 :result-types :auto
756 :flatp t)) ))
758 (dolist (object objects)
759 (when (or force-p (not (slot-boundp object slotdef-name)))
760 (let ((res (if results
761 (remove-if-not #'(lambda (obj)
762 (equal obj (slot-value
763 object
764 home-key)))
765 results
766 :key #'(lambda (res)
767 (slot-value res
768 foreign-key)))
770 (progn
771 (when (gethash :target-slot dbi)
772 (fault-join-target-slot class object slotdef))))))
773 (when res
774 (setf (slot-value object slotdef-name)
775 (if (gethash :set dbi) res (car res)))))))))))))
776 (values))
778 (defun fault-join-slot-raw (class object slot-def)
779 (let* ((dbi (view-class-slot-db-info slot-def))
780 (jc (gethash :join-class dbi)))
781 (let ((jq (join-qualifier class object slot-def)))
782 (when jq
783 (select jc :where jq :flatp t :result-types nil
784 :database (view-database object))))))
786 (defun fault-join-slot (class object slot-def)
787 (let* ((dbi (view-class-slot-db-info slot-def))
788 (ts (gethash :target-slot dbi)))
789 (if (and ts (gethash :set dbi))
790 (fault-join-target-slot class object slot-def)
791 (let ((res (fault-join-slot-raw class object slot-def)))
792 (when res
793 (cond
794 ((and ts (not (gethash :set dbi)))
795 (mapcar (lambda (obj) (slot-value obj ts)) res))
796 ((and (not ts) (not (gethash :set dbi)))
797 (car res))
798 ((and (not ts) (gethash :set dbi))
799 res)))))))
801 (defun join-qualifier (class object slot-def)
802 (declare (ignore class))
803 (let* ((dbi (view-class-slot-db-info slot-def))
804 (jc (find-class (gethash :join-class dbi)))
805 ;;(ts (gethash :target-slot dbi))
806 ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
807 (foreign-keys (gethash :foreign-key dbi))
808 (home-keys (gethash :home-key dbi)))
809 (when (every #'(lambda (slt)
810 (and (slot-boundp object slt)
811 (not (null (slot-value object slt)))))
812 (if (listp home-keys) home-keys (list home-keys)))
813 (let ((jc
814 (mapcar #'(lambda (hk fk)
815 (let ((fksd (slotdef-for-slot-with-class fk jc)))
816 (sql-operation '==
817 (typecase fk
818 (symbol
819 (sql-expression
820 :attribute
821 (view-class-slot-column fksd)
822 :table (view-table jc)))
823 (t fk))
824 (typecase hk
825 (symbol
826 (slot-value object hk))
828 hk)))))
829 (if (listp home-keys)
830 home-keys
831 (list home-keys))
832 (if (listp foreign-keys)
833 foreign-keys
834 (list foreign-keys)))))
835 (when jc
836 (if (> (length jc) 1)
837 (apply #'sql-and jc)
838 jc))))))
840 ;; FIXME: add retrieval immediate for efficiency
841 ;; For example, for (select 'employee-address) in test suite =>
842 ;; select addr.*,ea_join.* FROM addr,ea_join WHERE ea_join.aaddressid=addr.addressid\g
844 (defun build-objects (vals sclasses immediate-join-classes sels immediate-joins database refresh flatp instances)
845 "Used by find-all to build objects."
846 (labels ((build-object (vals vclass jclasses selects immediate-selects instance)
847 (let* ((db-vals (butlast vals (- (list-length vals)
848 (list-length selects))))
849 (obj (if instance instance (make-instance (class-name vclass) :view-database database)))
850 (join-vals (subseq vals (list-length selects)))
851 (joins (mapcar #'(lambda (c) (when c (make-instance c :view-database database)))
852 jclasses)))
854 ;;(format t "joins: ~S~%db-vals: ~S~%join-values: ~S~%selects: ~S~%immediate-selects: ~S~%"
855 ;;joins db-vals join-vals selects immediate-selects)
857 ;; use refresh keyword here
858 (setf obj (get-slot-values-from-view obj (mapcar #'car selects) db-vals))
859 (mapc #'(lambda (jo)
860 ;; find all immediate-select slots and join-vals for this object
861 (let* ((slots (class-slots (class-of jo)))
862 (pos-list (remove-if #'null
863 (mapcar
864 #'(lambda (s)
865 (position s immediate-selects
866 :key #'car
867 :test #'eq))
868 slots))))
869 (get-slot-values-from-view jo
870 (mapcar #'car
871 (mapcar #'(lambda (pos)
872 (nth pos immediate-selects))
873 pos-list))
874 (mapcar #'(lambda (pos) (nth pos join-vals))
875 pos-list))))
876 joins)
877 (mapc
878 #'(lambda (jc)
879 (let ((slot (find (class-name (class-of jc)) (class-slots vclass)
880 :key #'(lambda (slot)
881 (when (and (eq :join (view-class-slot-db-kind slot))
882 (eq (slot-definition-name slot)
883 (gethash :join-class (view-class-slot-db-info slot))))
884 (slot-definition-name slot))))))
885 (when slot
886 (setf (slot-value obj (slot-definition-name slot)) jc))))
887 joins)
888 (when refresh (instance-refreshed obj))
889 obj)))
890 (let* ((objects
891 (mapcar #'(lambda (sclass jclass sel immediate-join instance)
892 (prog1
893 (build-object vals sclass jclass sel immediate-join instance)
894 (setf vals (nthcdr (+ (list-length sel) (list-length immediate-join))
895 vals))))
896 sclasses immediate-join-classes sels immediate-joins instances)))
897 (if (and flatp (= (length sclasses) 1))
898 (car objects)
899 objects))))
901 (defun find-all (view-classes
902 &rest args
903 &key all set-operation distinct from where group-by having
904 order-by offset limit refresh flatp result-types
905 inner-join on
906 (database *default-database*)
907 instances)
908 "Called by SELECT to generate object query results when the
909 View Classes VIEW-CLASSES are passed as arguments to SELECT."
910 (declare (ignore all set-operation group-by having offset limit inner-join on))
911 (flet ((ref-equal (ref1 ref2)
912 (string= (sql-output ref1 database)
913 (sql-output ref2 database)))
914 (table-sql-expr (table)
915 (sql-expression :table (view-table table)))
916 (tables-equal (table-a table-b)
917 (when (and table-a table-b)
918 (string= (string (slot-value table-a 'name))
919 (string (slot-value table-b 'name))))))
920 (remf args :from)
921 (remf args :where)
922 (remf args :flatp)
923 (remf args :additional-fields)
924 (remf args :result-types)
925 (remf args :instances)
926 (let* ((*db-deserializing* t)
927 (sclasses (mapcar #'find-class view-classes))
928 (immediate-join-slots
929 (mapcar #'(lambda (c) (generate-retrieval-joins-list c :immediate)) sclasses))
930 (immediate-join-classes
931 (mapcar #'(lambda (jcs)
932 (mapcar #'(lambda (slotdef)
933 (find-class (gethash :join-class (view-class-slot-db-info slotdef))))
934 jcs))
935 immediate-join-slots))
936 (immediate-join-sels (mapcar #'generate-immediate-joins-selection-list sclasses))
937 (sels (mapcar #'generate-selection-list sclasses))
938 (fullsels (apply #'append (mapcar #'append sels immediate-join-sels)))
939 (sel-tables (collect-table-refs where))
940 (tables (remove-if #'null
941 (remove-duplicates
942 (append (mapcar #'table-sql-expr sclasses)
943 (mapcan #'(lambda (jc-list)
944 (mapcar
945 #'(lambda (jc) (when jc (table-sql-expr jc)))
946 jc-list))
947 immediate-join-classes)
948 sel-tables)
949 :test #'tables-equal)))
950 (order-by-slots (mapcar #'(lambda (ob) (if (atom ob) ob (car ob)))
951 (listify order-by)))
952 (join-where nil))
954 ;;(format t "sclasses: ~W~%ijc: ~W~%tables: ~W~%" sclasses immediate-join-classes tables)
956 (dolist (ob order-by-slots)
957 (when (and ob (not (member ob (mapcar #'cdr fullsels)
958 :test #'ref-equal)))
959 (setq fullsels
960 (append fullsels (mapcar #'(lambda (att) (cons nil att))
961 order-by-slots)))))
962 (dolist (ob (listify distinct))
963 (when (and (typep ob 'sql-ident)
964 (not (member ob (mapcar #'cdr fullsels)
965 :test #'ref-equal)))
966 (setq fullsels
967 (append fullsels (mapcar #'(lambda (att) (cons nil att))
968 (listify ob))))))
969 (mapcar #'(lambda (vclass jclasses jslots)
970 (when jclasses
971 (mapcar
972 #'(lambda (jclass jslot)
973 (let ((dbi (view-class-slot-db-info jslot)))
974 (setq join-where
975 (append
976 (list (sql-operation '==
977 (sql-expression
978 :attribute (gethash :foreign-key dbi)
979 :table (view-table jclass))
980 (sql-expression
981 :attribute (gethash :home-key dbi)
982 :table (view-table vclass))))
983 (when join-where (listify join-where))))))
984 jclasses jslots)))
985 sclasses immediate-join-classes immediate-join-slots)
986 ;; Reported buggy on clsql-devel
987 ;; (when where (setq where (listify where)))
988 (cond
989 ((and where join-where)
990 (setq where (list (apply #'sql-and where join-where))))
991 ((and (null where) (> (length join-where) 1))
992 (setq where (list (apply #'sql-and join-where)))))
994 (let* ((rows (apply #'select
995 (append (mapcar #'cdr fullsels)
996 (cons :from
997 (list (append (when from (listify from))
998 (listify tables))))
999 (list :result-types result-types)
1000 (when where
1001 (list :where where))
1002 args)))
1003 (instances-to-add (- (length rows) (length instances)))
1004 (perhaps-extended-instances
1005 (if (plusp instances-to-add)
1006 (append instances (do ((i 0 (1+ i))
1007 (res nil))
1008 ((= i instances-to-add) res)
1009 (push (make-list (length sclasses) :initial-element nil) res)))
1010 instances))
1011 (objects (mapcar
1012 #'(lambda (row instance)
1013 (build-objects row sclasses immediate-join-classes sels
1014 immediate-join-sels database refresh flatp
1015 (if (and flatp (atom instance))
1016 (list instance)
1017 instance)))
1018 rows perhaps-extended-instances)))
1019 objects))))
1021 (defmethod instance-refreshed ((instance standard-db-object)))
1023 (defvar *default-caching* t
1024 "Controls whether SELECT caches objects by default. The CommonSQL
1025 specification states caching is on by default.")
1027 (defun select (&rest select-all-args)
1028 "Executes a query on DATABASE, which has a default value of
1029 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
1030 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
1031 argument can be used to generate queries in both functional and
1032 object oriented contexts.
1034 In the functional case, the required arguments specify the
1035 columns selected by the query and may be symbolic SQL expressions
1036 or strings representing attribute identifiers. Type modified
1037 identifiers indicate that the values selected from the specified
1038 column are converted to the specified lisp type. The keyword
1039 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
1040 SET-OPERATION and WHERE are used to specify, using the symbolic
1041 SQL syntax, the corresponding components of the SQL query
1042 generated by the call to SELECT. RESULT-TYPES is a list of
1043 symbols which specifies the lisp type for each field returned by
1044 the query. If RESULT-TYPES is nil all results are returned as
1045 strings whereas the default value of :auto means that the lisp
1046 types are automatically computed for each field. FIELD-NAMES is t
1047 by default which means that the second value returned is a list
1048 of strings representing the columns selected by the query. If
1049 FIELD-NAMES is nil, the list of column names is not returned as a
1050 second value.
1052 In the object oriented case, the required arguments to SELECT are
1053 symbols denoting View Classes which specify the database tables
1054 to query. In this case, SELECT returns a list of View Class
1055 instances whose slots are set from the attribute values of the
1056 records in the specified table. Slot-value is a legal operator
1057 which can be employed as part of the symbolic SQL syntax used in
1058 the WHERE keyword argument to SELECT. REFRESH is nil by default
1059 which means that the View Class instances returned are retrieved
1060 from a cache if an equivalent call to SELECT has previously been
1061 issued. If REFRESH is true, the View Class instances returned are
1062 updated as necessary from the database and the generic function
1063 INSTANCE-REFRESHED is called to perform any necessary operations
1064 on the updated instances.
1066 In both object oriented and functional contexts, FLATP has a
1067 default value of nil which means that the results are returned as
1068 a list of lists. If FLATP is t and only one result is returned
1069 for each record selected in the query, the results are returned
1070 as elements of a list."
1072 (flet ((select-objects (target-args)
1073 (and target-args
1074 (every #'(lambda (arg)
1075 (and (symbolp arg)
1076 (find-class arg nil)))
1077 target-args))))
1078 (multiple-value-bind (target-args qualifier-args)
1079 (query-get-selections select-all-args)
1080 (unless (or *default-database* (getf qualifier-args :database))
1081 (signal-no-database-error nil))
1083 (cond
1084 ((select-objects target-args)
1085 (let ((caching (getf qualifier-args :caching *default-caching*))
1086 (result-types (getf qualifier-args :result-types :auto))
1087 (refresh (getf qualifier-args :refresh nil))
1088 (database (or (getf qualifier-args :database) *default-database*))
1089 (order-by (getf qualifier-args :order-by)))
1090 (remf qualifier-args :caching)
1091 (remf qualifier-args :refresh)
1092 (remf qualifier-args :result-types)
1094 ;; Add explicity table name to order-by if not specified and only
1095 ;; one selected table. This is required so FIND-ALL won't duplicate
1096 ;; the field
1097 (when (and order-by (= 1 (length target-args)))
1098 (let ((table-name (view-table (find-class (car target-args))))
1099 (order-by-list (copy-seq (listify order-by))))
1101 (loop for i from 0 below (length order-by-list)
1102 do (etypecase (nth i order-by-list)
1103 (sql-ident-attribute
1104 (unless (slot-value (nth i order-by-list) 'qualifier)
1105 (setf (slot-value (nth i order-by-list) 'qualifier) table-name)))
1106 (cons
1107 (unless (slot-value (car (nth i order-by-list)) 'qualifier)
1108 (setf (slot-value (car (nth i order-by-list)) 'qualifier) table-name)))))
1109 (setf (getf qualifier-args :order-by) order-by-list)))
1111 (cond
1112 ((null caching)
1113 (apply #'find-all target-args
1114 (append qualifier-args
1115 (list :result-types result-types :refresh refresh))))
1117 (let ((cached (records-cache-results target-args qualifier-args database)))
1118 (cond
1119 ((and cached (not refresh))
1120 cached)
1121 ((and cached refresh)
1122 (let ((results (apply #'find-all (append (list target-args) qualifier-args `(:instances ,cached :result-types :auto :refresh ,refresh)))))
1123 (setf (records-cache-results target-args qualifier-args database) results)
1124 results))
1126 (let ((results (apply #'find-all target-args (append qualifier-args
1127 `(:result-types :auto :refresh ,refresh)))))
1128 (setf (records-cache-results target-args qualifier-args database) results)
1129 results))))))))
1131 (let* ((expr (apply #'make-query select-all-args))
1132 (specified-types
1133 (mapcar #'(lambda (attrib)
1134 (if (typep attrib 'sql-ident-attribute)
1135 (let ((type (slot-value attrib 'type)))
1136 (if type
1137 type
1140 (slot-value expr 'selections))))
1141 (destructuring-bind (&key (flatp nil)
1142 (result-types :auto)
1143 (field-names t)
1144 (database *default-database*)
1145 &allow-other-keys)
1146 qualifier-args
1147 (query expr :flatp flatp
1148 :result-types
1149 ;; specifying a type for an attribute overrides result-types
1150 (if (some #'(lambda (x) (not (eq t x))) specified-types)
1151 specified-types
1152 result-types)
1153 :field-names field-names
1154 :database database))))))))
1156 (defun compute-records-cache-key (targets qualifiers)
1157 (list targets
1158 (do ((args *select-arguments* (cdr args))
1159 (results nil))
1160 ((null args) results)
1161 (let* ((arg (car args))
1162 (value (getf qualifiers arg)))
1163 (when value
1164 (push (list arg
1165 (typecase value
1166 (cons (cons (sql (car value)) (cdr value)))
1167 (%sql-expression (sql value))
1168 (t value)))
1169 results))))))
1171 (defun records-cache-results (targets qualifiers database)
1172 (when (record-caches database)
1173 (gethash (compute-records-cache-key targets qualifiers) (record-caches database))))
1175 (defun (setf records-cache-results) (results targets qualifiers database)
1176 (unless (record-caches database)
1177 (setf (record-caches database)
1178 (make-hash-table :test 'equal
1179 #+allegro :values #+allegro :weak
1180 #+clisp :weak #+clisp :value
1181 #+lispworks :weak-kind #+lispworks :value)))
1182 (setf (gethash (compute-records-cache-key targets qualifiers)
1183 (record-caches database)) results)
1184 results)
1188 ;;; Serialization functions
1190 (defun write-instance-to-stream (obj stream)
1191 "Writes an instance to a stream where it can be later be read.
1192 NOTE: an error will occur if a slot holds a value which can not be written readably."
1193 (let* ((class (class-of obj))
1194 (alist '()))
1195 (dolist (slot (ordered-class-slots (class-of obj)))
1196 (let ((name (slot-definition-name slot)))
1197 (when (and (not (eq 'view-database name))
1198 (slot-boundp obj name))
1199 (push (cons name (slot-value obj name)) alist))))
1200 (setq alist (reverse alist))
1201 (write (cons (class-name class) alist) :stream stream :readably t))
1202 obj)
1204 (defun read-instance-from-stream (stream)
1205 (let ((raw (read stream nil nil)))
1206 (when raw
1207 (let ((obj (make-instance (car raw))))
1208 (dolist (pair (cdr raw))
1209 (setf (slot-value obj (car pair)) (cdr pair)))
1210 obj))))