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)
15 (defun find-normalized-key (obj)
16 "Find the first / primary key of a normalized object"
17 (find-slot-if obj #'key-slot-p T T))
19 (defun normalized-key-value (obj)
20 "Normalized classes share a single key for all their key slots"
21 (when (normalizedp (class-of obj))
22 (easy-slot-value obj (find-normalized-key obj))))
24 (defun key-qualifier-for-instance (obj &key (database *default-database*) this-class)
25 "Generate a boolean sql-expression that identifies an object by its keys"
26 (let* ((obj-class (or this-class (class-of obj)))
27 (keys (keyslots-for-class obj-class))
28 (normal-db-value (normalized-key-value obj)))
30 (labels ((db-value (k)
34 (easy-slot-value obj k)
37 (sql-operation '== (generate-attribute-reference obj-class k database)
39 (clsql-ands (mapcar #'key-equal-exp keys))))))
41 (defun generate-attribute-reference (vclass slotdef &optional (database *default-database*))
42 "Turns key class and slot-def into a sql-expression representing the
43 table and column it comes from
45 used by things like make-select-list, update-slot-from-record"
46 (when (key-or-base-slot-p slotdef)
47 (sql-expression :attribute (database-identifier slotdef database)
48 :table (database-identifier vclass database))))
50 (defun get-join-slots (class &optional retrieval-method)
51 "Returns list of join slots for a class.
53 if a retrieval method is specified only return slots of that type
54 if the retrieval method is T, nil or :all return all join slots"
55 (assert (member retrieval-method '(nil t :all :immediate :deferred)))
56 (setf class (to-class class))
57 (let ((all? (member retrieval-method '(nil t :all))))
58 (loop for slot in (ordered-class-slots class)
59 when (and (join-slot-p slot)
60 (or all? (eql (join-slot-retrieval-method slot) retrieval-method)))
63 (defun immediate-join-slots (class)
64 (get-join-slots class :immediate))
66 (defmethod choose-database-for-instance ((obj standard-db-object) &optional database)
67 "Determine which database connection to use for a standard-db-object.
68 Errs if none is available."
69 (or (find-if #'(lambda (db)
70 (and db (is-database-open db)))
71 (list (view-database obj)
74 (signal-no-database-error nil)))
78 (defmethod update-slot-with-null ((object standard-db-object) slotdef)
79 "sets a slot to the void value of the slot-def (usually nil)"
80 (setf (easy-slot-value object slotdef)
81 (slot-value slotdef 'void-value)))
83 (defmethod update-slot-from-db-value ((instance standard-db-object) slotdef value)
84 "This gets a value from the database and turns it itno a lisp value
85 based on the slot's slot-db-reader or baring that read-sql-value"
86 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
87 (let* ((slot-reader (view-class-slot-db-reader slotdef))
88 (slot-type (specified-type slotdef)))
90 ((null value) (update-slot-with-null instance slotdef))
92 (setf (easy-slot-value instance slotdef)
93 (read-sql-value value (delistify slot-type)
94 (choose-database-for-instance instance)
95 (database-underlying-type
96 (choose-database-for-instance instance)))))
97 (t (etypecase slot-reader
99 (setf (easy-slot-value instance slotdef)
100 (apply slot-reader (list value))))
102 (setf (easy-slot-value instance slotdef)
103 (format nil slot-reader value))))))))
105 (defmethod key-value-from-db (slotdef value database)
106 "TODO: is this deprecated? there are no uses anywhere in clsql"
107 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
108 (let ((slot-reader (view-class-slot-db-reader slotdef))
109 (slot-type (specified-type slotdef)))
110 (cond ((and value (null slot-reader))
111 (read-sql-value value (delistify slot-type) database
112 (database-underlying-type database)))
115 ((typep slot-reader 'string)
116 (format nil slot-reader value))
117 ((typep slot-reader '(or symbol function))
118 (apply slot-reader (list value)))
120 (error "Slot reader is of an unusual type.")))))
122 (defun db-value-from-slot (slotdef val database)
123 (let ((dbwriter (view-class-slot-db-writer slotdef))
124 (dbtype (specified-type slotdef)))
126 (string (format nil dbwriter val))
127 ((and (or symbol function) (not null)) (apply dbwriter (list val)))
129 (database-output-sql-as-type
133 val database (database-underlying-type database))))))
135 (defun check-slot-type (slotdef val)
136 (let* ((slot-type (specified-type slotdef))
137 (basetype (if (listp slot-type) (car slot-type) slot-type)))
138 (when (and slot-type val)
139 (unless (typep val basetype)
140 (error 'sql-user-error
142 (format nil "Invalid value ~A in slot ~A, not of type ~A."
143 val (slot-definition-name slotdef) slot-type))))))
145 (defmethod get-slot-values-from-view (obj slotdeflist values)
146 "Used to copy values from the database into the object
147 used by things like find-all and select"
148 (loop for slot in slotdeflist
150 do (update-slot-from-db-value obj slot value))
153 (defclass class-and-slots ()
154 ((view-class :accessor view-class :initarg :view-class :initform nil)
155 (slot-defs :accessor slot-defs :initarg :slot-defs :initform nil))
156 (:documentation "A helper class to keep track of which slot-defs from a
157 table need to be updated, a normalized class might have many of these
158 because each of its parent classes might represent some other table and we
159 need to match which slots came from which parent class/table"))
161 (defun make-class-and-slots (c &optional s)
162 "Create a new class-and-slots object"
163 (make-instance 'class-and-slots :view-class c :slot-defs (listify s) ))
165 (defmethod view-table ((o class-and-slots))
166 "get the view-table of the view-class of o"
167 (view-table (view-class o)))
169 (defmethod view-table-exp ((o class-and-slots))
170 (sql-expression :table (view-table o)))
172 (defmethod view-table-exp ((o standard-db-class))
173 (sql-expression :table (view-table o)))
175 (defmethod attribute-references ((o class-and-slots))
176 "build sql-ident-attributes for a given class-and-slots"
178 with class = (view-class o)
179 for sd in (slot-defs o)
180 collect (generate-attribute-reference class sd)))
182 (defmethod attribute-value-pairs ((def class-and-slots) (o standard-db-object)
184 "for a given class-and-slots and object, create the sql-expression & value pairs
185 that need to be sent to the database"
186 (loop for s in (slot-defs def)
187 for n = (to-slot-name s)
188 when (slot-boundp o n)
189 collect (make-attribute-value-pair s (slot-value o n) database)))
191 (defmethod view-classes-and-slots-by-name ((obj standard-db-object) slots-to-match)
192 "If it's normalized, find the class that actually contains
193 the slot that's tied to the db,
195 otherwise just search the current class
197 (let* ((view-class (class-of obj))
198 (normalizedp (normalizedp view-class))
200 (labels ((get-c&s-obj (class)
201 (or (find class rtns :key #'view-class)
202 (first (push (make-class-and-slots class) rtns))))
203 (associate-slot-with-class (class slot)
204 "Find the best class to associate with the slot. If it is
205 normalized then it needs to be a direct slot otherwise it just
206 needs to be on the class."
207 (let ((sd (find-slot-by-name class slot normalizedp nil)))
209 ;;we found it directly or it's (not normalized)
210 (pushnew sd (slot-defs (get-c&s-obj class)))
212 (loop for parent in (class-direct-superclasses class)
213 until (associate-slot-with-class parent slot))))
216 for in-slot in (listify slots-to-match)
217 do (associate-slot-with-class view-class in-slot)))
220 (defun update-auto-increments-keys (class obj database)
221 " handle pulling any autoincrement values into the object
222 if normalized and we now that all the "
223 (let ((pk-slots (keyslots-for-class class))
224 (table (view-table class))
226 (labels ((do-update (slot)
227 (when (and (null (easy-slot-value obj slot))
228 (auto-increment-column-p slot database))
229 (update-slot-from-db-value
233 (database-last-auto-increment-id
234 database table slot))))))
235 (chain-primary-keys (in-class)
236 "This seems kindof wrong, but this is mostly how it was working, so
237 its here to keep the normalized code path working"
238 (when (typep in-class 'standard-db-class)
239 (loop for slot in (ordered-class-slots in-class)
240 when (key-slot-p slot)
241 do (do-update slot)))))
242 (loop for slot in pk-slots do (do-update slot))
243 (let ((direct-class (to-class obj)))
244 (when (and new-pk-value (normalizedp direct-class))
245 (chain-primary-keys direct-class)))
248 (defmethod %update-instance-helper
249 (class-and-slots obj database
250 &aux (avps (attribute-value-pairs class-and-slots obj database)))
251 "A function to help us update a given table (based on class-and-slots)
252 with values from an object"
253 ;; we dont actually need to update anything on this particular
254 ;; class / parent class
255 (unless avps (return-from %update-instance-helper))
257 (let* ((view-class (view-class class-and-slots))
258 (table (view-table view-class))
259 (table-sql (sql-expression :table table)))
261 ;; view database is the flag we use to tell it was pulled from a database
262 ;; and thus probably needs an update instead of an insert
263 (cond ((view-database obj)
264 (let ((where (key-qualifier-for-instance
265 obj :database database :this-class view-class)))
267 (error "update-record-from-*: could not generate a where clause for ~a using ~A"
269 (update-records table-sql
272 :database database)))
273 (T ;; was not pulled from the db so insert it
274 ;; avps MUST contain any primary key slots set
275 ;; by previous inserts of the same object into different
276 ;; tables (ie: normalized stuff)
277 (insert-records :into table-sql
280 (update-auto-increments-keys view-class obj database)
281 ;; we dont set view database here, because there could be
282 ;; N of these for each call to update-record-from-* because
283 ;; of normalized classes
285 (update-slot-default-values obj class-and-slots)))
287 (defmethod update-record-from-slots ((obj standard-db-object) slots
288 &key (database *default-database*))
289 "For a given list of slots, update all records associated with those slots
292 Generally this will update the single record associated with this object,
293 but for normalized classes might update as many records as there are
295 (setf slots (listify slots))
296 (let* ((classes-and-slots (view-classes-and-slots-by-name obj slots))
297 (database (choose-database-for-instance obj database)))
298 (loop for class-and-slots in classes-and-slots
299 do (%update-instance-helper class-and-slots obj database))
300 (setf (slot-value obj 'view-database) database))
303 (defmethod update-record-from-slot
304 ((obj standard-db-object) slot &key (database *default-database*))
305 "just call update-records-from-slots which now handles this.
307 This function is only here to maintain backwards compatibility in
309 (update-record-from-slots obj slot :database database))
311 (defmethod view-classes-and-storable-slots (class)
312 "Get a list of all the tables we need to update and the slots on them
314 for non normalized classes we return the class and all its storable slots
316 for normalized classes we return a list of direct slots and the class they
317 came from for each normalized view class
319 (setf class (to-class class))
321 (labels ((storable-slots (class)
322 (loop for sd in (slots-for-possibly-normalized-class class)
323 when (key-or-base-slot-p sd)
325 (get-classes-and-slots (class &aux (normalizedp (normalizedp class)))
326 (let ((slots (storable-slots class)))
328 (push (make-class-and-slots class slots) rtns)))
330 (loop for new-class in (class-direct-superclasses class)
331 do (when (typep new-class 'standard-db-class)
332 (get-classes-and-slots new-class))))))
333 (get-classes-and-slots class))
336 (defmethod primary-key-slot-values ((obj standard-db-object)
338 "Returns the values of all key-slots for a given class"
339 (defaulting class (class-of obj)
340 slots (keyslots-for-class class))
341 (loop for slot in slots
342 collect (easy-slot-value obj slot)))
344 (defmethod update-slot-default-values ((obj standard-db-object)
346 "Makes sure that if a class has unfilled slots that claim to have a default,
347 that we retrieve those defaults from the database
349 TODO: use update-slots-from-record (doesnt exist) instead to batch this!"
350 (loop for class-and-slots in (listify classes-and-slots)
351 do (loop for slot in (slot-defs class-and-slots)
352 do (when (and (slot-has-default-p slot)
353 (not (easy-slot-value obj slot)))
354 (update-slot-from-record obj (to-slot-name slot))))))
356 (defmethod update-records-from-instance ((obj standard-db-object)
357 &key (database *default-database*))
358 "Updates the records in the database associated with this object if
359 view-database slot on the object is nil then the object is assumed to be
361 (let ((database (choose-database-for-instance obj database))
362 (classes-and-slots (view-classes-and-storable-slots obj)))
363 (loop for class-and-slots in classes-and-slots
364 do (%update-instance-helper class-and-slots obj database))
365 (setf (slot-value obj 'view-database) database)
366 (primary-key-slot-values obj)))
368 (defmethod delete-instance-records ((instance standard-db-object) &key database)
369 "Removes the records associated with a given instance
370 (as determined by key-qualifier-for-instance)
372 TODO: Doesnt handle normalized classes at all afaict"
373 (let ((database (choose-database-for-instance instance database))
374 (vt (sql-expression :table (view-table (class-of instance)))))
376 (let ((qualifier (key-qualifier-for-instance instance :database database)))
377 (delete-records :from vt :where qualifier :database database)
378 (setf (record-caches database) nil)
379 (setf (slot-value instance 'view-database) nil)
381 (signal-no-database-error database))))
383 (defmethod update-instance-from-records ((instance standard-db-object)
384 &key (database *default-database*))
385 "Updates a database object with the current values stored in the database
387 TODO: Should this update immediate join slots similar to build-objects?
388 Can we just call build-objects?, update-objects-joins?
391 (let* ((classes-and-slots (view-classes-and-storable-slots instance))
392 (vd (choose-database-for-instance instance database)))
393 (labels ((do-update (class-and-slots)
394 (let* ((select-list (make-select-list class-and-slots :do-joins-p nil))
395 (view-table (sql-table select-list))
396 (view-qual (key-qualifier-for-instance
397 instance :database vd
398 :this-class (view-class select-list)))
402 (append (full-select-list select-list)
403 (list :from view-table
408 (setf (slot-value instance 'view-database) vd)
409 (get-slot-values-from-view instance (slot-list select-list) res))
411 (loop for class-and-slots in classes-and-slots
412 do (do-update class-and-slots)))))
415 (defmethod get-slot-value-from-record ((instance standard-db-object)
416 slot &key (database *default-database*))
417 (let* ((class-and-slot
419 (view-classes-and-slots-by-name instance slot)))
420 (view-class (view-class class-and-slot))
421 (slot-def (first (slot-defs class-and-slot)))
422 (vd (choose-database-for-instance instance database))
423 (att-ref (first (attribute-references class-and-slot)))
426 :from (view-table-exp class-and-slot)
427 :where (key-qualifier-for-instance
430 :this-class view-class)
433 (values res slot-def)))
435 (defmethod update-slot-from-record ((instance standard-db-object)
436 slot &key (database *default-database*))
437 "Pulls the value of a given slot form the database and stores that in the
438 appropriate slot on instance"
439 (multiple-value-bind (res slot-def)
440 (get-slot-value-from-record instance slot :database database)
441 (let ((vd (choose-database-for-instance instance database)))
442 (setf (slot-value instance 'view-database) vd)
443 (update-slot-from-db-value instance slot-def res))))
446 (defvar +no-slot-value+ '+no-slot-value+)
448 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
449 (let* ((class (find-class classname))
450 (sld (slotdef-for-slot-with-class slot class)))
452 (if (eq value +no-slot-value+)
453 (sql-expression :attribute (database-identifier sld database)
454 :table (view-table class))
459 (error "Unknown slot ~A for class ~A" slot classname))))
461 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
462 (declare (ignore database))
463 (let* ((class (find-class classname)))
464 (unless (view-table class)
465 (error "No view-table for class ~A" classname))
466 (sql-expression :table (view-table class))))
469 "An 8-bit integer, this width may vary by SQL implementation."
473 "An integer smaller than a 32-bit integer. this width may vary by SQL implementation."
476 (deftype mediumint ()
477 "An integer smaller than a 32-bit integer, but may be larger than a smallint. This width may vary by SQL implementation."
481 "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
484 (deftype varchar (&optional size)
485 "A variable length string for the SQL varchar type."
486 (declare (ignore size))
489 (deftype universal-time ()
490 "A positive integer as returned by GET-UNIVERSAL-TIME."
493 (deftype generalized-boolean ()
494 "A type which outputs a SQL boolean value, though any lisp type can be stored in the slot."
498 (deftype char (&optional len)
499 "A lisp type for the SQL CHAR type."
502 (defmethod database-get-type-specifier ((type string) args database (db-type t))
503 "Pass through the literal type as defined in the type string"
504 (declare (ignore args database db-type))
508 (defmethod database-get-type-specifier ((type symbol) args database db-type)
511 (format nil "CHAR(~D)" (first args))
515 (format nil "VARCHAR(~A)" (car args))
516 (format nil "VARCHAR(~D)" *default-string-length*)))
517 ((longchar text) "text")
519 (format nil "INT(~A)" (car args))
521 ((tinyint smallint mediumint) "INT")
524 (format nil "FLOAT(~A)" (car args))
526 ((bigint universal-time) "BIGINT")
529 ((and (consp args) (= (length args) 2))
530 (format nil "NUMBER(~D,~D)" (first args) (second args)))
531 ((and (consp args) (= (length args) 1))
532 (format nil "NUMBER(~D)" (first args)))
535 (wall-time "TIMESTAMP")
539 ((boolean generalized-boolean) "BOOL")
540 (t (warn "Could not determine a valid ~A type specifier for ~A ~A ~A, defaulting to VARCHAR "
541 db-type type args database)
542 (format nil "VARCHAR(~D)" *default-string-length*))))
544 (defmethod database-output-sql-as-type (type val database db-type)
545 (declare (ignore type database db-type))
548 (defmethod database-output-sql-as-type ((type symbol) val database db-type)
549 (declare (ignore database))
550 (case type ;; booleans handle null differently
551 ((boolean generalized-boolean)
553 ;; done here so it can be done once
554 ((:mssql :mysql) (if val 1 0))
555 (otherwise (if val "t" "f"))))
557 ;; in all other cases if we have nil give everyone else a shot at it,
558 ;; which by default returns nil
564 (package-name (symbol-package val))
566 (keyword (symbol-name val))
569 (character (write-to-string val))
571 (float (format nil "~F" val))
573 (let* ((*print-circle* t)
575 (value (prin1-to-string val)))
577 (otherwise (call-next-method)))))))
579 (defmethod read-sql-value (val type database db-type
581 (declare (ignore database db-type))
582 ;; TODO: All the read-from-strings in here do not check that
583 ;; what we read was of the correct type, should this change?
585 ;; TODO: Should this case `(typep val type)=>t` be an around
586 ;; method that short ciruits?
588 ((null type) val) ;;we have no desired type, just give the value
589 ((typep val type) val) ;;check that it hasn't already been converted.
590 ((typep val 'string) (read-from-string val)) ;;maybe read will just take care of it?
591 (T (error "Unable to read-sql-value ~a as type ~a" val type))))
593 (defmethod read-sql-value (val (type symbol) database db-type
594 ;; never eval while reading values
596 ;; TODO: All the read-from-strings in here do not check that
597 ;; what we read was of the correct type, should this change?
598 (unless (or (equalp "nil" val) (eql 'null val))
600 ((string varchar) val)
602 (string (schar val 0))
605 (when (< 0 (length val))
606 (intern (symbol-name-default-case val) :keyword)))
608 (when (< 0 (length val))
609 (intern (symbol-name-default-case val))))
610 ((smallint mediumint bigint integer universal-time)
612 (string (parse-integer val))
614 ((double-float float)
615 ;; ensure that whatever we got is coerced to a float of the correct
616 ;; type (eg: 1=>1.0d0)
619 (string (let ((*read-default-float-format*
621 (float 'single-float)
622 (double-float 'double-float))))
623 (read-from-string val)))
625 (if (eql type 'double-float) 1.0d0 1.0s0)))
628 (string (read-from-string val))
630 ((boolean generalized-boolean)
631 (if (member val '(nil t))
635 (when (member val '("1" "t" "true" "y") :test #'string-equal)
637 (number (not (zerop val))))))
638 ((wall-time duration)
639 (parse-timestring val))
641 (parse-datestring val))
642 (t (call-next-method)))))
644 ;; ------------------------------------------------------------
645 ;; Logic for 'faulting in' :join slots
647 ;; this works, but is inefficient requiring (+ 1 n-rows)
650 (defun fault-join-target-slot (class object slot-def)
651 (let* ((res (fault-join-slot-raw class object slot-def))
652 (dbi (view-class-slot-db-info slot-def))
653 (target-name (gethash :target-slot dbi))
654 (target-class (find-class target-name)))
656 (mapcar (lambda (obj)
662 (find target-name (class-slots (class-of obj))
663 :key #'slot-definition-name)))
666 #+ignore ;; this doesn't work when attempting to call slot-value
667 (mapcar (lambda (obj)
668 (cons obj (slot-value obj ts))) res))))
670 (defun fault-join-target-slot (class object slot-def)
671 (let* ((dbi (view-class-slot-db-info slot-def))
672 (ts (gethash :target-slot dbi))
673 (jc (gethash :join-class dbi))
674 (jc-view-table (view-table (find-class jc)))
675 (tdbi (view-class-slot-db-info
676 (find ts (class-slots (find-class jc))
677 :key #'slot-definition-name)))
678 (retrieval (gethash :retrieval tdbi))
679 (tsc (gethash :join-class tdbi))
680 (ts-view-table (view-table (find-class tsc)))
681 (jq (join-qualifier class object slot-def))
682 (key (slot-value object (gethash :home-key dbi))))
689 :inner-join (sql-expression :table jc-view-table)
693 :attribute (gethash :foreign-key tdbi)
694 :table ts-view-table)
696 :attribute (gethash :home-key tdbi)
697 :table jc-view-table))
700 :database (choose-database-for-instance object))))
701 (mapcar #'(lambda (i)
702 (let* ((instance (car i))
703 (jcc (make-instance jc :view-database (choose-database-for-instance instance))))
704 (setf (slot-value jcc (gethash :foreign-key dbi))
706 (setf (slot-value jcc (gethash :home-key tdbi))
707 (slot-value instance (gethash :foreign-key tdbi)))
708 (list instance jcc)))
711 ;; just fill in minimal slots
714 (let ((instance (make-instance tsc :view-database (choose-database-for-instance object)))
715 (jcc (make-instance jc :view-database (choose-database-for-instance object)))
717 (setf (slot-value instance (gethash :home-key tdbi)) fk)
718 (setf (slot-value jcc (gethash :foreign-key dbi))
720 (setf (slot-value jcc (gethash :home-key tdbi))
722 (list instance jcc)))
723 (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
724 :from (sql-expression :table jc-view-table)
726 :database (choose-database-for-instance object))))))))
731 (defvar *default-update-objects-max-len* nil
732 "The default value to use for the MAX-LEN keyword argument to
733 UPDATE-OBJECT-JOINS.")
735 (defun %update-objects-joins-slot-defs (class slot-names)
736 "Get the slot definitions for the joins slots specified as slot-names
737 if slot-names is :immediate, :deferred or (or :all t) return all of
738 that type of slot definitions"
739 (setf class (to-class class))
740 (when (eq t slot-names) (setf slot-names :all))
741 (etypecase slot-names
744 ;; slot-names is the retrieval type of the join-slot or :all
745 (get-join-slots class slot-names))
747 (loop for slot in (listify slot-names)
748 for def = (find-slot-by-name class slot)
749 when (and def (join-slot-p def))
751 unless (and def (join-slot-p def))
752 do (warn "Unable to find join slot named ~S in class ~S." slot class)))))
754 (defun get-joined-objects (objects slotdef &key force-p
755 (batch-size *default-update-objects-max-len*))
756 "Given a list of objects and a join slot-def get the objects that need to be
757 joined to the input objects
759 we will query in batches as large as batch-size"
760 (when (join-slot-p slotdef)
761 (let* ((slot-name (to-slot-name slotdef))
762 (join-class (join-slot-class-name slotdef))
763 (home-key (join-slot-info-value slotdef :home-key))
764 (foreign-key (join-slot-info-value slotdef :foreign-key))
767 (loop for object in (listify objects)
768 for hk = (slot-value object home-key)
770 (not (slot-boundp object slot-name)))
773 ;; we want to retrieve at most batch-size objects per query
777 :where (make-instance
780 :sub-expressions (list (sql-expression :attribute foreign-key)
784 (if (null batch-size)
785 (fetch foreign-key-values)
787 for keys = (pop-n foreign-key-values batch-size)
789 nconcing (fetch keys)))))))
791 (defun %object-joins-from-list (object slot joins force-p )
792 "Given a list of objects that we are trying to join to, pull the correct
793 ones for this object"
794 (when (or force-p (not (slot-boundp object (to-slot-name slot))))
795 (let ((home-key (join-slot-info-value slot :home-key))
796 (foreign-key (join-slot-info-value slot :foreign-key)))
797 (loop for join in joins
798 when (equal (slot-value join foreign-key)
799 (slot-value object home-key))
802 (defun update-objects-joins (objects &key (slots :immediate) (force-p t)
803 class-name (max-len *default-update-objects-max-len*))
804 "Updates from the records of the appropriate database tables the join slots
805 specified by SLOTS in the supplied list of View Class instances OBJECTS.
807 A simpler method of causing a join-slot to be requeried is to set it to
808 unbound, then request it again. This function has efficiency gains where
809 join-objects are shared among the `objects` (querying all join-objects,
810 then attaching them appropriately to each of the `objects`)
814 * :immediate (DEFAULT) - refresh join slots created with :retrieval :immediate
815 * :deferred - refresh join slots created with :retrieval :deferred
816 * :all,t - refresh all join slots regardless of :retrieval
817 * list of symbols - which explicit slots to refresh
818 * a single symobl - what slot to refresh
820 CLASS-NAME is used to specify the View Class of all instance in OBJECTS and
821 default to nil which means that the class of the first instance in OBJECTS
824 FORCE-P is t by default which means that all join slots are updated whereas
825 a value of nil means that only unbound join slots are updated.
827 MAX-LEN defaults to *DEFAULT-UPDATE-OBJECTS-MAX-LEN* When non-nil this is
828 essentially a batch size for the max number of objects to query from the
829 database at a time. If we need more than max-len we loop till we have all
831 (assert (or (null max-len) (plusp max-len)))
833 (defaulting class-name (class-name (class-of (first objects))))
834 (let* ((class (find-class class-name))
835 (slotdefs (%update-objects-joins-slot-defs class slots)))
836 (loop for slotdef in slotdefs
837 ;; all the joins we will need for *all* the objects
838 ;; which then get filtered below for each object
839 for joins = (unless (join-slot-info-value slotdef :target-slot)
840 (get-joined-objects objects slotdef
841 :force-p force-p :batch-size max-len))
842 do (loop for object in objects
843 for these-joins = ;; the joins just for this object (filtered from above)
844 ;; or retrieved via fault-join-target-slot
845 (or (%object-joins-from-list object slotdef joins force-p)
846 (when (join-slot-info-value slotdef :target-slot)
847 (fault-join-target-slot class object slotdef)))
848 ;; when this object has joined-objects copy them in to the correct slot
850 (setf (easy-slot-value object slotdef)
851 (if (join-slot-info-value slotdef :set)
853 (first these-joins))))))))
856 (defun fault-join-slot-raw (class object slot-def)
857 (let* ((dbi (view-class-slot-db-info slot-def))
858 (jc (gethash :join-class dbi)))
859 (let ((jq (join-qualifier class object slot-def)))
861 (select jc :where jq :flatp t :result-types nil
862 :database (choose-database-for-instance object))))))
864 (defun fault-join-slot (class object slot-def)
865 (let* ((dbi (view-class-slot-db-info slot-def))
866 (ts (gethash :target-slot dbi))
867 (dbi-set (gethash :set dbi)))
869 (fault-join-target-slot class object slot-def)
870 (let ((res (fault-join-slot-raw class object slot-def)))
873 ((and ts (not dbi-set))
874 (mapcar (lambda (obj) (slot-value obj ts)) res))
875 ((and (not ts) (not dbi-set))
877 ((and (not ts) dbi-set)
880 (defun update-fault-join-normalized-slot (class object slot-def)
881 (if (and (normalizedp class) (key-slot-p slot-def))
882 (setf (easy-slot-value object slot-def)
883 (normalized-key-value object))
884 (update-slot-from-record object slot-def)))
886 (defun all-home-keys-have-values-p (object slot-def)
887 "Do all of the home-keys have values ?"
888 (let ((home-keys (join-slot-info-value slot-def :home-key)))
889 (loop for key in (listify home-keys)
890 always (easy-slot-value object key))))
892 (defun join-qualifier (class object slot-def)
893 "Builds the join where clause based on the keys of the join slot and values
895 (declare (ignore class))
896 (let* ((jc (join-slot-class slot-def))
897 ;;(ts (gethash :target-slot dbi))
898 ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
899 (foreign-keys (listify (join-slot-info-value slot-def :foreign-key)))
900 (home-keys (listify (join-slot-info-value slot-def :home-key))))
901 (when (all-home-keys-have-values-p object slot-def)
903 (loop for hk in home-keys
904 for fk in foreign-keys
905 for fksd = (slotdef-for-slot-with-class fk jc)
906 for fk-sql = (typecase fk
909 :attribute (database-identifier fksd nil)
910 :table (database-identifier jc nil)))
912 for hk-val = (typecase hk
914 view-class-effective-slot-definition
915 view-class-direct-slot-definition)
916 (easy-slot-value object hk))
918 collect (sql-operation '== fk-sql hk-val))))))
920 (defmethod select-table-sql-expr ((table T))
921 "Turns an object representing a table into the :from part of the sql expression that will be executed "
922 (sql-expression :table (view-table table)))
924 (defun select-reference-equal (r1 r2)
925 "determines if two sql select references are equal
926 using database identifier equal"
930 (sql-ident-attribute r))))
931 (database-identifier-equal (id-of r1) (id-of r2))))
933 (defun join-slot-qualifier (class join-slot)
934 "Creates a sql-expression expressing the join between the home-key on the table
935 and its respective key on the joined-to-table"
939 :attribute (join-slot-info-value join-slot :foreign-key)
940 :table (view-table (join-slot-class join-slot)))
942 :attribute (join-slot-info-value join-slot :home-key)
943 :table (view-table class))))
945 (defun all-immediate-join-classes-for (classes)
946 "returns a list of all join-classes needed for a list of classes"
947 (loop for class in (listify classes)
948 appending (loop for slot in (immediate-join-slots class)
949 collect (join-slot-class slot))))
951 (defun %tables-for-query (classes from where inner-joins)
952 "Given lists of classes froms wheres and inner-join compile a list
953 of tables that should appear in the FROM section of the query.
955 This includes any immediate join classes from each of the classes"
956 (let ((inner-join-tables (collect-table-refs (listify inner-joins))))
957 (loop for tbl in (append
958 (mapcar #'select-table-sql-expr classes)
959 (mapcar #'select-table-sql-expr
960 (all-immediate-join-classes-for classes))
961 (collect-table-refs (listify where))
962 (collect-table-refs (listify from)))
964 (not (find tbl rtn :test #'database-identifier-equal))
965 ;; TODO: inner-join is currently hacky as can be
966 (not (find tbl inner-join-tables :test #'database-identifier-equal)))
968 finally (return rtn))))
971 (defclass select-list ()
972 ((view-class :accessor view-class :initarg :view-class :initform nil)
973 (select-list :accessor select-list :initarg :select-list :initform nil)
974 (slot-list :accessor slot-list :initarg :slot-list :initform nil)
975 (joins :accessor joins :initarg :joins :initform nil)
976 (join-slots :accessor join-slots :initarg :join-slots :initform nil))
978 "Collects the classes, slots and their respective sql representations
979 so that update-instance-from-recors, find-all, build-objects can share this
980 info and calculate it once. Joins are select-lists for each immediate join-slot
981 but only if make-select-list is called with do-joins-p"))
983 (defmethod view-table ((o select-list))
984 (view-table (view-class o)))
986 (defmethod sql-table ((o select-list))
987 (sql-expression :table (view-table o)))
989 (defun make-select-list (class-and-slots &key (do-joins-p nil))
990 "Make a select-list for the current class (or class-and-slots) object."
991 (let* ((class-and-slots
992 (etypecase class-and-slots
993 (class-and-slots class-and-slots)
994 ((or symbol standard-db-class)
995 ;; find the first class with slots for us to select (this should be)
996 ;; the first of its classes / parent-classes with slots
997 (first (reverse (view-classes-and-storable-slots
998 (to-class class-and-slots)))))))
999 (class (view-class class-and-slots))
1000 (join-slots (when do-joins-p (immediate-join-slots class))))
1001 (multiple-value-bind (slots sqls)
1002 (loop for slot in (slot-defs class-and-slots)
1003 for sql = (generate-attribute-reference class slot)
1004 collect slot into slots
1005 collect sql into sqls
1006 finally (return (values slots sqls)))
1008 (error "No slots of type :base in view-class ~A" (class-name class)))
1014 :join-slots join-slots
1015 ;; only do a single layer of join objects
1016 :joins (when do-joins-p
1017 (loop for js in join-slots
1018 collect (make-select-list
1019 (join-slot-class js)
1020 :do-joins-p nil)))))))
1022 (defun full-select-list ( select-lists )
1023 "Returns a list of sql-ref of things to select for the given classes
1025 THIS NEEDS TO MATCH THE ORDER OF build-objects
1027 (loop for s in (listify select-lists)
1028 appending (select-list s)
1029 appending (loop for join in (joins s)
1030 appending (select-list join))))
1032 (defun build-objects (select-lists row database &optional existing-instances)
1033 "Used by find-all to build objects.
1035 THIS NEEDS TO MATCH THE ORDER OF FULL-SELECT-LIST
1037 TODO: this caching scheme seems bad for a number of reasons
1038 * order is not guaranteed so references being held by one object
1039 might change to represent a different database row (seems HIGHLY
1041 * also join objects are overwritten rather than refreshed
1043 TODO: the way we handle immediate joins seems only valid if it is a single
1044 object. I suspect that making a :set :immediate join column would result
1045 in an invalid number of objects returned from the database, because there
1046 would be multiple rows per object, but we would return an object per row
1048 (setf existing-instances (listify existing-instances))
1050 for select-list in select-lists
1051 for class = (view-class select-list)
1052 for existing = (pop existing-instances)
1053 for object = (or existing
1054 (make-instance class :view-database database))
1055 do (loop for slot in (slot-list select-list)
1056 do (update-slot-from-db-value object slot (pop row)))
1057 do (loop for join-slot in (join-slots select-list)
1058 for join in (joins select-list)
1059 for join-class = (view-class join)
1061 (setf (easy-slot-value object join-slot)
1062 (make-instance join-class))
1063 do (loop for slot in (slot-list join)
1064 do (update-slot-from-db-value join-object slot (pop row))))
1065 do (when existing (instance-refreshed object))
1068 (defun find-all (view-classes
1070 &key all set-operation distinct from where group-by having
1071 order-by offset limit refresh flatp result-types
1073 (database *default-database*)
1074 instances parameters)
1075 "Called by SELECT to generate object query results when the
1076 View Classes VIEW-CLASSES are passed as arguments to SELECT.
1078 TODO: the caching scheme of passing in instances and overwriting their
1079 values seems bad for a number of reasons
1080 * order is not guaranteed so references being held by one object
1081 might change to represent a different database row (seems HIGHLY
1084 TODO: the way we handle immediate joins seems only valid if it is a single
1085 object. I suspect that making a :set :immediate join column would result
1086 in an invalid number of objects returned from the database, because there
1087 would be multiple objects returned from the database
1089 (declare (ignore all set-operation group-by having offset limit on parameters
1091 (dynamic-extent args))
1092 (let* ((args (filter-plist
1093 args :from :where :flatp :additional-fields :result-types :instances))
1094 (*db-deserializing* t)
1095 (sclasses (mapcar #'to-class view-classes))
1096 (tables (%tables-for-query sclasses from where inner-join))
1098 (loop for class in sclasses
1099 appending (loop for slot in (immediate-join-slots class)
1100 collect (join-slot-qualifier class slot))))
1101 (select-lists (loop for class in sclasses
1102 collect (make-select-list class :do-joins-p t)))
1103 (full-select-list (full-select-list select-lists))
1104 (where (clsql-ands (append (listify where) (listify join-where))))
1106 (_ (format t "~&sclasses: ~W~%ijc: ~W~%tables: ~W~%"
1107 sclasses immediate-join-classes tables))
1109 (rows (apply #'select
1110 (append full-select-list
1112 :result-types result-types
1116 (loop for row in rows
1117 for old-objs = (pop instances)
1118 for objs = (build-objects select-lists row database
1119 (when refresh old-objs))
1120 collecting (if flatp
1121 (delist-if-single objs)
1125 (defmethod instance-refreshed ((instance standard-db-object)))
1127 (defvar *default-caching* t
1128 "Controls whether SELECT caches objects by default. The CommonSQL
1129 specification states caching is on by default.")
1131 (defun select (&rest select-all-args)
1132 "Executes a query on DATABASE, which has a default value of
1133 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
1134 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
1135 argument can be used to generate queries in both functional and
1136 object oriented contexts.
1138 In the functional case, the required arguments specify the
1139 columns selected by the query and may be symbolic SQL expressions
1140 or strings representing attribute identifiers. Type modified
1141 identifiers indicate that the values selected from the specified
1142 column are converted to the specified lisp type. The keyword
1143 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
1144 SET-OPERATION and WHERE are used to specify, using the symbolic
1145 SQL syntax, the corresponding components of the SQL query
1146 generated by the call to SELECT. RESULT-TYPES is a list of
1147 symbols which specifies the lisp type for each field returned by
1148 the query. If RESULT-TYPES is nil all results are returned as
1149 strings whereas the default value of :auto means that the lisp
1150 types are automatically computed for each field. FIELD-NAMES is t
1151 by default which means that the second value returned is a list
1152 of strings representing the columns selected by the query. If
1153 FIELD-NAMES is nil, the list of column names is not returned as a
1156 In the object oriented case, the required arguments to SELECT are
1157 symbols denoting View Classes which specify the database tables
1158 to query. In this case, SELECT returns a list of View Class
1159 instances whose slots are set from the attribute values of the
1160 records in the specified table. Slot-value is a legal operator
1161 which can be employed as part of the symbolic SQL syntax used in
1162 the WHERE keyword argument to SELECT. REFRESH is nil by default
1163 which means that the View Class instances returned are retrieved
1164 from a cache if an equivalent call to SELECT has previously been
1165 issued. If REFRESH is true, the View Class instances returned are
1166 updated as necessary from the database and the generic function
1167 INSTANCE-REFRESHED is called to perform any necessary operations
1168 on the updated instances.
1170 In both object oriented and functional contexts, FLATP has a
1171 default value of nil which means that the results are returned as
1172 a list of lists. If FLATP is t and only one result is returned
1173 for each record selected in the query, the results are returned
1174 as elements of a list."
1175 (multiple-value-bind (target-args qualifier-args)
1176 (query-get-selections select-all-args)
1177 (unless (or *default-database* (getf qualifier-args :database))
1178 (signal-no-database-error nil))
1180 (let ((caching (getf qualifier-args :caching *default-caching*))
1181 (result-types (getf qualifier-args :result-types :auto))
1182 (refresh (getf qualifier-args :refresh nil))
1183 (database (getf qualifier-args :database *default-database*)))
1187 (every #'(lambda (arg)
1189 (find-class arg nil)))
1192 (setf qualifier-args (filter-plist qualifier-args :caching :refresh :result-types))
1194 ;; Add explicity table name to order-by if not specified and only
1195 ;; one selected table. This is required so FIND-ALL won't duplicate
1197 (let ((order-by (getf qualifier-args :order-by)))
1198 (when (and order-by (= 1 (length target-args)))
1199 (let ((table-name (view-table (find-class (car target-args))))
1200 (order-by-list (copy-seq (listify order-by))))
1201 (labels ((sv (val name) (ignore-errors (slot-value val name)))
1202 (set-table-if-needed (val)
1204 (sql-ident-attribute
1206 (if (sv val 'qualifier)
1208 (make-instance 'sql-ident-attribute
1209 :name (sv val 'name)
1210 :qualifier table-name))
1212 ;; TODO: Check for a specific error we expect
1214 (cons (cons (set-table-if-needed (car val))
1218 (loop for i from 0 below (length order-by-list)
1219 for id in order-by-list
1220 collect (set-table-if-needed id))))
1221 (setf (getf qualifier-args :order-by) order-by-list))))
1225 (apply #'find-all target-args :result-types result-types :refresh refresh qualifier-args))
1227 (let ((cached (records-cache-results target-args qualifier-args database)))
1228 (if (and cached (not refresh))
1230 (let ((results (apply #'find-all target-args
1231 :result-types :auto :refresh refresh
1234 (setf (records-cache-results target-args qualifier-args database) results)
1238 (let* ((expr (apply #'make-query select-all-args))
1239 (parameters (second (member :parameters select-all-args)))
1241 (mapcar #'(lambda (attrib)
1242 (if (typep attrib 'sql-ident-attribute)
1243 (let ((type (slot-value attrib 'type)))
1248 (slot-value expr 'selections)))
1249 (flatp (getf qualifier-args :flatp))
1250 (field-names (getf qualifier-args :field-names t)))
1253 (setf expr (command-object (sql-output expr database) parameters)))
1254 (query expr :flatp flatp
1256 ;; specifying a type for an attribute overrides result-types
1257 (if (some #'(lambda (x) (not (eq t x))) specified-types)
1260 :field-names field-names
1261 :database database)))))))
1263 (defun compute-records-cache-key (targets qualifiers)
1265 (do ((args *select-arguments* (cdr args))
1267 ((null args) results)
1268 (let* ((arg (car args))
1269 (value (getf qualifiers arg)))
1273 (cons (cons (sql (car value)) (cdr value)))
1274 (%sql-expression (sql value))
1278 (defun records-cache-results (targets qualifiers database)
1279 (when (record-caches database)
1280 (gethash (compute-records-cache-key targets qualifiers) (record-caches database))))
1282 (defun (setf records-cache-results) (results targets qualifiers database)
1283 (unless (record-caches database)
1284 (setf (record-caches database)
1285 (make-weak-hash-table :test 'equal)))
1286 (setf (gethash (compute-records-cache-key (copy-list targets) qualifiers)
1287 (record-caches database)) results)
1292 ;;; Serialization functions
1294 (defun write-instance-to-stream (obj stream)
1295 "Writes an instance to a stream where it can be later be read.
1296 NOTE: an error will occur if a slot holds a value which can not be written readably."
1297 (let* ((class (class-of obj))
1299 (dolist (slot (ordered-class-slots (class-of obj)))
1300 (let ((name (slot-definition-name slot)))
1301 (when (and (not (eq 'view-database name))
1302 (slot-boundp obj name))
1303 (push (cons name (slot-value obj name)) alist))))
1304 (setq alist (reverse alist))
1305 (write (cons (class-name class) alist) :stream stream :readably t))
1308 (defun read-instance-from-stream (stream)
1309 (let ((raw (read stream nil nil)))
1311 (let ((obj (make-instance (car raw))))
1312 (dolist (pair (cdr raw))
1313 (setf (slot-value obj (car pair)) (cdr pair)))