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-slot-if obj #'key-slot-p T T))
18 (defun normalized-key-value (obj)
19 "Normalized classes share a single key for all their key slots"
20 (when (normalizedp (class-of obj))
21 (easy-slot-value obj (find-normalized-key obj))))
23 (defun key-qualifier-for-instance (obj &key (database *default-database*) this-class)
24 (let* ((obj-class (or this-class (class-of obj)))
25 (keys (keyslots-for-class obj-class))
26 (normal-db-value (normalized-key-value obj)))
28 (labels ((db-value (k)
32 (easy-slot-value obj k)
35 (sql-operation '== (generate-attribute-reference obj-class k database)
37 (clsql-ands (mapcar #'key-equal-exp keys))))))
39 (defun generate-attribute-reference (vclass slotdef &optional (database *default-database*))
40 "Turns key class and slot-def into a sql-expression representing the
41 table and column it comes from
43 used by things like generate-selection-list, update-slot-from-record"
44 (when (key-or-base-slot-p slotdef)
45 (sql-expression :attribute (database-identifier slotdef database)
46 :table (database-identifier vclass database))))
49 ;; Function used by 'find-all'
52 (defun generate-selection-list (vclass)
55 (slots (if (normalizedp vclass)
56 (labels ((getdslots ()
57 (let ((sl (ordered-class-direct-slots this-class)))
61 (car (class-direct-superclasses this-class)))
64 (ordered-class-slots this-class))))
65 (dolist (slotdef slots)
66 (let ((res (generate-attribute-reference this-class slotdef)))
68 (push (cons slotdef res) sels))))
71 (error "No slots of type :base in view-class ~A" (class-name vclass)))))
75 (defun generate-retrieval-joins-list (vclass retrieval-method)
76 "Returns list of immediate join slots for a class."
77 (let ((join-slotdefs nil))
78 (dolist (slotdef (ordered-class-slots vclass) join-slotdefs)
79 (when (and (eq :join (view-class-slot-db-kind slotdef))
80 (eq retrieval-method (gethash :retrieval (view-class-slot-db-info slotdef))))
81 (push slotdef join-slotdefs)))))
83 (defun generate-immediate-joins-selection-list (vclass)
84 "Returns list of immediate join slots for a class."
86 (dolist (joined-slot (generate-retrieval-joins-list vclass :immediate) sels)
87 (let* ((join-class-name (gethash :join-class (view-class-slot-db-info joined-slot)))
88 (join-class (when join-class-name (find-class join-class-name))))
89 (dolist (slotdef (ordered-class-slots join-class))
90 (let ((res (generate-attribute-reference join-class slotdef)))
92 (push (cons slotdef res) sels))))))
95 (defmethod choose-database-for-instance ((obj standard-db-object) &optional database)
96 "Determine which database connection to use for a standard-db-object.
97 Errs if none is available."
98 (or (find-if #'(lambda (db)
99 (and db (is-database-open db)))
100 (list (view-database obj)
103 (signal-no-database-error nil)))
107 (defmethod update-slot-with-null ((object standard-db-object) slotdef)
108 (setf (easy-slot-value object slotdef)
109 (slot-value slotdef 'void-value)))
111 (defmethod update-slot-from-db-value ((instance standard-db-object) slotdef value)
112 "This gets a value from the database and turns it itno a lisp value
113 based on the slot's slot-db-reader or baring that read-sql-value"
114 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
115 (let* ((slot-reader (view-class-slot-db-reader slotdef))
116 (slot-type (specified-type slotdef)))
118 ((null value) (update-slot-with-null instance slotdef))
120 (setf (easy-slot-value instance slotdef)
121 (read-sql-value value (delistify slot-type)
122 (choose-database-for-instance instance)
123 (database-underlying-type
124 (choose-database-for-instance instance)))))
125 (t (etypecase slot-reader
126 ((or symbol function)
127 (setf (easy-slot-value instance slotdef)
128 (apply slot-reader (list value))))
130 (setf (easy-slot-value instance slotdef)
131 (format nil slot-reader value))))))))
133 (defmethod key-value-from-db (slotdef value database)
134 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
135 (let ((slot-reader (view-class-slot-db-reader slotdef))
136 (slot-type (specified-type slotdef)))
137 (cond ((and value (null slot-reader))
138 (read-sql-value value (delistify slot-type) database
139 (database-underlying-type database)))
142 ((typep slot-reader 'string)
143 (format nil slot-reader value))
144 ((typep slot-reader '(or symbol function))
145 (apply slot-reader (list value)))
147 (error "Slot reader is of an unusual type.")))))
149 (defun db-value-from-slot (slotdef val database)
150 (let ((dbwriter (view-class-slot-db-writer slotdef))
151 (dbtype (specified-type slotdef)))
153 (string (format nil dbwriter val))
154 ((and (or symbol function) (not null)) (apply dbwriter (list val)))
156 (database-output-sql-as-type
160 val database (database-underlying-type database))))))
162 (defun check-slot-type (slotdef val)
163 (let* ((slot-type (specified-type slotdef))
164 (basetype (if (listp slot-type) (car slot-type) slot-type)))
165 (when (and slot-type val)
166 (unless (typep val basetype)
167 (error 'sql-user-error
169 (format nil "Invalid value ~A in slot ~A, not of type ~A."
170 val (slot-definition-name slotdef) slot-type))))))
172 (defmethod get-slot-values-from-view (obj slotdeflist values)
173 "Used to copy values from the database into the object
174 used by things like find-all and select"
175 (loop for slot in slotdeflist
177 do (update-slot-from-db-value obj slot value))
180 (defclass class-and-slots ()
181 ((view-class :accessor view-class :initarg :view-class :initform nil)
182 (slot-defs :accessor slot-defs :initarg :slot-defs :initform nil))
183 (:documentation "A helper class to keep track of which slot-defs from a
184 table need to be updated, a normalized class might have many of these
185 because each of its parent classes might represent some other table and we
186 need to match which slots came from which parent class/table"))
188 (defun make-class-and-slots (c &optional s)
189 "Create a new class-and-slots object"
190 (make-instance 'class-and-slots :view-class c :slot-defs (listify s) ))
192 (defmethod view-table ((o class-and-slots))
193 "get the view-table of the view-class of o"
194 (view-table (view-class o)))
196 (defmethod view-table-exp ((o class-and-slots))
197 (sql-expression :table (view-table o)))
199 (defmethod view-table-exp ((o standard-db-class))
200 (sql-expression :table (view-table o)))
202 (defmethod attribute-references ((o class-and-slots))
204 with class = (view-class o)
205 for sd in (slot-defs o)
206 collect (generate-attribute-reference class sd)))
208 (defmethod attribute-value-pairs ((def class-and-slots) (o standard-db-object)
210 "for a given class-and-slots and object, create the sql-expression & value pairs
211 that need to be sent to the database"
212 (loop for s in (slot-defs def)
213 for n = (to-slot-name s)
214 when (slot-boundp o n)
215 collect (make-attribute-value-pair s (slot-value o n) database)))
217 (defmethod view-classes-and-slots-by-name ((obj standard-db-object) slots-to-match)
218 "If it's normalized, find the class that actually contains
219 the slot that's tied to the db,
221 otherwise just search the current class
223 (let* ((view-class (class-of obj))
224 (normalizedp (normalizedp view-class))
226 (labels ((get-c&s-obj (class)
227 (or (find class rtns :key #'view-class)
228 (first (push (make-class-and-slots class) rtns))))
229 (associate-slot-with-class (class slot)
230 "Find the best class to associate with the slot. If it is
231 normalized then it needs to be a direct slot otherwise it just
232 needs to be on the class."
233 (let ((sd (find-slot-by-name class slot normalizedp nil)))
235 ;;we found it directly or it's (not normalized)
236 (pushnew sd (slot-defs (get-c&s-obj class)))
238 (loop for parent in (class-direct-superclasses class)
239 until (associate-slot-with-class parent slot))))
242 for in-slot in (listify slots-to-match)
243 do (associate-slot-with-class view-class in-slot)))
246 (defun update-auto-increments-keys (class obj database)
247 ;; handle pulling any autoincrement values into the object
248 (let ((pk-slots (keyslots-for-class class))
249 (table (view-table class))
251 (labels ((do-update (slot)
252 (when (and (null (easy-slot-value obj slot))
253 (auto-increment-column-p slot database))
254 (update-slot-from-db-value
258 (database-last-auto-increment-id
259 database table slot))))))
260 (chain-primary-keys (in-class)
261 "This seems kindof wrong, but this is mostly how it was working, so
262 its here to keep the normalized code path working"
263 (when (typep in-class 'standard-db-class)
264 (loop for slot in (keyslots-for-class in-class)
266 (loop for c in (class-direct-superclasses in-class)
267 do (chain-primary-keys c)))))
268 (loop for slot in pk-slots do (do-update slot))
269 (let ((direct-class (to-class obj)))
270 (when (and new-pk-value (normalizedp direct-class))
271 (chain-primary-keys direct-class)))
274 (defmethod %update-instance-helper
275 (class-and-slots obj database
276 &aux (avps (attribute-value-pairs class-and-slots obj database)))
277 ;; we dont actually need to update anything on this particular parent class
278 (unless avps (return-from %update-instance-helper))
280 (let* ((view-class (view-class class-and-slots))
281 (table (view-table view-class))
282 (table-sql (sql-expression :table table)))
284 ;; view database is the flag we use to tell it was pulled from a database
285 ;; and thus probably needs an update instead of an insert
286 (cond ((view-database obj)
287 (let ((where (key-qualifier-for-instance
288 obj :database database :this-class view-class)))
290 (error "update-record-from-*: could not generate a where clause for ~a using ~A"
292 (update-records table-sql
295 :database database)))
296 (T ;; was not pulled from the db so insert it
297 ;; avps MUST contain any primary key slots set
298 ;; by previous inserts of the same object into different
299 ;; tables (ie: normalized stuff)
300 (insert-records :into table-sql
303 (update-auto-increments-keys view-class obj database)
304 ;; we dont set view database here, because there could be
305 ;; N of these for each call to update-record-from-* because
306 ;; of normalized classes
308 (update-slot-default-values obj class-and-slots)))
310 (defmethod update-record-from-slots ((obj standard-db-object) slots
311 &key (database *default-database*))
312 (setf slots (listify slots))
313 (let* ((classes-and-slots (view-classes-and-slots-by-name obj slots))
314 (database (choose-database-for-instance obj database)))
315 (loop for class-and-slots in classes-and-slots
316 do (%update-instance-helper class-and-slots obj database))
317 (setf (slot-value obj 'view-database) database))
320 (defmethod update-record-from-slot
321 ((obj standard-db-object) slot &key (database *default-database*))
322 (update-record-from-slots obj slot :database database))
326 (defmethod view-classes-and-storable-slots-for-instance ((obj standard-db-object))
327 "Get a list of all the tables we need to update and the slots on them
329 for non normalized classes we return the class and all its storable slots
331 for normalized classes we return a list of direct slots and the class they
332 came from for each normalized view class
334 (let* ((view-class (class-of obj))
336 (labels ((storable-slots (class)
337 (loop for sd in (slots-for-possibly-normalized-class class)
338 when (key-or-base-slot-p sd)
340 (get-classes-and-slots (class &aux (normalizedp (normalizedp class)))
341 (let ((slots (storable-slots class)))
343 (push (make-class-and-slots class slots) rtns)))
345 (loop for new-class in (class-direct-superclasses class)
346 do (when (typep new-class 'standard-db-class)
347 (get-classes-and-slots new-class))))))
348 (get-classes-and-slots view-class))
351 (defmethod primary-key-slot-values ((obj standard-db-object)
353 (defaulting class (class-of obj)
354 slots (keyslots-for-class class))
355 (loop for slot in slots
356 collect (easy-slot-value obj slot)))
358 (defmethod update-slot-default-values ((obj standard-db-object)
360 "Makes sure that if a class has unfilled slots that claim to have a default,
361 that we retrieve those defaults from the database
363 TODO: use update slots-from-record instead to batch this!"
364 (loop for class-and-slots in (listify classes-and-slots)
365 do (loop for slot in (slot-defs class-and-slots)
366 do (when (and (slot-has-default-p slot)
367 (not (easy-slot-value obj slot)))
368 (update-slot-from-record obj (to-slot-name slot))))))
370 (defmethod update-records-from-instance ((obj standard-db-object)
371 &key (database *default-database*))
372 "Updates the records in the database associated with this object if
373 view-database slot on the object is nil then the object is assumed to be
375 (let ((database (choose-database-for-instance obj database))
376 (classes-and-slots (view-classes-and-storable-slots-for-instance obj)))
377 (loop for class-and-slots in classes-and-slots
378 do (%update-instance-helper class-and-slots obj database))
379 (setf (slot-value obj 'view-database) database)
380 (primary-key-slot-values obj)))
382 (defmethod delete-instance-records ((instance standard-db-object) &key database)
383 (let ((database (choose-database-for-instance instance database))
384 (vt (sql-expression :table (view-table (class-of instance)))))
386 (let ((qualifier (key-qualifier-for-instance instance :database database)))
387 (delete-records :from vt :where qualifier :database database)
388 (setf (record-caches database) nil)
389 (setf (slot-value instance 'view-database) nil)
391 (signal-no-database-error database))))
393 (defmethod update-instance-from-records ((instance standard-db-object)
394 &key (database *default-database*)
396 (let* ((view-class (or this-class (class-of instance)))
397 (pclass (car (class-direct-superclasses view-class)))
399 (when (normalizedp view-class)
400 (setf pres (update-instance-from-records instance :database database
401 :this-class pclass)))
402 (let* ((view-table (sql-expression :table (view-table view-class)))
403 (vd (choose-database-for-instance instance database))
404 (view-qual (key-qualifier-for-instance instance :database vd
405 :this-class view-class))
406 (sels (generate-selection-list view-class))
409 (setf res (apply #'select (append (mapcar #'cdr sels)
410 (list :from view-table
415 (setf (slot-value instance 'view-database) vd)
416 (get-slot-values-from-view instance (mapcar #'car sels) (car res))))
421 (defmethod get-slot-value-from-record ((instance standard-db-object)
422 slot &key (database *default-database*))
423 (let* ((class-and-slot
425 (view-classes-and-slots-by-name instance slot)))
426 (view-class (view-class class-and-slot))
427 (slot-def (first (slot-defs class-and-slot)))
428 (vd (choose-database-for-instance instance database))
429 (att-ref (first (attribute-references class-and-slot)))
432 :from (view-table-exp class-and-slot)
433 :where (key-qualifier-for-instance
436 :this-class view-class)
439 (values res slot-def)))
441 (defmethod update-slot-from-record ((instance standard-db-object)
442 slot &key (database *default-database*))
443 (multiple-value-bind (res slot-def)
444 (get-slot-value-from-record instance slot :database database)
445 (let ((vd (choose-database-for-instance instance database)))
446 (setf (slot-value instance 'view-database) vd)
447 (update-slot-from-db-value instance slot-def res))))
450 (defvar +no-slot-value+ '+no-slot-value+)
452 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
453 (let* ((class (find-class classname))
454 (sld (slotdef-for-slot-with-class slot class)))
456 (if (eq value +no-slot-value+)
457 (sql-expression :attribute (database-identifier sld database)
458 :table (view-table class))
463 (error "Unknown slot ~A for class ~A" slot classname))))
465 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
466 (declare (ignore database))
467 (let* ((class (find-class classname)))
468 (unless (view-table class)
469 (error "No view-table for class ~A" classname))
470 (sql-expression :table (view-table class))))
473 (defmethod database-get-type-specifier (type args database db-type)
474 (declare (ignore type args database db-type))
475 (format nil "VARCHAR(~D)" *default-string-length*))
477 (defmethod database-get-type-specifier ((type (eql 'integer)) args database db-type)
478 (declare (ignore database db-type))
480 (format nil "INT(~A)" (car args))
484 "An 8-bit integer, this width may vary by SQL implementation."
487 (defmethod database-get-type-specifier ((type (eql 'tinyint)) args database db-type)
488 (declare (ignore args database db-type))
492 "An integer smaller than a 32-bit integer. this width may vary by SQL implementation."
495 (defmethod database-get-type-specifier ((type (eql 'smallint)) args database db-type)
496 (declare (ignore args database db-type))
499 (deftype mediumint ()
500 "An integer smaller than a 32-bit integer, but may be larger than a smallint. This width may vary by SQL implementation."
503 (defmethod database-get-type-specifier ((type (eql 'mediumint)) args database db-type)
504 (declare (ignore args database db-type))
508 "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
511 (defmethod database-get-type-specifier ((type (eql 'bigint)) args database db-type)
512 (declare (ignore args database db-type))
515 (deftype varchar (&optional size)
516 "A variable length string for the SQL varchar type."
517 (declare (ignore size))
520 (defmethod database-get-type-specifier ((type (eql 'varchar)) args
522 (declare (ignore database db-type))
524 (format nil "VARCHAR(~A)" (car args))
525 (format nil "VARCHAR(~D)" *default-string-length*)))
527 (defmethod database-get-type-specifier ((type (eql 'string)) args database db-type)
528 (declare (ignore database db-type))
530 (format nil "CHAR(~A)" (car args))
531 (format nil "VARCHAR(~D)" *default-string-length*)))
533 (deftype universal-time ()
534 "A positive integer as returned by GET-UNIVERSAL-TIME."
537 (defmethod database-get-type-specifier ((type (eql 'universal-time)) args database db-type)
538 (declare (ignore args database db-type))
541 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database db-type)
542 (declare (ignore args database db-type))
545 (defmethod database-get-type-specifier ((type (eql 'date)) args database db-type)
546 (declare (ignore args database db-type))
549 (defmethod database-get-type-specifier ((type (eql 'duration)) args database db-type)
550 (declare (ignore database args db-type))
553 (defmethod database-get-type-specifier ((type (eql 'money)) args database db-type)
554 (declare (ignore database args db-type))
558 (deftype char (&optional len)
559 "A lisp type for the SQL CHAR type."
562 (defmethod database-get-type-specifier ((type (eql 'float)) args database db-type)
563 (declare (ignore database db-type))
565 (format nil "FLOAT(~A)" (car args))
568 (defmethod database-get-type-specifier ((type (eql 'long-float)) args database db-type)
569 (declare (ignore database db-type))
571 (format nil "FLOAT(~A)" (car args))
574 (deftype generalized-boolean ()
575 "A type which outputs a SQL boolean value, though any lisp type can be stored in the slot."
578 (defmethod database-get-type-specifier ((type (eql 'boolean)) args database db-type)
579 (declare (ignore args database db-type))
582 (defmethod database-get-type-specifier ((type (eql 'generalized-boolean)) args database db-type)
583 (declare (ignore args database db-type))
586 (defmethod database-get-type-specifier ((type (eql 'number)) args database db-type)
587 (declare (ignore database db-type))
589 ((and (consp args) (= (length args) 2))
590 (format nil "NUMBER(~D,~D)" (first args) (second args)))
591 ((and (consp args) (= (length args) 1))
592 (format nil "NUMBER(~D)" (first args)))
596 (defmethod database-get-type-specifier ((type (eql 'char)) args database db-type)
597 (declare (ignore database db-type))
599 (format nil "CHAR(~D)" (first args))
603 (defmethod database-output-sql-as-type (type val database db-type)
604 (declare (ignore type database db-type))
607 (defmethod database-output-sql-as-type ((type (eql 'list)) val database db-type)
608 (declare (ignore database db-type))
609 (progv '(*print-circle* *print-array*) '(t t)
610 (let ((escaped (prin1-to-string val)))
611 (substitute-char-string
612 escaped #\Null " "))))
614 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database db-type)
615 (declare (ignore database db-type))
618 (package-name (symbol-package val))
623 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database db-type)
624 (declare (ignore database db-type))
629 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database db-type)
630 (declare (ignore database db-type))
631 (progv '(*print-circle* *print-array*) '(t t)
632 (prin1-to-string val)))
634 (defmethod database-output-sql-as-type ((type (eql 'array)) val database db-type)
635 (declare (ignore database db-type))
636 (progv '(*print-circle* *print-array*) '(t t)
637 (prin1-to-string val)))
639 (defmethod database-output-sql-as-type ((type (eql 'boolean)) val database db-type)
640 (declare (ignore database db-type))
643 (defmethod database-output-sql-as-type ((type (eql 'generalized-boolean)) val database db-type)
644 (declare (ignore database db-type))
647 (defmethod database-output-sql-as-type ((type (eql 'string)) val database db-type)
648 (declare (ignore database db-type))
651 (defmethod database-output-sql-as-type ((type (eql 'char)) val database db-type)
652 (declare (ignore database db-type))
654 (character (write-to-string val))
657 (defmethod database-output-sql-as-type ((type (eql 'float)) val database db-type)
658 (declare (ignore database db-type))
659 (if (eq (type-of val) 'null)
661 (let ((*read-default-float-format* (type-of val)))
662 (format nil "~F" val))))
664 (defmethod read-sql-value (val type database db-type)
665 (declare (ignore database db-type))
667 ((null type) val) ;;we have no desired type, just give the value
668 ((typep val type) val) ;;check that it hasn't already been converted.
669 ((typep val 'string) (read-from-string val)) ;;maybe read will just take care of it?
670 (T (error "Unable to read-sql-value ~a as type ~a" val type))))
672 (defmethod read-sql-value (val (type (eql 'string)) database db-type)
673 (declare (ignore database db-type))
676 (defmethod read-sql-value (val (type (eql 'varchar)) database db-type)
677 (declare (ignore database db-type))
680 (defmethod read-sql-value (val (type (eql 'char)) database db-type)
681 (declare (ignore database db-type))
684 (defmethod read-sql-value (val (type (eql 'keyword)) database db-type)
685 (declare (ignore database db-type))
686 (when (< 0 (length val))
687 (intern (symbol-name-default-case val)
688 (find-package '#:keyword))))
690 (defmethod read-sql-value (val (type (eql 'symbol)) database db-type)
691 (declare (ignore database db-type))
692 (when (< 0 (length val))
693 (unless (string= val (symbol-name-default-case "NIL"))
694 (read-from-string val))))
696 (defmethod read-sql-value (val (type (eql 'integer)) database db-type)
697 (declare (ignore database db-type))
700 (unless (string-equal "NIL" val)
701 (parse-integer val)))
704 (defmethod read-sql-value (val (type (eql 'smallint)) database db-type)
705 (declare (ignore database db-type))
708 (unless (string-equal "NIL" val)
709 (parse-integer val)))
712 (defmethod read-sql-value (val (type (eql 'bigint)) database db-type)
713 (declare (ignore database db-type))
716 (unless (string-equal "NIL" val)
717 (parse-integer val)))
720 (defmethod read-sql-value (val (type (eql 'float)) database db-type)
721 (declare (ignore database db-type))
722 ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
724 (string (float (read-from-string val)))
727 (defmethod read-sql-value (val (type (eql 'double-float)) database db-type)
728 (declare (ignore database db-type))
729 ;; writing 1.0 writes 1, so if we *really* want a float, must do (float ...)
732 (let ((*read-default-float-format* 'double-float))
733 (read-from-string val))
736 (float (coerce val 'double-float))))
738 (defmethod read-sql-value (val (type (eql 'boolean)) database db-type)
739 (declare (ignore database db-type))
742 (defmethod read-sql-value (val (type (eql 'generalized-boolean)) database db-type)
743 (declare (ignore database db-type))
746 (defmethod read-sql-value (val (type (eql 'number)) database db-type)
747 (declare (ignore database db-type))
750 (unless (string-equal "NIL" val)
751 (read-from-string val)))
754 (defmethod read-sql-value (val (type (eql 'universal-time)) database db-type)
755 (declare (ignore database db-type))
756 (unless (eq 'NULL val)
762 (defmethod read-sql-value (val (type (eql 'wall-time)) database db-type)
763 (declare (ignore database db-type))
764 (unless (eq 'NULL val)
765 (parse-timestring val)))
767 (defmethod read-sql-value (val (type (eql 'date)) database db-type)
768 (declare (ignore database db-type))
769 (unless (eq 'NULL val)
770 (parse-datestring val)))
772 (defmethod read-sql-value (val (type (eql 'duration)) database db-type)
773 (declare (ignore database db-type))
774 (unless (or (eq 'NULL val)
776 (parse-timestring val)))
778 ;; ------------------------------------------------------------
779 ;; Logic for 'faulting in' :join slots
781 ;; this works, but is inefficient requiring (+ 1 n-rows)
784 (defun fault-join-target-slot (class object slot-def)
785 (let* ((res (fault-join-slot-raw class object slot-def))
786 (dbi (view-class-slot-db-info slot-def))
787 (target-name (gethash :target-slot dbi))
788 (target-class (find-class target-name)))
790 (mapcar (lambda (obj)
796 (find target-name (class-slots (class-of obj))
797 :key #'slot-definition-name)))
800 #+ignore ;; this doesn't work when attempting to call slot-value
801 (mapcar (lambda (obj)
802 (cons obj (slot-value obj ts))) res))))
804 (defun fault-join-target-slot (class object slot-def)
805 (let* ((dbi (view-class-slot-db-info slot-def))
806 (ts (gethash :target-slot dbi))
807 (jc (gethash :join-class dbi))
808 (jc-view-table (view-table (find-class jc)))
809 (tdbi (view-class-slot-db-info
810 (find ts (class-slots (find-class jc))
811 :key #'slot-definition-name)))
812 (retrieval (gethash :retrieval tdbi))
813 (tsc (gethash :join-class tdbi))
814 (ts-view-table (view-table (find-class tsc)))
815 (jq (join-qualifier class object slot-def))
816 (key (slot-value object (gethash :home-key dbi))))
823 :inner-join (sql-expression :table jc-view-table)
827 :attribute (gethash :foreign-key tdbi)
828 :table ts-view-table)
830 :attribute (gethash :home-key tdbi)
831 :table jc-view-table))
834 :database (choose-database-for-instance object))))
835 (mapcar #'(lambda (i)
836 (let* ((instance (car i))
837 (jcc (make-instance jc :view-database (choose-database-for-instance instance))))
838 (setf (slot-value jcc (gethash :foreign-key dbi))
840 (setf (slot-value jcc (gethash :home-key tdbi))
841 (slot-value instance (gethash :foreign-key tdbi)))
842 (list instance jcc)))
845 ;; just fill in minimal slots
848 (let ((instance (make-instance tsc :view-database (choose-database-for-instance object)))
849 (jcc (make-instance jc :view-database (choose-database-for-instance object)))
851 (setf (slot-value instance (gethash :home-key tdbi)) fk)
852 (setf (slot-value jcc (gethash :foreign-key dbi))
854 (setf (slot-value jcc (gethash :home-key tdbi))
856 (list instance jcc)))
857 (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
858 :from (sql-expression :table jc-view-table)
860 :database (choose-database-for-instance object))))))))
865 (defvar *default-update-objects-max-len* nil
866 "The default value to use for the MAX-LEN keyword argument to
867 UPDATE-OBJECT-JOINS.")
869 (defun update-objects-joins (objects &key (slots t) (force-p t)
871 *default-update-objects-max-len*))
872 "Updates from the records of the appropriate database tables
873 the join slots specified by SLOTS in the supplied list of View
874 Class instances OBJECTS. SLOTS is t by default which means that
875 all join slots with :retrieval :immediate are updated. CLASS-NAME
876 is used to specify the View Class of all instance in OBJECTS and
877 default to nil which means that the class of the first instance
878 in OBJECTS is used. FORCE-P is t by default which means that all
879 join slots are updated whereas a value of nil means that only
880 unbound join slots are updated. MAX-LEN defaults to
881 *DEFAULT-UPDATE-OBJECTS-MAX-LEN* and when non-nil specifies that
882 UPDATE-OBJECT-JOINS may issue multiple database queries with a
883 maximum of MAX-LEN instances updated in each query."
884 (assert (or (null max-len) (plusp max-len)))
887 (setq class-name (class-name (class-of (first objects)))))
888 (let* ((class (find-class class-name))
889 (class-slots (ordered-class-slots class))
892 (generate-retrieval-joins-list class :deferred)
894 (mapcar #'(lambda (name)
895 (let ((slotdef (find name class-slots :key #'slot-definition-name)))
897 (warn "Unable to find slot named ~S in class ~S." name class))
900 (dolist (slotdef slotdefs)
901 (let* ((dbi (view-class-slot-db-info slotdef))
902 (slotdef-name (slot-definition-name slotdef))
903 (foreign-key (gethash :foreign-key dbi))
904 (home-key (gethash :home-key dbi))
908 (mapcar #'(lambda (o) (slot-value o home-key)) objects)
911 #'(lambda (o) (if (slot-boundp o slotdef-name)
913 (slot-value o home-key)))
915 (n-object-keys (length object-keys))
916 (query-len (or max-len n-object-keys)))
918 (do ((i 0 (+ i query-len)))
919 ((>= i n-object-keys))
920 (let* ((keys (if max-len
921 (subseq object-keys i (min (+ i query-len) n-object-keys))
923 (results (unless (gethash :target-slot dbi)
924 (find-all (list (gethash :join-class dbi))
925 :where (make-instance 'sql-relational-exp
927 :sub-expressions (list (sql-expression :attribute foreign-key)
932 (dolist (object objects)
933 (when (or force-p (not (slot-boundp object slotdef-name)))
934 (let ((res (if results
935 (remove-if-not #'(lambda (obj)
936 (equal obj (slot-value
945 (when (gethash :target-slot dbi)
946 (fault-join-target-slot class object slotdef))))))
948 (setf (slot-value object slotdef-name)
949 (if (gethash :set dbi) res (car res)))))))))))))
952 (defun fault-join-slot-raw (class object slot-def)
953 (let* ((dbi (view-class-slot-db-info slot-def))
954 (jc (gethash :join-class dbi)))
955 (let ((jq (join-qualifier class object slot-def)))
957 (select jc :where jq :flatp t :result-types nil
958 :database (choose-database-for-instance object))))))
962 (defun fault-join-slot (class object slot-def)
963 (let* ((dbi (view-class-slot-db-info slot-def))
964 (ts (gethash :target-slot dbi))
965 (dbi-set (gethash :set dbi)))
967 (fault-join-target-slot class object slot-def)
968 (let ((res (fault-join-slot-raw class object slot-def)))
971 ((and ts (not dbi-set))
972 (mapcar (lambda (obj) (slot-value obj ts)) res))
973 ((and (not ts) (not dbi-set))
975 ((and (not ts) dbi-set)
978 (defun update-fault-join-normalized-slot (class object slot-def)
979 (if (and (normalizedp class) (key-slot-p slot-def))
980 (setf (easy-slot-value object slot-def)
981 (normalized-key-value object))
982 (update-slot-from-record object slot-def)))
984 (defun join-qualifier (class object slot-def)
985 (declare (ignore class))
986 (let* ((dbi (view-class-slot-db-info slot-def))
987 (jc (find-class (gethash :join-class dbi)))
988 ;;(ts (gethash :target-slot dbi))
989 ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
990 (foreign-keys (gethash :foreign-key dbi))
991 (home-keys (gethash :home-key dbi)))
992 (when (every #'(lambda (slt)
993 (and (slot-boundp object slt)
994 (not (null (slot-value object slt)))))
995 (if (listp home-keys) home-keys (list home-keys)))
997 (mapcar #'(lambda (hk fk)
998 (let ((fksd (slotdef-for-slot-with-class fk jc)))
1004 (database-identifier fksd nil)
1005 :table (database-identifier jc nil)))
1009 (slot-value object hk))
1012 (if (listp home-keys)
1015 (if (listp foreign-keys)
1017 (list foreign-keys)))))
1019 (if (> (length jc) 1)
1020 (apply #'sql-and jc)
1023 ;; FIXME: add retrieval immediate for efficiency
1024 ;; For example, for (select 'employee-address) in test suite =>
1025 ;; select addr.*,ea_join.* FROM addr,ea_join WHERE ea_join.aaddressid=addr.addressid\g
1027 (defun build-objects (vals sclasses immediate-join-classes sels immediate-joins database refresh flatp instances)
1028 "Used by find-all to build objects."
1029 (labels ((build-object (vals vclass jclasses selects immediate-selects instance)
1030 (let* ((db-vals (butlast vals (- (list-length vals)
1031 (list-length selects))))
1032 (obj (if instance instance (make-instance (class-name vclass) :view-database database)))
1033 (join-vals (subseq vals (list-length selects)))
1034 (joins (mapcar #'(lambda (c) (when c (make-instance c :view-database database)))
1037 ;;(format t "joins: ~S~%db-vals: ~S~%join-values: ~S~%selects: ~S~%immediate-selects: ~S~%"
1038 ;;joins db-vals join-vals selects immediate-selects)
1040 ;; use refresh keyword here
1041 (setf obj (get-slot-values-from-view obj (mapcar #'car selects) db-vals))
1042 (mapc #'(lambda (jo)
1043 ;; find all immediate-select slots and join-vals for this object
1044 (let* ((jo-class (class-of jo))
1045 (slots (slots-for-possibly-normalized-class jo-class))
1046 (pos-list (remove-if #'null
1049 (position s immediate-selects
1053 (get-slot-values-from-view jo
1055 (mapcar #'(lambda (pos)
1056 (nth pos immediate-selects))
1058 (mapcar #'(lambda (pos) (nth pos join-vals))
1064 (class-slots vclass))
1065 (slot (find (class-name (class-of jc)) vslots
1066 :key #'(lambda (slot)
1067 (when (and (eq :join (view-class-slot-db-kind slot))
1068 (eq (slot-definition-name slot)
1069 (gethash :join-class (view-class-slot-db-info slot))))
1070 (slot-definition-name slot))))))
1072 (setf (slot-value obj (slot-definition-name slot)) jc))))
1074 (when refresh (instance-refreshed obj))
1077 (mapcar #'(lambda (sclass jclass sel immediate-join instance)
1079 (build-object vals sclass jclass sel immediate-join instance)
1080 (setf vals (nthcdr (+ (list-length sel) (list-length immediate-join))
1082 sclasses immediate-join-classes sels immediate-joins instances)))
1083 (if (and flatp (= (length sclasses) 1))
1087 (defmethod select-table-sql-expr ((table T))
1088 "Turns an object representing a table into the :from part of the sql expression that will be executed "
1089 (sql-expression :table (view-table table)))
1092 (defun find-all (view-classes
1094 &key all set-operation distinct from where group-by having
1095 order-by offset limit refresh flatp result-types
1097 (database *default-database*)
1098 instances parameters)
1099 "Called by SELECT to generate object query results when the
1100 View Classes VIEW-CLASSES are passed as arguments to SELECT."
1101 (declare (ignore all set-operation group-by having offset limit inner-join on parameters)
1102 (dynamic-extent args))
1103 (flet ((ref-equal (ref1 ref2)
1104 (string= (sql-output ref1 database)
1105 (sql-output ref2 database))))
1106 (declare (dynamic-extent (function ref-equal)))
1107 (let ((args (filter-plist args :from :where :flatp :additional-fields :result-types :instances)))
1108 (let* ((*db-deserializing* t)
1109 (sclasses (mapcar #'find-class view-classes))
1110 (immediate-join-slots
1111 (mapcar #'(lambda (c) (generate-retrieval-joins-list c :immediate)) sclasses))
1112 (immediate-join-classes
1113 (mapcar #'(lambda (jcs)
1114 (mapcar #'(lambda (slotdef)
1115 (find-class (gethash :join-class (view-class-slot-db-info slotdef))))
1117 immediate-join-slots))
1118 (immediate-join-sels (mapcar #'generate-immediate-joins-selection-list sclasses))
1119 (sels (mapcar #'generate-selection-list sclasses))
1120 (fullsels (apply #'append (mapcar #'append sels immediate-join-sels)))
1121 (sel-tables (collect-table-refs where))
1122 (tables (remove-if #'null
1124 (append (mapcar #'select-table-sql-expr sclasses)
1125 (mapcan #'(lambda (jc-list)
1127 #'(lambda (jc) (when jc (select-table-sql-expr jc)))
1129 immediate-join-classes)
1131 :test #'database-identifier-equal)))
1132 (order-by-slots (mapcar #'(lambda (ob) (if (atom ob) ob (car ob)))
1133 (listify order-by)))
1136 ;;(format t "sclasses: ~W~%ijc: ~W~%tables: ~W~%" sclasses immediate-join-classes tables)
1138 (dolist (ob order-by-slots)
1139 (when (and ob (not (member ob (mapcar #'cdr fullsels)
1140 :test #'ref-equal)))
1142 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1144 (dolist (ob (listify distinct))
1145 (when (and (typep ob 'sql-ident)
1146 (not (member ob (mapcar #'cdr fullsels)
1147 :test #'ref-equal)))
1149 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1151 (mapcar #'(lambda (vclass jclasses jslots)
1154 #'(lambda (jclass jslot)
1155 (let ((dbi (view-class-slot-db-info jslot)))
1158 (list (sql-operation '==
1160 :attribute (gethash :foreign-key dbi)
1161 :table (view-table jclass))
1163 :attribute (gethash :home-key dbi)
1164 :table (view-table vclass))))
1165 (when join-where (listify join-where))))))
1167 sclasses immediate-join-classes immediate-join-slots)
1168 ;; Reported buggy on clsql-devel
1169 ;; (when where (setq where (listify where)))
1171 ((and where join-where)
1172 (setq where (list (apply #'sql-and where join-where))))
1173 ((and (null where) (> (length join-where) 1))
1174 (setq where (list (apply #'sql-and join-where)))))
1176 (let* ((rows (apply #'select
1177 (append (mapcar #'cdr fullsels)
1179 (list (append (when from (listify from))
1181 (list :result-types result-types)
1183 (list :where where))
1185 (instances-to-add (- (length rows) (length instances)))
1186 (perhaps-extended-instances
1187 (if (plusp instances-to-add)
1188 (append instances (do ((i 0 (1+ i))
1190 ((= i instances-to-add) res)
1191 (push (make-list (length sclasses) :initial-element nil) res)))
1194 #'(lambda (row instance)
1195 (build-objects row sclasses immediate-join-classes sels
1196 immediate-join-sels database refresh flatp
1197 (if (and flatp (atom instance))
1200 rows perhaps-extended-instances)))
1203 (defmethod instance-refreshed ((instance standard-db-object)))
1205 (defvar *default-caching* t
1206 "Controls whether SELECT caches objects by default. The CommonSQL
1207 specification states caching is on by default.")
1209 (defun select (&rest select-all-args)
1210 "Executes a query on DATABASE, which has a default value of
1211 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
1212 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
1213 argument can be used to generate queries in both functional and
1214 object oriented contexts.
1216 In the functional case, the required arguments specify the
1217 columns selected by the query and may be symbolic SQL expressions
1218 or strings representing attribute identifiers. Type modified
1219 identifiers indicate that the values selected from the specified
1220 column are converted to the specified lisp type. The keyword
1221 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
1222 SET-OPERATION and WHERE are used to specify, using the symbolic
1223 SQL syntax, the corresponding components of the SQL query
1224 generated by the call to SELECT. RESULT-TYPES is a list of
1225 symbols which specifies the lisp type for each field returned by
1226 the query. If RESULT-TYPES is nil all results are returned as
1227 strings whereas the default value of :auto means that the lisp
1228 types are automatically computed for each field. FIELD-NAMES is t
1229 by default which means that the second value returned is a list
1230 of strings representing the columns selected by the query. If
1231 FIELD-NAMES is nil, the list of column names is not returned as a
1234 In the object oriented case, the required arguments to SELECT are
1235 symbols denoting View Classes which specify the database tables
1236 to query. In this case, SELECT returns a list of View Class
1237 instances whose slots are set from the attribute values of the
1238 records in the specified table. Slot-value is a legal operator
1239 which can be employed as part of the symbolic SQL syntax used in
1240 the WHERE keyword argument to SELECT. REFRESH is nil by default
1241 which means that the View Class instances returned are retrieved
1242 from a cache if an equivalent call to SELECT has previously been
1243 issued. If REFRESH is true, the View Class instances returned are
1244 updated as necessary from the database and the generic function
1245 INSTANCE-REFRESHED is called to perform any necessary operations
1246 on the updated instances.
1248 In both object oriented and functional contexts, FLATP has a
1249 default value of nil which means that the results are returned as
1250 a list of lists. If FLATP is t and only one result is returned
1251 for each record selected in the query, the results are returned
1252 as elements of a list."
1253 (multiple-value-bind (target-args qualifier-args)
1254 (query-get-selections select-all-args)
1255 (unless (or *default-database* (getf qualifier-args :database))
1256 (signal-no-database-error nil))
1258 (let ((caching (getf qualifier-args :caching *default-caching*))
1259 (result-types (getf qualifier-args :result-types :auto))
1260 (refresh (getf qualifier-args :refresh nil))
1261 (database (getf qualifier-args :database *default-database*)))
1265 (every #'(lambda (arg)
1267 (find-class arg nil)))
1270 (setf qualifier-args (filter-plist qualifier-args :caching :refresh :result-types))
1272 ;; Add explicity table name to order-by if not specified and only
1273 ;; one selected table. This is required so FIND-ALL won't duplicate
1275 (let ((order-by (getf qualifier-args :order-by)))
1276 (when (and order-by (= 1 (length target-args)))
1277 (let ((table-name (view-table (find-class (car target-args))))
1278 (order-by-list (copy-seq (listify order-by))))
1279 (labels ((sv (val name) (ignore-errors (slot-value val name)))
1280 (set-table-if-needed (val)
1282 (sql-ident-attribute
1284 (if (sv val 'qualifier)
1286 (make-instance 'sql-ident-attribute
1287 :name (sv val 'name)
1288 :qualifier table-name))
1290 ;; TODO: Check for a specific error we expect
1292 (cons (cons (set-table-if-needed (car val))
1296 (loop for i from 0 below (length order-by-list)
1297 for id in order-by-list
1298 collect (set-table-if-needed id))))
1299 (setf (getf qualifier-args :order-by) order-by-list))))
1303 (apply #'find-all target-args :result-types result-types :refresh refresh qualifier-args))
1305 (let ((cached (records-cache-results target-args qualifier-args database)))
1306 (if (and cached (not refresh))
1308 (let ((results (apply #'find-all target-args
1309 :result-types :auto :refresh refresh
1312 (setf (records-cache-results target-args qualifier-args database) results)
1316 (let* ((expr (apply #'make-query select-all-args))
1317 (parameters (second (member :parameters select-all-args)))
1319 (mapcar #'(lambda (attrib)
1320 (if (typep attrib 'sql-ident-attribute)
1321 (let ((type (slot-value attrib 'type)))
1326 (slot-value expr 'selections)))
1327 (flatp (getf qualifier-args :flatp))
1328 (field-names (getf qualifier-args :field-names t)))
1331 (setf expr (command-object (sql-output expr database) parameters)))
1332 (query expr :flatp flatp
1334 ;; specifying a type for an attribute overrides result-types
1335 (if (some #'(lambda (x) (not (eq t x))) specified-types)
1338 :field-names field-names
1339 :database database)))))))
1341 (defun compute-records-cache-key (targets qualifiers)
1343 (do ((args *select-arguments* (cdr args))
1345 ((null args) results)
1346 (let* ((arg (car args))
1347 (value (getf qualifiers arg)))
1351 (cons (cons (sql (car value)) (cdr value)))
1352 (%sql-expression (sql value))
1356 (defun records-cache-results (targets qualifiers database)
1357 (when (record-caches database)
1358 (gethash (compute-records-cache-key targets qualifiers) (record-caches database))))
1360 (defun (setf records-cache-results) (results targets qualifiers database)
1361 (unless (record-caches database)
1362 (setf (record-caches database)
1363 (make-weak-hash-table :test 'equal)))
1364 (setf (gethash (compute-records-cache-key (copy-list targets) qualifiers)
1365 (record-caches database)) results)
1370 ;;; Serialization functions
1372 (defun write-instance-to-stream (obj stream)
1373 "Writes an instance to a stream where it can be later be read.
1374 NOTE: an error will occur if a slot holds a value which can not be written readably."
1375 (let* ((class (class-of obj))
1377 (dolist (slot (ordered-class-slots (class-of obj)))
1378 (let ((name (slot-definition-name slot)))
1379 (when (and (not (eq 'view-database name))
1380 (slot-boundp obj name))
1381 (push (cons name (slot-value obj name)) alist))))
1382 (setq alist (reverse alist))
1383 (write (cons (class-name class) alist) :stream stream :readably t))
1386 (defun read-instance-from-stream (stream)
1387 (let ((raw (read stream nil nil)))
1389 (let ((obj (make-instance (car raw))))
1390 (dolist (pair (cdr raw))
1391 (setf (slot-value obj (car pair)) (cdr pair)))