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 generate-retrieval-joins-list (class retrieval-method)
51 "Returns list of immediate join slots for a class."
52 (setf class (to-class class))
53 (loop for slot in (ordered-class-slots class)
54 when (eql (join-slot-retrieval-method slot) retrieval-method)
57 (defun immediate-join-slots (class)
58 (generate-retrieval-joins-list class :immediate))
60 (defmethod choose-database-for-instance ((obj standard-db-object) &optional database)
61 "Determine which database connection to use for a standard-db-object.
62 Errs if none is available."
63 (or (find-if #'(lambda (db)
64 (and db (is-database-open db)))
65 (list (view-database obj)
68 (signal-no-database-error nil)))
72 (defmethod update-slot-with-null ((object standard-db-object) slotdef)
73 "sets a slot to the void value of the slot-def (usually nil)"
74 (setf (easy-slot-value object slotdef)
75 (slot-value slotdef 'void-value)))
77 (defmethod update-slot-from-db-value ((instance standard-db-object) slotdef value)
78 "This gets a value from the database and turns it itno a lisp value
79 based on the slot's slot-db-reader or baring that read-sql-value"
80 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
81 (let* ((slot-reader (view-class-slot-db-reader slotdef))
82 (slot-type (specified-type slotdef)))
84 ((null value) (update-slot-with-null instance slotdef))
86 (setf (easy-slot-value instance slotdef)
87 (read-sql-value value (delistify slot-type)
88 (choose-database-for-instance instance)
89 (database-underlying-type
90 (choose-database-for-instance instance)))))
91 (t (etypecase slot-reader
93 (setf (easy-slot-value instance slotdef)
94 (apply slot-reader (list value))))
96 (setf (easy-slot-value instance slotdef)
97 (format nil slot-reader value))))))))
99 (defmethod key-value-from-db (slotdef value database)
100 "TODO: is this deprecated? there are no uses anywhere in clsql"
101 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
102 (let ((slot-reader (view-class-slot-db-reader slotdef))
103 (slot-type (specified-type slotdef)))
104 (cond ((and value (null slot-reader))
105 (read-sql-value value (delistify slot-type) database
106 (database-underlying-type database)))
109 ((typep slot-reader 'string)
110 (format nil slot-reader value))
111 ((typep slot-reader '(or symbol function))
112 (apply slot-reader (list value)))
114 (error "Slot reader is of an unusual type.")))))
116 (defun db-value-from-slot (slotdef val database)
117 (let ((dbwriter (view-class-slot-db-writer slotdef))
118 (dbtype (specified-type slotdef)))
120 (string (format nil dbwriter val))
121 ((and (or symbol function) (not null)) (apply dbwriter (list val)))
123 (database-output-sql-as-type
127 val database (database-underlying-type database))))))
129 (defun check-slot-type (slotdef val)
130 (let* ((slot-type (specified-type slotdef))
131 (basetype (if (listp slot-type) (car slot-type) slot-type)))
132 (when (and slot-type val)
133 (unless (typep val basetype)
134 (error 'sql-user-error
136 (format nil "Invalid value ~A in slot ~A, not of type ~A."
137 val (slot-definition-name slotdef) slot-type))))))
139 (defmethod get-slot-values-from-view (obj slotdeflist values)
140 "Used to copy values from the database into the object
141 used by things like find-all and select"
142 (loop for slot in slotdeflist
144 do (update-slot-from-db-value obj slot value))
147 (defclass class-and-slots ()
148 ((view-class :accessor view-class :initarg :view-class :initform nil)
149 (slot-defs :accessor slot-defs :initarg :slot-defs :initform nil))
150 (:documentation "A helper class to keep track of which slot-defs from a
151 table need to be updated, a normalized class might have many of these
152 because each of its parent classes might represent some other table and we
153 need to match which slots came from which parent class/table"))
155 (defun make-class-and-slots (c &optional s)
156 "Create a new class-and-slots object"
157 (make-instance 'class-and-slots :view-class c :slot-defs (listify s) ))
159 (defmethod view-table ((o class-and-slots))
160 "get the view-table of the view-class of o"
161 (view-table (view-class o)))
163 (defmethod view-table-exp ((o class-and-slots))
164 (sql-expression :table (view-table o)))
166 (defmethod view-table-exp ((o standard-db-class))
167 (sql-expression :table (view-table o)))
169 (defmethod attribute-references ((o class-and-slots))
170 "build sql-ident-attributes for a given class-and-slots"
172 with class = (view-class o)
173 for sd in (slot-defs o)
174 collect (generate-attribute-reference class sd)))
176 (defmethod attribute-value-pairs ((def class-and-slots) (o standard-db-object)
178 "for a given class-and-slots and object, create the sql-expression & value pairs
179 that need to be sent to the database"
180 (loop for s in (slot-defs def)
181 for n = (to-slot-name s)
182 when (slot-boundp o n)
183 collect (make-attribute-value-pair s (slot-value o n) database)))
185 (defmethod view-classes-and-slots-by-name ((obj standard-db-object) slots-to-match)
186 "If it's normalized, find the class that actually contains
187 the slot that's tied to the db,
189 otherwise just search the current class
191 (let* ((view-class (class-of obj))
192 (normalizedp (normalizedp view-class))
194 (labels ((get-c&s-obj (class)
195 (or (find class rtns :key #'view-class)
196 (first (push (make-class-and-slots class) rtns))))
197 (associate-slot-with-class (class slot)
198 "Find the best class to associate with the slot. If it is
199 normalized then it needs to be a direct slot otherwise it just
200 needs to be on the class."
201 (let ((sd (find-slot-by-name class slot normalizedp nil)))
203 ;;we found it directly or it's (not normalized)
204 (pushnew sd (slot-defs (get-c&s-obj class)))
206 (loop for parent in (class-direct-superclasses class)
207 until (associate-slot-with-class parent slot))))
210 for in-slot in (listify slots-to-match)
211 do (associate-slot-with-class view-class in-slot)))
214 (defun update-auto-increments-keys (class obj database)
215 " handle pulling any autoincrement values into the object
216 if normalized and we now that all the "
217 (let ((pk-slots (keyslots-for-class class))
218 (table (view-table class))
220 (labels ((do-update (slot)
221 (when (and (null (easy-slot-value obj slot))
222 (auto-increment-column-p slot database))
223 (update-slot-from-db-value
227 (database-last-auto-increment-id
228 database table slot))))))
229 (chain-primary-keys (in-class)
230 "This seems kindof wrong, but this is mostly how it was working, so
231 its here to keep the normalized code path working"
232 (when (typep in-class 'standard-db-class)
233 (loop for slot in (ordered-class-slots in-class)
234 when (key-slot-p slot)
235 do (do-update slot)))))
236 (loop for slot in pk-slots do (do-update slot))
237 (let ((direct-class (to-class obj)))
238 (when (and new-pk-value (normalizedp direct-class))
239 (chain-primary-keys direct-class)))
242 (defmethod %update-instance-helper
243 (class-and-slots obj database
244 &aux (avps (attribute-value-pairs class-and-slots obj database)))
245 "A function to help us update a given table (based on class-and-slots)
246 with values from an object"
247 ;; we dont actually need to update anything on this particular
248 ;; class / parent class
249 (unless avps (return-from %update-instance-helper))
251 (let* ((view-class (view-class class-and-slots))
252 (table (view-table view-class))
253 (table-sql (sql-expression :table table)))
255 ;; view database is the flag we use to tell it was pulled from a database
256 ;; and thus probably needs an update instead of an insert
257 (cond ((view-database obj)
258 (let ((where (key-qualifier-for-instance
259 obj :database database :this-class view-class)))
261 (error "update-record-from-*: could not generate a where clause for ~a using ~A"
263 (update-records table-sql
266 :database database)))
267 (T ;; was not pulled from the db so insert it
268 ;; avps MUST contain any primary key slots set
269 ;; by previous inserts of the same object into different
270 ;; tables (ie: normalized stuff)
271 (insert-records :into table-sql
274 (update-auto-increments-keys view-class obj database)
275 ;; we dont set view database here, because there could be
276 ;; N of these for each call to update-record-from-* because
277 ;; of normalized classes
279 (update-slot-default-values obj class-and-slots)))
281 (defmethod update-record-from-slots ((obj standard-db-object) slots
282 &key (database *default-database*))
283 "For a given list of slots, update all records associated with those slots
286 Generally this will update the single record associated with this object,
287 but for normalized classes might update as many records as there are
289 (setf slots (listify slots))
290 (let* ((classes-and-slots (view-classes-and-slots-by-name obj slots))
291 (database (choose-database-for-instance obj database)))
292 (loop for class-and-slots in classes-and-slots
293 do (%update-instance-helper class-and-slots obj database))
294 (setf (slot-value obj 'view-database) database))
297 (defmethod update-record-from-slot
298 ((obj standard-db-object) slot &key (database *default-database*))
299 "just call update-records-from-slots which now handles this.
301 This function is only here to maintain backwards compatibility in
303 (update-record-from-slots obj slot :database database))
305 (defun view-classes-and-storable-slots (class)
306 "Get a list of all the tables we need to update and the slots on them
308 for non normalized classes we return the class and all its storable slots
310 for normalized classes we return a list of direct slots and the class they
311 came from for each normalized view class
313 (setf class (to-class class))
315 (labels ((storable-slots (class)
316 (loop for sd in (slots-for-possibly-normalized-class class)
317 when (key-or-base-slot-p sd)
319 (get-classes-and-slots (class &aux (normalizedp (normalizedp class)))
320 (let ((slots (storable-slots class)))
322 (push (make-class-and-slots class slots) rtns)))
324 (loop for new-class in (class-direct-superclasses class)
325 do (when (typep new-class 'standard-db-class)
326 (get-classes-and-slots new-class))))))
327 (get-classes-and-slots class))
330 (defmethod primary-key-slot-values ((obj standard-db-object)
332 "Returns the values of all key-slots for a given class"
333 (defaulting class (class-of obj)
334 slots (keyslots-for-class class))
335 (loop for slot in slots
336 collect (easy-slot-value obj slot)))
338 (defmethod update-slot-default-values ((obj standard-db-object)
340 "Makes sure that if a class has unfilled slots that claim to have a default,
341 that we retrieve those defaults from the database
343 TODO: use update slots-from-record instead to batch this!"
344 (loop for class-and-slots in (listify classes-and-slots)
345 do (loop for slot in (slot-defs class-and-slots)
346 do (when (and (slot-has-default-p slot)
347 (not (easy-slot-value obj slot)))
348 (update-slot-from-record obj (to-slot-name slot))))))
350 (defmethod update-records-from-instance ((obj standard-db-object)
351 &key (database *default-database*))
352 "Updates the records in the database associated with this object if
353 view-database slot on the object is nil then the object is assumed to be
355 (let ((database (choose-database-for-instance obj database))
356 (classes-and-slots (view-classes-and-storable-slots obj)))
357 (loop for class-and-slots in classes-and-slots
358 do (%update-instance-helper class-and-slots obj database))
359 (setf (slot-value obj 'view-database) database)
360 (primary-key-slot-values obj)))
362 (defmethod delete-instance-records ((instance standard-db-object) &key database)
363 "Removes the records associated with a given instance
364 (as determined by key-qualifier-for-instance)
366 TODO: Doesnt handle normalized classes at all afaict"
367 (let ((database (choose-database-for-instance instance database))
368 (vt (sql-expression :table (view-table (class-of instance)))))
370 (let ((qualifier (key-qualifier-for-instance instance :database database)))
371 (delete-records :from vt :where qualifier :database database)
372 (setf (record-caches database) nil)
373 (setf (slot-value instance 'view-database) nil)
375 (signal-no-database-error database))))
377 (defmethod update-instance-from-records ((instance standard-db-object)
378 &key (database *default-database*))
379 "Updates a database object with the current values stored in the database
381 TODO: Should this update immediate join slots similar to build-objects?
382 Can we just call build-objects?, update-objects-joins?
385 (let* ((classes-and-slots (view-classes-and-storable-slots instance))
386 (vd (choose-database-for-instance instance database)))
387 (labels ((do-update (class-and-slots)
388 (let* ((select-list (make-select-list class-and-slots :do-joins-p nil))
389 (view-table (sql-table select-list))
390 (view-qual (key-qualifier-for-instance
391 instance :database vd
392 :this-class (view-class select-list)))
396 (append (full-select-list select-list)
397 (list :from view-table
402 (setf (slot-value instance 'view-database) vd)
403 (get-slot-values-from-view instance (slot-list select-list) res))
405 (loop for class-and-slots in classes-and-slots
406 do (do-update class-and-slots)))))
409 (defmethod get-slot-value-from-record ((instance standard-db-object)
410 slot &key (database *default-database*))
411 (let* ((class-and-slot
413 (view-classes-and-slots-by-name instance slot)))
414 (view-class (view-class class-and-slot))
415 (slot-def (first (slot-defs class-and-slot)))
416 (vd (choose-database-for-instance instance database))
417 (att-ref (first (attribute-references class-and-slot)))
420 :from (view-table-exp class-and-slot)
421 :where (key-qualifier-for-instance
424 :this-class view-class)
427 (values res slot-def)))
429 (defmethod update-slot-from-record ((instance standard-db-object)
430 slot &key (database *default-database*))
431 "Pulls the value of a given slot form the database and stores that in the
432 appropriate slot on instance"
433 (multiple-value-bind (res slot-def)
434 (get-slot-value-from-record instance slot :database database)
435 (let ((vd (choose-database-for-instance instance database)))
436 (setf (slot-value instance 'view-database) vd)
437 (update-slot-from-db-value instance slot-def res))))
440 (defvar +no-slot-value+ '+no-slot-value+)
442 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
443 (let* ((class (find-class classname))
444 (sld (slotdef-for-slot-with-class slot class)))
446 (if (eq value +no-slot-value+)
447 (sql-expression :attribute (database-identifier sld database)
448 :table (view-table class))
453 (error "Unknown slot ~A for class ~A" slot classname))))
455 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
456 (declare (ignore database))
457 (let* ((class (find-class classname)))
458 (unless (view-table class)
459 (error "No view-table for class ~A" classname))
460 (sql-expression :table (view-table class))))
463 (defmethod database-get-type-specifier (type args database db-type)
464 (declare (ignore type args database db-type))
465 (format nil "VARCHAR(~D)" *default-string-length*))
467 (defmethod database-get-type-specifier ((type (eql 'integer)) args database db-type)
468 (declare (ignore database db-type))
470 (format nil "INT(~A)" (car args))
474 "An 8-bit integer, this width may vary by SQL implementation."
477 (defmethod database-get-type-specifier ((type (eql 'tinyint)) args database db-type)
478 (declare (ignore args database db-type))
482 "An integer smaller than a 32-bit integer. this width may vary by SQL implementation."
485 (defmethod database-get-type-specifier ((type (eql 'smallint)) args database db-type)
486 (declare (ignore args database db-type))
489 (deftype mediumint ()
490 "An integer smaller than a 32-bit integer, but may be larger than a smallint. This width may vary by SQL implementation."
493 (defmethod database-get-type-specifier ((type (eql 'mediumint)) args database db-type)
494 (declare (ignore args database db-type))
498 "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
501 (defmethod database-get-type-specifier ((type (eql 'bigint)) args database db-type)
502 (declare (ignore args database db-type))
505 (deftype varchar (&optional size)
506 "A variable length string for the SQL varchar type."
507 (declare (ignore size))
510 (defmethod database-get-type-specifier ((type (eql 'varchar)) args
512 (declare (ignore database db-type))
514 (format nil "VARCHAR(~A)" (car args))
515 (format nil "VARCHAR(~D)" *default-string-length*)))
517 (defmethod database-get-type-specifier ((type (eql 'string)) args database db-type)
518 (declare (ignore database db-type))
520 (format nil "CHAR(~A)" (car args))
521 (format nil "VARCHAR(~D)" *default-string-length*)))
523 (deftype universal-time ()
524 "A positive integer as returned by GET-UNIVERSAL-TIME."
527 (defmethod database-get-type-specifier ((type (eql 'universal-time)) args database db-type)
528 (declare (ignore args database db-type))
531 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database db-type)
532 (declare (ignore args database db-type))
535 (defmethod database-get-type-specifier ((type (eql 'date)) args database db-type)
536 (declare (ignore args database db-type))
539 (defmethod database-get-type-specifier ((type (eql 'duration)) args database db-type)
540 (declare (ignore database args db-type))
543 (defmethod database-get-type-specifier ((type (eql 'money)) args database db-type)
544 (declare (ignore database args db-type))
548 (deftype char (&optional len)
549 "A lisp type for the SQL CHAR type."
552 (defmethod database-get-type-specifier ((type (eql 'float)) args database db-type)
553 (declare (ignore database db-type))
555 (format nil "FLOAT(~A)" (car args))
558 (defmethod database-get-type-specifier ((type (eql 'long-float)) args database db-type)
559 (declare (ignore database db-type))
561 (format nil "FLOAT(~A)" (car args))
564 (deftype generalized-boolean ()
565 "A type which outputs a SQL boolean value, though any lisp type can be stored in the slot."
568 (defmethod database-get-type-specifier ((type (eql 'boolean)) args database db-type)
569 (declare (ignore args database db-type))
572 (defmethod database-get-type-specifier ((type (eql 'generalized-boolean)) args database db-type)
573 (declare (ignore args database db-type))
576 (defmethod database-get-type-specifier ((type (eql 'number)) args database db-type)
577 (declare (ignore database db-type))
579 ((and (consp args) (= (length args) 2))
580 (format nil "NUMBER(~D,~D)" (first args) (second args)))
581 ((and (consp args) (= (length args) 1))
582 (format nil "NUMBER(~D)" (first args)))
586 (defmethod database-get-type-specifier ((type (eql 'char)) args database db-type)
587 (declare (ignore database db-type))
589 (format nil "CHAR(~D)" (first args))
593 (defmethod database-output-sql-as-type (type val database db-type)
594 (declare (ignore type database db-type))
597 (defmethod database-output-sql-as-type ((type (eql 'list)) val database db-type)
598 (declare (ignore database db-type))
599 (progv '(*print-circle* *print-array*) '(t t)
600 (let ((escaped (prin1-to-string val)))
601 (substitute-char-string
602 escaped #\Null " "))))
604 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database db-type)
605 (declare (ignore database db-type))
608 (package-name (symbol-package val))
613 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database db-type)
614 (declare (ignore database db-type))
619 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database db-type)
620 (declare (ignore database db-type))
621 (progv '(*print-circle* *print-array*) '(t t)
622 (prin1-to-string val)))
624 (defmethod database-output-sql-as-type ((type (eql 'array)) val database db-type)
625 (declare (ignore database db-type))
626 (progv '(*print-circle* *print-array*) '(t t)
627 (prin1-to-string val)))
629 (defmethod database-output-sql-as-type ((type (eql 'boolean)) val database db-type)
630 (declare (ignore database db-type))
633 (defmethod database-output-sql-as-type ((type (eql 'generalized-boolean)) val database db-type)
634 (declare (ignore database db-type))
637 (defmethod database-output-sql-as-type ((type (eql 'string)) val database db-type)
638 (declare (ignore database db-type))
641 (defmethod database-output-sql-as-type ((type (eql 'char)) val database db-type)
642 (declare (ignore database db-type))
644 (character (write-to-string val))
647 (defmethod database-output-sql-as-type ((type (eql 'float)) val database db-type)
648 (declare (ignore database db-type))
649 (if (eq (type-of val) 'null)
651 (let ((*read-default-float-format* (type-of val)))
652 (format nil "~F" val))))
654 (defmethod read-sql-value (val type database db-type)
655 (declare (ignore database db-type))
657 ((null type) val) ;;we have no desired type, just give the value
658 ((typep val type) val) ;;check that it hasn't already been converted.
659 ((typep val 'string) (read-from-string val)) ;;maybe read will just take care of it?
660 (T (error "Unable to read-sql-value ~a as type ~a" val type))))
662 (defmethod read-sql-value (val (type (eql 'string)) database db-type)
663 (declare (ignore database db-type))
666 (defmethod read-sql-value (val (type (eql 'varchar)) database db-type)
667 (declare (ignore database db-type))
670 (defmethod read-sql-value (val (type (eql 'char)) database db-type)
671 (declare (ignore database db-type))
674 (defmethod read-sql-value (val (type (eql 'keyword)) database db-type)
675 (declare (ignore database db-type))
676 (when (< 0 (length val))
677 (intern (symbol-name-default-case val)
678 (find-package '#:keyword))))
680 (defmethod read-sql-value (val (type (eql 'symbol)) database db-type)
681 (declare (ignore database db-type))
682 (when (< 0 (length val))
683 (unless (string= val (symbol-name-default-case "NIL"))
684 (read-from-string val))))
686 (defmethod read-sql-value (val (type (eql 'integer)) database db-type)
687 (declare (ignore database db-type))
690 (unless (string-equal "NIL" val)
691 (parse-integer val)))
694 (defmethod read-sql-value (val (type (eql 'smallint)) database db-type)
695 (declare (ignore database db-type))
698 (unless (string-equal "NIL" val)
699 (parse-integer val)))
702 (defmethod read-sql-value (val (type (eql 'bigint)) database db-type)
703 (declare (ignore database db-type))
706 (unless (string-equal "NIL" val)
707 (parse-integer val)))
710 (defmethod read-sql-value (val (type (eql 'float)) database db-type)
711 (declare (ignore database db-type))
712 ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
714 (string (float (read-from-string val)))
717 (defmethod read-sql-value (val (type (eql 'double-float)) database db-type)
718 (declare (ignore database db-type))
719 ;; writing 1.0 writes 1, so if we *really* want a float, must do (float ...)
722 (let ((*read-default-float-format* 'double-float))
723 (read-from-string val))
726 (float (coerce val 'double-float))))
728 (defmethod read-sql-value (val (type (eql 'boolean)) database db-type)
729 (declare (ignore database db-type))
732 (defmethod read-sql-value (val (type (eql 'generalized-boolean)) database db-type)
733 (declare (ignore database db-type))
736 (defmethod read-sql-value (val (type (eql 'number)) database db-type)
737 (declare (ignore database db-type))
740 (unless (string-equal "NIL" val)
741 (read-from-string val)))
744 (defmethod read-sql-value (val (type (eql 'universal-time)) database db-type)
745 (declare (ignore database db-type))
746 (unless (eq 'NULL val)
752 (defmethod read-sql-value (val (type (eql 'wall-time)) database db-type)
753 (declare (ignore database db-type))
754 (unless (eq 'NULL val)
755 (parse-timestring val)))
757 (defmethod read-sql-value (val (type (eql 'date)) database db-type)
758 (declare (ignore database db-type))
759 (unless (eq 'NULL val)
760 (parse-datestring val)))
762 (defmethod read-sql-value (val (type (eql 'duration)) database db-type)
763 (declare (ignore database db-type))
764 (unless (or (eq 'NULL val)
766 (parse-timestring val)))
768 ;; ------------------------------------------------------------
769 ;; Logic for 'faulting in' :join slots
771 ;; this works, but is inefficient requiring (+ 1 n-rows)
774 (defun fault-join-target-slot (class object slot-def)
775 (let* ((res (fault-join-slot-raw class object slot-def))
776 (dbi (view-class-slot-db-info slot-def))
777 (target-name (gethash :target-slot dbi))
778 (target-class (find-class target-name)))
780 (mapcar (lambda (obj)
786 (find target-name (class-slots (class-of obj))
787 :key #'slot-definition-name)))
790 #+ignore ;; this doesn't work when attempting to call slot-value
791 (mapcar (lambda (obj)
792 (cons obj (slot-value obj ts))) res))))
794 (defun fault-join-target-slot (class object slot-def)
795 (let* ((dbi (view-class-slot-db-info slot-def))
796 (ts (gethash :target-slot dbi))
797 (jc (gethash :join-class dbi))
798 (jc-view-table (view-table (find-class jc)))
799 (tdbi (view-class-slot-db-info
800 (find ts (class-slots (find-class jc))
801 :key #'slot-definition-name)))
802 (retrieval (gethash :retrieval tdbi))
803 (tsc (gethash :join-class tdbi))
804 (ts-view-table (view-table (find-class tsc)))
805 (jq (join-qualifier class object slot-def))
806 (key (slot-value object (gethash :home-key dbi))))
813 :inner-join (sql-expression :table jc-view-table)
817 :attribute (gethash :foreign-key tdbi)
818 :table ts-view-table)
820 :attribute (gethash :home-key tdbi)
821 :table jc-view-table))
824 :database (choose-database-for-instance object))))
825 (mapcar #'(lambda (i)
826 (let* ((instance (car i))
827 (jcc (make-instance jc :view-database (choose-database-for-instance instance))))
828 (setf (slot-value jcc (gethash :foreign-key dbi))
830 (setf (slot-value jcc (gethash :home-key tdbi))
831 (slot-value instance (gethash :foreign-key tdbi)))
832 (list instance jcc)))
835 ;; just fill in minimal slots
838 (let ((instance (make-instance tsc :view-database (choose-database-for-instance object)))
839 (jcc (make-instance jc :view-database (choose-database-for-instance object)))
841 (setf (slot-value instance (gethash :home-key tdbi)) fk)
842 (setf (slot-value jcc (gethash :foreign-key dbi))
844 (setf (slot-value jcc (gethash :home-key tdbi))
846 (list instance jcc)))
847 (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
848 :from (sql-expression :table jc-view-table)
850 :database (choose-database-for-instance object))))))))
855 (defvar *default-update-objects-max-len* nil
856 "The default value to use for the MAX-LEN keyword argument to
857 UPDATE-OBJECT-JOINS.")
859 (defun update-objects-joins (objects &key (slots t) (force-p t)
861 *default-update-objects-max-len*))
862 "Updates from the records of the appropriate database tables
863 the join slots specified by SLOTS in the supplied list of View
864 Class instances OBJECTS. SLOTS is t by default which means that
865 all join slots with :retrieval :immediate are updated. CLASS-NAME
866 is used to specify the View Class of all instance in OBJECTS and
867 default to nil which means that the class of the first instance
868 in OBJECTS is used. FORCE-P is t by default which means that all
869 join slots are updated whereas a value of nil means that only
870 unbound join slots are updated. MAX-LEN defaults to
871 *DEFAULT-UPDATE-OBJECTS-MAX-LEN* and when non-nil specifies that
872 UPDATE-OBJECT-JOINS may issue multiple database queries with a
873 maximum of MAX-LEN instances updated in each query."
874 (assert (or (null max-len) (plusp max-len)))
877 (setq class-name (class-name (class-of (first objects)))))
878 (let* ((class (find-class class-name))
879 (class-slots (ordered-class-slots class))
882 (generate-retrieval-joins-list class :deferred)
884 (mapcar #'(lambda (name)
885 (let ((slotdef (find name class-slots :key #'slot-definition-name)))
887 (warn "Unable to find slot named ~S in class ~S." name class))
890 (dolist (slotdef slotdefs)
891 (let* ((dbi (view-class-slot-db-info slotdef))
892 (slotdef-name (slot-definition-name slotdef))
893 (foreign-key (gethash :foreign-key dbi))
894 (home-key (gethash :home-key dbi))
898 (mapcar #'(lambda (o) (slot-value o home-key)) objects)
901 #'(lambda (o) (if (slot-boundp o slotdef-name)
903 (slot-value o home-key)))
905 (n-object-keys (length object-keys))
906 (query-len (or max-len n-object-keys)))
908 (do ((i 0 (+ i query-len)))
909 ((>= i n-object-keys))
910 (let* ((keys (if max-len
911 (subseq object-keys i (min (+ i query-len) n-object-keys))
913 (results (unless (gethash :target-slot dbi)
914 (find-all (list (gethash :join-class dbi))
915 :where (make-instance 'sql-relational-exp
917 :sub-expressions (list (sql-expression :attribute foreign-key)
922 (dolist (object objects)
923 (when (or force-p (not (slot-boundp object slotdef-name)))
924 (let ((res (if results
925 (remove-if-not #'(lambda (obj)
926 (equal obj (slot-value
935 (when (gethash :target-slot dbi)
936 (fault-join-target-slot class object slotdef))))))
938 (setf (slot-value object slotdef-name)
939 (if (gethash :set dbi) res (car res)))))))))))))
942 (defun fault-join-slot-raw (class object slot-def)
943 (let* ((dbi (view-class-slot-db-info slot-def))
944 (jc (gethash :join-class dbi)))
945 (let ((jq (join-qualifier class object slot-def)))
947 (select jc :where jq :flatp t :result-types nil
948 :database (choose-database-for-instance object))))))
952 (defun fault-join-slot (class object slot-def)
953 (let* ((dbi (view-class-slot-db-info slot-def))
954 (ts (gethash :target-slot dbi))
955 (dbi-set (gethash :set dbi)))
957 (fault-join-target-slot class object slot-def)
958 (let ((res (fault-join-slot-raw class object slot-def)))
961 ((and ts (not dbi-set))
962 (mapcar (lambda (obj) (slot-value obj ts)) res))
963 ((and (not ts) (not dbi-set))
965 ((and (not ts) dbi-set)
968 (defun update-fault-join-normalized-slot (class object slot-def)
969 (if (and (normalizedp class) (key-slot-p slot-def))
970 (setf (easy-slot-value object slot-def)
971 (normalized-key-value object))
972 (update-slot-from-record object slot-def)))
974 (defun all-home-keys-have-values-p (object slot-def)
975 "Do all of the home-keys have values ?"
976 (let ((home-keys (join-slot-info-value slot-def :home-key)))
977 (loop for key in (listify home-keys)
978 always (easy-slot-value object key))))
980 (defun join-qualifier (class object slot-def)
981 "Builds the join where clause based on the keys of the join slot and values
983 (declare (ignore class))
984 (let* ((jc (join-slot-class slot-def))
985 ;;(ts (gethash :target-slot dbi))
986 ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
987 (foreign-keys (listify (join-slot-info-value slot-def :foreign-key)))
988 (home-keys (listify (join-slot-info-value slot-def :home-key))))
989 (when (all-home-keys-have-values-p object slot-def)
991 (loop for hk in home-keys
992 for fk in foreign-keys
993 for fksd = (slotdef-for-slot-with-class fk jc)
994 for fk-sql = (typecase fk
997 :attribute (database-identifier fksd nil)
998 :table (database-identifier jc nil)))
1000 for hk-val = (typecase hk
1002 view-class-effective-slot-definition
1003 view-class-direct-slot-definition)
1004 (easy-slot-value object hk))
1006 collect (sql-operation '== fk-sql hk-val))))))
1008 (defmethod select-table-sql-expr ((table T))
1009 "Turns an object representing a table into the :from part of the sql expression that will be executed "
1010 (sql-expression :table (view-table table)))
1012 (defun select-reference-equal (r1 r2)
1013 "determines if two sql select references are equal
1014 using database identifier equal"
1018 (sql-ident-attribute r))))
1019 (database-identifier-equal (id-of r1) (id-of r2))))
1021 (defun join-slot-qualifier (class join-slot)
1022 "Creates a sql-expression expressing the join between the home-key on the table
1023 and its respective key on the joined-to-table"
1027 :attribute (join-slot-info-value join-slot :foreign-key)
1028 :table (view-table (join-slot-class join-slot)))
1030 :attribute (join-slot-info-value join-slot :home-key)
1031 :table (view-table class))))
1033 (defun all-immediate-join-classes-for (classes)
1034 "returns a list of all join-classes needed for a list of classes"
1035 (loop for class in (listify classes)
1036 appending (loop for slot in (immediate-join-slots class)
1037 collect (join-slot-class slot))))
1039 (defun %tables-for-query (classes from where inner-joins)
1040 "Given lists of classes froms wheres and inner-join compile a list
1041 of tables that should appear in the FROM section of the query.
1043 This includes any immediate join classes from each of the classes"
1044 (let ((inner-join-tables (collect-table-refs (listify inner-joins))))
1045 (loop for tbl in (append
1046 (mapcar #'select-table-sql-expr classes)
1047 (mapcar #'select-table-sql-expr
1048 (all-immediate-join-classes-for classes))
1049 (collect-table-refs (listify where))
1050 (collect-table-refs (listify from)))
1052 (not (find tbl rtn :test #'database-identifier-equal))
1053 ;; TODO: inner-join is currently hacky as can be
1054 (not (find tbl inner-join-tables :test #'database-identifier-equal)))
1055 collect tbl into rtn
1056 finally (return rtn))))
1059 (defclass select-list ()
1060 ((view-class :accessor view-class :initarg :view-class :initform nil)
1061 (select-list :accessor select-list :initarg :select-list :initform nil)
1062 (slot-list :accessor slot-list :initarg :slot-list :initform nil)
1063 (joins :accessor joins :initarg :joins :initform nil)
1064 (join-slots :accessor join-slots :initarg :join-slots :initform nil))
1066 "Collects the classes, slots and their respective sql representations
1067 so that update-instance-from-recors, find-all, build-objects can share this
1068 info and calculate it once. Joins are select-lists for each immediate join-slot
1069 but only if make-select-list is called with do-joins-p"))
1071 (defmethod view-table ((o select-list))
1072 (view-table (view-class o)))
1074 (defmethod sql-table ((o select-list))
1075 (sql-expression :table (view-table o)))
1077 (defun make-select-list (class-and-slots &key (do-joins-p nil))
1078 "Make a select-list for the current class (or class-and-slots) object."
1079 (let* ((class-and-slots
1080 (etypecase class-and-slots
1081 (class-and-slots class-and-slots)
1082 ((or symbol standard-db-class)
1083 ;; find the first class with slots for us to select (this should be)
1084 ;; the first of its classes / parent-classes with slots
1085 (first (reverse (view-classes-and-storable-slots
1086 (to-class class-and-slots)))))))
1087 (class (view-class class-and-slots))
1088 (join-slots (when do-joins-p (immediate-join-slots class))))
1089 (multiple-value-bind (slots sqls)
1090 (loop for slot in (slot-defs class-and-slots)
1091 for sql = (generate-attribute-reference class slot)
1092 collect slot into slots
1093 collect sql into sqls
1094 finally (return (values slots sqls)))
1096 (error "No slots of type :base in view-class ~A" (class-name class)))
1102 :join-slots join-slots
1103 ;; only do a single layer of join objects
1104 :joins (when do-joins-p
1105 (loop for js in join-slots
1106 collect (make-select-list
1107 (join-slot-class js)
1108 :do-joins-p nil)))))))
1110 (defun full-select-list ( select-lists )
1111 "Returns a list of sql-ref of things to select for the given classes
1113 THIS NEEDS TO MATCH THE ORDER OF build-objects
1115 (loop for s in (listify select-lists)
1116 appending (select-list s)
1117 appending (loop for join in (joins s)
1118 appending (select-list join))))
1120 (defun build-objects (select-lists row database &optional existing-instances)
1121 "Used by find-all to build objects.
1123 THIS NEEDS TO MATCH THE ORDER OF FULL-SELECT-LIST
1125 TODO: this caching scheme seems bad for a number of reasons
1126 * order is not guaranteed so references being held by one object
1127 might change to represent a different database row (seems HIGHLY
1129 * also join objects are overwritten rather than refreshed
1131 TODO: the way we handle immediate joins seems only valid if it is a single
1132 object. I suspect that making a :set :immediate join column would result
1133 in an invalid number of objects returned from the database, because there
1134 would be multiple rows per object, but we would return an object per row
1136 (setf existing-instances (listify existing-instances))
1138 for select-list in select-lists
1139 for class = (view-class select-list)
1140 for existing = (pop existing-instances)
1141 for object = (or existing
1142 (make-instance class :view-database database))
1143 do (loop for slot in (slot-list select-list)
1144 do (update-slot-from-db-value object slot (pop row)))
1145 do (loop for join-slot in (join-slots select-list)
1146 for join in (joins select-list)
1147 for join-class = (view-class join)
1149 (setf (easy-slot-value object join-slot)
1150 (make-instance join-class))
1151 do (loop for slot in (slot-list join)
1152 do (update-slot-from-db-value join-object slot (pop row))))
1153 do (when existing (instance-refreshed object))
1156 (defun find-all (view-classes
1158 &key all set-operation distinct from where group-by having
1159 order-by offset limit refresh flatp result-types
1161 (database *default-database*)
1162 instances parameters)
1163 "Called by SELECT to generate object query results when the
1164 View Classes VIEW-CLASSES are passed as arguments to SELECT.
1166 TODO: the caching scheme of passing in instances and overwriting their
1167 values seems bad for a number of reasons
1168 * order is not guaranteed so references being held by one object
1169 might change to represent a different database row (seems HIGHLY
1172 TODO: the way we handle immediate joins seems only valid if it is a single
1173 object. I suspect that making a :set :immediate join column would result
1174 in an invalid number of objects returned from the database, because there
1175 would be multiple objects returned from the database
1177 (declare (ignore all set-operation group-by having offset limit on parameters
1179 (dynamic-extent args))
1180 (let* ((args (filter-plist
1181 args :from :where :flatp :additional-fields :result-types :instances))
1182 (*db-deserializing* t)
1183 (sclasses (mapcar #'to-class view-classes))
1184 (tables (%tables-for-query sclasses from where inner-join))
1186 (loop for class in sclasses
1187 appending (loop for slot in (immediate-join-slots class)
1188 collect (join-slot-qualifier class slot))))
1189 (select-lists (loop for class in sclasses
1190 collect (make-select-list class :do-joins-p t)))
1191 (full-select-list (full-select-list select-lists))
1192 (where (clsql-ands (append (listify where) (listify join-where))))
1194 (_ (format t "~&sclasses: ~W~%ijc: ~W~%tables: ~W~%"
1195 sclasses immediate-join-classes tables))
1197 (rows (apply #'select
1198 (append full-select-list
1200 :result-types result-types
1204 (loop for row in rows
1205 for old-objs = (pop instances)
1206 for objs = (build-objects select-lists row database
1207 (when refresh old-objs))
1208 collecting (if flatp
1209 (delist-if-single objs)
1213 (defmethod instance-refreshed ((instance standard-db-object)))
1215 (defvar *default-caching* t
1216 "Controls whether SELECT caches objects by default. The CommonSQL
1217 specification states caching is on by default.")
1219 (defun select (&rest select-all-args)
1220 "Executes a query on DATABASE, which has a default value of
1221 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
1222 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
1223 argument can be used to generate queries in both functional and
1224 object oriented contexts.
1226 In the functional case, the required arguments specify the
1227 columns selected by the query and may be symbolic SQL expressions
1228 or strings representing attribute identifiers. Type modified
1229 identifiers indicate that the values selected from the specified
1230 column are converted to the specified lisp type. The keyword
1231 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
1232 SET-OPERATION and WHERE are used to specify, using the symbolic
1233 SQL syntax, the corresponding components of the SQL query
1234 generated by the call to SELECT. RESULT-TYPES is a list of
1235 symbols which specifies the lisp type for each field returned by
1236 the query. If RESULT-TYPES is nil all results are returned as
1237 strings whereas the default value of :auto means that the lisp
1238 types are automatically computed for each field. FIELD-NAMES is t
1239 by default which means that the second value returned is a list
1240 of strings representing the columns selected by the query. If
1241 FIELD-NAMES is nil, the list of column names is not returned as a
1244 In the object oriented case, the required arguments to SELECT are
1245 symbols denoting View Classes which specify the database tables
1246 to query. In this case, SELECT returns a list of View Class
1247 instances whose slots are set from the attribute values of the
1248 records in the specified table. Slot-value is a legal operator
1249 which can be employed as part of the symbolic SQL syntax used in
1250 the WHERE keyword argument to SELECT. REFRESH is nil by default
1251 which means that the View Class instances returned are retrieved
1252 from a cache if an equivalent call to SELECT has previously been
1253 issued. If REFRESH is true, the View Class instances returned are
1254 updated as necessary from the database and the generic function
1255 INSTANCE-REFRESHED is called to perform any necessary operations
1256 on the updated instances.
1258 In both object oriented and functional contexts, FLATP has a
1259 default value of nil which means that the results are returned as
1260 a list of lists. If FLATP is t and only one result is returned
1261 for each record selected in the query, the results are returned
1262 as elements of a list."
1263 (multiple-value-bind (target-args qualifier-args)
1264 (query-get-selections select-all-args)
1265 (unless (or *default-database* (getf qualifier-args :database))
1266 (signal-no-database-error nil))
1268 (let ((caching (getf qualifier-args :caching *default-caching*))
1269 (result-types (getf qualifier-args :result-types :auto))
1270 (refresh (getf qualifier-args :refresh nil))
1271 (database (getf qualifier-args :database *default-database*)))
1275 (every #'(lambda (arg)
1277 (find-class arg nil)))
1280 (setf qualifier-args (filter-plist qualifier-args :caching :refresh :result-types))
1282 ;; Add explicity table name to order-by if not specified and only
1283 ;; one selected table. This is required so FIND-ALL won't duplicate
1285 (let ((order-by (getf qualifier-args :order-by)))
1286 (when (and order-by (= 1 (length target-args)))
1287 (let ((table-name (view-table (find-class (car target-args))))
1288 (order-by-list (copy-seq (listify order-by))))
1289 (labels ((sv (val name) (ignore-errors (slot-value val name)))
1290 (set-table-if-needed (val)
1292 (sql-ident-attribute
1294 (if (sv val 'qualifier)
1296 (make-instance 'sql-ident-attribute
1297 :name (sv val 'name)
1298 :qualifier table-name))
1300 ;; TODO: Check for a specific error we expect
1302 (cons (cons (set-table-if-needed (car val))
1306 (loop for i from 0 below (length order-by-list)
1307 for id in order-by-list
1308 collect (set-table-if-needed id))))
1309 (setf (getf qualifier-args :order-by) order-by-list))))
1313 (apply #'find-all target-args :result-types result-types :refresh refresh qualifier-args))
1315 (let ((cached (records-cache-results target-args qualifier-args database)))
1316 (if (and cached (not refresh))
1318 (let ((results (apply #'find-all target-args
1319 :result-types :auto :refresh refresh
1322 (setf (records-cache-results target-args qualifier-args database) results)
1326 (let* ((expr (apply #'make-query select-all-args))
1327 (parameters (second (member :parameters select-all-args)))
1329 (mapcar #'(lambda (attrib)
1330 (if (typep attrib 'sql-ident-attribute)
1331 (let ((type (slot-value attrib 'type)))
1336 (slot-value expr 'selections)))
1337 (flatp (getf qualifier-args :flatp))
1338 (field-names (getf qualifier-args :field-names t)))
1341 (setf expr (command-object (sql-output expr database) parameters)))
1342 (query expr :flatp flatp
1344 ;; specifying a type for an attribute overrides result-types
1345 (if (some #'(lambda (x) (not (eq t x))) specified-types)
1348 :field-names field-names
1349 :database database)))))))
1351 (defun compute-records-cache-key (targets qualifiers)
1353 (do ((args *select-arguments* (cdr args))
1355 ((null args) results)
1356 (let* ((arg (car args))
1357 (value (getf qualifiers arg)))
1361 (cons (cons (sql (car value)) (cdr value)))
1362 (%sql-expression (sql value))
1366 (defun records-cache-results (targets qualifiers database)
1367 (when (record-caches database)
1368 (gethash (compute-records-cache-key targets qualifiers) (record-caches database))))
1370 (defun (setf records-cache-results) (results targets qualifiers database)
1371 (unless (record-caches database)
1372 (setf (record-caches database)
1373 (make-weak-hash-table :test 'equal)))
1374 (setf (gethash (compute-records-cache-key (copy-list targets) qualifiers)
1375 (record-caches database)) results)
1380 ;;; Serialization functions
1382 (defun write-instance-to-stream (obj stream)
1383 "Writes an instance to a stream where it can be later be read.
1384 NOTE: an error will occur if a slot holds a value which can not be written readably."
1385 (let* ((class (class-of obj))
1387 (dolist (slot (ordered-class-slots (class-of obj)))
1388 (let ((name (slot-definition-name slot)))
1389 (when (and (not (eq 'view-database name))
1390 (slot-boundp obj name))
1391 (push (cons name (slot-value obj name)) alist))))
1392 (setq alist (reverse alist))
1393 (write (cons (class-name class) alist) :stream stream :readably t))
1396 (defun read-instance-from-stream (stream)
1397 (let ((raw (read stream nil nil)))
1399 (let ((obj (make-instance (car raw))))
1400 (dolist (pair (cdr raw))
1401 (setf (slot-value obj (car pair)) (cdr pair)))