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-slot-by-name class slot normalizedp nil)))
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))
315 (defmethod view-classes-and-storable-slots-for-instance ((obj standard-db-object))
316 "Get a list of all the tables we need to update and the slots on them
318 for non normalized classes we return the class and all its storable slots
320 for normalized classes we return a list of direct slots and the class they
321 came from for each normalized view class
323 (let* ((view-class (class-of obj))
325 (labels ((storable-slots (class)
326 (loop for sd in (slots-for-possibly-normalized-class class)
327 when (key-or-base-slot-p sd)
329 (get-classes-and-slots (class &aux (normalizedp (normalizedp class)))
330 (let ((slots (storable-slots class)))
332 (push (make-class-and-slots class slots) rtns)))
334 (loop for new-class in (class-direct-superclasses class)
335 do (when (typep new-class 'standard-db-class)
336 (get-classes-and-slots new-class))))))
337 (get-classes-and-slots view-class))
340 (defmethod primary-key-slot-values ((obj standard-db-object)
342 (defaulting class (class-of obj)
343 slots (keyslots-for-class class))
344 (loop for slot in slots
345 collect (easy-slot-value obj slot)))
347 (defmethod update-slot-default-values ((obj standard-db-object)
349 "Makes sure that if a class has unfilled slots that claim to have a default,
350 that we retrieve those defaults from the database
352 TODO: use update slots-from-record instead to batch this!"
353 (loop for class-and-slots in (listify classes-and-slots)
354 do (loop for slot in (slot-defs class-and-slots)
355 do (when (and (slot-has-default-p slot)
356 (not (easy-slot-value obj slot)))
357 (update-slot-from-record obj (to-slot-name slot))))))
359 (defmethod update-records-from-instance ((obj standard-db-object)
360 &key (database *default-database*))
361 "Updates the records in the database associated with this object if
362 view-database slot on the object is nil then the object is assumed to be
364 (let ((database (choose-database-for-instance obj database))
365 (classes-and-slots (view-classes-and-storable-slots-for-instance obj)))
366 (loop for class-and-slots in classes-and-slots
367 do (%update-instance-helper class-and-slots obj database))
368 (setf (slot-value obj 'view-database) database)
369 (primary-key-slot-values obj)))
371 (defmethod delete-instance-records ((instance standard-db-object) &key database)
372 (let ((database (choose-database-for-instance instance database))
373 (vt (sql-expression :table (view-table (class-of instance)))))
375 (let ((qualifier (key-qualifier-for-instance instance :database database)))
376 (delete-records :from vt :where qualifier :database database)
377 (setf (record-caches database) nil)
378 (setf (slot-value instance 'view-database) nil)
380 (signal-no-database-error database))))
382 (defmethod update-instance-from-records ((instance standard-db-object)
383 &key (database *default-database*)
385 (let* ((view-class (or this-class (class-of instance)))
386 (pclass (car (class-direct-superclasses view-class)))
388 (when (normalizedp view-class)
389 (setf pres (update-instance-from-records instance :database database
390 :this-class pclass)))
391 (let* ((view-table (sql-expression :table (view-table view-class)))
392 (vd (choose-database-for-instance instance database))
393 (view-qual (key-qualifier-for-instance instance :database vd
394 :this-class view-class))
395 (sels (generate-selection-list view-class))
398 (setf res (apply #'select (append (mapcar #'cdr sels)
399 (list :from view-table
404 (setf (slot-value instance 'view-database) vd)
405 (get-slot-values-from-view instance (mapcar #'car sels) (car res))))
409 (defmethod update-slot-from-record ((instance standard-db-object)
410 slot &key (database *default-database*))
411 (let* ((view-class (find-class (class-name (class-of instance))))
412 (slot-def (slotdef-for-slot-with-class slot view-class)))
413 (when (normalizedp view-class)
414 ;; If it's normalized, find the class that actually contains
415 ;; the slot that's tied to the db
417 (do ((this-class view-class
418 (car (class-direct-superclasses this-class))))
419 ((direct-normalized-slot-p this-class slot)
421 (let* ((view-table (sql-expression :table (view-table view-class)))
422 (vd (choose-database-for-instance instance database))
423 (view-qual (key-qualifier-for-instance instance :database vd
424 :this-class view-class))
425 (att-ref (generate-attribute-reference view-class slot-def))
426 (res (select att-ref :from view-table :where view-qual
429 (setf (slot-value instance 'view-database) vd)
430 (get-slot-values-from-view instance (list slot-def) (car res))))))
433 (defvar +no-slot-value+ '+no-slot-value+)
435 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
436 (let* ((class (find-class classname))
437 (sld (slotdef-for-slot-with-class slot class)))
439 (if (eq value +no-slot-value+)
440 (sql-expression :attribute (database-identifier sld database)
441 :table (view-table class))
446 (error "Unknown slot ~A for class ~A" slot classname))))
448 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
449 (declare (ignore database))
450 (let* ((class (find-class classname)))
451 (unless (view-table class)
452 (error "No view-table for class ~A" classname))
453 (sql-expression :table (view-table class))))
456 (defmethod database-get-type-specifier (type args database db-type)
457 (declare (ignore type args database db-type))
458 (format nil "VARCHAR(~D)" *default-string-length*))
460 (defmethod database-get-type-specifier ((type (eql 'integer)) args database db-type)
461 (declare (ignore database db-type))
463 (format nil "INT(~A)" (car args))
467 "An 8-bit integer, this width may vary by SQL implementation."
470 (defmethod database-get-type-specifier ((type (eql 'tinyint)) args database db-type)
471 (declare (ignore args database db-type))
475 "An integer smaller than a 32-bit integer. this width may vary by SQL implementation."
478 (defmethod database-get-type-specifier ((type (eql 'smallint)) args database db-type)
479 (declare (ignore args database db-type))
482 (deftype mediumint ()
483 "An integer smaller than a 32-bit integer, but may be larger than a smallint. This width may vary by SQL implementation."
486 (defmethod database-get-type-specifier ((type (eql 'mediumint)) args database db-type)
487 (declare (ignore args database db-type))
491 "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
494 (defmethod database-get-type-specifier ((type (eql 'bigint)) args database db-type)
495 (declare (ignore args database db-type))
498 (deftype varchar (&optional size)
499 "A variable length string for the SQL varchar type."
500 (declare (ignore size))
503 (defmethod database-get-type-specifier ((type (eql 'varchar)) args
505 (declare (ignore database db-type))
507 (format nil "VARCHAR(~A)" (car args))
508 (format nil "VARCHAR(~D)" *default-string-length*)))
510 (defmethod database-get-type-specifier ((type (eql 'string)) args database db-type)
511 (declare (ignore database db-type))
513 (format nil "CHAR(~A)" (car args))
514 (format nil "VARCHAR(~D)" *default-string-length*)))
516 (deftype universal-time ()
517 "A positive integer as returned by GET-UNIVERSAL-TIME."
520 (defmethod database-get-type-specifier ((type (eql 'universal-time)) args database db-type)
521 (declare (ignore args database db-type))
524 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database db-type)
525 (declare (ignore args database db-type))
528 (defmethod database-get-type-specifier ((type (eql 'date)) args database db-type)
529 (declare (ignore args database db-type))
532 (defmethod database-get-type-specifier ((type (eql 'duration)) args database db-type)
533 (declare (ignore database args db-type))
536 (defmethod database-get-type-specifier ((type (eql 'money)) args database db-type)
537 (declare (ignore database args db-type))
541 (deftype char (&optional len)
542 "A lisp type for the SQL CHAR type."
545 (defmethod database-get-type-specifier ((type (eql 'float)) args database db-type)
546 (declare (ignore database db-type))
548 (format nil "FLOAT(~A)" (car args))
551 (defmethod database-get-type-specifier ((type (eql 'long-float)) args database db-type)
552 (declare (ignore database db-type))
554 (format nil "FLOAT(~A)" (car args))
557 (deftype generalized-boolean ()
558 "A type which outputs a SQL boolean value, though any lisp type can be stored in the slot."
561 (defmethod database-get-type-specifier ((type (eql 'boolean)) args database db-type)
562 (declare (ignore args database db-type))
565 (defmethod database-get-type-specifier ((type (eql 'generalized-boolean)) args database db-type)
566 (declare (ignore args database db-type))
569 (defmethod database-get-type-specifier ((type (eql 'number)) args database db-type)
570 (declare (ignore database db-type))
572 ((and (consp args) (= (length args) 2))
573 (format nil "NUMBER(~D,~D)" (first args) (second args)))
574 ((and (consp args) (= (length args) 1))
575 (format nil "NUMBER(~D)" (first args)))
579 (defmethod database-get-type-specifier ((type (eql 'char)) args database db-type)
580 (declare (ignore database db-type))
582 (format nil "CHAR(~D)" (first args))
586 (defmethod database-output-sql-as-type (type val database db-type)
587 (declare (ignore type database db-type))
590 (defmethod database-output-sql-as-type ((type (eql 'list)) val database db-type)
591 (declare (ignore database db-type))
592 (progv '(*print-circle* *print-array*) '(t t)
593 (let ((escaped (prin1-to-string val)))
594 (substitute-char-string
595 escaped #\Null " "))))
597 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database db-type)
598 (declare (ignore database db-type))
601 (package-name (symbol-package val))
606 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database db-type)
607 (declare (ignore database db-type))
612 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database db-type)
613 (declare (ignore database db-type))
614 (progv '(*print-circle* *print-array*) '(t t)
615 (prin1-to-string val)))
617 (defmethod database-output-sql-as-type ((type (eql 'array)) val database db-type)
618 (declare (ignore database db-type))
619 (progv '(*print-circle* *print-array*) '(t t)
620 (prin1-to-string val)))
622 (defmethod database-output-sql-as-type ((type (eql 'boolean)) val database db-type)
623 (declare (ignore database db-type))
626 (defmethod database-output-sql-as-type ((type (eql 'generalized-boolean)) val database db-type)
627 (declare (ignore database db-type))
630 (defmethod database-output-sql-as-type ((type (eql 'string)) val database db-type)
631 (declare (ignore database db-type))
634 (defmethod database-output-sql-as-type ((type (eql 'char)) val database db-type)
635 (declare (ignore database db-type))
637 (character (write-to-string val))
640 (defmethod database-output-sql-as-type ((type (eql 'float)) val database db-type)
641 (declare (ignore database db-type))
642 (if (eq (type-of val) 'null)
644 (let ((*read-default-float-format* (type-of val)))
645 (format nil "~F" val))))
647 (defmethod read-sql-value (val type database db-type)
648 (declare (ignore database db-type))
650 ((null type) val) ;;we have no desired type, just give the value
651 ((typep val type) val) ;;check that it hasn't already been converted.
652 ((typep val 'string) (read-from-string val)) ;;maybe read will just take care of it?
653 (T (error "Unable to read-sql-value ~a as type ~a" val type))))
655 (defmethod read-sql-value (val (type (eql 'string)) database db-type)
656 (declare (ignore database db-type))
659 (defmethod read-sql-value (val (type (eql 'varchar)) database db-type)
660 (declare (ignore database db-type))
663 (defmethod read-sql-value (val (type (eql 'char)) database db-type)
664 (declare (ignore database db-type))
667 (defmethod read-sql-value (val (type (eql 'keyword)) database db-type)
668 (declare (ignore database db-type))
669 (when (< 0 (length val))
670 (intern (symbol-name-default-case val)
671 (find-package '#:keyword))))
673 (defmethod read-sql-value (val (type (eql 'symbol)) database db-type)
674 (declare (ignore database db-type))
675 (when (< 0 (length val))
676 (unless (string= val (symbol-name-default-case "NIL"))
677 (read-from-string val))))
679 (defmethod read-sql-value (val (type (eql 'integer)) database db-type)
680 (declare (ignore database db-type))
683 (unless (string-equal "NIL" val)
684 (parse-integer val)))
687 (defmethod read-sql-value (val (type (eql 'smallint)) database db-type)
688 (declare (ignore database db-type))
691 (unless (string-equal "NIL" val)
692 (parse-integer val)))
695 (defmethod read-sql-value (val (type (eql 'bigint)) database db-type)
696 (declare (ignore database db-type))
699 (unless (string-equal "NIL" val)
700 (parse-integer val)))
703 (defmethod read-sql-value (val (type (eql 'float)) database db-type)
704 (declare (ignore database db-type))
705 ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
707 (string (float (read-from-string val)))
710 (defmethod read-sql-value (val (type (eql 'double-float)) database db-type)
711 (declare (ignore database db-type))
712 ;; writing 1.0 writes 1, so if we *really* want a float, must do (float ...)
715 (let ((*read-default-float-format* 'double-float))
716 (read-from-string val))
719 (float (coerce val 'double-float))))
721 (defmethod read-sql-value (val (type (eql 'boolean)) database db-type)
722 (declare (ignore database db-type))
725 (defmethod read-sql-value (val (type (eql 'generalized-boolean)) database db-type)
726 (declare (ignore database db-type))
729 (defmethod read-sql-value (val (type (eql 'number)) database db-type)
730 (declare (ignore database db-type))
733 (unless (string-equal "NIL" val)
734 (read-from-string val)))
737 (defmethod read-sql-value (val (type (eql 'universal-time)) database db-type)
738 (declare (ignore database db-type))
739 (unless (eq 'NULL val)
745 (defmethod read-sql-value (val (type (eql 'wall-time)) database db-type)
746 (declare (ignore database db-type))
747 (unless (eq 'NULL val)
748 (parse-timestring val)))
750 (defmethod read-sql-value (val (type (eql 'date)) database db-type)
751 (declare (ignore database db-type))
752 (unless (eq 'NULL val)
753 (parse-datestring val)))
755 (defmethod read-sql-value (val (type (eql 'duration)) database db-type)
756 (declare (ignore database db-type))
757 (unless (or (eq 'NULL val)
759 (parse-timestring val)))
761 ;; ------------------------------------------------------------
762 ;; Logic for 'faulting in' :join slots
764 ;; this works, but is inefficient requiring (+ 1 n-rows)
767 (defun fault-join-target-slot (class object slot-def)
768 (let* ((res (fault-join-slot-raw class object slot-def))
769 (dbi (view-class-slot-db-info slot-def))
770 (target-name (gethash :target-slot dbi))
771 (target-class (find-class target-name)))
773 (mapcar (lambda (obj)
779 (find target-name (class-slots (class-of obj))
780 :key #'slot-definition-name)))
783 #+ignore ;; this doesn't work when attempting to call slot-value
784 (mapcar (lambda (obj)
785 (cons obj (slot-value obj ts))) res))))
787 (defun fault-join-target-slot (class object slot-def)
788 (let* ((dbi (view-class-slot-db-info slot-def))
789 (ts (gethash :target-slot dbi))
790 (jc (gethash :join-class dbi))
791 (jc-view-table (view-table (find-class jc)))
792 (tdbi (view-class-slot-db-info
793 (find ts (class-slots (find-class jc))
794 :key #'slot-definition-name)))
795 (retrieval (gethash :retrieval tdbi))
796 (tsc (gethash :join-class tdbi))
797 (ts-view-table (view-table (find-class tsc)))
798 (jq (join-qualifier class object slot-def))
799 (key (slot-value object (gethash :home-key dbi))))
806 :inner-join (sql-expression :table jc-view-table)
810 :attribute (gethash :foreign-key tdbi)
811 :table ts-view-table)
813 :attribute (gethash :home-key tdbi)
814 :table jc-view-table))
817 :database (choose-database-for-instance object))))
818 (mapcar #'(lambda (i)
819 (let* ((instance (car i))
820 (jcc (make-instance jc :view-database (choose-database-for-instance instance))))
821 (setf (slot-value jcc (gethash :foreign-key dbi))
823 (setf (slot-value jcc (gethash :home-key tdbi))
824 (slot-value instance (gethash :foreign-key tdbi)))
825 (list instance jcc)))
828 ;; just fill in minimal slots
831 (let ((instance (make-instance tsc :view-database (choose-database-for-instance object)))
832 (jcc (make-instance jc :view-database (choose-database-for-instance object)))
834 (setf (slot-value instance (gethash :home-key tdbi)) fk)
835 (setf (slot-value jcc (gethash :foreign-key dbi))
837 (setf (slot-value jcc (gethash :home-key tdbi))
839 (list instance jcc)))
840 (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
841 :from (sql-expression :table jc-view-table)
843 :database (choose-database-for-instance object))))))))
848 (defvar *default-update-objects-max-len* nil
849 "The default value to use for the MAX-LEN keyword argument to
850 UPDATE-OBJECT-JOINS.")
852 (defun update-objects-joins (objects &key (slots t) (force-p t)
854 *default-update-objects-max-len*))
855 "Updates from the records of the appropriate database tables
856 the join slots specified by SLOTS in the supplied list of View
857 Class instances OBJECTS. SLOTS is t by default which means that
858 all join slots with :retrieval :immediate are updated. CLASS-NAME
859 is used to specify the View Class of all instance in OBJECTS and
860 default to nil which means that the class of the first instance
861 in OBJECTS is used. FORCE-P is t by default which means that all
862 join slots are updated whereas a value of nil means that only
863 unbound join slots are updated. MAX-LEN defaults to
864 *DEFAULT-UPDATE-OBJECTS-MAX-LEN* and when non-nil specifies that
865 UPDATE-OBJECT-JOINS may issue multiple database queries with a
866 maximum of MAX-LEN instances updated in each query."
867 (assert (or (null max-len) (plusp max-len)))
870 (setq class-name (class-name (class-of (first objects)))))
871 (let* ((class (find-class class-name))
872 (class-slots (ordered-class-slots class))
875 (generate-retrieval-joins-list class :deferred)
877 (mapcar #'(lambda (name)
878 (let ((slotdef (find name class-slots :key #'slot-definition-name)))
880 (warn "Unable to find slot named ~S in class ~S." name class))
883 (dolist (slotdef slotdefs)
884 (let* ((dbi (view-class-slot-db-info slotdef))
885 (slotdef-name (slot-definition-name slotdef))
886 (foreign-key (gethash :foreign-key dbi))
887 (home-key (gethash :home-key dbi))
891 (mapcar #'(lambda (o) (slot-value o home-key)) objects)
894 #'(lambda (o) (if (slot-boundp o slotdef-name)
896 (slot-value o home-key)))
898 (n-object-keys (length object-keys))
899 (query-len (or max-len n-object-keys)))
901 (do ((i 0 (+ i query-len)))
902 ((>= i n-object-keys))
903 (let* ((keys (if max-len
904 (subseq object-keys i (min (+ i query-len) n-object-keys))
906 (results (unless (gethash :target-slot dbi)
907 (find-all (list (gethash :join-class dbi))
908 :where (make-instance 'sql-relational-exp
910 :sub-expressions (list (sql-expression :attribute foreign-key)
915 (dolist (object objects)
916 (when (or force-p (not (slot-boundp object slotdef-name)))
917 (let ((res (if results
918 (remove-if-not #'(lambda (obj)
919 (equal obj (slot-value
928 (when (gethash :target-slot dbi)
929 (fault-join-target-slot class object slotdef))))))
931 (setf (slot-value object slotdef-name)
932 (if (gethash :set dbi) res (car res)))))))))))))
935 (defun fault-join-slot-raw (class object slot-def)
936 (let* ((dbi (view-class-slot-db-info slot-def))
937 (jc (gethash :join-class dbi)))
938 (let ((jq (join-qualifier class object slot-def)))
940 (select jc :where jq :flatp t :result-types nil
941 :database (choose-database-for-instance object))))))
943 (defun fault-join-slot (class object slot-def)
944 (let* ((dbi (view-class-slot-db-info slot-def))
945 (ts (gethash :target-slot dbi)))
946 (if (and ts (gethash :set dbi))
947 (fault-join-target-slot class object slot-def)
948 (let ((res (fault-join-slot-raw class object slot-def)))
951 ((and ts (not (gethash :set dbi)))
952 (mapcar (lambda (obj) (slot-value obj ts)) res))
953 ((and (not ts) (not (gethash :set dbi)))
955 ((and (not ts) (gethash :set dbi))
958 ;;;; Should we not return the whole result, instead of only
959 ;;;; the one slot-value? We get all the values from the db
961 (defun fault-join-normalized-slot (class object slot-def)
962 (labels ((getsc (this-class)
963 (let ((sc (car (class-direct-superclasses this-class))))
967 (let* ((sc (getsc class))
968 (hk (slot-definition-name (car (key-slots class))))
969 (fk (slot-definition-name (car (key-slots sc)))))
970 (let ((jq (sql-operation '==
976 (slotdef-for-slot-with-class fk sc) nil)
977 :table (view-table sc)))
981 (slot-value object hk))
984 ;; Caching nil in next select, because in normalized mode
985 ;; records can be changed through other instances (children,
986 ;; parents) so changes possibly won't be noticed
987 (let ((res (car (select (class-name sc) :where jq
988 :flatp t :result-types nil
990 :database (choose-database-for-instance object))))
991 (slot-name (slot-definition-name slot-def)))
993 ;; If current class is normalized and wanted slot is not
994 ;; a direct member, recurse up
995 (if (and (normalizedp class)
996 (not (member slot-name
997 (mapcar #'(lambda (esd) (slot-definition-name esd))
998 (ordered-class-direct-slots class))))
999 (not (slot-boundp res slot-name)))
1000 (fault-join-normalized-slot sc res slot-def)
1001 (slot-value res slot-name)))))) )
1003 (defun join-qualifier (class object slot-def)
1004 (declare (ignore class))
1005 (let* ((dbi (view-class-slot-db-info slot-def))
1006 (jc (find-class (gethash :join-class dbi)))
1007 ;;(ts (gethash :target-slot dbi))
1008 ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
1009 (foreign-keys (gethash :foreign-key dbi))
1010 (home-keys (gethash :home-key dbi)))
1011 (when (every #'(lambda (slt)
1012 (and (slot-boundp object slt)
1013 (not (null (slot-value object slt)))))
1014 (if (listp home-keys) home-keys (list home-keys)))
1016 (mapcar #'(lambda (hk fk)
1017 (let ((fksd (slotdef-for-slot-with-class fk jc)))
1023 (database-identifier fksd nil)
1024 :table (database-identifier jc nil)))
1028 (slot-value object hk))
1031 (if (listp home-keys)
1034 (if (listp foreign-keys)
1036 (list foreign-keys)))))
1038 (if (> (length jc) 1)
1039 (apply #'sql-and jc)
1042 ;; FIXME: add retrieval immediate for efficiency
1043 ;; For example, for (select 'employee-address) in test suite =>
1044 ;; select addr.*,ea_join.* FROM addr,ea_join WHERE ea_join.aaddressid=addr.addressid\g
1046 (defun build-objects (vals sclasses immediate-join-classes sels immediate-joins database refresh flatp instances)
1047 "Used by find-all to build objects."
1048 (labels ((build-object (vals vclass jclasses selects immediate-selects instance)
1049 (let* ((db-vals (butlast vals (- (list-length vals)
1050 (list-length selects))))
1051 (obj (if instance instance (make-instance (class-name vclass) :view-database database)))
1052 (join-vals (subseq vals (list-length selects)))
1053 (joins (mapcar #'(lambda (c) (when c (make-instance c :view-database database)))
1056 ;;(format t "joins: ~S~%db-vals: ~S~%join-values: ~S~%selects: ~S~%immediate-selects: ~S~%"
1057 ;;joins db-vals join-vals selects immediate-selects)
1059 ;; use refresh keyword here
1060 (setf obj (get-slot-values-from-view obj (mapcar #'car selects) db-vals))
1061 (mapc #'(lambda (jo)
1062 ;; find all immediate-select slots and join-vals for this object
1063 (let* ((jo-class (class-of jo))
1064 (slots (slots-for-possibly-normalized-class jo-class))
1065 (pos-list (remove-if #'null
1068 (position s immediate-selects
1072 (get-slot-values-from-view jo
1074 (mapcar #'(lambda (pos)
1075 (nth pos immediate-selects))
1077 (mapcar #'(lambda (pos) (nth pos join-vals))
1083 (class-slots vclass))
1084 (slot (find (class-name (class-of jc)) vslots
1085 :key #'(lambda (slot)
1086 (when (and (eq :join (view-class-slot-db-kind slot))
1087 (eq (slot-definition-name slot)
1088 (gethash :join-class (view-class-slot-db-info slot))))
1089 (slot-definition-name slot))))))
1091 (setf (slot-value obj (slot-definition-name slot)) jc))))
1093 (when refresh (instance-refreshed obj))
1096 (mapcar #'(lambda (sclass jclass sel immediate-join instance)
1098 (build-object vals sclass jclass sel immediate-join instance)
1099 (setf vals (nthcdr (+ (list-length sel) (list-length immediate-join))
1101 sclasses immediate-join-classes sels immediate-joins instances)))
1102 (if (and flatp (= (length sclasses) 1))
1106 (defmethod select-table-sql-expr ((table T))
1107 "Turns an object representing a table into the :from part of the sql expression that will be executed "
1108 (sql-expression :table (view-table table)))
1111 (defun find-all (view-classes
1113 &key all set-operation distinct from where group-by having
1114 order-by offset limit refresh flatp result-types
1116 (database *default-database*)
1117 instances parameters)
1118 "Called by SELECT to generate object query results when the
1119 View Classes VIEW-CLASSES are passed as arguments to SELECT."
1120 (declare (ignore all set-operation group-by having offset limit inner-join on parameters)
1121 (dynamic-extent args))
1122 (flet ((ref-equal (ref1 ref2)
1123 (string= (sql-output ref1 database)
1124 (sql-output ref2 database))))
1125 (declare (dynamic-extent (function ref-equal)))
1126 (let ((args (filter-plist args :from :where :flatp :additional-fields :result-types :instances)))
1127 (let* ((*db-deserializing* t)
1128 (sclasses (mapcar #'find-class view-classes))
1129 (immediate-join-slots
1130 (mapcar #'(lambda (c) (generate-retrieval-joins-list c :immediate)) sclasses))
1131 (immediate-join-classes
1132 (mapcar #'(lambda (jcs)
1133 (mapcar #'(lambda (slotdef)
1134 (find-class (gethash :join-class (view-class-slot-db-info slotdef))))
1136 immediate-join-slots))
1137 (immediate-join-sels (mapcar #'generate-immediate-joins-selection-list sclasses))
1138 (sels (mapcar #'generate-selection-list sclasses))
1139 (fullsels (apply #'append (mapcar #'append sels immediate-join-sels)))
1140 (sel-tables (collect-table-refs where))
1141 (tables (remove-if #'null
1143 (append (mapcar #'select-table-sql-expr sclasses)
1144 (mapcan #'(lambda (jc-list)
1146 #'(lambda (jc) (when jc (select-table-sql-expr jc)))
1148 immediate-join-classes)
1150 :test #'database-identifier-equal)))
1151 (order-by-slots (mapcar #'(lambda (ob) (if (atom ob) ob (car ob)))
1152 (listify order-by)))
1155 ;;(format t "sclasses: ~W~%ijc: ~W~%tables: ~W~%" sclasses immediate-join-classes tables)
1157 (dolist (ob order-by-slots)
1158 (when (and ob (not (member ob (mapcar #'cdr fullsels)
1159 :test #'ref-equal)))
1161 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1163 (dolist (ob (listify distinct))
1164 (when (and (typep ob 'sql-ident)
1165 (not (member ob (mapcar #'cdr fullsels)
1166 :test #'ref-equal)))
1168 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1170 (mapcar #'(lambda (vclass jclasses jslots)
1173 #'(lambda (jclass jslot)
1174 (let ((dbi (view-class-slot-db-info jslot)))
1177 (list (sql-operation '==
1179 :attribute (gethash :foreign-key dbi)
1180 :table (view-table jclass))
1182 :attribute (gethash :home-key dbi)
1183 :table (view-table vclass))))
1184 (when join-where (listify join-where))))))
1186 sclasses immediate-join-classes immediate-join-slots)
1187 ;; Reported buggy on clsql-devel
1188 ;; (when where (setq where (listify where)))
1190 ((and where join-where)
1191 (setq where (list (apply #'sql-and where join-where))))
1192 ((and (null where) (> (length join-where) 1))
1193 (setq where (list (apply #'sql-and join-where)))))
1195 (let* ((rows (apply #'select
1196 (append (mapcar #'cdr fullsels)
1198 (list (append (when from (listify from))
1200 (list :result-types result-types)
1202 (list :where where))
1204 (instances-to-add (- (length rows) (length instances)))
1205 (perhaps-extended-instances
1206 (if (plusp instances-to-add)
1207 (append instances (do ((i 0 (1+ i))
1209 ((= i instances-to-add) res)
1210 (push (make-list (length sclasses) :initial-element nil) res)))
1213 #'(lambda (row instance)
1214 (build-objects row sclasses immediate-join-classes sels
1215 immediate-join-sels database refresh flatp
1216 (if (and flatp (atom instance))
1219 rows perhaps-extended-instances)))
1222 (defmethod instance-refreshed ((instance standard-db-object)))
1224 (defvar *default-caching* t
1225 "Controls whether SELECT caches objects by default. The CommonSQL
1226 specification states caching is on by default.")
1228 (defun select (&rest select-all-args)
1229 "Executes a query on DATABASE, which has a default value of
1230 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
1231 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
1232 argument can be used to generate queries in both functional and
1233 object oriented contexts.
1235 In the functional case, the required arguments specify the
1236 columns selected by the query and may be symbolic SQL expressions
1237 or strings representing attribute identifiers. Type modified
1238 identifiers indicate that the values selected from the specified
1239 column are converted to the specified lisp type. The keyword
1240 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
1241 SET-OPERATION and WHERE are used to specify, using the symbolic
1242 SQL syntax, the corresponding components of the SQL query
1243 generated by the call to SELECT. RESULT-TYPES is a list of
1244 symbols which specifies the lisp type for each field returned by
1245 the query. If RESULT-TYPES is nil all results are returned as
1246 strings whereas the default value of :auto means that the lisp
1247 types are automatically computed for each field. FIELD-NAMES is t
1248 by default which means that the second value returned is a list
1249 of strings representing the columns selected by the query. If
1250 FIELD-NAMES is nil, the list of column names is not returned as a
1253 In the object oriented case, the required arguments to SELECT are
1254 symbols denoting View Classes which specify the database tables
1255 to query. In this case, SELECT returns a list of View Class
1256 instances whose slots are set from the attribute values of the
1257 records in the specified table. Slot-value is a legal operator
1258 which can be employed as part of the symbolic SQL syntax used in
1259 the WHERE keyword argument to SELECT. REFRESH is nil by default
1260 which means that the View Class instances returned are retrieved
1261 from a cache if an equivalent call to SELECT has previously been
1262 issued. If REFRESH is true, the View Class instances returned are
1263 updated as necessary from the database and the generic function
1264 INSTANCE-REFRESHED is called to perform any necessary operations
1265 on the updated instances.
1267 In both object oriented and functional contexts, FLATP has a
1268 default value of nil which means that the results are returned as
1269 a list of lists. If FLATP is t and only one result is returned
1270 for each record selected in the query, the results are returned
1271 as elements of a list."
1272 (multiple-value-bind (target-args qualifier-args)
1273 (query-get-selections select-all-args)
1274 (unless (or *default-database* (getf qualifier-args :database))
1275 (signal-no-database-error nil))
1277 (let ((caching (getf qualifier-args :caching *default-caching*))
1278 (result-types (getf qualifier-args :result-types :auto))
1279 (refresh (getf qualifier-args :refresh nil))
1280 (database (getf qualifier-args :database *default-database*)))
1284 (every #'(lambda (arg)
1286 (find-class arg nil)))
1289 (setf qualifier-args (filter-plist qualifier-args :caching :refresh :result-types))
1291 ;; Add explicity table name to order-by if not specified and only
1292 ;; one selected table. This is required so FIND-ALL won't duplicate
1294 (let ((order-by (getf qualifier-args :order-by)))
1295 (when (and order-by (= 1 (length target-args)))
1296 (let ((table-name (view-table (find-class (car target-args))))
1297 (order-by-list (copy-seq (listify order-by))))
1298 (labels ((sv (val name) (ignore-errors (slot-value val name)))
1299 (set-table-if-needed (val)
1301 (sql-ident-attribute
1303 (if (sv val 'qualifier)
1305 (make-instance 'sql-ident-attribute
1306 :name (sv val 'name)
1307 :qualifier table-name))
1309 ;; TODO: Check for a specific error we expect
1311 (cons (cons (set-table-if-needed (car val))
1315 (loop for i from 0 below (length order-by-list)
1316 for id in order-by-list
1317 collect (set-table-if-needed id))))
1318 (setf (getf qualifier-args :order-by) order-by-list))))
1322 (apply #'find-all target-args :result-types result-types :refresh refresh qualifier-args))
1324 (let ((cached (records-cache-results target-args qualifier-args database)))
1325 (if (and cached (not refresh))
1327 (let ((results (apply #'find-all target-args
1328 :result-types :auto :refresh refresh
1331 (setf (records-cache-results target-args qualifier-args database) results)
1335 (let* ((expr (apply #'make-query select-all-args))
1336 (parameters (second (member :parameters select-all-args)))
1338 (mapcar #'(lambda (attrib)
1339 (if (typep attrib 'sql-ident-attribute)
1340 (let ((type (slot-value attrib 'type)))
1345 (slot-value expr 'selections)))
1346 (flatp (getf qualifier-args :flatp))
1347 (field-names (getf qualifier-args :field-names t)))
1350 (setf expr (command-object (sql-output expr database) parameters)))
1351 (query expr :flatp flatp
1353 ;; specifying a type for an attribute overrides result-types
1354 (if (some #'(lambda (x) (not (eq t x))) specified-types)
1357 :field-names field-names
1358 :database database)))))))
1360 (defun compute-records-cache-key (targets qualifiers)
1362 (do ((args *select-arguments* (cdr args))
1364 ((null args) results)
1365 (let* ((arg (car args))
1366 (value (getf qualifiers arg)))
1370 (cons (cons (sql (car value)) (cdr value)))
1371 (%sql-expression (sql value))
1375 (defun records-cache-results (targets qualifiers database)
1376 (when (record-caches database)
1377 (gethash (compute-records-cache-key targets qualifiers) (record-caches database))))
1379 (defun (setf records-cache-results) (results targets qualifiers database)
1380 (unless (record-caches database)
1381 (setf (record-caches database)
1382 (make-weak-hash-table :test 'equal)))
1383 (setf (gethash (compute-records-cache-key (copy-list targets) qualifiers)
1384 (record-caches database)) results)
1389 ;;; Serialization functions
1391 (defun write-instance-to-stream (obj stream)
1392 "Writes an instance to a stream where it can be later be read.
1393 NOTE: an error will occur if a slot holds a value which can not be written readably."
1394 (let* ((class (class-of obj))
1396 (dolist (slot (ordered-class-slots (class-of obj)))
1397 (let ((name (slot-definition-name slot)))
1398 (when (and (not (eq 'view-database name))
1399 (slot-boundp obj name))
1400 (push (cons name (slot-value obj name)) alist))))
1401 (setq alist (reverse alist))
1402 (write (cons (class-name class) alist) :stream stream :readably t))
1405 (defun read-instance-from-stream (stream)
1406 (let ((raw (read stream nil nil)))
1408 (let ((obj (make-instance (car raw))))
1409 (dolist (pair (cdr raw))
1410 (setf (slot-value obj (car pair)) (cdr pair)))