1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
4 ;;;; The CLSQL Object Oriented Data Manipulation Language (OODML).
6 ;;;; This file is part of CLSQL.
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 ;;;; *************************************************************************
13 (in-package #:clsql-sys)
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)))
21 (sql-expression :attribute
22 (view-class-slot-column k)
26 (slot-value obj (slot-definition-name k))
28 (let* ((keys (keyslots-for-class obj-class))
29 (keyxprs (mapcar #'qfk (reverse keys))))
31 ((= (length keyxprs) 0) nil)
32 ((= (length keyxprs) 1) (car keyxprs))
33 ((> (length keyxprs) 1) (apply #'sql-operation 'and keyxprs)))))))
36 ;; Function used by 'generate-selection-list'
39 (defun generate-attribute-reference (vclass slotdef)
41 ((eq (view-class-slot-db-kind slotdef) :base)
42 (sql-expression :attribute (view-class-slot-column slotdef)
43 :table (view-table vclass)))
44 ((eq (view-class-slot-db-kind slotdef) :key)
45 (sql-expression :attribute (view-class-slot-column slotdef)
46 :table (view-table vclass)))
50 ;; Function used by 'find-all'
53 (defun generate-selection-list (vclass)
56 (slots (if (normalizedp vclass)
57 (labels ((getdslots ()
58 (let ((sl (ordered-class-direct-slots this-class)))
62 (car (class-direct-superclasses this-class)))
65 (ordered-class-slots this-class))))
66 (dolist (slotdef slots)
67 (let ((res (generate-attribute-reference this-class slotdef)))
69 (push (cons slotdef res) sels))))
72 (error "No slots of type :base in view-class ~A" (class-name vclass)))))
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)))))
84 (defun generate-immediate-joins-selection-list (vclass)
85 "Returns list of immediate join slots for a class."
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)))
93 (push (cons slotdef res) sels))))))
97 ;; Called by 'get-slot-values-from-view'
100 (defmethod update-slot-from-db ((instance standard-db-object) slotdef value)
101 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
102 (let* ((slot-reader (view-class-slot-db-reader slotdef))
103 (slot-name (slot-definition-name slotdef))
104 (slot-type (specified-type slotdef)))
105 (cond ((and value (null slot-reader))
106 (setf (slot-value instance slot-name)
107 (read-sql-value value (delistify slot-type)
108 (view-database instance)
109 (database-underlying-type
110 (view-database instance)))))
112 (update-slot-with-null instance slot-name slotdef))
113 ((typep slot-reader 'string)
114 (setf (slot-value instance slot-name)
115 (format nil slot-reader value)))
116 ((typep slot-reader '(or symbol function))
117 (setf (slot-value instance slot-name)
118 (apply slot-reader (list value))))
120 (error "Slot reader is of an unusual type.")))))
122 (defmethod key-value-from-db (slotdef value database)
123 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
124 (let ((slot-reader (view-class-slot-db-reader slotdef))
125 (slot-type (specified-type slotdef)))
126 (cond ((and value (null slot-reader))
127 (read-sql-value value (delistify slot-type) database
128 (database-underlying-type database)))
131 ((typep slot-reader 'string)
132 (format nil slot-reader value))
133 ((typep slot-reader '(or symbol function))
134 (apply slot-reader (list value)))
136 (error "Slot reader is of an unusual type.")))))
138 (defun db-value-from-slot (slotdef val database)
139 (let ((dbwriter (view-class-slot-db-writer slotdef))
140 (dbtype (specified-type slotdef)))
142 (string (format nil dbwriter val))
143 ((and (or symbol function) (not null)) (apply dbwriter (list val)))
145 (database-output-sql-as-type
149 val database (database-underlying-type database))))))
151 (defun check-slot-type (slotdef val)
152 (let* ((slot-type (specified-type slotdef))
153 (basetype (if (listp slot-type) (car slot-type) slot-type)))
154 (when (and slot-type val)
155 (unless (typep val basetype)
156 (error 'sql-user-error
158 (format nil "Invalid value ~A in slot ~A, not of type ~A."
159 val (slot-definition-name slotdef) slot-type))))))
162 ;; Called by find-all
165 (defmethod get-slot-values-from-view (obj slotdeflist values)
166 (flet ((update-slot (slot-def values)
167 (update-slot-from-db obj slot-def values)))
168 (mapc #'update-slot slotdeflist values)
171 (defmethod update-record-from-slot ((obj standard-db-object) slot &key
172 (database *default-database*))
173 (let* ((database (or (view-database obj) database))
174 (view-class (class-of obj)))
175 (when (normalizedp view-class)
176 ;; If it's normalized, find the class that actually contains
177 ;; the slot that's tied to the db
179 (do ((this-class view-class
180 (car (class-direct-superclasses this-class))))
182 (mapcar #'(lambda (esd) (slot-definition-name esd))
183 (ordered-class-direct-slots this-class)))
185 (let* ((vct (view-table view-class))
186 (sd (slotdef-for-slot-with-class slot view-class)))
187 (check-slot-type sd (slot-value obj slot))
188 (let* ((att (view-class-slot-column sd))
189 (val (db-value-from-slot sd (slot-value obj slot) database)))
190 (cond ((and vct sd (view-database obj))
191 (update-records (sql-expression :table vct)
192 :attributes (list (sql-expression :attribute att))
194 :where (key-qualifier-for-instance
195 obj :database database :this-class view-class)
197 ((and vct sd (not (view-database obj)))
198 (insert-records :into (sql-expression :table vct)
199 :attributes (list (sql-expression :attribute att))
202 (setf (slot-value obj 'view-database) database))
204 (error "Unable to update record.")))))
207 (defmethod update-record-from-slots ((obj standard-db-object) slots &key
208 (database *default-database*))
209 (when (normalizedp (class-of obj))
210 ;; FIXME: Rewrite to bundle slots for same table to be written
211 ;; as avpairs (like how is done for non-normalized view-classes below)
213 (update-record-from-slot obj slot :database database))
214 (return-from update-record-from-slots (values)))
216 (let* ((database (or (view-database obj) database))
217 (vct (view-table (class-of obj)))
218 (sds (slotdefs-for-slots-with-class slots (class-of obj)))
219 (avps (mapcar #'(lambda (s)
220 (let ((val (slot-value
221 obj (slot-definition-name s))))
222 (check-slot-type s val)
223 (list (sql-expression
224 :attribute (view-class-slot-column s))
225 (db-value-from-slot s val database))))
227 (cond ((and avps (view-database obj))
228 (update-records (sql-expression :table vct)
230 :where (key-qualifier-for-instance
231 obj :database database)
233 ((and avps (not (view-database obj)))
234 (insert-records :into (sql-expression :table vct)
237 (setf (slot-value obj 'view-database) database))
239 (error "Unable to update records"))))
242 (defmethod update-records-from-instance ((obj standard-db-object)
243 &key database this-class)
244 (let ((database (or database (view-database obj) *default-database*))
246 (labels ((slot-storedp (slot)
247 (and (member (view-class-slot-db-kind slot) '(:base :key))
248 (slot-boundp obj (slot-definition-name slot))))
249 (slot-value-list (slot)
250 (let ((value (slot-value obj (slot-definition-name slot))))
251 (check-slot-type slot value)
252 (list (sql-expression :attribute (view-class-slot-column slot))
253 (db-value-from-slot slot value database)))))
254 (let* ((view-class (or this-class (class-of obj)))
255 (pk-slot (car (keyslots-for-class view-class)))
256 (view-class-table (view-table view-class))
257 (pclass (car (class-direct-superclasses view-class))))
258 (when (normalizedp view-class)
259 (setf pk (update-records-from-instance obj :database database
262 (setf (slot-value obj (slot-definition-name pk-slot)) pk)))
263 (let* ((slots (remove-if-not #'slot-storedp
264 (if (normalizedp view-class)
265 (ordered-class-direct-slots view-class)
266 (ordered-class-slots view-class))))
267 (record-values (mapcar #'slot-value-list slots)))
269 (cond ((and (not (normalizedp view-class))
271 (error "No settable slots."))
272 ((and (normalizedp view-class)
276 (update-records (sql-expression :table view-class-table)
277 :av-pairs record-values
278 :where (key-qualifier-for-instance
279 obj :database database
280 :this-class view-class)
284 (slot-value obj (slot-definition-name pk-slot))))))
286 (insert-records :into (sql-expression :table view-class-table)
287 :av-pairs record-values
290 (when (and pk-slot (not pk))
291 (setf pk (if (or (member :auto-increment (listify (view-class-slot-db-constraints pk-slot)))
292 (not (null (view-class-slot-autoincrement-sequence pk-slot))))
293 (setf (slot-value obj (slot-definition-name pk-slot))
294 (database-last-auto-increment-id database
300 obj (slot-definition-name pk-slot)))))
301 (when (eql this-class nil)
302 (setf (slot-value obj 'view-database) database)))))))
303 ;; handle slots with defaults
304 (let* ((view-class (or this-class (class-of obj)))
305 (slots (if (normalizedp view-class)
306 (ordered-class-direct-slots view-class)
307 (ordered-class-slots view-class))))
309 (when (and (slot-exists-p slot 'db-constraints)
310 (listp (view-class-slot-db-constraints slot))
311 (member :default (view-class-slot-db-constraints slot)))
312 (unless (and (slot-boundp obj (slot-definition-name slot))
313 (slot-value obj (slot-definition-name slot)))
314 (update-slot-from-record obj (slot-definition-name slot))))))
318 (defmethod delete-instance-records ((instance standard-db-object))
319 (let ((vt (sql-expression :table (view-table (class-of instance))))
320 (vd (view-database instance)))
322 (let ((qualifier (key-qualifier-for-instance instance :database vd)))
323 (delete-records :from vt :where qualifier :database vd)
324 (setf (record-caches vd) nil)
325 (setf (slot-value instance 'view-database) nil)
327 (signal-no-database-error vd))))
329 (defmethod update-instance-from-records ((instance standard-db-object)
330 &key (database *default-database*)
332 (let* ((view-class (or this-class (class-of instance)))
333 (pclass (car (class-direct-superclasses view-class)))
335 (when (normalizedp view-class)
336 (setf pres (update-instance-from-records instance :database database
337 :this-class pclass)))
338 (let* ((view-table (sql-expression :table (view-table view-class)))
339 (vd (or (view-database instance) database))
340 (view-qual (key-qualifier-for-instance instance :database vd
341 :this-class view-class))
342 (sels (generate-selection-list view-class))
345 (setf res (apply #'select (append (mapcar #'cdr sels)
346 (list :from view-table
351 (setf (slot-value instance 'view-database) vd)
352 (get-slot-values-from-view instance (mapcar #'car sels) (car res))))
356 (defmethod update-slot-from-record ((instance standard-db-object)
357 slot &key (database *default-database*))
358 (let* ((view-class (find-class (class-name (class-of instance))))
359 (slot-def (slotdef-for-slot-with-class slot view-class)))
360 (when (normalizedp view-class)
361 ;; If it's normalized, find the class that actually contains
362 ;; the slot that's tied to the db
364 (do ((this-class view-class
365 (car (class-direct-superclasses this-class))))
367 (mapcar #'(lambda (esd) (slot-definition-name esd))
368 (ordered-class-direct-slots this-class)))
370 (let* ((view-table (sql-expression :table (view-table view-class)))
371 (vd (or (view-database instance) database))
372 (view-qual (key-qualifier-for-instance instance :database vd
373 :this-class view-class))
374 (att-ref (generate-attribute-reference view-class slot-def))
375 (res (select att-ref :from view-table :where view-qual
378 (setf (slot-value instance 'view-database) vd)
379 (get-slot-values-from-view instance (list slot-def) (car res))))))
381 (defmethod update-slot-with-null ((object standard-db-object)
384 (setf (slot-value object slotname) (slot-value slotdef 'void-value)))
386 (defvar +no-slot-value+ '+no-slot-value+)
388 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
389 (let* ((class (find-class classname))
390 (sld (slotdef-for-slot-with-class slot class)))
392 (if (eq value +no-slot-value+)
393 (sql-expression :attribute (view-class-slot-column sld)
394 :table (view-table class))
399 (error "Unknown slot ~A for class ~A" slot classname))))
401 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
402 (declare (ignore database))
403 (let* ((class (find-class classname)))
404 (unless (view-table class)
405 (error "No view-table for class ~A" classname))
406 (sql-expression :table (view-table class))))
409 (defmethod database-get-type-specifier (type args database db-type)
410 (declare (ignore type args database db-type))
411 (format nil "VARCHAR(~D)" *default-string-length*))
413 (defmethod database-get-type-specifier ((type (eql 'integer)) args database db-type)
414 (declare (ignore database db-type))
416 (format nil "INT(~A)" (car args))
420 "An 8-bit integer, this width may vary by SQL implementation."
423 (defmethod database-get-type-specifier ((type (eql 'tinyint)) args database db-type)
424 (declare (ignore args database db-type))
428 "An integer smaller than a 32-bit integer. this width may vary by SQL implementation."
431 (defmethod database-get-type-specifier ((type (eql 'smallint)) args database db-type)
432 (declare (ignore args database db-type))
435 (deftype mediumint ()
436 "An integer smaller than a 32-bit integer, but may be larger than a smallint. This width may vary by SQL implementation."
439 (defmethod database-get-type-specifier ((type (eql 'mediumint)) args database db-type)
440 (declare (ignore args database db-type))
444 "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
447 (defmethod database-get-type-specifier ((type (eql 'bigint)) args database db-type)
448 (declare (ignore args database db-type))
451 (deftype varchar (&optional size)
452 "A variable length string for the SQL varchar type."
453 (declare (ignore size))
456 (defmethod database-get-type-specifier ((type (eql 'varchar)) args
458 (declare (ignore database db-type))
460 (format nil "VARCHAR(~A)" (car args))
461 (format nil "VARCHAR(~D)" *default-string-length*)))
463 (defmethod database-get-type-specifier ((type (eql 'string)) args database db-type)
464 (declare (ignore database db-type))
466 (format nil "CHAR(~A)" (car args))
467 (format nil "VARCHAR(~D)" *default-string-length*)))
469 (deftype universal-time ()
470 "A positive integer as returned by GET-UNIVERSAL-TIME."
473 (defmethod database-get-type-specifier ((type (eql 'universal-time)) args database db-type)
474 (declare (ignore args database db-type))
477 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database db-type)
478 (declare (ignore args database db-type))
481 (defmethod database-get-type-specifier ((type (eql 'date)) args database db-type)
482 (declare (ignore args database db-type))
485 (defmethod database-get-type-specifier ((type (eql 'duration)) args database db-type)
486 (declare (ignore database args db-type))
489 (defmethod database-get-type-specifier ((type (eql 'money)) args database db-type)
490 (declare (ignore database args db-type))
494 (deftype char (&optional len)
495 "A lisp type for the SQL CHAR type."
498 (defmethod database-get-type-specifier ((type (eql 'float)) args database db-type)
499 (declare (ignore database db-type))
501 (format nil "FLOAT(~A)" (car args))
504 (defmethod database-get-type-specifier ((type (eql 'long-float)) args database db-type)
505 (declare (ignore database db-type))
507 (format nil "FLOAT(~A)" (car args))
510 (deftype generalized-boolean ()
511 "A type which outputs a SQL boolean value, though any lisp type can be stored in the slot."
514 (defmethod database-get-type-specifier ((type (eql 'boolean)) args database db-type)
515 (declare (ignore args database db-type))
518 (defmethod database-get-type-specifier ((type (eql 'generalized-boolean)) args database db-type)
519 (declare (ignore args database db-type))
522 (defmethod database-get-type-specifier ((type (eql 'number)) args database db-type)
523 (declare (ignore database db-type))
525 ((and (consp args) (= (length args) 2))
526 (format nil "NUMBER(~D,~D)" (first args) (second args)))
527 ((and (consp args) (= (length args) 1))
528 (format nil "NUMBER(~D)" (first args)))
532 (defmethod database-get-type-specifier ((type (eql 'char)) args database db-type)
533 (declare (ignore database db-type))
535 (format nil "CHAR(~D)" (first args))
539 (defmethod database-output-sql-as-type (type val database db-type)
540 (declare (ignore type database db-type))
543 (defmethod database-output-sql-as-type ((type (eql 'list)) val database db-type)
544 (declare (ignore database db-type))
545 (progv '(*print-circle* *print-array*) '(t t)
546 (let ((escaped (prin1-to-string val)))
547 (substitute-char-string
548 escaped #\Null " "))))
550 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database db-type)
551 (declare (ignore database db-type))
554 (package-name (symbol-package val))
559 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database db-type)
560 (declare (ignore database db-type))
565 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database db-type)
566 (declare (ignore database db-type))
567 (progv '(*print-circle* *print-array*) '(t t)
568 (prin1-to-string val)))
570 (defmethod database-output-sql-as-type ((type (eql 'array)) val database db-type)
571 (declare (ignore database db-type))
572 (progv '(*print-circle* *print-array*) '(t t)
573 (prin1-to-string val)))
575 (defmethod database-output-sql-as-type ((type (eql 'boolean)) val database db-type)
576 (declare (ignore database db-type))
579 (defmethod database-output-sql-as-type ((type (eql 'generalized-boolean)) val database db-type)
580 (declare (ignore database db-type))
583 (defmethod database-output-sql-as-type ((type (eql 'string)) val database db-type)
584 (declare (ignore database db-type))
587 (defmethod database-output-sql-as-type ((type (eql 'char)) val database db-type)
588 (declare (ignore database db-type))
590 (character (write-to-string val))
593 (defmethod database-output-sql-as-type ((type (eql 'float)) val database db-type)
594 (declare (ignore database db-type))
595 (if (eq (type-of val) 'null)
597 (let ((*read-default-float-format* (type-of val)))
598 (format nil "~F" val))))
600 (defmethod read-sql-value (val type database db-type)
601 (declare (ignore database db-type))
603 ((null type) val) ;;we have no desired type, just give the value
604 ((typep val type) val) ;;check that it hasn't already been converted.
605 ((typep val 'string) (read-from-string val)) ;;maybe read will just take care of it?
606 (T (error "Unable to read-sql-value ~a as type ~a" val type))))
608 (defmethod read-sql-value (val (type (eql 'string)) database db-type)
609 (declare (ignore database db-type))
612 (defmethod read-sql-value (val (type (eql 'varchar)) database db-type)
613 (declare (ignore database db-type))
616 (defmethod read-sql-value (val (type (eql 'char)) database db-type)
617 (declare (ignore database db-type))
620 (defmethod read-sql-value (val (type (eql 'keyword)) database db-type)
621 (declare (ignore database db-type))
622 (when (< 0 (length val))
623 (intern (symbol-name-default-case val)
624 (find-package '#:keyword))))
626 (defmethod read-sql-value (val (type (eql 'symbol)) database db-type)
627 (declare (ignore database db-type))
628 (when (< 0 (length val))
629 (unless (string= val (symbol-name-default-case "NIL"))
630 (read-from-string val))))
632 (defmethod read-sql-value (val (type (eql 'integer)) database db-type)
633 (declare (ignore database db-type))
636 (unless (string-equal "NIL" val)
637 (parse-integer val)))
640 (defmethod read-sql-value (val (type (eql 'smallint)) database db-type)
641 (declare (ignore database db-type))
644 (unless (string-equal "NIL" val)
645 (parse-integer val)))
648 (defmethod read-sql-value (val (type (eql 'bigint)) database db-type)
649 (declare (ignore database db-type))
652 (unless (string-equal "NIL" val)
653 (parse-integer val)))
656 (defmethod read-sql-value (val (type (eql 'float)) database db-type)
657 (declare (ignore database db-type))
658 ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
660 (string (float (read-from-string val)))
663 (defmethod read-sql-value (val (type (eql 'double-float)) database db-type)
664 (declare (ignore database db-type))
665 ;; writing 1.0 writes 1, so if we *really* want a float, must do (float ...)
668 (let ((*read-default-float-format* 'double-float))
669 (read-from-string val))
672 (float (coerce val 'double-float))))
674 (defmethod read-sql-value (val (type (eql 'boolean)) database db-type)
675 (declare (ignore database db-type))
678 (defmethod read-sql-value (val (type (eql 'generalized-boolean)) database db-type)
679 (declare (ignore database db-type))
682 (defmethod read-sql-value (val (type (eql 'number)) database db-type)
683 (declare (ignore database db-type))
686 (unless (string-equal "NIL" val)
687 (read-from-string val)))
690 (defmethod read-sql-value (val (type (eql 'universal-time)) database db-type)
691 (declare (ignore database db-type))
692 (unless (eq 'NULL val)
698 (defmethod read-sql-value (val (type (eql 'wall-time)) database db-type)
699 (declare (ignore database db-type))
700 (unless (eq 'NULL val)
701 (parse-timestring val)))
703 (defmethod read-sql-value (val (type (eql 'date)) database db-type)
704 (declare (ignore database db-type))
705 (unless (eq 'NULL val)
706 (parse-datestring val)))
708 (defmethod read-sql-value (val (type (eql 'duration)) database db-type)
709 (declare (ignore database db-type))
710 (unless (or (eq 'NULL val)
712 (parse-timestring val)))
714 ;; ------------------------------------------------------------
715 ;; Logic for 'faulting in' :join slots
717 ;; this works, but is inefficient requiring (+ 1 n-rows)
720 (defun fault-join-target-slot (class object slot-def)
721 (let* ((res (fault-join-slot-raw class object slot-def))
722 (dbi (view-class-slot-db-info slot-def))
723 (target-name (gethash :target-slot dbi))
724 (target-class (find-class target-name)))
726 (mapcar (lambda (obj)
732 (find target-name (class-slots (class-of obj))
733 :key #'slot-definition-name)))
736 #+ignore ;; this doesn't work when attempting to call slot-value
737 (mapcar (lambda (obj)
738 (cons obj (slot-value obj ts))) res))))
740 (defun fault-join-target-slot (class object slot-def)
741 (let* ((dbi (view-class-slot-db-info slot-def))
742 (ts (gethash :target-slot dbi))
743 (jc (gethash :join-class dbi))
744 (jc-view-table (view-table (find-class jc)))
745 (tdbi (view-class-slot-db-info
746 (find ts (class-slots (find-class jc))
747 :key #'slot-definition-name)))
748 (retrieval (gethash :retrieval tdbi))
749 (tsc (gethash :join-class tdbi))
750 (ts-view-table (view-table (find-class tsc)))
751 (jq (join-qualifier class object slot-def))
752 (key (slot-value object (gethash :home-key dbi))))
759 :inner-join (sql-expression :table jc-view-table)
763 :attribute (gethash :foreign-key tdbi)
764 :table ts-view-table)
766 :attribute (gethash :home-key tdbi)
767 :table jc-view-table))
770 :database (view-database object))))
771 (mapcar #'(lambda (i)
772 (let* ((instance (car i))
773 (jcc (make-instance jc :view-database (view-database instance))))
774 (setf (slot-value jcc (gethash :foreign-key dbi))
776 (setf (slot-value jcc (gethash :home-key tdbi))
777 (slot-value instance (gethash :foreign-key tdbi)))
778 (list instance jcc)))
781 ;; just fill in minimal slots
784 (let ((instance (make-instance tsc :view-database (view-database object)))
785 (jcc (make-instance jc :view-database (view-database object)))
787 (setf (slot-value instance (gethash :home-key tdbi)) fk)
788 (setf (slot-value jcc (gethash :foreign-key dbi))
790 (setf (slot-value jcc (gethash :home-key tdbi))
792 (list instance jcc)))
793 (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
794 :from (sql-expression :table jc-view-table)
796 :database (view-database object))))))))
801 (defvar *default-update-objects-max-len* nil
802 "The default value to use for the MAX-LEN keyword argument to
803 UPDATE-OBJECT-JOINS.")
805 (defun update-objects-joins (objects &key (slots t) (force-p t)
807 *default-update-objects-max-len*))
808 "Updates from the records of the appropriate database tables
809 the join slots specified by SLOTS in the supplied list of View
810 Class instances OBJECTS. SLOTS is t by default which means that
811 all join slots with :retrieval :immediate are updated. CLASS-NAME
812 is used to specify the View Class of all instance in OBJECTS and
813 default to nil which means that the class of the first instance
814 in OBJECTS is used. FORCE-P is t by default which means that all
815 join slots are updated whereas a value of nil means that only
816 unbound join slots are updated. MAX-LEN defaults to
817 *DEFAULT-UPDATE-OBJECTS-MAX-LEN* and when non-nil specifies that
818 UPDATE-OBJECT-JOINS may issue multiple database queries with a
819 maximum of MAX-LEN instances updated in each query."
820 (assert (or (null max-len) (plusp max-len)))
823 (setq class-name (class-name (class-of (first objects)))))
824 (let* ((class (find-class class-name))
825 (class-slots (ordered-class-slots class))
828 (generate-retrieval-joins-list class :deferred)
830 (mapcar #'(lambda (name)
831 (let ((slotdef (find name class-slots :key #'slot-definition-name)))
833 (warn "Unable to find slot named ~S in class ~S." name class))
836 (dolist (slotdef slotdefs)
837 (let* ((dbi (view-class-slot-db-info slotdef))
838 (slotdef-name (slot-definition-name slotdef))
839 (foreign-key (gethash :foreign-key dbi))
840 (home-key (gethash :home-key dbi))
844 (mapcar #'(lambda (o) (slot-value o home-key)) objects)
847 #'(lambda (o) (if (slot-boundp o slotdef-name)
849 (slot-value o home-key)))
851 (n-object-keys (length object-keys))
852 (query-len (or max-len n-object-keys)))
854 (do ((i 0 (+ i query-len)))
855 ((>= i n-object-keys))
856 (let* ((keys (if max-len
857 (subseq object-keys i (min (+ i query-len) n-object-keys))
859 (results (unless (gethash :target-slot dbi)
860 (find-all (list (gethash :join-class dbi))
861 :where (make-instance 'sql-relational-exp
863 :sub-expressions (list (sql-expression :attribute foreign-key)
868 (dolist (object objects)
869 (when (or force-p (not (slot-boundp object slotdef-name)))
870 (let ((res (if results
871 (remove-if-not #'(lambda (obj)
872 (equal obj (slot-value
881 (when (gethash :target-slot dbi)
882 (fault-join-target-slot class object slotdef))))))
884 (setf (slot-value object slotdef-name)
885 (if (gethash :set dbi) res (car res)))))))))))))
888 (defun fault-join-slot-raw (class object slot-def)
889 (let* ((dbi (view-class-slot-db-info slot-def))
890 (jc (gethash :join-class dbi)))
891 (let ((jq (join-qualifier class object slot-def)))
893 (select jc :where jq :flatp t :result-types nil
894 :database (view-database object))))))
896 (defun fault-join-slot (class object slot-def)
897 (let* ((dbi (view-class-slot-db-info slot-def))
898 (ts (gethash :target-slot dbi)))
899 (if (and ts (gethash :set dbi))
900 (fault-join-target-slot class object slot-def)
901 (let ((res (fault-join-slot-raw class object slot-def)))
904 ((and ts (not (gethash :set dbi)))
905 (mapcar (lambda (obj) (slot-value obj ts)) res))
906 ((and (not ts) (not (gethash :set dbi)))
908 ((and (not ts) (gethash :set dbi))
911 ;;;; Should we not return the whole result, instead of only
912 ;;;; the one slot-value? We get all the values from the db
914 (defun fault-join-normalized-slot (class object slot-def)
915 (labels ((getsc (this-class)
916 (let ((sc (car (class-direct-superclasses this-class))))
920 (let* ((sc (getsc class))
921 (hk (slot-definition-name (car (key-slots class))))
922 (fk (slot-definition-name (car (key-slots sc)))))
923 (let ((jq (sql-operation '==
928 (view-class-slot-column
929 (slotdef-for-slot-with-class fk sc))
930 :table (view-table sc)))
934 (slot-value object hk))
937 ;; Caching nil in next select, because in normalized mode
938 ;; records can be changed through other instances (children,
939 ;; parents) so changes possibly won't be noticed
940 (let ((res (car (select (class-name sc) :where jq
941 :flatp t :result-types nil
943 :database (view-database object))))
944 (slot-name (slot-definition-name slot-def)))
946 ;; If current class is normalized and wanted slot is not
947 ;; a direct member, recurse up
948 (if (and (normalizedp class)
949 (not (member slot-name
950 (mapcar #'(lambda (esd) (slot-definition-name esd))
951 (ordered-class-direct-slots class))))
952 (not (slot-boundp res slot-name)))
953 (fault-join-normalized-slot sc res slot-def)
954 (slot-value res slot-name)))))) )
956 (defun join-qualifier (class object slot-def)
957 (declare (ignore class))
958 (let* ((dbi (view-class-slot-db-info slot-def))
959 (jc (find-class (gethash :join-class dbi)))
960 ;;(ts (gethash :target-slot dbi))
961 ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
962 (foreign-keys (gethash :foreign-key dbi))
963 (home-keys (gethash :home-key dbi)))
964 (when (every #'(lambda (slt)
965 (and (slot-boundp object slt)
966 (not (null (slot-value object slt)))))
967 (if (listp home-keys) home-keys (list home-keys)))
969 (mapcar #'(lambda (hk fk)
970 (let ((fksd (slotdef-for-slot-with-class fk jc)))
976 (view-class-slot-column fksd)
977 :table (view-table jc)))
981 (slot-value object hk))
984 (if (listp home-keys)
987 (if (listp foreign-keys)
989 (list foreign-keys)))))
991 (if (> (length jc) 1)
995 ;; FIXME: add retrieval immediate for efficiency
996 ;; For example, for (select 'employee-address) in test suite =>
997 ;; select addr.*,ea_join.* FROM addr,ea_join WHERE ea_join.aaddressid=addr.addressid\g
999 (defun build-objects (vals sclasses immediate-join-classes sels immediate-joins database refresh flatp instances)
1000 "Used by find-all to build objects."
1001 (labels ((build-object (vals vclass jclasses selects immediate-selects instance)
1002 (let* ((db-vals (butlast vals (- (list-length vals)
1003 (list-length selects))))
1004 (obj (if instance instance (make-instance (class-name vclass) :view-database database)))
1005 (join-vals (subseq vals (list-length selects)))
1006 (joins (mapcar #'(lambda (c) (when c (make-instance c :view-database database)))
1009 ;;(format t "joins: ~S~%db-vals: ~S~%join-values: ~S~%selects: ~S~%immediate-selects: ~S~%"
1010 ;;joins db-vals join-vals selects immediate-selects)
1012 ;; use refresh keyword here
1013 (setf obj (get-slot-values-from-view obj (mapcar #'car selects) db-vals))
1014 (mapc #'(lambda (jo)
1015 ;; find all immediate-select slots and join-vals for this object
1016 (let* ((jo-class (class-of jo))
1018 (if (normalizedp jo-class)
1019 (class-direct-slots jo-class)
1020 (class-slots jo-class)))
1021 (pos-list (remove-if #'null
1024 (position s immediate-selects
1028 (get-slot-values-from-view jo
1030 (mapcar #'(lambda (pos)
1031 (nth pos immediate-selects))
1033 (mapcar #'(lambda (pos) (nth pos join-vals))
1039 (class-slots vclass))
1040 (slot (find (class-name (class-of jc)) vslots
1041 :key #'(lambda (slot)
1042 (when (and (eq :join (view-class-slot-db-kind slot))
1043 (eq (slot-definition-name slot)
1044 (gethash :join-class (view-class-slot-db-info slot))))
1045 (slot-definition-name slot))))))
1047 (setf (slot-value obj (slot-definition-name slot)) jc))))
1049 (when refresh (instance-refreshed obj))
1052 (mapcar #'(lambda (sclass jclass sel immediate-join instance)
1054 (build-object vals sclass jclass sel immediate-join instance)
1055 (setf vals (nthcdr (+ (list-length sel) (list-length immediate-join))
1057 sclasses immediate-join-classes sels immediate-joins instances)))
1058 (if (and flatp (= (length sclasses) 1))
1062 (defun find-all (view-classes
1064 &key all set-operation distinct from where group-by having
1065 order-by offset limit refresh flatp result-types
1067 (database *default-database*)
1069 "Called by SELECT to generate object query results when the
1070 View Classes VIEW-CLASSES are passed as arguments to SELECT."
1071 (declare (ignore all set-operation group-by having offset limit inner-join on))
1072 (flet ((ref-equal (ref1 ref2)
1073 (string= (sql-output ref1 database)
1074 (sql-output ref2 database)))
1075 (table-sql-expr (table)
1076 (sql-expression :table (view-table table)))
1077 (tables-equal (table-a table-b)
1078 (when (and table-a table-b)
1079 (string= (string (slot-value table-a 'name))
1080 (string (slot-value table-b 'name))))))
1084 (remf args :additional-fields)
1085 (remf args :result-types)
1086 (remf args :instances)
1087 (let* ((*db-deserializing* t)
1088 (sclasses (mapcar #'find-class view-classes))
1089 (immediate-join-slots
1090 (mapcar #'(lambda (c) (generate-retrieval-joins-list c :immediate)) sclasses))
1091 (immediate-join-classes
1092 (mapcar #'(lambda (jcs)
1093 (mapcar #'(lambda (slotdef)
1094 (find-class (gethash :join-class (view-class-slot-db-info slotdef))))
1096 immediate-join-slots))
1097 (immediate-join-sels (mapcar #'generate-immediate-joins-selection-list sclasses))
1098 (sels (mapcar #'generate-selection-list sclasses))
1099 (fullsels (apply #'append (mapcar #'append sels immediate-join-sels)))
1100 (sel-tables (collect-table-refs where))
1101 (tables (remove-if #'null
1103 (append (mapcar #'table-sql-expr sclasses)
1104 (mapcan #'(lambda (jc-list)
1106 #'(lambda (jc) (when jc (table-sql-expr jc)))
1108 immediate-join-classes)
1110 :test #'tables-equal)))
1111 (order-by-slots (mapcar #'(lambda (ob) (if (atom ob) ob (car ob)))
1112 (listify order-by)))
1115 ;;(format t "sclasses: ~W~%ijc: ~W~%tables: ~W~%" sclasses immediate-join-classes tables)
1117 (dolist (ob order-by-slots)
1118 (when (and ob (not (member ob (mapcar #'cdr fullsels)
1119 :test #'ref-equal)))
1121 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1123 (dolist (ob (listify distinct))
1124 (when (and (typep ob 'sql-ident)
1125 (not (member ob (mapcar #'cdr fullsels)
1126 :test #'ref-equal)))
1128 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1130 (mapcar #'(lambda (vclass jclasses jslots)
1133 #'(lambda (jclass jslot)
1134 (let ((dbi (view-class-slot-db-info jslot)))
1137 (list (sql-operation '==
1139 :attribute (gethash :foreign-key dbi)
1140 :table (view-table jclass))
1142 :attribute (gethash :home-key dbi)
1143 :table (view-table vclass))))
1144 (when join-where (listify join-where))))))
1146 sclasses immediate-join-classes immediate-join-slots)
1147 ;; Reported buggy on clsql-devel
1148 ;; (when where (setq where (listify where)))
1150 ((and where join-where)
1151 (setq where (list (apply #'sql-and where join-where))))
1152 ((and (null where) (> (length join-where) 1))
1153 (setq where (list (apply #'sql-and join-where)))))
1155 (let* ((rows (apply #'select
1156 (append (mapcar #'cdr fullsels)
1158 (list (append (when from (listify from))
1160 (list :result-types result-types)
1162 (list :where where))
1164 (instances-to-add (- (length rows) (length instances)))
1165 (perhaps-extended-instances
1166 (if (plusp instances-to-add)
1167 (append instances (do ((i 0 (1+ i))
1169 ((= i instances-to-add) res)
1170 (push (make-list (length sclasses) :initial-element nil) res)))
1173 #'(lambda (row instance)
1174 (build-objects row sclasses immediate-join-classes sels
1175 immediate-join-sels database refresh flatp
1176 (if (and flatp (atom instance))
1179 rows perhaps-extended-instances)))
1182 (defmethod instance-refreshed ((instance standard-db-object)))
1184 (defvar *default-caching* t
1185 "Controls whether SELECT caches objects by default. The CommonSQL
1186 specification states caching is on by default.")
1188 (defun select (&rest select-all-args)
1189 "Executes a query on DATABASE, which has a default value of
1190 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
1191 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
1192 argument can be used to generate queries in both functional and
1193 object oriented contexts.
1195 In the functional case, the required arguments specify the
1196 columns selected by the query and may be symbolic SQL expressions
1197 or strings representing attribute identifiers. Type modified
1198 identifiers indicate that the values selected from the specified
1199 column are converted to the specified lisp type. The keyword
1200 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
1201 SET-OPERATION and WHERE are used to specify, using the symbolic
1202 SQL syntax, the corresponding components of the SQL query
1203 generated by the call to SELECT. RESULT-TYPES is a list of
1204 symbols which specifies the lisp type for each field returned by
1205 the query. If RESULT-TYPES is nil all results are returned as
1206 strings whereas the default value of :auto means that the lisp
1207 types are automatically computed for each field. FIELD-NAMES is t
1208 by default which means that the second value returned is a list
1209 of strings representing the columns selected by the query. If
1210 FIELD-NAMES is nil, the list of column names is not returned as a
1213 In the object oriented case, the required arguments to SELECT are
1214 symbols denoting View Classes which specify the database tables
1215 to query. In this case, SELECT returns a list of View Class
1216 instances whose slots are set from the attribute values of the
1217 records in the specified table. Slot-value is a legal operator
1218 which can be employed as part of the symbolic SQL syntax used in
1219 the WHERE keyword argument to SELECT. REFRESH is nil by default
1220 which means that the View Class instances returned are retrieved
1221 from a cache if an equivalent call to SELECT has previously been
1222 issued. If REFRESH is true, the View Class instances returned are
1223 updated as necessary from the database and the generic function
1224 INSTANCE-REFRESHED is called to perform any necessary operations
1225 on the updated instances.
1227 In both object oriented and functional contexts, FLATP has a
1228 default value of nil which means that the results are returned as
1229 a list of lists. If FLATP is t and only one result is returned
1230 for each record selected in the query, the results are returned
1231 as elements of a list."
1233 (flet ((select-objects (target-args)
1235 (every #'(lambda (arg)
1237 (find-class arg nil)))
1239 (multiple-value-bind (target-args qualifier-args)
1240 (query-get-selections select-all-args)
1241 (unless (or *default-database* (getf qualifier-args :database))
1242 (signal-no-database-error nil))
1245 ((select-objects target-args)
1246 (let ((caching (getf qualifier-args :caching *default-caching*))
1247 (result-types (getf qualifier-args :result-types :auto))
1248 (refresh (getf qualifier-args :refresh nil))
1249 (database (or (getf qualifier-args :database) *default-database*))
1250 (order-by (getf qualifier-args :order-by)))
1251 (remf qualifier-args :caching)
1252 (remf qualifier-args :refresh)
1253 (remf qualifier-args :result-types)
1255 ;; Add explicity table name to order-by if not specified and only
1256 ;; one selected table. This is required so FIND-ALL won't duplicate
1258 (when (and order-by (= 1 (length target-args)))
1259 (let ((table-name (view-table (find-class (car target-args))))
1260 (order-by-list (copy-seq (listify order-by))))
1262 (loop for i from 0 below (length order-by-list)
1263 do (etypecase (nth i order-by-list)
1264 (sql-ident-attribute
1265 (unless (slot-value (nth i order-by-list) 'qualifier)
1266 (setf (slot-value (nth i order-by-list) 'qualifier) table-name)))
1268 (unless (slot-value (car (nth i order-by-list)) 'qualifier)
1269 (setf (slot-value (car (nth i order-by-list)) 'qualifier) table-name)))))
1270 (setf (getf qualifier-args :order-by) order-by-list)))
1274 (apply #'find-all target-args
1275 (append qualifier-args
1276 (list :result-types result-types :refresh refresh))))
1278 (let ((cached (records-cache-results target-args qualifier-args database)))
1280 ((and cached (not refresh))
1282 ((and cached refresh)
1283 (let ((results (apply #'find-all (append (list target-args) qualifier-args `(:instances ,cached :result-types :auto :refresh ,refresh)))))
1284 (setf (records-cache-results target-args qualifier-args database) results)
1287 (let ((results (apply #'find-all target-args (append qualifier-args
1288 `(:result-types :auto :refresh ,refresh)))))
1289 (setf (records-cache-results target-args qualifier-args database) results)
1292 (let* ((expr (apply #'make-query select-all-args))
1294 (mapcar #'(lambda (attrib)
1295 (if (typep attrib 'sql-ident-attribute)
1296 (let ((type (slot-value attrib 'type)))
1301 (slot-value expr 'selections))))
1302 (destructuring-bind (&key (flatp nil)
1303 (result-types :auto)
1305 (database *default-database*)
1308 (query expr :flatp flatp
1310 ;; specifying a type for an attribute overrides result-types
1311 (if (some #'(lambda (x) (not (eq t x))) specified-types)
1314 :field-names field-names
1315 :database database))))))))
1317 (defun compute-records-cache-key (targets qualifiers)
1319 (do ((args *select-arguments* (cdr args))
1321 ((null args) results)
1322 (let* ((arg (car args))
1323 (value (getf qualifiers arg)))
1327 (cons (cons (sql (car value)) (cdr value)))
1328 (%sql-expression (sql value))
1332 (defun records-cache-results (targets qualifiers database)
1333 (when (record-caches database)
1334 (gethash (compute-records-cache-key targets qualifiers) (record-caches database))))
1336 (defun (setf records-cache-results) (results targets qualifiers database)
1337 (unless (record-caches database)
1338 (setf (record-caches database)
1339 (make-hash-table :test 'equal
1340 #+allegro :values #+allegro :weak
1341 #+clisp :weak #+clisp :value
1342 #+lispworks :weak-kind #+lispworks :value)))
1343 (setf (gethash (compute-records-cache-key targets qualifiers)
1344 (record-caches database)) results)
1349 ;;; Serialization functions
1351 (defun write-instance-to-stream (obj stream)
1352 "Writes an instance to a stream where it can be later be read.
1353 NOTE: an error will occur if a slot holds a value which can not be written readably."
1354 (let* ((class (class-of obj))
1356 (dolist (slot (ordered-class-slots (class-of obj)))
1357 (let ((name (slot-definition-name slot)))
1358 (when (and (not (eq 'view-database name))
1359 (slot-boundp obj name))
1360 (push (cons name (slot-value obj name)) alist))))
1361 (setq alist (reverse alist))
1362 (write (cons (class-name class) alist) :stream stream :readably t))
1365 (defun read-instance-from-stream (stream)
1366 (let ((raw (read stream nil nil)))
1368 (let ((obj (make-instance (car raw))))
1369 (dolist (pair (cdr raw))
1370 (setf (slot-value obj (car pair)) (cdr pair)))