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 (defmethod update-slot-with-null ((object standard-db-object) slotdef)
109 (setf (easy-slot-value object slotdef)
110 (slot-value slotdef 'void-value)))
112 (defmethod update-slot-from-db-value ((instance standard-db-object) slotdef value)
113 "This gets a value from the database and turns it itno a lisp value
114 based on the slot's slot-db-reader or baring that read-sql-value"
115 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
116 (let* ((slot-reader (view-class-slot-db-reader slotdef))
117 (slot-type (specified-type slotdef)))
119 ((null value) (update-slot-with-null instance slotdef))
121 (setf (easy-slot-value instance slotdef)
122 (read-sql-value value (delistify slot-type)
123 (choose-database-for-instance instance)
124 (database-underlying-type
125 (choose-database-for-instance instance)))))
126 (t (etypecase slot-reader
127 ((or symbol function)
128 (setf (easy-slot-value instance slotdef)
129 (apply slot-reader (list value))))
131 (setf (easy-slot-value instance slotdef)
132 (format nil slot-reader value))))))))
134 (defmethod key-value-from-db (slotdef value database)
135 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
136 (let ((slot-reader (view-class-slot-db-reader slotdef))
137 (slot-type (specified-type slotdef)))
138 (cond ((and value (null slot-reader))
139 (read-sql-value value (delistify slot-type) database
140 (database-underlying-type database)))
143 ((typep slot-reader 'string)
144 (format nil slot-reader value))
145 ((typep slot-reader '(or symbol function))
146 (apply slot-reader (list value)))
148 (error "Slot reader is of an unusual type.")))))
150 (defun db-value-from-slot (slotdef val database)
151 (let ((dbwriter (view-class-slot-db-writer slotdef))
152 (dbtype (specified-type slotdef)))
154 (string (format nil dbwriter val))
155 ((and (or symbol function) (not null)) (apply dbwriter (list val)))
157 (database-output-sql-as-type
161 val database (database-underlying-type database))))))
163 (defun check-slot-type (slotdef val)
164 (let* ((slot-type (specified-type slotdef))
165 (basetype (if (listp slot-type) (car slot-type) slot-type)))
166 (when (and slot-type val)
167 (unless (typep val basetype)
168 (error 'sql-user-error
170 (format nil "Invalid value ~A in slot ~A, not of type ~A."
171 val (slot-definition-name slotdef) slot-type))))))
173 (defmethod get-slot-values-from-view (obj slotdeflist values)
174 "Used to copy values from the database into the object
175 used by things like find-all and select"
176 (loop for slot in slotdeflist
178 do (update-slot-from-db-value obj slot value))
181 (defclass class-and-slots ()
182 ((view-class :accessor view-class :initarg :view-class :initform nil)
183 (slot-defs :accessor slot-defs :initarg :slot-defs :initform nil))
184 (:documentation "A helper class to keep track of which slot-defs from a
185 table need to be updated, a normalized class might have many of these
186 because each of its parent classes might represent some other table and we
187 need to match which slots came from which parent class/table"))
189 (defun make-class-and-slots (c &optional s)
190 "Create a new class-and-slots object"
191 (make-instance 'class-and-slots :view-class c :slot-defs (listify s) ))
193 (defmethod view-table ((o class-and-slots))
194 "get the view-table of the view-class of o"
195 (view-table (view-class o)))
197 (defmethod attribute-value-pairs ((def class-and-slots) (o standard-db-object)
199 "for a given class-and-slots and object, create the sql-expression & value pairs
200 that need to be sent to the database"
201 (loop for s in (slot-defs def)
202 for n = (to-slot-name s)
203 when (slot-boundp o n)
204 collect (make-attribute-value-pair s (slot-value o n) database)))
206 (defmethod view-classes-and-slots-by-name ((obj standard-db-object) slots-to-match)
207 "If it's normalized, find the class that actually contains
208 the slot that's tied to the db,
210 otherwise just search the current class
212 (let* ((view-class (class-of obj))
213 (normalizedp (normalizedp view-class))
215 (labels ((get-c&s-obj (class)
216 (or (find class rtns :key #'view-class)
217 (first (push (make-class-and-slots class) rtns))))
218 (associate-slot-with-class (class slot)
219 "Find the best class to associate with the slot. If it is
220 normalized then it needs to be a direct slot otherwise it just
221 needs to be on the class."
222 (let ((sd (find-class-slot-by-name class slot normalizedp)))
224 ;;we found it directly or it's (not normalized)
225 (pushnew sd (slot-defs (get-c&s-obj class)))
227 (loop for parent in (class-direct-superclasses class)
228 until (associate-slot-with-class parent slot))))
231 for in-slot in (listify slots-to-match)
232 do (associate-slot-with-class view-class in-slot)))
235 (defun update-auto-increments-keys (class obj database)
236 ;; handle pulling any autoincrement values into the object
237 (let ((pk-slots (keyslots-for-class class))
238 (table (view-table class))
240 (labels ((do-update (slot)
241 (when (and (null (easy-slot-value obj slot))
242 (auto-increment-column-p slot database))
243 (update-slot-from-db-value
247 (database-last-auto-increment-id
248 database table slot))))))
249 (chain-primary-keys (in-class)
250 "This seems kindof wrong, but this is mostly how it was working, so
251 its here to keep the normalized code path working"
252 (when (typep in-class 'standard-db-class)
253 (loop for slot in (keyslots-for-class in-class)
255 (loop for c in (class-direct-superclasses in-class)
256 do (chain-primary-keys c)))))
257 (loop for slot in pk-slots do (do-update slot))
258 (let ((direct-class (to-class obj)))
259 (when (and new-pk-value (normalizedp direct-class))
260 (chain-primary-keys direct-class)))
263 (defmethod %update-instance-helper
264 (class-and-slots obj database
265 &aux (avps (attribute-value-pairs class-and-slots obj database)))
266 ;; we dont actually need to update anything on this particular parent class
267 (unless avps (return-from %update-instance-helper))
269 (let* ((view-class (view-class class-and-slots))
270 (table (view-table view-class))
271 (table-sql (sql-expression :table table)))
273 ;; view database is the flag we use to tell it was pulled from a database
274 ;; and thus probably needs an update instead of an insert
275 (cond ((view-database obj)
276 (let ((where (key-qualifier-for-instance
277 obj :database database :this-class view-class)))
279 (error "update-record-from-*: could not generate a where clause for ~a using ~A"
281 (update-records table-sql
284 :database database)))
285 (T ;; was not pulled from the db so insert it
286 ;; avps MUST contain any primary key slots set
287 ;; by previous inserts of the same object into different
288 ;; tables (ie: normalized stuff)
289 (insert-records :into table-sql
292 (update-auto-increments-keys view-class obj database)
293 ;; we dont set view database here, because there could be
294 ;; N of these for each call to update-record-from-* because
295 ;; of normalized classes
297 (update-slot-default-values obj class-and-slots)))
299 (defmethod update-record-from-slots ((obj standard-db-object) slots
300 &key (database *default-database*))
301 (setf slots (listify slots))
302 (let* ((classes-and-slots (view-classes-and-slots-by-name obj slots))
303 (database (choose-database-for-instance obj database)))
304 (loop for class-and-slots in classes-and-slots
305 do (%update-instance-helper class-and-slots obj database))
306 (setf (slot-value obj 'view-database) database))
309 (defmethod update-record-from-slot
310 ((obj standard-db-object) slot &key (database *default-database*))
311 (update-record-from-slots obj slot :database database))
313 (defun %slot-storedp (slot-def)
314 "Whether or not a slot should be stored in the database based on its db-kind
315 and whether it is bound"
316 (member (view-class-slot-db-kind slot-def) '(:base :key)))
318 (defmethod view-classes-and-storable-slots-for-instance ((obj standard-db-object))
319 "Get a list of all the tables we need to update and the slots on them
321 for non normalized classes we return the class and all its storable slots
323 for normalized classes we return a list of direct slots and the class they
324 came from for each normalized view class
326 (let* ((view-class (class-of obj))
328 (labels ((storable-slots (class)
329 (loop for sd in (slots-for-possibly-normalized-class class)
330 when (%slot-storedp sd)
332 (get-classes-and-slots (class &aux (normalizedp (normalizedp class)))
333 (let ((slots (storable-slots class)))
335 (push (make-class-and-slots class slots) rtns)))
337 (loop for new-class in (class-direct-superclasses class)
338 do (when (typep new-class 'standard-db-class)
339 (get-classes-and-slots new-class))))))
340 (get-classes-and-slots view-class))
343 (defmethod primary-key-slot-values ((obj standard-db-object)
345 (defaulting class (class-of obj)
346 slots (keyslots-for-class class))
347 (loop for slot in slots
348 collect (easy-slot-value obj slot)))
350 (defmethod update-slot-default-values ((obj standard-db-object)
352 "Makes sure that if a class has unfilled slots that claim to have a default,
353 that we retrieve those defaults from the database
355 TODO: use update slots-from-record instead to batch this!"
356 (loop for class-and-slots in (listify classes-and-slots)
357 do (loop for slot in (slot-defs class-and-slots)
358 do (when (and (slot-has-default-p slot)
359 (not (easy-slot-value obj slot)))
360 (update-slot-from-record obj (to-slot-name slot))))))
362 (defmethod update-records-from-instance ((obj standard-db-object)
363 &key (database *default-database*))
364 "Updates the records in the database associated with this object if
365 view-database slot on the object is nil then the object is assumed to be
367 (let ((database (choose-database-for-instance obj database))
368 (classes-and-slots (view-classes-and-storable-slots-for-instance obj)))
369 (loop for class-and-slots in classes-and-slots
370 do (%update-instance-helper class-and-slots obj database))
371 (setf (slot-value obj 'view-database) database)
372 (primary-key-slot-values obj)))
374 (defmethod delete-instance-records ((instance standard-db-object) &key database)
375 (let ((database (choose-database-for-instance instance database))
376 (vt (sql-expression :table (view-table (class-of instance)))))
378 (let ((qualifier (key-qualifier-for-instance instance :database database)))
379 (delete-records :from vt :where qualifier :database database)
380 (setf (record-caches database) nil)
381 (setf (slot-value instance 'view-database) nil)
383 (signal-no-database-error database))))
385 (defmethod update-instance-from-records ((instance standard-db-object)
386 &key (database *default-database*)
388 (let* ((view-class (or this-class (class-of instance)))
389 (pclass (car (class-direct-superclasses view-class)))
391 (when (normalizedp view-class)
392 (setf pres (update-instance-from-records instance :database database
393 :this-class pclass)))
394 (let* ((view-table (sql-expression :table (view-table view-class)))
395 (vd (choose-database-for-instance instance database))
396 (view-qual (key-qualifier-for-instance instance :database vd
397 :this-class view-class))
398 (sels (generate-selection-list view-class))
401 (setf res (apply #'select (append (mapcar #'cdr sels)
402 (list :from view-table
407 (setf (slot-value instance 'view-database) vd)
408 (get-slot-values-from-view instance (mapcar #'car sels) (car res))))
412 (defmethod update-slot-from-record ((instance standard-db-object)
413 slot &key (database *default-database*))
414 (let* ((view-class (find-class (class-name (class-of instance))))
415 (slot-def (slotdef-for-slot-with-class slot view-class)))
416 (when (normalizedp view-class)
417 ;; If it's normalized, find the class that actually contains
418 ;; the slot that's tied to the db
420 (do ((this-class view-class
421 (car (class-direct-superclasses this-class))))
422 ((direct-normalized-slot-p this-class slot)
424 (let* ((view-table (sql-expression :table (view-table view-class)))
425 (vd (choose-database-for-instance instance database))
426 (view-qual (key-qualifier-for-instance instance :database vd
427 :this-class view-class))
428 (att-ref (generate-attribute-reference view-class slot-def))
429 (res (select att-ref :from view-table :where view-qual
432 (setf (slot-value instance 'view-database) vd)
433 (get-slot-values-from-view instance (list slot-def) (car res))))))
436 (defvar +no-slot-value+ '+no-slot-value+)
438 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
439 (let* ((class (find-class classname))
440 (sld (slotdef-for-slot-with-class slot class)))
442 (if (eq value +no-slot-value+)
443 (sql-expression :attribute (database-identifier sld database)
444 :table (view-table class))
449 (error "Unknown slot ~A for class ~A" slot classname))))
451 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
452 (declare (ignore database))
453 (let* ((class (find-class classname)))
454 (unless (view-table class)
455 (error "No view-table for class ~A" classname))
456 (sql-expression :table (view-table class))))
459 (defmethod database-get-type-specifier (type args database db-type)
460 (declare (ignore type args database db-type))
461 (format nil "VARCHAR(~D)" *default-string-length*))
463 (defmethod database-get-type-specifier ((type (eql 'integer)) args database db-type)
464 (declare (ignore database db-type))
466 (format nil "INT(~A)" (car args))
470 "An 8-bit integer, this width may vary by SQL implementation."
473 (defmethod database-get-type-specifier ((type (eql 'tinyint)) args database db-type)
474 (declare (ignore args database db-type))
478 "An integer smaller than a 32-bit integer. this width may vary by SQL implementation."
481 (defmethod database-get-type-specifier ((type (eql 'smallint)) args database db-type)
482 (declare (ignore args database db-type))
485 (deftype mediumint ()
486 "An integer smaller than a 32-bit integer, but may be larger than a smallint. This width may vary by SQL implementation."
489 (defmethod database-get-type-specifier ((type (eql 'mediumint)) args database db-type)
490 (declare (ignore args database db-type))
494 "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
497 (defmethod database-get-type-specifier ((type (eql 'bigint)) args database db-type)
498 (declare (ignore args database db-type))
501 (deftype varchar (&optional size)
502 "A variable length string for the SQL varchar type."
503 (declare (ignore size))
506 (defmethod database-get-type-specifier ((type (eql 'varchar)) args
508 (declare (ignore database db-type))
510 (format nil "VARCHAR(~A)" (car args))
511 (format nil "VARCHAR(~D)" *default-string-length*)))
513 (defmethod database-get-type-specifier ((type (eql 'string)) args database db-type)
514 (declare (ignore database db-type))
516 (format nil "CHAR(~A)" (car args))
517 (format nil "VARCHAR(~D)" *default-string-length*)))
519 (deftype universal-time ()
520 "A positive integer as returned by GET-UNIVERSAL-TIME."
523 (defmethod database-get-type-specifier ((type (eql 'universal-time)) args database db-type)
524 (declare (ignore args database db-type))
527 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database db-type)
528 (declare (ignore args database db-type))
531 (defmethod database-get-type-specifier ((type (eql 'date)) args database db-type)
532 (declare (ignore args database db-type))
535 (defmethod database-get-type-specifier ((type (eql 'duration)) args database db-type)
536 (declare (ignore database args db-type))
539 (defmethod database-get-type-specifier ((type (eql 'money)) args database db-type)
540 (declare (ignore database args db-type))
544 (deftype char (&optional len)
545 "A lisp type for the SQL CHAR type."
548 (defmethod database-get-type-specifier ((type (eql 'float)) args database db-type)
549 (declare (ignore database db-type))
551 (format nil "FLOAT(~A)" (car args))
554 (defmethod database-get-type-specifier ((type (eql 'long-float)) args database db-type)
555 (declare (ignore database db-type))
557 (format nil "FLOAT(~A)" (car args))
560 (deftype generalized-boolean ()
561 "A type which outputs a SQL boolean value, though any lisp type can be stored in the slot."
564 (defmethod database-get-type-specifier ((type (eql 'boolean)) args database db-type)
565 (declare (ignore args database db-type))
568 (defmethod database-get-type-specifier ((type (eql 'generalized-boolean)) args database db-type)
569 (declare (ignore args database db-type))
572 (defmethod database-get-type-specifier ((type (eql 'number)) args database db-type)
573 (declare (ignore database db-type))
575 ((and (consp args) (= (length args) 2))
576 (format nil "NUMBER(~D,~D)" (first args) (second args)))
577 ((and (consp args) (= (length args) 1))
578 (format nil "NUMBER(~D)" (first args)))
582 (defmethod database-get-type-specifier ((type (eql 'char)) args database db-type)
583 (declare (ignore database db-type))
585 (format nil "CHAR(~D)" (first args))
589 (defmethod database-output-sql-as-type (type val database db-type)
590 (declare (ignore type database db-type))
593 (defmethod database-output-sql-as-type ((type (eql 'list)) val database db-type)
594 (declare (ignore database db-type))
595 (progv '(*print-circle* *print-array*) '(t t)
596 (let ((escaped (prin1-to-string val)))
597 (substitute-char-string
598 escaped #\Null " "))))
600 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database db-type)
601 (declare (ignore database db-type))
604 (package-name (symbol-package val))
609 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database db-type)
610 (declare (ignore database db-type))
615 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database db-type)
616 (declare (ignore database db-type))
617 (progv '(*print-circle* *print-array*) '(t t)
618 (prin1-to-string val)))
620 (defmethod database-output-sql-as-type ((type (eql 'array)) val database db-type)
621 (declare (ignore database db-type))
622 (progv '(*print-circle* *print-array*) '(t t)
623 (prin1-to-string val)))
625 (defmethod database-output-sql-as-type ((type (eql 'boolean)) val database db-type)
626 (declare (ignore database db-type))
629 (defmethod database-output-sql-as-type ((type (eql 'generalized-boolean)) val database db-type)
630 (declare (ignore database db-type))
633 (defmethod database-output-sql-as-type ((type (eql 'string)) val database db-type)
634 (declare (ignore database db-type))
637 (defmethod database-output-sql-as-type ((type (eql 'char)) val database db-type)
638 (declare (ignore database db-type))
640 (character (write-to-string val))
643 (defmethod database-output-sql-as-type ((type (eql 'float)) val database db-type)
644 (declare (ignore database db-type))
645 (if (eq (type-of val) 'null)
647 (let ((*read-default-float-format* (type-of val)))
648 (format nil "~F" val))))
650 (defmethod read-sql-value (val type database db-type)
651 (declare (ignore database db-type))
653 ((null type) val) ;;we have no desired type, just give the value
654 ((typep val type) val) ;;check that it hasn't already been converted.
655 ((typep val 'string) (read-from-string val)) ;;maybe read will just take care of it?
656 (T (error "Unable to read-sql-value ~a as type ~a" val type))))
658 (defmethod read-sql-value (val (type (eql 'string)) database db-type)
659 (declare (ignore database db-type))
662 (defmethod read-sql-value (val (type (eql 'varchar)) database db-type)
663 (declare (ignore database db-type))
666 (defmethod read-sql-value (val (type (eql 'char)) database db-type)
667 (declare (ignore database db-type))
670 (defmethod read-sql-value (val (type (eql 'keyword)) database db-type)
671 (declare (ignore database db-type))
672 (when (< 0 (length val))
673 (intern (symbol-name-default-case val)
674 (find-package '#:keyword))))
676 (defmethod read-sql-value (val (type (eql 'symbol)) database db-type)
677 (declare (ignore database db-type))
678 (when (< 0 (length val))
679 (unless (string= val (symbol-name-default-case "NIL"))
680 (read-from-string val))))
682 (defmethod read-sql-value (val (type (eql 'integer)) database db-type)
683 (declare (ignore database db-type))
686 (unless (string-equal "NIL" val)
687 (parse-integer val)))
690 (defmethod read-sql-value (val (type (eql 'smallint)) database db-type)
691 (declare (ignore database db-type))
694 (unless (string-equal "NIL" val)
695 (parse-integer val)))
698 (defmethod read-sql-value (val (type (eql 'bigint)) database db-type)
699 (declare (ignore database db-type))
702 (unless (string-equal "NIL" val)
703 (parse-integer val)))
706 (defmethod read-sql-value (val (type (eql 'float)) database db-type)
707 (declare (ignore database db-type))
708 ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
710 (string (float (read-from-string val)))
713 (defmethod read-sql-value (val (type (eql 'double-float)) database db-type)
714 (declare (ignore database db-type))
715 ;; writing 1.0 writes 1, so if we *really* want a float, must do (float ...)
718 (let ((*read-default-float-format* 'double-float))
719 (read-from-string val))
722 (float (coerce val 'double-float))))
724 (defmethod read-sql-value (val (type (eql 'boolean)) database db-type)
725 (declare (ignore database db-type))
728 (defmethod read-sql-value (val (type (eql 'generalized-boolean)) database db-type)
729 (declare (ignore database db-type))
732 (defmethod read-sql-value (val (type (eql 'number)) database db-type)
733 (declare (ignore database db-type))
736 (unless (string-equal "NIL" val)
737 (read-from-string val)))
740 (defmethod read-sql-value (val (type (eql 'universal-time)) database db-type)
741 (declare (ignore database db-type))
742 (unless (eq 'NULL val)
748 (defmethod read-sql-value (val (type (eql 'wall-time)) database db-type)
749 (declare (ignore database db-type))
750 (unless (eq 'NULL val)
751 (parse-timestring val)))
753 (defmethod read-sql-value (val (type (eql 'date)) database db-type)
754 (declare (ignore database db-type))
755 (unless (eq 'NULL val)
756 (parse-datestring val)))
758 (defmethod read-sql-value (val (type (eql 'duration)) database db-type)
759 (declare (ignore database db-type))
760 (unless (or (eq 'NULL val)
762 (parse-timestring val)))
764 ;; ------------------------------------------------------------
765 ;; Logic for 'faulting in' :join slots
767 ;; this works, but is inefficient requiring (+ 1 n-rows)
770 (defun fault-join-target-slot (class object slot-def)
771 (let* ((res (fault-join-slot-raw class object slot-def))
772 (dbi (view-class-slot-db-info slot-def))
773 (target-name (gethash :target-slot dbi))
774 (target-class (find-class target-name)))
776 (mapcar (lambda (obj)
782 (find target-name (class-slots (class-of obj))
783 :key #'slot-definition-name)))
786 #+ignore ;; this doesn't work when attempting to call slot-value
787 (mapcar (lambda (obj)
788 (cons obj (slot-value obj ts))) res))))
790 (defun fault-join-target-slot (class object slot-def)
791 (let* ((dbi (view-class-slot-db-info slot-def))
792 (ts (gethash :target-slot dbi))
793 (jc (gethash :join-class dbi))
794 (jc-view-table (view-table (find-class jc)))
795 (tdbi (view-class-slot-db-info
796 (find ts (class-slots (find-class jc))
797 :key #'slot-definition-name)))
798 (retrieval (gethash :retrieval tdbi))
799 (tsc (gethash :join-class tdbi))
800 (ts-view-table (view-table (find-class tsc)))
801 (jq (join-qualifier class object slot-def))
802 (key (slot-value object (gethash :home-key dbi))))
809 :inner-join (sql-expression :table jc-view-table)
813 :attribute (gethash :foreign-key tdbi)
814 :table ts-view-table)
816 :attribute (gethash :home-key tdbi)
817 :table jc-view-table))
820 :database (choose-database-for-instance object))))
821 (mapcar #'(lambda (i)
822 (let* ((instance (car i))
823 (jcc (make-instance jc :view-database (choose-database-for-instance instance))))
824 (setf (slot-value jcc (gethash :foreign-key dbi))
826 (setf (slot-value jcc (gethash :home-key tdbi))
827 (slot-value instance (gethash :foreign-key tdbi)))
828 (list instance jcc)))
831 ;; just fill in minimal slots
834 (let ((instance (make-instance tsc :view-database (choose-database-for-instance object)))
835 (jcc (make-instance jc :view-database (choose-database-for-instance object)))
837 (setf (slot-value instance (gethash :home-key tdbi)) fk)
838 (setf (slot-value jcc (gethash :foreign-key dbi))
840 (setf (slot-value jcc (gethash :home-key tdbi))
842 (list instance jcc)))
843 (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
844 :from (sql-expression :table jc-view-table)
846 :database (choose-database-for-instance object))))))))
851 (defvar *default-update-objects-max-len* nil
852 "The default value to use for the MAX-LEN keyword argument to
853 UPDATE-OBJECT-JOINS.")
855 (defun update-objects-joins (objects &key (slots t) (force-p t)
857 *default-update-objects-max-len*))
858 "Updates from the records of the appropriate database tables
859 the join slots specified by SLOTS in the supplied list of View
860 Class instances OBJECTS. SLOTS is t by default which means that
861 all join slots with :retrieval :immediate are updated. CLASS-NAME
862 is used to specify the View Class of all instance in OBJECTS and
863 default to nil which means that the class of the first instance
864 in OBJECTS is used. FORCE-P is t by default which means that all
865 join slots are updated whereas a value of nil means that only
866 unbound join slots are updated. MAX-LEN defaults to
867 *DEFAULT-UPDATE-OBJECTS-MAX-LEN* and when non-nil specifies that
868 UPDATE-OBJECT-JOINS may issue multiple database queries with a
869 maximum of MAX-LEN instances updated in each query."
870 (assert (or (null max-len) (plusp max-len)))
873 (setq class-name (class-name (class-of (first objects)))))
874 (let* ((class (find-class class-name))
875 (class-slots (ordered-class-slots class))
878 (generate-retrieval-joins-list class :deferred)
880 (mapcar #'(lambda (name)
881 (let ((slotdef (find name class-slots :key #'slot-definition-name)))
883 (warn "Unable to find slot named ~S in class ~S." name class))
886 (dolist (slotdef slotdefs)
887 (let* ((dbi (view-class-slot-db-info slotdef))
888 (slotdef-name (slot-definition-name slotdef))
889 (foreign-key (gethash :foreign-key dbi))
890 (home-key (gethash :home-key dbi))
894 (mapcar #'(lambda (o) (slot-value o home-key)) objects)
897 #'(lambda (o) (if (slot-boundp o slotdef-name)
899 (slot-value o home-key)))
901 (n-object-keys (length object-keys))
902 (query-len (or max-len n-object-keys)))
904 (do ((i 0 (+ i query-len)))
905 ((>= i n-object-keys))
906 (let* ((keys (if max-len
907 (subseq object-keys i (min (+ i query-len) n-object-keys))
909 (results (unless (gethash :target-slot dbi)
910 (find-all (list (gethash :join-class dbi))
911 :where (make-instance 'sql-relational-exp
913 :sub-expressions (list (sql-expression :attribute foreign-key)
918 (dolist (object objects)
919 (when (or force-p (not (slot-boundp object slotdef-name)))
920 (let ((res (if results
921 (remove-if-not #'(lambda (obj)
922 (equal obj (slot-value
931 (when (gethash :target-slot dbi)
932 (fault-join-target-slot class object slotdef))))))
934 (setf (slot-value object slotdef-name)
935 (if (gethash :set dbi) res (car res)))))))))))))
938 (defun fault-join-slot-raw (class object slot-def)
939 (let* ((dbi (view-class-slot-db-info slot-def))
940 (jc (gethash :join-class dbi)))
941 (let ((jq (join-qualifier class object slot-def)))
943 (select jc :where jq :flatp t :result-types nil
944 :database (choose-database-for-instance object))))))
946 (defun fault-join-slot (class object slot-def)
947 (let* ((dbi (view-class-slot-db-info slot-def))
948 (ts (gethash :target-slot dbi)))
949 (if (and ts (gethash :set dbi))
950 (fault-join-target-slot class object slot-def)
951 (let ((res (fault-join-slot-raw class object slot-def)))
954 ((and ts (not (gethash :set dbi)))
955 (mapcar (lambda (obj) (slot-value obj ts)) res))
956 ((and (not ts) (not (gethash :set dbi)))
958 ((and (not ts) (gethash :set dbi))
961 ;;;; Should we not return the whole result, instead of only
962 ;;;; the one slot-value? We get all the values from the db
964 (defun fault-join-normalized-slot (class object slot-def)
965 (labels ((getsc (this-class)
966 (let ((sc (car (class-direct-superclasses this-class))))
970 (let* ((sc (getsc class))
971 (hk (slot-definition-name (car (key-slots class))))
972 (fk (slot-definition-name (car (key-slots sc)))))
973 (let ((jq (sql-operation '==
979 (slotdef-for-slot-with-class fk sc) nil)
980 :table (view-table sc)))
984 (slot-value object hk))
987 ;; Caching nil in next select, because in normalized mode
988 ;; records can be changed through other instances (children,
989 ;; parents) so changes possibly won't be noticed
990 (let ((res (car (select (class-name sc) :where jq
991 :flatp t :result-types nil
993 :database (choose-database-for-instance object))))
994 (slot-name (slot-definition-name slot-def)))
996 ;; If current class is normalized and wanted slot is not
997 ;; a direct member, recurse up
998 (if (and (normalizedp class)
999 (not (member slot-name
1000 (mapcar #'(lambda (esd) (slot-definition-name esd))
1001 (ordered-class-direct-slots class))))
1002 (not (slot-boundp res slot-name)))
1003 (fault-join-normalized-slot sc res slot-def)
1004 (slot-value res slot-name)))))) )
1006 (defun join-qualifier (class object slot-def)
1007 (declare (ignore class))
1008 (let* ((dbi (view-class-slot-db-info slot-def))
1009 (jc (find-class (gethash :join-class dbi)))
1010 ;;(ts (gethash :target-slot dbi))
1011 ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
1012 (foreign-keys (gethash :foreign-key dbi))
1013 (home-keys (gethash :home-key dbi)))
1014 (when (every #'(lambda (slt)
1015 (and (slot-boundp object slt)
1016 (not (null (slot-value object slt)))))
1017 (if (listp home-keys) home-keys (list home-keys)))
1019 (mapcar #'(lambda (hk fk)
1020 (let ((fksd (slotdef-for-slot-with-class fk jc)))
1026 (database-identifier fksd nil)
1027 :table (database-identifier jc nil)))
1031 (slot-value object hk))
1034 (if (listp home-keys)
1037 (if (listp foreign-keys)
1039 (list foreign-keys)))))
1041 (if (> (length jc) 1)
1042 (apply #'sql-and jc)
1045 ;; FIXME: add retrieval immediate for efficiency
1046 ;; For example, for (select 'employee-address) in test suite =>
1047 ;; select addr.*,ea_join.* FROM addr,ea_join WHERE ea_join.aaddressid=addr.addressid\g
1049 (defun build-objects (vals sclasses immediate-join-classes sels immediate-joins database refresh flatp instances)
1050 "Used by find-all to build objects."
1051 (labels ((build-object (vals vclass jclasses selects immediate-selects instance)
1052 (let* ((db-vals (butlast vals (- (list-length vals)
1053 (list-length selects))))
1054 (obj (if instance instance (make-instance (class-name vclass) :view-database database)))
1055 (join-vals (subseq vals (list-length selects)))
1056 (joins (mapcar #'(lambda (c) (when c (make-instance c :view-database database)))
1059 ;;(format t "joins: ~S~%db-vals: ~S~%join-values: ~S~%selects: ~S~%immediate-selects: ~S~%"
1060 ;;joins db-vals join-vals selects immediate-selects)
1062 ;; use refresh keyword here
1063 (setf obj (get-slot-values-from-view obj (mapcar #'car selects) db-vals))
1064 (mapc #'(lambda (jo)
1065 ;; find all immediate-select slots and join-vals for this object
1066 (let* ((jo-class (class-of jo))
1067 (slots (slots-for-possibly-normalized-class jo-class))
1068 (pos-list (remove-if #'null
1071 (position s immediate-selects
1075 (get-slot-values-from-view jo
1077 (mapcar #'(lambda (pos)
1078 (nth pos immediate-selects))
1080 (mapcar #'(lambda (pos) (nth pos join-vals))
1086 (class-slots vclass))
1087 (slot (find (class-name (class-of jc)) vslots
1088 :key #'(lambda (slot)
1089 (when (and (eq :join (view-class-slot-db-kind slot))
1090 (eq (slot-definition-name slot)
1091 (gethash :join-class (view-class-slot-db-info slot))))
1092 (slot-definition-name slot))))))
1094 (setf (slot-value obj (slot-definition-name slot)) jc))))
1096 (when refresh (instance-refreshed obj))
1099 (mapcar #'(lambda (sclass jclass sel immediate-join instance)
1101 (build-object vals sclass jclass sel immediate-join instance)
1102 (setf vals (nthcdr (+ (list-length sel) (list-length immediate-join))
1104 sclasses immediate-join-classes sels immediate-joins instances)))
1105 (if (and flatp (= (length sclasses) 1))
1109 (defmethod select-table-sql-expr ((table T))
1110 "Turns an object representing a table into the :from part of the sql expression that will be executed "
1111 (sql-expression :table (view-table table)))
1114 (defun find-all (view-classes
1116 &key all set-operation distinct from where group-by having
1117 order-by offset limit refresh flatp result-types
1119 (database *default-database*)
1120 instances parameters)
1121 "Called by SELECT to generate object query results when the
1122 View Classes VIEW-CLASSES are passed as arguments to SELECT."
1123 (declare (ignore all set-operation group-by having offset limit inner-join on parameters)
1124 (dynamic-extent args))
1125 (flet ((ref-equal (ref1 ref2)
1126 (string= (sql-output ref1 database)
1127 (sql-output ref2 database))))
1128 (declare (dynamic-extent (function ref-equal)))
1129 (let ((args (filter-plist args :from :where :flatp :additional-fields :result-types :instances)))
1130 (let* ((*db-deserializing* t)
1131 (sclasses (mapcar #'find-class view-classes))
1132 (immediate-join-slots
1133 (mapcar #'(lambda (c) (generate-retrieval-joins-list c :immediate)) sclasses))
1134 (immediate-join-classes
1135 (mapcar #'(lambda (jcs)
1136 (mapcar #'(lambda (slotdef)
1137 (find-class (gethash :join-class (view-class-slot-db-info slotdef))))
1139 immediate-join-slots))
1140 (immediate-join-sels (mapcar #'generate-immediate-joins-selection-list sclasses))
1141 (sels (mapcar #'generate-selection-list sclasses))
1142 (fullsels (apply #'append (mapcar #'append sels immediate-join-sels)))
1143 (sel-tables (collect-table-refs where))
1144 (tables (remove-if #'null
1146 (append (mapcar #'select-table-sql-expr sclasses)
1147 (mapcan #'(lambda (jc-list)
1149 #'(lambda (jc) (when jc (select-table-sql-expr jc)))
1151 immediate-join-classes)
1153 :test #'database-identifier-equal)))
1154 (order-by-slots (mapcar #'(lambda (ob) (if (atom ob) ob (car ob)))
1155 (listify order-by)))
1158 ;;(format t "sclasses: ~W~%ijc: ~W~%tables: ~W~%" sclasses immediate-join-classes tables)
1160 (dolist (ob order-by-slots)
1161 (when (and ob (not (member ob (mapcar #'cdr fullsels)
1162 :test #'ref-equal)))
1164 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1166 (dolist (ob (listify distinct))
1167 (when (and (typep ob 'sql-ident)
1168 (not (member ob (mapcar #'cdr fullsels)
1169 :test #'ref-equal)))
1171 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1173 (mapcar #'(lambda (vclass jclasses jslots)
1176 #'(lambda (jclass jslot)
1177 (let ((dbi (view-class-slot-db-info jslot)))
1180 (list (sql-operation '==
1182 :attribute (gethash :foreign-key dbi)
1183 :table (view-table jclass))
1185 :attribute (gethash :home-key dbi)
1186 :table (view-table vclass))))
1187 (when join-where (listify join-where))))))
1189 sclasses immediate-join-classes immediate-join-slots)
1190 ;; Reported buggy on clsql-devel
1191 ;; (when where (setq where (listify where)))
1193 ((and where join-where)
1194 (setq where (list (apply #'sql-and where join-where))))
1195 ((and (null where) (> (length join-where) 1))
1196 (setq where (list (apply #'sql-and join-where)))))
1198 (let* ((rows (apply #'select
1199 (append (mapcar #'cdr fullsels)
1201 (list (append (when from (listify from))
1203 (list :result-types result-types)
1205 (list :where where))
1207 (instances-to-add (- (length rows) (length instances)))
1208 (perhaps-extended-instances
1209 (if (plusp instances-to-add)
1210 (append instances (do ((i 0 (1+ i))
1212 ((= i instances-to-add) res)
1213 (push (make-list (length sclasses) :initial-element nil) res)))
1216 #'(lambda (row instance)
1217 (build-objects row sclasses immediate-join-classes sels
1218 immediate-join-sels database refresh flatp
1219 (if (and flatp (atom instance))
1222 rows perhaps-extended-instances)))
1225 (defmethod instance-refreshed ((instance standard-db-object)))
1227 (defvar *default-caching* t
1228 "Controls whether SELECT caches objects by default. The CommonSQL
1229 specification states caching is on by default.")
1231 (defun select (&rest select-all-args)
1232 "Executes a query on DATABASE, which has a default value of
1233 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
1234 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
1235 argument can be used to generate queries in both functional and
1236 object oriented contexts.
1238 In the functional case, the required arguments specify the
1239 columns selected by the query and may be symbolic SQL expressions
1240 or strings representing attribute identifiers. Type modified
1241 identifiers indicate that the values selected from the specified
1242 column are converted to the specified lisp type. The keyword
1243 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
1244 SET-OPERATION and WHERE are used to specify, using the symbolic
1245 SQL syntax, the corresponding components of the SQL query
1246 generated by the call to SELECT. RESULT-TYPES is a list of
1247 symbols which specifies the lisp type for each field returned by
1248 the query. If RESULT-TYPES is nil all results are returned as
1249 strings whereas the default value of :auto means that the lisp
1250 types are automatically computed for each field. FIELD-NAMES is t
1251 by default which means that the second value returned is a list
1252 of strings representing the columns selected by the query. If
1253 FIELD-NAMES is nil, the list of column names is not returned as a
1256 In the object oriented case, the required arguments to SELECT are
1257 symbols denoting View Classes which specify the database tables
1258 to query. In this case, SELECT returns a list of View Class
1259 instances whose slots are set from the attribute values of the
1260 records in the specified table. Slot-value is a legal operator
1261 which can be employed as part of the symbolic SQL syntax used in
1262 the WHERE keyword argument to SELECT. REFRESH is nil by default
1263 which means that the View Class instances returned are retrieved
1264 from a cache if an equivalent call to SELECT has previously been
1265 issued. If REFRESH is true, the View Class instances returned are
1266 updated as necessary from the database and the generic function
1267 INSTANCE-REFRESHED is called to perform any necessary operations
1268 on the updated instances.
1270 In both object oriented and functional contexts, FLATP has a
1271 default value of nil which means that the results are returned as
1272 a list of lists. If FLATP is t and only one result is returned
1273 for each record selected in the query, the results are returned
1274 as elements of a list."
1275 (multiple-value-bind (target-args qualifier-args)
1276 (query-get-selections select-all-args)
1277 (unless (or *default-database* (getf qualifier-args :database))
1278 (signal-no-database-error nil))
1280 (let ((caching (getf qualifier-args :caching *default-caching*))
1281 (result-types (getf qualifier-args :result-types :auto))
1282 (refresh (getf qualifier-args :refresh nil))
1283 (database (getf qualifier-args :database *default-database*)))
1287 (every #'(lambda (arg)
1289 (find-class arg nil)))
1292 (setf qualifier-args (filter-plist qualifier-args :caching :refresh :result-types))
1294 ;; Add explicity table name to order-by if not specified and only
1295 ;; one selected table. This is required so FIND-ALL won't duplicate
1297 (let ((order-by (getf qualifier-args :order-by)))
1298 (when (and order-by (= 1 (length target-args)))
1299 (let ((table-name (view-table (find-class (car target-args))))
1300 (order-by-list (copy-seq (listify order-by))))
1301 (labels ((sv (val name) (ignore-errors (slot-value val name)))
1302 (set-table-if-needed (val)
1304 (sql-ident-attribute
1306 (if (sv val 'qualifier)
1308 (make-instance 'sql-ident-attribute
1309 :name (sv val 'name)
1310 :qualifier table-name))
1312 ;; TODO: Check for a specific error we expect
1314 (cons (cons (set-table-if-needed (car val))
1318 (loop for i from 0 below (length order-by-list)
1319 for id in order-by-list
1320 collect (set-table-if-needed id))))
1321 (setf (getf qualifier-args :order-by) order-by-list))))
1325 (apply #'find-all target-args :result-types result-types :refresh refresh qualifier-args))
1327 (let ((cached (records-cache-results target-args qualifier-args database)))
1328 (if (and cached (not refresh))
1330 (let ((results (apply #'find-all target-args
1331 :result-types :auto :refresh refresh
1334 (setf (records-cache-results target-args qualifier-args database) results)
1338 (let* ((expr (apply #'make-query select-all-args))
1339 (parameters (second (member :parameters select-all-args)))
1341 (mapcar #'(lambda (attrib)
1342 (if (typep attrib 'sql-ident-attribute)
1343 (let ((type (slot-value attrib 'type)))
1348 (slot-value expr 'selections)))
1349 (flatp (getf qualifier-args :flatp))
1350 (field-names (getf qualifier-args :field-names t)))
1353 (setf expr (command-object (sql-output expr database) parameters)))
1354 (query expr :flatp flatp
1356 ;; specifying a type for an attribute overrides result-types
1357 (if (some #'(lambda (x) (not (eq t x))) specified-types)
1360 :field-names field-names
1361 :database database)))))))
1363 (defun compute-records-cache-key (targets qualifiers)
1365 (do ((args *select-arguments* (cdr args))
1367 ((null args) results)
1368 (let* ((arg (car args))
1369 (value (getf qualifiers arg)))
1373 (cons (cons (sql (car value)) (cdr value)))
1374 (%sql-expression (sql value))
1378 (defun records-cache-results (targets qualifiers database)
1379 (when (record-caches database)
1380 (gethash (compute-records-cache-key targets qualifiers) (record-caches database))))
1382 (defun (setf records-cache-results) (results targets qualifiers database)
1383 (unless (record-caches database)
1384 (setf (record-caches database)
1385 (make-weak-hash-table :test 'equal)))
1386 (setf (gethash (compute-records-cache-key (copy-list targets) qualifiers)
1387 (record-caches database)) results)
1392 ;;; Serialization functions
1394 (defun write-instance-to-stream (obj stream)
1395 "Writes an instance to a stream where it can be later be read.
1396 NOTE: an error will occur if a slot holds a value which can not be written readably."
1397 (let* ((class (class-of obj))
1399 (dolist (slot (ordered-class-slots (class-of obj)))
1400 (let ((name (slot-definition-name slot)))
1401 (when (and (not (eq 'view-database name))
1402 (slot-boundp obj name))
1403 (push (cons name (slot-value obj name)) alist))))
1404 (setq alist (reverse alist))
1405 (write (cons (class-name class) alist) :stream stream :readably t))
1408 (defun read-instance-from-stream (stream)
1409 (let ((raw (read stream nil nil)))
1411 (let ((obj (make-instance (car raw))))
1412 (dolist (pair (cdr raw))
1413 (setf (slot-value obj (car pair)) (cdr pair)))