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 (database-identifier k database)
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 (database-identifier slotdef nil)
43 :table (database-identifier vclass nil)))
44 ((eq (view-class-slot-db-kind slotdef) :key)
45 (sql-expression :attribute (database-identifier slotdef nil)
46 :table (database-identifier vclass nil)))
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))))))
96 (defmethod choose-database-for-instance ((obj standard-db-object) &optional database)
97 "Determine which database connection to use for a standard-db-object.
98 Errs if none is available."
99 (or (find-if #'(lambda (db)
100 (and db (is-database-open db)))
101 (list (view-database obj)
104 (signal-no-database-error nil)))
108 ;; Called by 'get-slot-values-from-view'
111 (defmethod update-slot-from-db ((instance standard-db-object) slotdef value)
112 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
113 (let* ((slot-reader (view-class-slot-db-reader slotdef))
114 (slot-name (slot-definition-name slotdef))
115 (slot-type (specified-type slotdef)))
116 (cond ((and value (null slot-reader))
117 (setf (slot-value instance slot-name)
118 (read-sql-value value (delistify slot-type)
119 (choose-database-for-instance instance)
120 (database-underlying-type
121 (choose-database-for-instance instance)))))
123 (update-slot-with-null instance slot-name slotdef))
124 ((typep slot-reader 'string)
125 (setf (slot-value instance slot-name)
126 (format nil slot-reader value)))
127 ((typep slot-reader '(or symbol function))
128 (setf (slot-value instance slot-name)
129 (apply slot-reader (list value))))
131 (error "Slot reader is of an unusual type.")))))
133 (defmethod key-value-from-db (slotdef value database)
134 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
135 (let ((slot-reader (view-class-slot-db-reader slotdef))
136 (slot-type (specified-type slotdef)))
137 (cond ((and value (null slot-reader))
138 (read-sql-value value (delistify slot-type) database
139 (database-underlying-type database)))
142 ((typep slot-reader 'string)
143 (format nil slot-reader value))
144 ((typep slot-reader '(or symbol function))
145 (apply slot-reader (list value)))
147 (error "Slot reader is of an unusual type.")))))
149 (defun db-value-from-slot (slotdef val database)
150 (let ((dbwriter (view-class-slot-db-writer slotdef))
151 (dbtype (specified-type slotdef)))
153 (string (format nil dbwriter val))
154 ((and (or symbol function) (not null)) (apply dbwriter (list val)))
156 (database-output-sql-as-type
160 val database (database-underlying-type database))))))
162 (defun check-slot-type (slotdef val)
163 (let* ((slot-type (specified-type slotdef))
164 (basetype (if (listp slot-type) (car slot-type) slot-type)))
165 (when (and slot-type val)
166 (unless (typep val basetype)
167 (error 'sql-user-error
169 (format nil "Invalid value ~A in slot ~A, not of type ~A."
170 val (slot-definition-name slotdef) slot-type))))))
173 ;; Called by find-all
176 (defmethod get-slot-values-from-view (obj slotdeflist values)
177 (flet ((update-slot (slot-def values)
178 (update-slot-from-db obj slot-def values)))
179 (mapc #'update-slot slotdeflist values)
182 (defmethod update-record-from-slot ((obj standard-db-object) slot &key
183 (database *default-database*))
184 (let* ((database (choose-database-for-instance obj database))
185 (view-class (class-of obj)))
186 (when (normalizedp view-class)
187 ;; If it's normalized, find the class that actually contains
188 ;; the slot that's tied to the db
190 (do ((this-class view-class
191 (car (class-direct-superclasses this-class))))
193 (mapcar #'(lambda (esd) (slot-definition-name esd))
194 (ordered-class-direct-slots this-class)))
196 (let* ((vct (view-table view-class))
197 (sd (slotdef-for-slot-with-class slot view-class)))
198 (check-slot-type sd (slot-value obj slot))
199 (let* ((att (database-identifier sd database))
200 (val (db-value-from-slot sd (slot-value obj slot) database)))
201 (cond ((and vct sd (view-database obj))
202 (update-records (sql-expression :table vct)
203 :attributes (list (sql-expression :attribute att))
205 :where (key-qualifier-for-instance
206 obj :database database :this-class view-class)
208 ((and vct sd (not (view-database obj)))
209 (insert-records :into (sql-expression :table vct)
210 :attributes (list (sql-expression :attribute att))
213 (setf (slot-value obj 'view-database) database))
215 (error "Unable to update record.")))))
218 (defmethod update-record-from-slots ((obj standard-db-object) slots &key
219 (database *default-database*))
220 (when (normalizedp (class-of obj))
221 ;; FIXME: Rewrite to bundle slots for same table to be written
222 ;; as avpairs (like how is done for non-normalized view-classes below)
224 (update-record-from-slot obj slot :database database))
225 (return-from update-record-from-slots (values)))
227 (let* ((database (choose-database-for-instance obj database))
228 (vct (view-table (class-of obj)))
229 (sds (slotdefs-for-slots-with-class slots (class-of obj)))
230 (avps (mapcar #'(lambda (s)
231 (let ((val (slot-value
232 obj (slot-definition-name s))))
233 (check-slot-type s val)
234 (list (sql-expression
235 :attribute (database-identifier s database))
236 (db-value-from-slot s val database))))
238 (cond ((and avps (view-database obj))
239 (let ((where (key-qualifier-for-instance
240 obj :database database)))
242 (error "update-record-from-slots: could not generate a where clause for ~a" obj))
243 (update-records (sql-expression :table vct)
246 :database database)))
247 ((and avps (not (view-database obj)))
248 (insert-records :into (sql-expression :table vct)
251 (setf (slot-value obj 'view-database) database))
253 (error "Unable to update records"))))
256 (defmethod update-records-from-instance ((obj standard-db-object)
257 &key database this-class)
258 (let ((database (choose-database-for-instance obj database))
260 (labels ((slot-storedp (slot)
261 (and (member (view-class-slot-db-kind slot) '(:base :key))
262 (slot-boundp obj (slot-definition-name slot))))
263 (slot-value-list (slot)
264 (let ((value (slot-value obj (slot-definition-name slot))))
265 (check-slot-type slot value)
266 (list (sql-expression :attribute (database-identifier slot database))
267 (db-value-from-slot slot value database)))))
268 (let* ((view-class (or this-class (class-of obj)))
269 (pk-slot (car (keyslots-for-class view-class)))
270 (view-class-table (view-table view-class))
271 (pclass (car (class-direct-superclasses view-class))))
272 (when (normalizedp view-class)
273 (setf pk (update-records-from-instance obj :database database
276 (setf (slot-value obj (slot-definition-name pk-slot)) pk)))
277 (let* ((slots (remove-if-not #'slot-storedp
278 (if (normalizedp view-class)
279 (ordered-class-direct-slots view-class)
280 (ordered-class-slots view-class))))
281 (record-values (mapcar #'slot-value-list slots)))
283 (cond ((and (not (normalizedp view-class))
285 (error "No settable slots."))
286 ((and (normalizedp view-class)
290 ;; if this slot is set, the database object was returned from a select
291 ;; and has already been in the database, so we must need an update
292 (update-records (sql-expression :table view-class-table)
293 :av-pairs record-values
294 :where (key-qualifier-for-instance
295 obj :database database
296 :this-class view-class)
300 (slot-value obj (slot-definition-name pk-slot))))))
302 (insert-records :into (sql-expression :table view-class-table)
303 :av-pairs record-values
306 (when (and pk-slot (not pk))
308 (when (auto-increment-column-p pk-slot database)
309 (setf (slot-value obj (slot-definition-name pk-slot))
310 (database-last-auto-increment-id
311 database view-class-table pk-slot)))))
315 obj (slot-definition-name pk-slot)))))
316 (when (eql this-class nil)
317 (setf (slot-value obj 'view-database) database)))))))
318 ;; handle slots with defaults
319 (let* ((view-class (or this-class (class-of obj)))
320 (slots (if (normalizedp view-class)
321 (ordered-class-direct-slots view-class)
322 (ordered-class-slots view-class))))
324 (when (and (slot-exists-p slot 'db-constraints)
325 (listp (view-class-slot-db-constraints slot))
326 (member :default (view-class-slot-db-constraints slot)))
327 (unless (and (slot-boundp obj (slot-definition-name slot))
328 (slot-value obj (slot-definition-name slot)))
329 (update-slot-from-record obj (slot-definition-name slot))))))
333 (defmethod delete-instance-records ((instance standard-db-object) &key database)
334 (let ((database (choose-database-for-instance instance database))
335 (vt (sql-expression :table (view-table (class-of instance)))))
337 (let ((qualifier (key-qualifier-for-instance instance :database database)))
338 (delete-records :from vt :where qualifier :database database)
339 (setf (record-caches database) nil)
340 (setf (slot-value instance 'view-database) nil)
342 (signal-no-database-error database))))
344 (defmethod update-instance-from-records ((instance standard-db-object)
345 &key (database *default-database*)
347 (let* ((view-class (or this-class (class-of instance)))
348 (pclass (car (class-direct-superclasses view-class)))
350 (when (normalizedp view-class)
351 (setf pres (update-instance-from-records instance :database database
352 :this-class pclass)))
353 (let* ((view-table (sql-expression :table (view-table view-class)))
354 (vd (choose-database-for-instance instance database))
355 (view-qual (key-qualifier-for-instance instance :database vd
356 :this-class view-class))
357 (sels (generate-selection-list view-class))
360 (setf res (apply #'select (append (mapcar #'cdr sels)
361 (list :from view-table
366 (setf (slot-value instance 'view-database) vd)
367 (get-slot-values-from-view instance (mapcar #'car sels) (car res))))
371 (defmethod update-slot-from-record ((instance standard-db-object)
372 slot &key (database *default-database*))
373 (let* ((view-class (find-class (class-name (class-of instance))))
374 (slot-def (slotdef-for-slot-with-class slot view-class)))
375 (when (normalizedp view-class)
376 ;; If it's normalized, find the class that actually contains
377 ;; the slot that's tied to the db
379 (do ((this-class view-class
380 (car (class-direct-superclasses this-class))))
382 (mapcar #'(lambda (esd) (slot-definition-name esd))
383 (ordered-class-direct-slots this-class)))
385 (let* ((view-table (sql-expression :table (view-table view-class)))
386 (vd (choose-database-for-instance instance database))
387 (view-qual (key-qualifier-for-instance instance :database vd
388 :this-class view-class))
389 (att-ref (generate-attribute-reference view-class slot-def))
390 (res (select att-ref :from view-table :where view-qual
393 (setf (slot-value instance 'view-database) vd)
394 (get-slot-values-from-view instance (list slot-def) (car res))))))
396 (defmethod update-slot-with-null ((object standard-db-object)
399 (setf (slot-value object slotname) (slot-value slotdef 'void-value)))
401 (defvar +no-slot-value+ '+no-slot-value+)
403 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
404 (let* ((class (find-class classname))
405 (sld (slotdef-for-slot-with-class slot class)))
407 (if (eq value +no-slot-value+)
408 (sql-expression :attribute (database-identifier sld database)
409 :table (view-table class))
414 (error "Unknown slot ~A for class ~A" slot classname))))
416 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
417 (declare (ignore database))
418 (let* ((class (find-class classname)))
419 (unless (view-table class)
420 (error "No view-table for class ~A" classname))
421 (sql-expression :table (view-table class))))
424 (defmethod database-get-type-specifier (type args database db-type)
425 (declare (ignore type args database db-type))
426 (format nil "VARCHAR(~D)" *default-string-length*))
428 (defmethod database-get-type-specifier ((type (eql 'integer)) args database db-type)
429 (declare (ignore database db-type))
431 (format nil "INT(~A)" (car args))
435 "An 8-bit integer, this width may vary by SQL implementation."
438 (defmethod database-get-type-specifier ((type (eql 'tinyint)) args database db-type)
439 (declare (ignore args database db-type))
443 "An integer smaller than a 32-bit integer. this width may vary by SQL implementation."
446 (defmethod database-get-type-specifier ((type (eql 'smallint)) args database db-type)
447 (declare (ignore args database db-type))
450 (deftype mediumint ()
451 "An integer smaller than a 32-bit integer, but may be larger than a smallint. This width may vary by SQL implementation."
454 (defmethod database-get-type-specifier ((type (eql 'mediumint)) args database db-type)
455 (declare (ignore args database db-type))
459 "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
462 (defmethod database-get-type-specifier ((type (eql 'bigint)) args database db-type)
463 (declare (ignore args database db-type))
466 (deftype varchar (&optional size)
467 "A variable length string for the SQL varchar type."
468 (declare (ignore size))
471 (defmethod database-get-type-specifier ((type (eql 'varchar)) args
473 (declare (ignore database db-type))
475 (format nil "VARCHAR(~A)" (car args))
476 (format nil "VARCHAR(~D)" *default-string-length*)))
478 (defmethod database-get-type-specifier ((type (eql 'string)) args database db-type)
479 (declare (ignore database db-type))
481 (format nil "CHAR(~A)" (car args))
482 (format nil "VARCHAR(~D)" *default-string-length*)))
484 (deftype universal-time ()
485 "A positive integer as returned by GET-UNIVERSAL-TIME."
488 (defmethod database-get-type-specifier ((type (eql 'universal-time)) args database db-type)
489 (declare (ignore args database db-type))
492 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database db-type)
493 (declare (ignore args database db-type))
496 (defmethod database-get-type-specifier ((type (eql 'date)) args database db-type)
497 (declare (ignore args database db-type))
500 (defmethod database-get-type-specifier ((type (eql 'duration)) args database db-type)
501 (declare (ignore database args db-type))
504 (defmethod database-get-type-specifier ((type (eql 'money)) args database db-type)
505 (declare (ignore database args db-type))
509 (deftype char (&optional len)
510 "A lisp type for the SQL CHAR type."
513 (defmethod database-get-type-specifier ((type (eql 'float)) args database db-type)
514 (declare (ignore database db-type))
516 (format nil "FLOAT(~A)" (car args))
519 (defmethod database-get-type-specifier ((type (eql 'long-float)) args database db-type)
520 (declare (ignore database db-type))
522 (format nil "FLOAT(~A)" (car args))
525 (deftype generalized-boolean ()
526 "A type which outputs a SQL boolean value, though any lisp type can be stored in the slot."
529 (defmethod database-get-type-specifier ((type (eql 'boolean)) args database db-type)
530 (declare (ignore args database db-type))
533 (defmethod database-get-type-specifier ((type (eql 'generalized-boolean)) args database db-type)
534 (declare (ignore args database db-type))
537 (defmethod database-get-type-specifier ((type (eql 'number)) args database db-type)
538 (declare (ignore database db-type))
540 ((and (consp args) (= (length args) 2))
541 (format nil "NUMBER(~D,~D)" (first args) (second args)))
542 ((and (consp args) (= (length args) 1))
543 (format nil "NUMBER(~D)" (first args)))
547 (defmethod database-get-type-specifier ((type (eql 'char)) args database db-type)
548 (declare (ignore database db-type))
550 (format nil "CHAR(~D)" (first args))
554 (defmethod database-output-sql-as-type (type val database db-type)
555 (declare (ignore type database db-type))
558 (defmethod database-output-sql-as-type ((type (eql 'list)) val database db-type)
559 (declare (ignore database db-type))
560 (progv '(*print-circle* *print-array*) '(t t)
561 (let ((escaped (prin1-to-string val)))
562 (substitute-char-string
563 escaped #\Null " "))))
565 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database db-type)
566 (declare (ignore database db-type))
569 (package-name (symbol-package val))
574 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database db-type)
575 (declare (ignore database db-type))
580 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database db-type)
581 (declare (ignore database db-type))
582 (progv '(*print-circle* *print-array*) '(t t)
583 (prin1-to-string val)))
585 (defmethod database-output-sql-as-type ((type (eql 'array)) val database db-type)
586 (declare (ignore database db-type))
587 (progv '(*print-circle* *print-array*) '(t t)
588 (prin1-to-string val)))
590 (defmethod database-output-sql-as-type ((type (eql 'boolean)) val database db-type)
591 (declare (ignore database db-type))
594 (defmethod database-output-sql-as-type ((type (eql 'generalized-boolean)) val database db-type)
595 (declare (ignore database db-type))
598 (defmethod database-output-sql-as-type ((type (eql 'string)) val database db-type)
599 (declare (ignore database db-type))
602 (defmethod database-output-sql-as-type ((type (eql 'char)) val database db-type)
603 (declare (ignore database db-type))
605 (character (write-to-string val))
608 (defmethod database-output-sql-as-type ((type (eql 'float)) val database db-type)
609 (declare (ignore database db-type))
610 (if (eq (type-of val) 'null)
612 (let ((*read-default-float-format* (type-of val)))
613 (format nil "~F" val))))
615 (defmethod read-sql-value (val type database db-type)
616 (declare (ignore database db-type))
618 ((null type) val) ;;we have no desired type, just give the value
619 ((typep val type) val) ;;check that it hasn't already been converted.
620 ((typep val 'string) (read-from-string val)) ;;maybe read will just take care of it?
621 (T (error "Unable to read-sql-value ~a as type ~a" val type))))
623 (defmethod read-sql-value (val (type (eql 'string)) database db-type)
624 (declare (ignore database db-type))
627 (defmethod read-sql-value (val (type (eql 'varchar)) database db-type)
628 (declare (ignore database db-type))
631 (defmethod read-sql-value (val (type (eql 'char)) database db-type)
632 (declare (ignore database db-type))
635 (defmethod read-sql-value (val (type (eql 'keyword)) database db-type)
636 (declare (ignore database db-type))
637 (when (< 0 (length val))
638 (intern (symbol-name-default-case val)
639 (find-package '#:keyword))))
641 (defmethod read-sql-value (val (type (eql 'symbol)) database db-type)
642 (declare (ignore database db-type))
643 (when (< 0 (length val))
644 (unless (string= val (symbol-name-default-case "NIL"))
645 (read-from-string val))))
647 (defmethod read-sql-value (val (type (eql 'integer)) database db-type)
648 (declare (ignore database db-type))
651 (unless (string-equal "NIL" val)
652 (parse-integer val)))
655 (defmethod read-sql-value (val (type (eql 'smallint)) database db-type)
656 (declare (ignore database db-type))
659 (unless (string-equal "NIL" val)
660 (parse-integer val)))
663 (defmethod read-sql-value (val (type (eql 'bigint)) database db-type)
664 (declare (ignore database db-type))
667 (unless (string-equal "NIL" val)
668 (parse-integer val)))
671 (defmethod read-sql-value (val (type (eql 'float)) database db-type)
672 (declare (ignore database db-type))
673 ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
675 (string (float (read-from-string val)))
678 (defmethod read-sql-value (val (type (eql 'double-float)) database db-type)
679 (declare (ignore database db-type))
680 ;; writing 1.0 writes 1, so if we *really* want a float, must do (float ...)
683 (let ((*read-default-float-format* 'double-float))
684 (read-from-string val))
687 (float (coerce val 'double-float))))
689 (defmethod read-sql-value (val (type (eql 'boolean)) database db-type)
690 (declare (ignore database db-type))
693 (defmethod read-sql-value (val (type (eql 'generalized-boolean)) database db-type)
694 (declare (ignore database db-type))
697 (defmethod read-sql-value (val (type (eql 'number)) database db-type)
698 (declare (ignore database db-type))
701 (unless (string-equal "NIL" val)
702 (read-from-string val)))
705 (defmethod read-sql-value (val (type (eql 'universal-time)) database db-type)
706 (declare (ignore database db-type))
707 (unless (eq 'NULL val)
713 (defmethod read-sql-value (val (type (eql 'wall-time)) database db-type)
714 (declare (ignore database db-type))
715 (unless (eq 'NULL val)
716 (parse-timestring val)))
718 (defmethod read-sql-value (val (type (eql 'date)) database db-type)
719 (declare (ignore database db-type))
720 (unless (eq 'NULL val)
721 (parse-datestring val)))
723 (defmethod read-sql-value (val (type (eql 'duration)) database db-type)
724 (declare (ignore database db-type))
725 (unless (or (eq 'NULL val)
727 (parse-timestring val)))
729 ;; ------------------------------------------------------------
730 ;; Logic for 'faulting in' :join slots
732 ;; this works, but is inefficient requiring (+ 1 n-rows)
735 (defun fault-join-target-slot (class object slot-def)
736 (let* ((res (fault-join-slot-raw class object slot-def))
737 (dbi (view-class-slot-db-info slot-def))
738 (target-name (gethash :target-slot dbi))
739 (target-class (find-class target-name)))
741 (mapcar (lambda (obj)
747 (find target-name (class-slots (class-of obj))
748 :key #'slot-definition-name)))
751 #+ignore ;; this doesn't work when attempting to call slot-value
752 (mapcar (lambda (obj)
753 (cons obj (slot-value obj ts))) res))))
755 (defun fault-join-target-slot (class object slot-def)
756 (let* ((dbi (view-class-slot-db-info slot-def))
757 (ts (gethash :target-slot dbi))
758 (jc (gethash :join-class dbi))
759 (jc-view-table (view-table (find-class jc)))
760 (tdbi (view-class-slot-db-info
761 (find ts (class-slots (find-class jc))
762 :key #'slot-definition-name)))
763 (retrieval (gethash :retrieval tdbi))
764 (tsc (gethash :join-class tdbi))
765 (ts-view-table (view-table (find-class tsc)))
766 (jq (join-qualifier class object slot-def))
767 (key (slot-value object (gethash :home-key dbi))))
774 :inner-join (sql-expression :table jc-view-table)
778 :attribute (gethash :foreign-key tdbi)
779 :table ts-view-table)
781 :attribute (gethash :home-key tdbi)
782 :table jc-view-table))
785 :database (choose-database-for-instance object))))
786 (mapcar #'(lambda (i)
787 (let* ((instance (car i))
788 (jcc (make-instance jc :view-database (choose-database-for-instance instance))))
789 (setf (slot-value jcc (gethash :foreign-key dbi))
791 (setf (slot-value jcc (gethash :home-key tdbi))
792 (slot-value instance (gethash :foreign-key tdbi)))
793 (list instance jcc)))
796 ;; just fill in minimal slots
799 (let ((instance (make-instance tsc :view-database (choose-database-for-instance object)))
800 (jcc (make-instance jc :view-database (choose-database-for-instance object)))
802 (setf (slot-value instance (gethash :home-key tdbi)) fk)
803 (setf (slot-value jcc (gethash :foreign-key dbi))
805 (setf (slot-value jcc (gethash :home-key tdbi))
807 (list instance jcc)))
808 (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
809 :from (sql-expression :table jc-view-table)
811 :database (choose-database-for-instance object))))))))
816 (defvar *default-update-objects-max-len* nil
817 "The default value to use for the MAX-LEN keyword argument to
818 UPDATE-OBJECT-JOINS.")
820 (defun update-objects-joins (objects &key (slots t) (force-p t)
822 *default-update-objects-max-len*))
823 "Updates from the records of the appropriate database tables
824 the join slots specified by SLOTS in the supplied list of View
825 Class instances OBJECTS. SLOTS is t by default which means that
826 all join slots with :retrieval :immediate are updated. CLASS-NAME
827 is used to specify the View Class of all instance in OBJECTS and
828 default to nil which means that the class of the first instance
829 in OBJECTS is used. FORCE-P is t by default which means that all
830 join slots are updated whereas a value of nil means that only
831 unbound join slots are updated. MAX-LEN defaults to
832 *DEFAULT-UPDATE-OBJECTS-MAX-LEN* and when non-nil specifies that
833 UPDATE-OBJECT-JOINS may issue multiple database queries with a
834 maximum of MAX-LEN instances updated in each query."
835 (assert (or (null max-len) (plusp max-len)))
838 (setq class-name (class-name (class-of (first objects)))))
839 (let* ((class (find-class class-name))
840 (class-slots (ordered-class-slots class))
843 (generate-retrieval-joins-list class :deferred)
845 (mapcar #'(lambda (name)
846 (let ((slotdef (find name class-slots :key #'slot-definition-name)))
848 (warn "Unable to find slot named ~S in class ~S." name class))
851 (dolist (slotdef slotdefs)
852 (let* ((dbi (view-class-slot-db-info slotdef))
853 (slotdef-name (slot-definition-name slotdef))
854 (foreign-key (gethash :foreign-key dbi))
855 (home-key (gethash :home-key dbi))
859 (mapcar #'(lambda (o) (slot-value o home-key)) objects)
862 #'(lambda (o) (if (slot-boundp o slotdef-name)
864 (slot-value o home-key)))
866 (n-object-keys (length object-keys))
867 (query-len (or max-len n-object-keys)))
869 (do ((i 0 (+ i query-len)))
870 ((>= i n-object-keys))
871 (let* ((keys (if max-len
872 (subseq object-keys i (min (+ i query-len) n-object-keys))
874 (results (unless (gethash :target-slot dbi)
875 (find-all (list (gethash :join-class dbi))
876 :where (make-instance 'sql-relational-exp
878 :sub-expressions (list (sql-expression :attribute foreign-key)
883 (dolist (object objects)
884 (when (or force-p (not (slot-boundp object slotdef-name)))
885 (let ((res (if results
886 (remove-if-not #'(lambda (obj)
887 (equal obj (slot-value
896 (when (gethash :target-slot dbi)
897 (fault-join-target-slot class object slotdef))))))
899 (setf (slot-value object slotdef-name)
900 (if (gethash :set dbi) res (car res)))))))))))))
903 (defun fault-join-slot-raw (class object slot-def)
904 (let* ((dbi (view-class-slot-db-info slot-def))
905 (jc (gethash :join-class dbi)))
906 (let ((jq (join-qualifier class object slot-def)))
908 (select jc :where jq :flatp t :result-types nil
909 :database (choose-database-for-instance object))))))
911 (defun fault-join-slot (class object slot-def)
912 (let* ((dbi (view-class-slot-db-info slot-def))
913 (ts (gethash :target-slot dbi)))
914 (if (and ts (gethash :set dbi))
915 (fault-join-target-slot class object slot-def)
916 (let ((res (fault-join-slot-raw class object slot-def)))
919 ((and ts (not (gethash :set dbi)))
920 (mapcar (lambda (obj) (slot-value obj ts)) res))
921 ((and (not ts) (not (gethash :set dbi)))
923 ((and (not ts) (gethash :set dbi))
926 ;;;; Should we not return the whole result, instead of only
927 ;;;; the one slot-value? We get all the values from the db
929 (defun fault-join-normalized-slot (class object slot-def)
930 (labels ((getsc (this-class)
931 (let ((sc (car (class-direct-superclasses this-class))))
935 (let* ((sc (getsc class))
936 (hk (slot-definition-name (car (key-slots class))))
937 (fk (slot-definition-name (car (key-slots sc)))))
938 (let ((jq (sql-operation '==
944 (slotdef-for-slot-with-class fk sc) nil)
945 :table (view-table sc)))
949 (slot-value object hk))
952 ;; Caching nil in next select, because in normalized mode
953 ;; records can be changed through other instances (children,
954 ;; parents) so changes possibly won't be noticed
955 (let ((res (car (select (class-name sc) :where jq
956 :flatp t :result-types nil
958 :database (choose-database-for-instance object))))
959 (slot-name (slot-definition-name slot-def)))
961 ;; If current class is normalized and wanted slot is not
962 ;; a direct member, recurse up
963 (if (and (normalizedp class)
964 (not (member slot-name
965 (mapcar #'(lambda (esd) (slot-definition-name esd))
966 (ordered-class-direct-slots class))))
967 (not (slot-boundp res slot-name)))
968 (fault-join-normalized-slot sc res slot-def)
969 (slot-value res slot-name)))))) )
971 (defun join-qualifier (class object slot-def)
972 (declare (ignore class))
973 (let* ((dbi (view-class-slot-db-info slot-def))
974 (jc (find-class (gethash :join-class dbi)))
975 ;;(ts (gethash :target-slot dbi))
976 ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
977 (foreign-keys (gethash :foreign-key dbi))
978 (home-keys (gethash :home-key dbi)))
979 (when (every #'(lambda (slt)
980 (and (slot-boundp object slt)
981 (not (null (slot-value object slt)))))
982 (if (listp home-keys) home-keys (list home-keys)))
984 (mapcar #'(lambda (hk fk)
985 (let ((fksd (slotdef-for-slot-with-class fk jc)))
991 (database-identifier fksd nil)
992 :table (database-identifier jc nil)))
996 (slot-value object hk))
999 (if (listp home-keys)
1002 (if (listp foreign-keys)
1004 (list foreign-keys)))))
1006 (if (> (length jc) 1)
1007 (apply #'sql-and jc)
1010 ;; FIXME: add retrieval immediate for efficiency
1011 ;; For example, for (select 'employee-address) in test suite =>
1012 ;; select addr.*,ea_join.* FROM addr,ea_join WHERE ea_join.aaddressid=addr.addressid\g
1014 (defun build-objects (vals sclasses immediate-join-classes sels immediate-joins database refresh flatp instances)
1015 "Used by find-all to build objects."
1016 (labels ((build-object (vals vclass jclasses selects immediate-selects instance)
1017 (let* ((db-vals (butlast vals (- (list-length vals)
1018 (list-length selects))))
1019 (obj (if instance instance (make-instance (class-name vclass) :view-database database)))
1020 (join-vals (subseq vals (list-length selects)))
1021 (joins (mapcar #'(lambda (c) (when c (make-instance c :view-database database)))
1024 ;;(format t "joins: ~S~%db-vals: ~S~%join-values: ~S~%selects: ~S~%immediate-selects: ~S~%"
1025 ;;joins db-vals join-vals selects immediate-selects)
1027 ;; use refresh keyword here
1028 (setf obj (get-slot-values-from-view obj (mapcar #'car selects) db-vals))
1029 (mapc #'(lambda (jo)
1030 ;; find all immediate-select slots and join-vals for this object
1031 (let* ((jo-class (class-of jo))
1033 (if (normalizedp jo-class)
1034 (class-direct-slots jo-class)
1035 (class-slots jo-class)))
1036 (pos-list (remove-if #'null
1039 (position s immediate-selects
1043 (get-slot-values-from-view jo
1045 (mapcar #'(lambda (pos)
1046 (nth pos immediate-selects))
1048 (mapcar #'(lambda (pos) (nth pos join-vals))
1054 (class-slots vclass))
1055 (slot (find (class-name (class-of jc)) vslots
1056 :key #'(lambda (slot)
1057 (when (and (eq :join (view-class-slot-db-kind slot))
1058 (eq (slot-definition-name slot)
1059 (gethash :join-class (view-class-slot-db-info slot))))
1060 (slot-definition-name slot))))))
1062 (setf (slot-value obj (slot-definition-name slot)) jc))))
1064 (when refresh (instance-refreshed obj))
1067 (mapcar #'(lambda (sclass jclass sel immediate-join instance)
1069 (build-object vals sclass jclass sel immediate-join instance)
1070 (setf vals (nthcdr (+ (list-length sel) (list-length immediate-join))
1072 sclasses immediate-join-classes sels immediate-joins instances)))
1073 (if (and flatp (= (length sclasses) 1))
1077 (defmethod select-table-sql-expr ((table T))
1078 "Turns an object representing a table into the :from part of the sql expression that will be executed "
1079 (sql-expression :table (view-table table)))
1082 (defun find-all (view-classes
1084 &key all set-operation distinct from where group-by having
1085 order-by offset limit refresh flatp result-types
1087 (database *default-database*)
1088 instances parameters)
1089 "Called by SELECT to generate object query results when the
1090 View Classes VIEW-CLASSES are passed as arguments to SELECT."
1091 (declare (ignore all set-operation group-by having offset limit inner-join on))
1092 (flet ((ref-equal (ref1 ref2)
1093 (string= (sql-output ref1 database)
1094 (sql-output ref2 database))))
1098 (remf args :additional-fields)
1099 (remf args :result-types)
1100 (remf args :instances)
1101 (let* ((*db-deserializing* t)
1102 (sclasses (mapcar #'find-class view-classes))
1103 (immediate-join-slots
1104 (mapcar #'(lambda (c) (generate-retrieval-joins-list c :immediate)) sclasses))
1105 (immediate-join-classes
1106 (mapcar #'(lambda (jcs)
1107 (mapcar #'(lambda (slotdef)
1108 (find-class (gethash :join-class (view-class-slot-db-info slotdef))))
1110 immediate-join-slots))
1111 (immediate-join-sels (mapcar #'generate-immediate-joins-selection-list sclasses))
1112 (sels (mapcar #'generate-selection-list sclasses))
1113 (fullsels (apply #'append (mapcar #'append sels immediate-join-sels)))
1114 (sel-tables (collect-table-refs where))
1115 (tables (remove-if #'null
1117 (append (mapcar #'select-table-sql-expr sclasses)
1118 (mapcan #'(lambda (jc-list)
1120 #'(lambda (jc) (when jc (select-table-sql-expr jc)))
1122 immediate-join-classes)
1124 :test #'database-identifier-equal)))
1125 (order-by-slots (mapcar #'(lambda (ob) (if (atom ob) ob (car ob)))
1126 (listify order-by)))
1129 ;;(format t "sclasses: ~W~%ijc: ~W~%tables: ~W~%" sclasses immediate-join-classes tables)
1131 (dolist (ob order-by-slots)
1132 (when (and ob (not (member ob (mapcar #'cdr fullsels)
1133 :test #'ref-equal)))
1135 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1137 (dolist (ob (listify distinct))
1138 (when (and (typep ob 'sql-ident)
1139 (not (member ob (mapcar #'cdr fullsels)
1140 :test #'ref-equal)))
1142 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1144 (mapcar #'(lambda (vclass jclasses jslots)
1147 #'(lambda (jclass jslot)
1148 (let ((dbi (view-class-slot-db-info jslot)))
1151 (list (sql-operation '==
1153 :attribute (gethash :foreign-key dbi)
1154 :table (view-table jclass))
1156 :attribute (gethash :home-key dbi)
1157 :table (view-table vclass))))
1158 (when join-where (listify join-where))))))
1160 sclasses immediate-join-classes immediate-join-slots)
1161 ;; Reported buggy on clsql-devel
1162 ;; (when where (setq where (listify where)))
1164 ((and where join-where)
1165 (setq where (list (apply #'sql-and where join-where))))
1166 ((and (null where) (> (length join-where) 1))
1167 (setq where (list (apply #'sql-and join-where)))))
1169 (let* ((rows (apply #'select
1170 (append (mapcar #'cdr fullsels)
1172 (list (append (when from (listify from))
1174 (list :result-types result-types)
1176 (list :where where))
1178 (instances-to-add (- (length rows) (length instances)))
1179 (perhaps-extended-instances
1180 (if (plusp instances-to-add)
1181 (append instances (do ((i 0 (1+ i))
1183 ((= i instances-to-add) res)
1184 (push (make-list (length sclasses) :initial-element nil) res)))
1187 #'(lambda (row instance)
1188 (build-objects row sclasses immediate-join-classes sels
1189 immediate-join-sels database refresh flatp
1190 (if (and flatp (atom instance))
1193 rows perhaps-extended-instances)))
1196 (defmethod instance-refreshed ((instance standard-db-object)))
1198 (defvar *default-caching* t
1199 "Controls whether SELECT caches objects by default. The CommonSQL
1200 specification states caching is on by default.")
1202 (defun select (&rest select-all-args)
1203 "Executes a query on DATABASE, which has a default value of
1204 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
1205 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
1206 argument can be used to generate queries in both functional and
1207 object oriented contexts.
1209 In the functional case, the required arguments specify the
1210 columns selected by the query and may be symbolic SQL expressions
1211 or strings representing attribute identifiers. Type modified
1212 identifiers indicate that the values selected from the specified
1213 column are converted to the specified lisp type. The keyword
1214 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
1215 SET-OPERATION and WHERE are used to specify, using the symbolic
1216 SQL syntax, the corresponding components of the SQL query
1217 generated by the call to SELECT. RESULT-TYPES is a list of
1218 symbols which specifies the lisp type for each field returned by
1219 the query. If RESULT-TYPES is nil all results are returned as
1220 strings whereas the default value of :auto means that the lisp
1221 types are automatically computed for each field. FIELD-NAMES is t
1222 by default which means that the second value returned is a list
1223 of strings representing the columns selected by the query. If
1224 FIELD-NAMES is nil, the list of column names is not returned as a
1227 In the object oriented case, the required arguments to SELECT are
1228 symbols denoting View Classes which specify the database tables
1229 to query. In this case, SELECT returns a list of View Class
1230 instances whose slots are set from the attribute values of the
1231 records in the specified table. Slot-value is a legal operator
1232 which can be employed as part of the symbolic SQL syntax used in
1233 the WHERE keyword argument to SELECT. REFRESH is nil by default
1234 which means that the View Class instances returned are retrieved
1235 from a cache if an equivalent call to SELECT has previously been
1236 issued. If REFRESH is true, the View Class instances returned are
1237 updated as necessary from the database and the generic function
1238 INSTANCE-REFRESHED is called to perform any necessary operations
1239 on the updated instances.
1241 In both object oriented and functional contexts, FLATP has a
1242 default value of nil which means that the results are returned as
1243 a list of lists. If FLATP is t and only one result is returned
1244 for each record selected in the query, the results are returned
1245 as elements of a list."
1247 (flet ((select-objects (target-args)
1249 (every #'(lambda (arg)
1251 (find-class arg nil)))
1253 (multiple-value-bind (target-args qualifier-args)
1254 (query-get-selections select-all-args)
1255 (unless (or *default-database* (getf qualifier-args :database))
1256 (signal-no-database-error nil))
1259 ((select-objects target-args)
1260 (let ((caching (getf qualifier-args :caching *default-caching*))
1261 (result-types (getf qualifier-args :result-types :auto))
1262 (refresh (getf qualifier-args :refresh nil))
1263 (database (or (getf qualifier-args :database) *default-database*))
1264 (order-by (getf qualifier-args :order-by)))
1265 (remf qualifier-args :caching)
1266 (remf qualifier-args :refresh)
1267 (remf qualifier-args :result-types)
1269 ;; Add explicity table name to order-by if not specified and only
1270 ;; one selected table. This is required so FIND-ALL won't duplicate
1272 (when (and order-by (= 1 (length target-args)))
1273 (let ((table-name (view-table (find-class (car target-args))))
1274 (order-by-list (copy-seq (listify order-by))))
1275 (labels ((set-table-if-needed (val)
1277 (sql-ident-attribute
1279 (unless (slot-value val 'qualifier)
1280 (setf (slot-value val 'qualifier) table-name))
1282 ;; TODO: Check for a specific error we expect
1284 (cons (set-table-if-needed (car val))))))
1285 (loop for i from 0 below (length order-by-list)
1286 for id = (nth i order-by-list)
1287 do (set-table-if-needed id)))
1288 (setf (getf qualifier-args :order-by) order-by-list)))
1292 (apply #'find-all target-args
1293 (append qualifier-args
1294 (list :result-types result-types :refresh refresh))))
1296 (let ((cached (records-cache-results target-args qualifier-args database)))
1298 ((and cached (not refresh))
1300 ((and cached refresh)
1301 (let ((results (apply #'find-all (append (list target-args) qualifier-args `(:instances ,cached :result-types :auto :refresh ,refresh)))))
1302 (setf (records-cache-results target-args qualifier-args database) results)
1305 (let ((results (apply #'find-all target-args (append qualifier-args
1306 `(:result-types :auto :refresh ,refresh)))))
1307 (setf (records-cache-results target-args qualifier-args database) results)
1310 (let* ((expr (apply #'make-query select-all-args))
1311 (parameters (second (member :parameters select-all-args)))
1313 (mapcar #'(lambda (attrib)
1314 (if (typep attrib 'sql-ident-attribute)
1315 (let ((type (slot-value attrib 'type)))
1320 (slot-value expr 'selections))))
1321 (destructuring-bind (&key (flatp nil)
1322 (result-types :auto)
1324 (database *default-database*)
1328 (setf expr (command-object (sql-output expr database) parameters)))
1329 (query expr :flatp flatp
1331 ;; specifying a type for an attribute overrides result-types
1332 (if (some #'(lambda (x) (not (eq t x))) specified-types)
1335 :field-names field-names
1336 :database database))))))))
1338 (defun compute-records-cache-key (targets qualifiers)
1340 (do ((args *select-arguments* (cdr args))
1342 ((null args) results)
1343 (let* ((arg (car args))
1344 (value (getf qualifiers arg)))
1348 (cons (cons (sql (car value)) (cdr value)))
1349 (%sql-expression (sql value))
1353 (defun records-cache-results (targets qualifiers database)
1354 (when (record-caches database)
1355 (gethash (compute-records-cache-key targets qualifiers) (record-caches database))))
1357 (defun (setf records-cache-results) (results targets qualifiers database)
1358 (unless (record-caches database)
1359 (setf (record-caches database)
1360 (make-hash-table :test 'equal
1361 #+allegro :values #+allegro :weak
1362 #+clisp :weak #+clisp :value
1363 #+lispworks :weak-kind #+lispworks :value)))
1364 (setf (gethash (compute-records-cache-key targets qualifiers)
1365 (record-caches database)) results)
1370 ;;; Serialization functions
1372 (defun write-instance-to-stream (obj stream)
1373 "Writes an instance to a stream where it can be later be read.
1374 NOTE: an error will occur if a slot holds a value which can not be written readably."
1375 (let* ((class (class-of obj))
1377 (dolist (slot (ordered-class-slots (class-of obj)))
1378 (let ((name (slot-definition-name slot)))
1379 (when (and (not (eq 'view-database name))
1380 (slot-boundp obj name))
1381 (push (cons name (slot-value obj name)) alist))))
1382 (setq alist (reverse alist))
1383 (write (cons (class-name class) alist) :stream stream :readably t))
1386 (defun read-instance-from-stream (stream)
1387 (let ((raw (read stream nil nil)))
1389 (let ((obj (make-instance (car raw))))
1390 (dolist (pair (cdr raw))
1391 (setf (slot-value obj (car pair)) (cdr pair)))