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)))
268 (cond ((and (not (normalizedp view-class))
270 (error "No settable slots."))
271 ((and (normalizedp view-class)
275 (update-records (sql-expression :table view-class-table)
276 :av-pairs record-values
277 :where (key-qualifier-for-instance
278 obj :database database
279 :this-class view-class)
283 (slot-value obj (slot-definition-name pk-slot))))))
285 (insert-records :into (sql-expression :table view-class-table)
286 :av-pairs record-values
289 (if (or (and (listp (view-class-slot-db-constraints pk-slot))
290 (member :auto-increment (view-class-slot-db-constraints pk-slot)))
291 (eql (view-class-slot-db-constraints pk-slot) :auto-increment))
293 (car (query "SELECT LAST_INSERT_ID();"
294 :flatp t :field-names nil
295 :database database))))
297 (slot-value obj (slot-definition-name pk-slot))))))
298 (when (eql this-class nil)
299 (setf (slot-value obj 'view-database) database)))))))
302 (defmethod delete-instance-records ((instance standard-db-object))
303 (let ((vt (sql-expression :table (view-table (class-of instance))))
304 (vd (view-database instance)))
306 (let ((qualifier (key-qualifier-for-instance instance :database vd)))
307 (delete-records :from vt :where qualifier :database vd)
308 (setf (record-caches vd) nil)
309 (setf (slot-value instance 'view-database) nil)
311 (signal-no-database-error vd))))
313 (defmethod update-instance-from-records ((instance standard-db-object)
314 &key (database *default-database*)
316 (let* ((view-class (or this-class (class-of instance)))
317 (pclass (car (class-direct-superclasses view-class)))
319 (when (normalizedp view-class)
320 (setf pres (update-instance-from-records instance :database database
321 :this-class pclass)))
322 (let* ((view-table (sql-expression :table (view-table view-class)))
323 (vd (or (view-database instance) database))
324 (view-qual (key-qualifier-for-instance instance :database vd
325 :this-class view-class))
326 (sels (generate-selection-list view-class))
329 (setf res (apply #'select (append (mapcar #'cdr sels)
330 (list :from view-table
335 (setf (slot-value instance 'view-database) vd)
336 (get-slot-values-from-view instance (mapcar #'car sels) (car res))))
340 (defmethod update-slot-from-record ((instance standard-db-object)
341 slot &key (database *default-database*))
342 (let* ((view-class (find-class (class-name (class-of instance))))
343 (slot-def (slotdef-for-slot-with-class slot view-class)))
344 (when (normalizedp view-class)
345 ;; If it's normalized, find the class that actually contains
346 ;; the slot that's tied to the db
348 (do ((this-class view-class
349 (car (class-direct-superclasses this-class))))
351 (mapcar #'(lambda (esd) (slot-definition-name esd))
352 (ordered-class-direct-slots this-class)))
354 (let* ((view-table (sql-expression :table (view-table view-class)))
355 (vd (or (view-database instance) database))
356 (view-qual (key-qualifier-for-instance instance :database vd
357 :this-class view-class))
358 (att-ref (generate-attribute-reference view-class slot-def))
359 (res (select att-ref :from view-table :where view-qual
362 (setf (slot-value instance 'view-database) vd)
363 (get-slot-values-from-view instance (list slot-def) (car res))))))
365 (defmethod update-slot-with-null ((object standard-db-object)
368 (setf (slot-value object slotname) (slot-value slotdef 'void-value)))
370 (defvar +no-slot-value+ '+no-slot-value+)
372 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
373 (let* ((class (find-class classname))
374 (sld (slotdef-for-slot-with-class slot class)))
376 (if (eq value +no-slot-value+)
377 (sql-expression :attribute (view-class-slot-column sld)
378 :table (view-table class))
383 (error "Unknown slot ~A for class ~A" slot classname))))
385 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
386 (declare (ignore database))
387 (let* ((class (find-class classname)))
388 (unless (view-table class)
389 (error "No view-table for class ~A" classname))
390 (sql-expression :table (view-table class))))
393 (defmethod database-get-type-specifier (type args database db-type)
394 (declare (ignore type args database db-type))
395 (format nil "VARCHAR(~D)" *default-string-length*))
397 (defmethod database-get-type-specifier ((type (eql 'integer)) args database db-type)
398 (declare (ignore database db-type))
400 (format nil "INT(~A)" (car args))
404 "An 8-bit integer, this width may vary by SQL implementation."
407 (defmethod database-get-type-specifier ((type (eql 'tinyint)) args database db-type)
408 (declare (ignore args database db-type))
412 "An integer smaller than a 32-bit integer. this width may vary by SQL implementation."
415 (defmethod database-get-type-specifier ((type (eql 'smallint)) args database db-type)
416 (declare (ignore args database db-type))
419 (deftype mediumint ()
420 "An integer smaller than a 32-bit integer, but may be larger than a smallint. This width may vary by SQL implementation."
423 (defmethod database-get-type-specifier ((type (eql 'mediumint)) args database db-type)
424 (declare (ignore args database db-type))
428 "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
431 (defmethod database-get-type-specifier ((type (eql 'bigint)) args database db-type)
432 (declare (ignore args database db-type))
435 (deftype varchar (&optional size)
436 "A variable length string for the SQL varchar type."
437 (declare (ignore size))
440 (defmethod database-get-type-specifier ((type (eql 'varchar)) args
442 (declare (ignore database db-type))
444 (format nil "VARCHAR(~A)" (car args))
445 (format nil "VARCHAR(~D)" *default-string-length*)))
447 (defmethod database-get-type-specifier ((type (eql 'string)) args database db-type)
448 (declare (ignore database db-type))
450 (format nil "CHAR(~A)" (car args))
451 (format nil "VARCHAR(~D)" *default-string-length*)))
453 (deftype universal-time ()
454 "A positive integer as returned by GET-UNIVERSAL-TIME."
457 (defmethod database-get-type-specifier ((type (eql 'universal-time)) args database db-type)
458 (declare (ignore args database db-type))
461 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database db-type)
462 (declare (ignore args database db-type))
465 (defmethod database-get-type-specifier ((type (eql 'date)) args database db-type)
466 (declare (ignore args database db-type))
469 (defmethod database-get-type-specifier ((type (eql 'duration)) args database db-type)
470 (declare (ignore database args db-type))
473 (defmethod database-get-type-specifier ((type (eql 'money)) args database db-type)
474 (declare (ignore database args db-type))
478 (deftype char (&optional len)
479 "A lisp type for the SQL CHAR type."
482 (defmethod database-get-type-specifier ((type (eql 'float)) args database db-type)
483 (declare (ignore database db-type))
485 (format nil "FLOAT(~A)" (car args))
488 (defmethod database-get-type-specifier ((type (eql 'long-float)) args database db-type)
489 (declare (ignore database db-type))
491 (format nil "FLOAT(~A)" (car args))
494 (deftype generalized-boolean ()
495 "A type which outputs a SQL boolean value, though any lisp type can be stored in the slot."
498 (defmethod database-get-type-specifier ((type (eql 'boolean)) args database db-type)
499 (declare (ignore args database db-type))
502 (defmethod database-get-type-specifier ((type (eql 'generalized-boolean)) args database db-type)
503 (declare (ignore args database db-type))
506 (defmethod database-get-type-specifier ((type (eql 'number)) args database db-type)
507 (declare (ignore database db-type))
509 ((and (consp args) (= (length args) 2))
510 (format nil "NUMBER(~D,~D)" (first args) (second args)))
511 ((and (consp args) (= (length args) 1))
512 (format nil "NUMBER(~D)" (first args)))
516 (defmethod database-get-type-specifier ((type (eql 'char)) args database db-type)
517 (declare (ignore database db-type))
519 (format nil "CHAR(~D)" (first args))
523 (defmethod database-output-sql-as-type (type val database db-type)
524 (declare (ignore type database db-type))
527 (defmethod database-output-sql-as-type ((type (eql 'list)) val database db-type)
528 (declare (ignore database db-type))
529 (progv '(*print-circle* *print-array*) '(t t)
530 (let ((escaped (prin1-to-string val)))
531 (substitute-char-string
532 escaped #\Null " "))))
534 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database db-type)
535 (declare (ignore database db-type))
538 (package-name (symbol-package val))
543 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database db-type)
544 (declare (ignore database db-type))
549 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database db-type)
550 (declare (ignore database db-type))
551 (progv '(*print-circle* *print-array*) '(t t)
552 (prin1-to-string val)))
554 (defmethod database-output-sql-as-type ((type (eql 'array)) val database db-type)
555 (declare (ignore database db-type))
556 (progv '(*print-circle* *print-array*) '(t t)
557 (prin1-to-string val)))
559 (defmethod database-output-sql-as-type ((type (eql 'boolean)) val database db-type)
560 (declare (ignore database db-type))
563 (defmethod database-output-sql-as-type ((type (eql 'generalized-boolean)) val database db-type)
564 (declare (ignore database db-type))
567 (defmethod database-output-sql-as-type ((type (eql 'string)) val database db-type)
568 (declare (ignore database db-type))
571 (defmethod database-output-sql-as-type ((type (eql 'char)) val database db-type)
572 (declare (ignore database db-type))
574 (character (write-to-string val))
577 (defmethod database-output-sql-as-type ((type (eql 'float)) val database db-type)
578 (declare (ignore database db-type))
579 (if (eq (type-of val) 'null)
581 (let ((*read-default-float-format* (type-of val)))
582 (format nil "~F" val))))
584 (defmethod read-sql-value (val type database db-type)
585 (declare (ignore database db-type))
587 ((null type) val) ;;we have no desired type, just give the value
588 ((typep val type) val) ;;check that it hasn't already been converted.
589 ((typep val 'string) (read-from-string val)) ;;maybe read will just take care of it?
590 (T (error "Unable to read-sql-value ~a as type ~a" val type))))
592 (defmethod read-sql-value (val (type (eql 'string)) database db-type)
593 (declare (ignore database db-type))
596 (defmethod read-sql-value (val (type (eql 'varchar)) database db-type)
597 (declare (ignore database db-type))
600 (defmethod read-sql-value (val (type (eql 'char)) database db-type)
601 (declare (ignore database db-type))
604 (defmethod read-sql-value (val (type (eql 'keyword)) database db-type)
605 (declare (ignore database db-type))
606 (when (< 0 (length val))
607 (intern (symbol-name-default-case val)
608 (find-package '#:keyword))))
610 (defmethod read-sql-value (val (type (eql 'symbol)) database db-type)
611 (declare (ignore database db-type))
612 (when (< 0 (length val))
613 (unless (string= val (symbol-name-default-case "NIL"))
614 (read-from-string val))))
616 (defmethod read-sql-value (val (type (eql 'integer)) database db-type)
617 (declare (ignore database db-type))
620 (unless (string-equal "NIL" val)
621 (parse-integer val)))
624 (defmethod read-sql-value (val (type (eql 'smallint)) database db-type)
625 (declare (ignore database db-type))
628 (unless (string-equal "NIL" val)
629 (parse-integer val)))
632 (defmethod read-sql-value (val (type (eql 'bigint)) 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 'float)) database db-type)
641 (declare (ignore database db-type))
642 ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
644 (string (float (read-from-string val)))
647 (defmethod read-sql-value (val (type (eql 'double-float)) database db-type)
648 (declare (ignore database db-type))
649 ;; writing 1.0 writes 1, so if we *really* want a float, must do (float ...)
652 (let ((*read-default-float-format* 'double-float))
653 (read-from-string val))
656 (float (coerce val 'double-float))))
658 (defmethod read-sql-value (val (type (eql 'boolean)) database db-type)
659 (declare (ignore database db-type))
662 (defmethod read-sql-value (val (type (eql 'generalized-boolean)) database db-type)
663 (declare (ignore database db-type))
666 (defmethod read-sql-value (val (type (eql 'number)) database db-type)
667 (declare (ignore database db-type))
670 (unless (string-equal "NIL" val)
671 (read-from-string val)))
674 (defmethod read-sql-value (val (type (eql 'universal-time)) database db-type)
675 (declare (ignore database db-type))
676 (unless (eq 'NULL val)
682 (defmethod read-sql-value (val (type (eql 'wall-time)) database db-type)
683 (declare (ignore database db-type))
684 (unless (eq 'NULL val)
685 (parse-timestring val)))
687 (defmethod read-sql-value (val (type (eql 'date)) database db-type)
688 (declare (ignore database db-type))
689 (unless (eq 'NULL val)
690 (parse-datestring val)))
692 (defmethod read-sql-value (val (type (eql 'duration)) database db-type)
693 (declare (ignore database db-type))
694 (unless (or (eq 'NULL val)
696 (parse-timestring val)))
698 ;; ------------------------------------------------------------
699 ;; Logic for 'faulting in' :join slots
701 ;; this works, but is inefficient requiring (+ 1 n-rows)
704 (defun fault-join-target-slot (class object slot-def)
705 (let* ((res (fault-join-slot-raw class object slot-def))
706 (dbi (view-class-slot-db-info slot-def))
707 (target-name (gethash :target-slot dbi))
708 (target-class (find-class target-name)))
710 (mapcar (lambda (obj)
716 (find target-name (class-slots (class-of obj))
717 :key #'slot-definition-name)))
720 #+ignore ;; this doesn't work when attempting to call slot-value
721 (mapcar (lambda (obj)
722 (cons obj (slot-value obj ts))) res))))
724 (defun fault-join-target-slot (class object slot-def)
725 (let* ((dbi (view-class-slot-db-info slot-def))
726 (ts (gethash :target-slot dbi))
727 (jc (gethash :join-class dbi))
728 (jc-view-table (view-table (find-class jc)))
729 (tdbi (view-class-slot-db-info
730 (find ts (class-slots (find-class jc))
731 :key #'slot-definition-name)))
732 (retrieval (gethash :retrieval tdbi))
733 (tsc (gethash :join-class tdbi))
734 (ts-view-table (view-table (find-class tsc)))
735 (jq (join-qualifier class object slot-def))
736 (key (slot-value object (gethash :home-key dbi))))
743 :inner-join (sql-expression :table jc-view-table)
747 :attribute (gethash :foreign-key tdbi)
748 :table ts-view-table)
750 :attribute (gethash :home-key tdbi)
751 :table jc-view-table))
754 :database (view-database object))))
755 (mapcar #'(lambda (i)
756 (let* ((instance (car i))
757 (jcc (make-instance jc :view-database (view-database instance))))
758 (setf (slot-value jcc (gethash :foreign-key dbi))
760 (setf (slot-value jcc (gethash :home-key tdbi))
761 (slot-value instance (gethash :foreign-key tdbi)))
762 (list instance jcc)))
765 ;; just fill in minimal slots
768 (let ((instance (make-instance tsc :view-database (view-database object)))
769 (jcc (make-instance jc :view-database (view-database object)))
771 (setf (slot-value instance (gethash :home-key tdbi)) fk)
772 (setf (slot-value jcc (gethash :foreign-key dbi))
774 (setf (slot-value jcc (gethash :home-key tdbi))
776 (list instance jcc)))
777 (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
778 :from (sql-expression :table jc-view-table)
780 :database (view-database object))))))))
785 (defvar *default-update-objects-max-len* nil
786 "The default value to use for the MAX-LEN keyword argument to
787 UPDATE-OBJECT-JOINS.")
789 (defun update-objects-joins (objects &key (slots t) (force-p t)
791 *default-update-objects-max-len*))
792 "Updates from the records of the appropriate database tables
793 the join slots specified by SLOTS in the supplied list of View
794 Class instances OBJECTS. SLOTS is t by default which means that
795 all join slots with :retrieval :immediate are updated. CLASS-NAME
796 is used to specify the View Class of all instance in OBJECTS and
797 default to nil which means that the class of the first instance
798 in OBJECTS is used. FORCE-P is t by default which means that all
799 join slots are updated whereas a value of nil means that only
800 unbound join slots are updated. MAX-LEN defaults to
801 *DEFAULT-UPDATE-OBJECTS-MAX-LEN* and when non-nil specifies that
802 UPDATE-OBJECT-JOINS may issue multiple database queries with a
803 maximum of MAX-LEN instances updated in each query."
804 (assert (or (null max-len) (plusp max-len)))
807 (setq class-name (class-name (class-of (first objects)))))
808 (let* ((class (find-class class-name))
809 (class-slots (ordered-class-slots class))
812 (generate-retrieval-joins-list class :deferred)
814 (mapcar #'(lambda (name)
815 (let ((slotdef (find name class-slots :key #'slot-definition-name)))
817 (warn "Unable to find slot named ~S in class ~S." name class))
820 (dolist (slotdef slotdefs)
821 (let* ((dbi (view-class-slot-db-info slotdef))
822 (slotdef-name (slot-definition-name slotdef))
823 (foreign-key (gethash :foreign-key dbi))
824 (home-key (gethash :home-key dbi))
828 (mapcar #'(lambda (o) (slot-value o home-key)) objects)
831 #'(lambda (o) (if (slot-boundp o slotdef-name)
833 (slot-value o home-key)))
835 (n-object-keys (length object-keys))
836 (query-len (or max-len n-object-keys)))
838 (do ((i 0 (+ i query-len)))
839 ((>= i n-object-keys))
840 (let* ((keys (if max-len
841 (subseq object-keys i (min (+ i query-len) n-object-keys))
843 (results (unless (gethash :target-slot dbi)
844 (find-all (list (gethash :join-class dbi))
845 :where (make-instance 'sql-relational-exp
847 :sub-expressions (list (sql-expression :attribute foreign-key)
852 (dolist (object objects)
853 (when (or force-p (not (slot-boundp object slotdef-name)))
854 (let ((res (if results
855 (remove-if-not #'(lambda (obj)
856 (equal obj (slot-value
865 (when (gethash :target-slot dbi)
866 (fault-join-target-slot class object slotdef))))))
868 (setf (slot-value object slotdef-name)
869 (if (gethash :set dbi) res (car res)))))))))))))
872 (defun fault-join-slot-raw (class object slot-def)
873 (let* ((dbi (view-class-slot-db-info slot-def))
874 (jc (gethash :join-class dbi)))
875 (let ((jq (join-qualifier class object slot-def)))
877 (select jc :where jq :flatp t :result-types nil
878 :database (view-database object))))))
880 (defun fault-join-slot (class object slot-def)
881 (let* ((dbi (view-class-slot-db-info slot-def))
882 (ts (gethash :target-slot dbi)))
883 (if (and ts (gethash :set dbi))
884 (fault-join-target-slot class object slot-def)
885 (let ((res (fault-join-slot-raw class object slot-def)))
888 ((and ts (not (gethash :set dbi)))
889 (mapcar (lambda (obj) (slot-value obj ts)) res))
890 ((and (not ts) (not (gethash :set dbi)))
892 ((and (not ts) (gethash :set dbi))
895 ;;;; Should we not return the whole result, instead of only
896 ;;;; the one slot-value? We get all the values from the db
898 (defun fault-join-normalized-slot (class object slot-def)
899 (labels ((getsc (this-class)
900 (let ((sc (car (class-direct-superclasses this-class))))
904 (let* ((sc (getsc class))
905 (hk (slot-definition-name (car (key-slots class))))
906 (fk (slot-definition-name (car (key-slots sc)))))
907 (let ((jq (sql-operation '==
912 (view-class-slot-column
913 (slotdef-for-slot-with-class fk sc))
914 :table (view-table sc)))
918 (slot-value object hk))
921 ;; Caching nil in next select, because in normalized mode
922 ;; records can be changed through other instances (children,
923 ;; parents) so changes possibly won't be noticed
924 (let ((res (car (select (class-name sc) :where jq
925 :flatp t :result-types nil
927 :database (view-database object))))
928 (slot-name (slot-definition-name slot-def)))
930 ;; If current class is normalized and wanted slot is not
931 ;; a direct member, recurse up
932 (if (and (normalizedp class)
933 (not (member slot-name
934 (mapcar #'(lambda (esd) (slot-definition-name esd))
935 (ordered-class-direct-slots class))))
936 (not (slot-boundp res slot-name)))
937 (fault-join-normalized-slot sc res slot-def)
938 (slot-value res slot-name)))))) )
940 (defun join-qualifier (class object slot-def)
941 (declare (ignore class))
942 (let* ((dbi (view-class-slot-db-info slot-def))
943 (jc (find-class (gethash :join-class dbi)))
944 ;;(ts (gethash :target-slot dbi))
945 ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
946 (foreign-keys (gethash :foreign-key dbi))
947 (home-keys (gethash :home-key dbi)))
948 (when (every #'(lambda (slt)
949 (and (slot-boundp object slt)
950 (not (null (slot-value object slt)))))
951 (if (listp home-keys) home-keys (list home-keys)))
953 (mapcar #'(lambda (hk fk)
954 (let ((fksd (slotdef-for-slot-with-class fk jc)))
960 (view-class-slot-column fksd)
961 :table (view-table jc)))
965 (slot-value object hk))
968 (if (listp home-keys)
971 (if (listp foreign-keys)
973 (list foreign-keys)))))
975 (if (> (length jc) 1)
979 ;; FIXME: add retrieval immediate for efficiency
980 ;; For example, for (select 'employee-address) in test suite =>
981 ;; select addr.*,ea_join.* FROM addr,ea_join WHERE ea_join.aaddressid=addr.addressid\g
983 (defun build-objects (vals sclasses immediate-join-classes sels immediate-joins database refresh flatp instances)
984 "Used by find-all to build objects."
985 (labels ((build-object (vals vclass jclasses selects immediate-selects instance)
986 (let* ((db-vals (butlast vals (- (list-length vals)
987 (list-length selects))))
988 (obj (if instance instance (make-instance (class-name vclass) :view-database database)))
989 (join-vals (subseq vals (list-length selects)))
990 (joins (mapcar #'(lambda (c) (when c (make-instance c :view-database database)))
993 ;;(format t "joins: ~S~%db-vals: ~S~%join-values: ~S~%selects: ~S~%immediate-selects: ~S~%"
994 ;;joins db-vals join-vals selects immediate-selects)
996 ;; use refresh keyword here
997 (setf obj (get-slot-values-from-view obj (mapcar #'car selects) db-vals))
999 ;; find all immediate-select slots and join-vals for this object
1000 (let* ((jo-class (class-of jo))
1002 (if (normalizedp jo-class)
1003 (class-direct-slots jo-class)
1004 (class-slots jo-class)))
1005 (pos-list (remove-if #'null
1008 (position s immediate-selects
1012 (get-slot-values-from-view jo
1014 (mapcar #'(lambda (pos)
1015 (nth pos immediate-selects))
1017 (mapcar #'(lambda (pos) (nth pos join-vals))
1023 (class-slots vclass))
1024 (slot (find (class-name (class-of jc)) vslots
1025 :key #'(lambda (slot)
1026 (when (and (eq :join (view-class-slot-db-kind slot))
1027 (eq (slot-definition-name slot)
1028 (gethash :join-class (view-class-slot-db-info slot))))
1029 (slot-definition-name slot))))))
1031 (setf (slot-value obj (slot-definition-name slot)) jc))))
1033 (when refresh (instance-refreshed obj))
1036 (mapcar #'(lambda (sclass jclass sel immediate-join instance)
1038 (build-object vals sclass jclass sel immediate-join instance)
1039 (setf vals (nthcdr (+ (list-length sel) (list-length immediate-join))
1041 sclasses immediate-join-classes sels immediate-joins instances)))
1042 (if (and flatp (= (length sclasses) 1))
1046 (defun find-all (view-classes
1048 &key all set-operation distinct from where group-by having
1049 order-by offset limit refresh flatp result-types
1051 (database *default-database*)
1053 "Called by SELECT to generate object query results when the
1054 View Classes VIEW-CLASSES are passed as arguments to SELECT."
1055 (declare (ignore all set-operation group-by having offset limit inner-join on))
1056 (flet ((ref-equal (ref1 ref2)
1057 (string= (sql-output ref1 database)
1058 (sql-output ref2 database)))
1059 (table-sql-expr (table)
1060 (sql-expression :table (view-table table)))
1061 (tables-equal (table-a table-b)
1062 (when (and table-a table-b)
1063 (string= (string (slot-value table-a 'name))
1064 (string (slot-value table-b 'name))))))
1068 (remf args :additional-fields)
1069 (remf args :result-types)
1070 (remf args :instances)
1071 (let* ((*db-deserializing* t)
1072 (sclasses (mapcar #'find-class view-classes))
1073 (immediate-join-slots
1074 (mapcar #'(lambda (c) (generate-retrieval-joins-list c :immediate)) sclasses))
1075 (immediate-join-classes
1076 (mapcar #'(lambda (jcs)
1077 (mapcar #'(lambda (slotdef)
1078 (find-class (gethash :join-class (view-class-slot-db-info slotdef))))
1080 immediate-join-slots))
1081 (immediate-join-sels (mapcar #'generate-immediate-joins-selection-list sclasses))
1082 (sels (mapcar #'generate-selection-list sclasses))
1083 (fullsels (apply #'append (mapcar #'append sels immediate-join-sels)))
1084 (sel-tables (collect-table-refs where))
1085 (tables (remove-if #'null
1087 (append (mapcar #'table-sql-expr sclasses)
1088 (mapcan #'(lambda (jc-list)
1090 #'(lambda (jc) (when jc (table-sql-expr jc)))
1092 immediate-join-classes)
1094 :test #'tables-equal)))
1095 (order-by-slots (mapcar #'(lambda (ob) (if (atom ob) ob (car ob)))
1096 (listify order-by)))
1099 ;;(format t "sclasses: ~W~%ijc: ~W~%tables: ~W~%" sclasses immediate-join-classes tables)
1101 (dolist (ob order-by-slots)
1102 (when (and ob (not (member ob (mapcar #'cdr fullsels)
1103 :test #'ref-equal)))
1105 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1107 (dolist (ob (listify distinct))
1108 (when (and (typep ob 'sql-ident)
1109 (not (member ob (mapcar #'cdr fullsels)
1110 :test #'ref-equal)))
1112 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1114 (mapcar #'(lambda (vclass jclasses jslots)
1117 #'(lambda (jclass jslot)
1118 (let ((dbi (view-class-slot-db-info jslot)))
1121 (list (sql-operation '==
1123 :attribute (gethash :foreign-key dbi)
1124 :table (view-table jclass))
1126 :attribute (gethash :home-key dbi)
1127 :table (view-table vclass))))
1128 (when join-where (listify join-where))))))
1130 sclasses immediate-join-classes immediate-join-slots)
1131 ;; Reported buggy on clsql-devel
1132 ;; (when where (setq where (listify where)))
1134 ((and where join-where)
1135 (setq where (list (apply #'sql-and where join-where))))
1136 ((and (null where) (> (length join-where) 1))
1137 (setq where (list (apply #'sql-and join-where)))))
1139 (let* ((rows (apply #'select
1140 (append (mapcar #'cdr fullsels)
1142 (list (append (when from (listify from))
1144 (list :result-types result-types)
1146 (list :where where))
1148 (instances-to-add (- (length rows) (length instances)))
1149 (perhaps-extended-instances
1150 (if (plusp instances-to-add)
1151 (append instances (do ((i 0 (1+ i))
1153 ((= i instances-to-add) res)
1154 (push (make-list (length sclasses) :initial-element nil) res)))
1157 #'(lambda (row instance)
1158 (build-objects row sclasses immediate-join-classes sels
1159 immediate-join-sels database refresh flatp
1160 (if (and flatp (atom instance))
1163 rows perhaps-extended-instances)))
1166 (defmethod instance-refreshed ((instance standard-db-object)))
1168 (defvar *default-caching* t
1169 "Controls whether SELECT caches objects by default. The CommonSQL
1170 specification states caching is on by default.")
1172 (defun select (&rest select-all-args)
1173 "Executes a query on DATABASE, which has a default value of
1174 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
1175 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
1176 argument can be used to generate queries in both functional and
1177 object oriented contexts.
1179 In the functional case, the required arguments specify the
1180 columns selected by the query and may be symbolic SQL expressions
1181 or strings representing attribute identifiers. Type modified
1182 identifiers indicate that the values selected from the specified
1183 column are converted to the specified lisp type. The keyword
1184 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
1185 SET-OPERATION and WHERE are used to specify, using the symbolic
1186 SQL syntax, the corresponding components of the SQL query
1187 generated by the call to SELECT. RESULT-TYPES is a list of
1188 symbols which specifies the lisp type for each field returned by
1189 the query. If RESULT-TYPES is nil all results are returned as
1190 strings whereas the default value of :auto means that the lisp
1191 types are automatically computed for each field. FIELD-NAMES is t
1192 by default which means that the second value returned is a list
1193 of strings representing the columns selected by the query. If
1194 FIELD-NAMES is nil, the list of column names is not returned as a
1197 In the object oriented case, the required arguments to SELECT are
1198 symbols denoting View Classes which specify the database tables
1199 to query. In this case, SELECT returns a list of View Class
1200 instances whose slots are set from the attribute values of the
1201 records in the specified table. Slot-value is a legal operator
1202 which can be employed as part of the symbolic SQL syntax used in
1203 the WHERE keyword argument to SELECT. REFRESH is nil by default
1204 which means that the View Class instances returned are retrieved
1205 from a cache if an equivalent call to SELECT has previously been
1206 issued. If REFRESH is true, the View Class instances returned are
1207 updated as necessary from the database and the generic function
1208 INSTANCE-REFRESHED is called to perform any necessary operations
1209 on the updated instances.
1211 In both object oriented and functional contexts, FLATP has a
1212 default value of nil which means that the results are returned as
1213 a list of lists. If FLATP is t and only one result is returned
1214 for each record selected in the query, the results are returned
1215 as elements of a list."
1217 (flet ((select-objects (target-args)
1219 (every #'(lambda (arg)
1221 (find-class arg nil)))
1223 (multiple-value-bind (target-args qualifier-args)
1224 (query-get-selections select-all-args)
1225 (unless (or *default-database* (getf qualifier-args :database))
1226 (signal-no-database-error nil))
1229 ((select-objects target-args)
1230 (let ((caching (getf qualifier-args :caching *default-caching*))
1231 (result-types (getf qualifier-args :result-types :auto))
1232 (refresh (getf qualifier-args :refresh nil))
1233 (database (or (getf qualifier-args :database) *default-database*))
1234 (order-by (getf qualifier-args :order-by)))
1235 (remf qualifier-args :caching)
1236 (remf qualifier-args :refresh)
1237 (remf qualifier-args :result-types)
1239 ;; Add explicity table name to order-by if not specified and only
1240 ;; one selected table. This is required so FIND-ALL won't duplicate
1242 (when (and order-by (= 1 (length target-args)))
1243 (let ((table-name (view-table (find-class (car target-args))))
1244 (order-by-list (copy-seq (listify order-by))))
1246 (loop for i from 0 below (length order-by-list)
1247 do (etypecase (nth i order-by-list)
1248 (sql-ident-attribute
1249 (unless (slot-value (nth i order-by-list) 'qualifier)
1250 (setf (slot-value (nth i order-by-list) 'qualifier) table-name)))
1252 (unless (slot-value (car (nth i order-by-list)) 'qualifier)
1253 (setf (slot-value (car (nth i order-by-list)) 'qualifier) table-name)))))
1254 (setf (getf qualifier-args :order-by) order-by-list)))
1258 (apply #'find-all target-args
1259 (append qualifier-args
1260 (list :result-types result-types :refresh refresh))))
1262 (let ((cached (records-cache-results target-args qualifier-args database)))
1264 ((and cached (not refresh))
1266 ((and cached refresh)
1267 (let ((results (apply #'find-all (append (list target-args) qualifier-args `(:instances ,cached :result-types :auto :refresh ,refresh)))))
1268 (setf (records-cache-results target-args qualifier-args database) results)
1271 (let ((results (apply #'find-all target-args (append qualifier-args
1272 `(:result-types :auto :refresh ,refresh)))))
1273 (setf (records-cache-results target-args qualifier-args database) results)
1276 (let* ((expr (apply #'make-query select-all-args))
1278 (mapcar #'(lambda (attrib)
1279 (if (typep attrib 'sql-ident-attribute)
1280 (let ((type (slot-value attrib 'type)))
1285 (slot-value expr 'selections))))
1286 (destructuring-bind (&key (flatp nil)
1287 (result-types :auto)
1289 (database *default-database*)
1292 (query expr :flatp flatp
1294 ;; specifying a type for an attribute overrides result-types
1295 (if (some #'(lambda (x) (not (eq t x))) specified-types)
1298 :field-names field-names
1299 :database database))))))))
1301 (defun compute-records-cache-key (targets qualifiers)
1303 (do ((args *select-arguments* (cdr args))
1305 ((null args) results)
1306 (let* ((arg (car args))
1307 (value (getf qualifiers arg)))
1311 (cons (cons (sql (car value)) (cdr value)))
1312 (%sql-expression (sql value))
1316 (defun records-cache-results (targets qualifiers database)
1317 (when (record-caches database)
1318 (gethash (compute-records-cache-key targets qualifiers) (record-caches database))))
1320 (defun (setf records-cache-results) (results targets qualifiers database)
1321 (unless (record-caches database)
1322 (setf (record-caches database)
1323 (make-hash-table :test 'equal
1324 #+allegro :values #+allegro :weak
1325 #+clisp :weak #+clisp :value
1326 #+lispworks :weak-kind #+lispworks :value)))
1327 (setf (gethash (compute-records-cache-key targets qualifiers)
1328 (record-caches database)) results)
1333 ;;; Serialization functions
1335 (defun write-instance-to-stream (obj stream)
1336 "Writes an instance to a stream where it can be later be read.
1337 NOTE: an error will occur if a slot holds a value which can not be written readably."
1338 (let* ((class (class-of obj))
1340 (dolist (slot (ordered-class-slots (class-of obj)))
1341 (let ((name (slot-definition-name slot)))
1342 (when (and (not (eq 'view-database name))
1343 (slot-boundp obj name))
1344 (push (cons name (slot-value obj name)) alist))))
1345 (setq alist (reverse alist))
1346 (write (cons (class-name class) alist) :stream stream :readably t))
1349 (defun read-instance-from-stream (stream)
1350 (let ((raw (read stream nil nil)))
1352 (let ((obj (make-instance (car raw))))
1353 (dolist (pair (cdr raw))
1354 (setf (slot-value obj (car pair)) (cdr pair)))