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 generate-selection-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))))
51 ;; Function used by 'find-all'
54 (defun generate-selection-list (vclass)
57 (slots (if (normalizedp vclass)
58 (labels ((getdslots ()
59 (let ((sl (ordered-class-direct-slots this-class)))
63 (car (class-direct-superclasses this-class)))
66 (ordered-class-slots this-class))))
67 (dolist (slotdef slots)
68 (let ((res (generate-attribute-reference this-class slotdef)))
70 (push (cons slotdef res) sels))))
73 (error "No slots of type :base in view-class ~A" (class-name vclass)))))
77 (defun generate-retrieval-joins-list (vclass retrieval-method)
78 "Returns list of immediate join slots for a class."
79 (let ((join-slotdefs nil))
80 (dolist (slotdef (ordered-class-slots vclass) join-slotdefs)
81 (when (and (eq :join (view-class-slot-db-kind slotdef))
82 (eq retrieval-method (gethash :retrieval (view-class-slot-db-info slotdef))))
83 (push slotdef join-slotdefs)))))
85 (defun generate-immediate-joins-selection-list (vclass)
86 "Returns list of immediate join slots for a class."
88 (dolist (joined-slot (generate-retrieval-joins-list vclass :immediate) sels)
89 (let* ((join-class-name (gethash :join-class (view-class-slot-db-info joined-slot)))
90 (join-class (when join-class-name (find-class join-class-name))))
91 (dolist (slotdef (ordered-class-slots join-class))
92 (let ((res (generate-attribute-reference join-class slotdef)))
94 (push (cons slotdef res) sels))))))
97 (defmethod choose-database-for-instance ((obj standard-db-object) &optional database)
98 "Determine which database connection to use for a standard-db-object.
99 Errs if none is available."
100 (or (find-if #'(lambda (db)
101 (and db (is-database-open db)))
102 (list (view-database obj)
105 (signal-no-database-error nil)))
109 (defmethod update-slot-with-null ((object standard-db-object) slotdef)
110 "sets a slot to the void value of the slot-def (usually nil)"
111 (setf (easy-slot-value object slotdef)
112 (slot-value slotdef 'void-value)))
114 (defmethod update-slot-from-db-value ((instance standard-db-object) slotdef value)
115 "This gets a value from the database and turns it itno a lisp value
116 based on the slot's slot-db-reader or baring that read-sql-value"
117 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
118 (let* ((slot-reader (view-class-slot-db-reader slotdef))
119 (slot-type (specified-type slotdef)))
121 ((null value) (update-slot-with-null instance slotdef))
123 (setf (easy-slot-value instance slotdef)
124 (read-sql-value value (delistify slot-type)
125 (choose-database-for-instance instance)
126 (database-underlying-type
127 (choose-database-for-instance instance)))))
128 (t (etypecase slot-reader
129 ((or symbol function)
130 (setf (easy-slot-value instance slotdef)
131 (apply slot-reader (list value))))
133 (setf (easy-slot-value instance slotdef)
134 (format nil slot-reader value))))))))
136 (defmethod key-value-from-db (slotdef value database)
137 "TODO: is this deprecated? there are no uses anywhere in clsql"
138 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
139 (let ((slot-reader (view-class-slot-db-reader slotdef))
140 (slot-type (specified-type slotdef)))
141 (cond ((and value (null slot-reader))
142 (read-sql-value value (delistify slot-type) database
143 (database-underlying-type database)))
146 ((typep slot-reader 'string)
147 (format nil slot-reader value))
148 ((typep slot-reader '(or symbol function))
149 (apply slot-reader (list value)))
151 (error "Slot reader is of an unusual type.")))))
153 (defun db-value-from-slot (slotdef val database)
154 (let ((dbwriter (view-class-slot-db-writer slotdef))
155 (dbtype (specified-type slotdef)))
157 (string (format nil dbwriter val))
158 ((and (or symbol function) (not null)) (apply dbwriter (list val)))
160 (database-output-sql-as-type
164 val database (database-underlying-type database))))))
166 (defun check-slot-type (slotdef val)
167 (let* ((slot-type (specified-type slotdef))
168 (basetype (if (listp slot-type) (car slot-type) slot-type)))
169 (when (and slot-type val)
170 (unless (typep val basetype)
171 (error 'sql-user-error
173 (format nil "Invalid value ~A in slot ~A, not of type ~A."
174 val (slot-definition-name slotdef) slot-type))))))
176 (defmethod get-slot-values-from-view (obj slotdeflist values)
177 "Used to copy values from the database into the object
178 used by things like find-all and select"
179 (loop for slot in slotdeflist
181 do (update-slot-from-db-value obj slot value))
184 (defclass class-and-slots ()
185 ((view-class :accessor view-class :initarg :view-class :initform nil)
186 (slot-defs :accessor slot-defs :initarg :slot-defs :initform nil))
187 (:documentation "A helper class to keep track of which slot-defs from a
188 table need to be updated, a normalized class might have many of these
189 because each of its parent classes might represent some other table and we
190 need to match which slots came from which parent class/table"))
192 (defun make-class-and-slots (c &optional s)
193 "Create a new class-and-slots object"
194 (make-instance 'class-and-slots :view-class c :slot-defs (listify s) ))
196 (defmethod view-table ((o class-and-slots))
197 "get the view-table of the view-class of o"
198 (view-table (view-class o)))
200 (defmethod view-table-exp ((o class-and-slots))
201 (sql-expression :table (view-table o)))
203 (defmethod view-table-exp ((o standard-db-class))
204 (sql-expression :table (view-table o)))
206 (defmethod attribute-references ((o class-and-slots))
208 with class = (view-class o)
209 for sd in (slot-defs o)
210 collect (generate-attribute-reference class sd)))
212 (defmethod attribute-value-pairs ((def class-and-slots) (o standard-db-object)
214 "for a given class-and-slots and object, create the sql-expression & value pairs
215 that need to be sent to the database"
216 (loop for s in (slot-defs def)
217 for n = (to-slot-name s)
218 when (slot-boundp o n)
219 collect (make-attribute-value-pair s (slot-value o n) database)))
221 (defmethod view-classes-and-slots-by-name ((obj standard-db-object) slots-to-match)
222 "If it's normalized, find the class that actually contains
223 the slot that's tied to the db,
225 otherwise just search the current class
227 (let* ((view-class (class-of obj))
228 (normalizedp (normalizedp view-class))
230 (labels ((get-c&s-obj (class)
231 (or (find class rtns :key #'view-class)
232 (first (push (make-class-and-slots class) rtns))))
233 (associate-slot-with-class (class slot)
234 "Find the best class to associate with the slot. If it is
235 normalized then it needs to be a direct slot otherwise it just
236 needs to be on the class."
237 (let ((sd (find-slot-by-name class slot normalizedp nil)))
239 ;;we found it directly or it's (not normalized)
240 (pushnew sd (slot-defs (get-c&s-obj class)))
242 (loop for parent in (class-direct-superclasses class)
243 until (associate-slot-with-class parent slot))))
246 for in-slot in (listify slots-to-match)
247 do (associate-slot-with-class view-class in-slot)))
250 (defun update-auto-increments-keys (class obj database)
251 ;; handle pulling any autoincrement values into the object
252 (let ((pk-slots (keyslots-for-class class))
253 (table (view-table class))
255 (labels ((do-update (slot)
256 (when (and (null (easy-slot-value obj slot))
257 (auto-increment-column-p slot database))
258 (update-slot-from-db-value
262 (database-last-auto-increment-id
263 database table slot))))))
264 (chain-primary-keys (in-class)
265 "This seems kindof wrong, but this is mostly how it was working, so
266 its here to keep the normalized code path working"
267 (when (typep in-class 'standard-db-class)
268 (loop for slot in (keyslots-for-class in-class)
270 (loop for c in (class-direct-superclasses in-class)
271 do (chain-primary-keys c)))))
272 (loop for slot in pk-slots do (do-update slot))
273 (let ((direct-class (to-class obj)))
274 (when (and new-pk-value (normalizedp direct-class))
275 (chain-primary-keys direct-class)))
278 (defmethod %update-instance-helper
279 (class-and-slots obj database
280 &aux (avps (attribute-value-pairs class-and-slots obj database)))
281 ;; we dont actually need to update anything on this particular parent class
282 (unless avps (return-from %update-instance-helper))
284 (let* ((view-class (view-class class-and-slots))
285 (table (view-table view-class))
286 (table-sql (sql-expression :table table)))
288 ;; view database is the flag we use to tell it was pulled from a database
289 ;; and thus probably needs an update instead of an insert
290 (cond ((view-database obj)
291 (let ((where (key-qualifier-for-instance
292 obj :database database :this-class view-class)))
294 (error "update-record-from-*: could not generate a where clause for ~a using ~A"
296 (update-records table-sql
299 :database database)))
300 (T ;; was not pulled from the db so insert it
301 ;; avps MUST contain any primary key slots set
302 ;; by previous inserts of the same object into different
303 ;; tables (ie: normalized stuff)
304 (insert-records :into table-sql
307 (update-auto-increments-keys view-class obj database)
308 ;; we dont set view database here, because there could be
309 ;; N of these for each call to update-record-from-* because
310 ;; of normalized classes
312 (update-slot-default-values obj class-and-slots)))
314 (defmethod update-record-from-slots ((obj standard-db-object) slots
315 &key (database *default-database*))
316 (setf slots (listify slots))
317 (let* ((classes-and-slots (view-classes-and-slots-by-name obj slots))
318 (database (choose-database-for-instance obj database)))
319 (loop for class-and-slots in classes-and-slots
320 do (%update-instance-helper class-and-slots obj database))
321 (setf (slot-value obj 'view-database) database))
324 (defmethod update-record-from-slot
325 ((obj standard-db-object) slot &key (database *default-database*))
326 (update-record-from-slots obj slot :database database))
328 (defun view-classes-and-storable-slots (class)
329 "Get a list of all the tables we need to update and the slots on them
331 for non normalized classes we return the class and all its storable slots
333 for normalized classes we return a list of direct slots and the class they
334 came from for each normalized view class
336 (setf class (to-class class))
338 (labels ((storable-slots (class)
339 (loop for sd in (slots-for-possibly-normalized-class class)
340 when (key-or-base-slot-p sd)
342 (get-classes-and-slots (class &aux (normalizedp (normalizedp class)))
343 (let ((slots (storable-slots class)))
345 (push (make-class-and-slots class slots) rtns)))
347 (loop for new-class in (class-direct-superclasses class)
348 do (when (typep new-class 'standard-db-class)
349 (get-classes-and-slots new-class))))))
350 (get-classes-and-slots class))
353 (defmethod primary-key-slot-values ((obj standard-db-object)
355 (defaulting class (class-of obj)
356 slots (keyslots-for-class class))
357 (loop for slot in slots
358 collect (easy-slot-value obj slot)))
360 (defmethod update-slot-default-values ((obj standard-db-object)
362 "Makes sure that if a class has unfilled slots that claim to have a default,
363 that we retrieve those defaults from the database
365 TODO: use update slots-from-record instead to batch this!"
366 (loop for class-and-slots in (listify classes-and-slots)
367 do (loop for slot in (slot-defs class-and-slots)
368 do (when (and (slot-has-default-p slot)
369 (not (easy-slot-value obj slot)))
370 (update-slot-from-record obj (to-slot-name slot))))))
372 (defmethod update-records-from-instance ((obj standard-db-object)
373 &key (database *default-database*))
374 "Updates the records in the database associated with this object if
375 view-database slot on the object is nil then the object is assumed to be
377 (let ((database (choose-database-for-instance obj database))
378 (classes-and-slots (view-classes-and-storable-slots obj)))
379 (loop for class-and-slots in classes-and-slots
380 do (%update-instance-helper class-and-slots obj database))
381 (setf (slot-value obj 'view-database) database)
382 (primary-key-slot-values obj)))
384 (defmethod delete-instance-records ((instance standard-db-object) &key database)
385 (let ((database (choose-database-for-instance instance database))
386 (vt (sql-expression :table (view-table (class-of instance)))))
388 (let ((qualifier (key-qualifier-for-instance instance :database database)))
389 (delete-records :from vt :where qualifier :database database)
390 (setf (record-caches database) nil)
391 (setf (slot-value instance 'view-database) nil)
393 (signal-no-database-error database))))
395 (defmethod update-instance-from-records ((instance standard-db-object)
396 &key (database *default-database*)
398 (let* ((view-class (or this-class (class-of instance)))
399 (pclass (car (class-direct-superclasses view-class)))
401 (when (normalizedp view-class)
402 (setf pres (update-instance-from-records instance :database database
403 :this-class pclass)))
404 (let* ((view-table (sql-expression :table (view-table view-class)))
405 (vd (choose-database-for-instance instance database))
406 (view-qual (key-qualifier-for-instance instance :database vd
407 :this-class view-class))
408 (sels (generate-selection-list view-class))
411 (setf res (apply #'select (append (mapcar #'cdr sels)
412 (list :from view-table
417 (setf (slot-value instance 'view-database) vd)
418 (get-slot-values-from-view instance (mapcar #'car sels) (car res))))
423 (defmethod get-slot-value-from-record ((instance standard-db-object)
424 slot &key (database *default-database*))
425 (let* ((class-and-slot
427 (view-classes-and-slots-by-name instance slot)))
428 (view-class (view-class class-and-slot))
429 (slot-def (first (slot-defs class-and-slot)))
430 (vd (choose-database-for-instance instance database))
431 (att-ref (first (attribute-references class-and-slot)))
434 :from (view-table-exp class-and-slot)
435 :where (key-qualifier-for-instance
438 :this-class view-class)
441 (values res slot-def)))
443 (defmethod update-slot-from-record ((instance standard-db-object)
444 slot &key (database *default-database*))
445 (multiple-value-bind (res slot-def)
446 (get-slot-value-from-record instance slot :database database)
447 (let ((vd (choose-database-for-instance instance database)))
448 (setf (slot-value instance 'view-database) vd)
449 (update-slot-from-db-value instance slot-def res))))
452 (defvar +no-slot-value+ '+no-slot-value+)
454 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
455 (let* ((class (find-class classname))
456 (sld (slotdef-for-slot-with-class slot class)))
458 (if (eq value +no-slot-value+)
459 (sql-expression :attribute (database-identifier sld database)
460 :table (view-table class))
465 (error "Unknown slot ~A for class ~A" slot classname))))
467 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
468 (declare (ignore database))
469 (let* ((class (find-class classname)))
470 (unless (view-table class)
471 (error "No view-table for class ~A" classname))
472 (sql-expression :table (view-table class))))
475 (defmethod database-get-type-specifier (type args database db-type)
476 (declare (ignore type args database db-type))
477 (format nil "VARCHAR(~D)" *default-string-length*))
479 (defmethod database-get-type-specifier ((type (eql 'integer)) args database db-type)
480 (declare (ignore database db-type))
482 (format nil "INT(~A)" (car args))
486 "An 8-bit integer, this width may vary by SQL implementation."
489 (defmethod database-get-type-specifier ((type (eql 'tinyint)) args database db-type)
490 (declare (ignore args database db-type))
494 "An integer smaller than a 32-bit integer. this width may vary by SQL implementation."
497 (defmethod database-get-type-specifier ((type (eql 'smallint)) args database db-type)
498 (declare (ignore args database db-type))
501 (deftype mediumint ()
502 "An integer smaller than a 32-bit integer, but may be larger than a smallint. This width may vary by SQL implementation."
505 (defmethod database-get-type-specifier ((type (eql 'mediumint)) args database db-type)
506 (declare (ignore args database db-type))
510 "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
513 (defmethod database-get-type-specifier ((type (eql 'bigint)) args database db-type)
514 (declare (ignore args database db-type))
517 (deftype varchar (&optional size)
518 "A variable length string for the SQL varchar type."
519 (declare (ignore size))
522 (defmethod database-get-type-specifier ((type (eql 'varchar)) args
524 (declare (ignore database db-type))
526 (format nil "VARCHAR(~A)" (car args))
527 (format nil "VARCHAR(~D)" *default-string-length*)))
529 (defmethod database-get-type-specifier ((type (eql 'string)) args database db-type)
530 (declare (ignore database db-type))
532 (format nil "CHAR(~A)" (car args))
533 (format nil "VARCHAR(~D)" *default-string-length*)))
535 (deftype universal-time ()
536 "A positive integer as returned by GET-UNIVERSAL-TIME."
539 (defmethod database-get-type-specifier ((type (eql 'universal-time)) args database db-type)
540 (declare (ignore args database db-type))
543 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database db-type)
544 (declare (ignore args database db-type))
547 (defmethod database-get-type-specifier ((type (eql 'date)) args database db-type)
548 (declare (ignore args database db-type))
551 (defmethod database-get-type-specifier ((type (eql 'duration)) args database db-type)
552 (declare (ignore database args db-type))
555 (defmethod database-get-type-specifier ((type (eql 'money)) args database db-type)
556 (declare (ignore database args db-type))
560 (deftype char (&optional len)
561 "A lisp type for the SQL CHAR type."
564 (defmethod database-get-type-specifier ((type (eql 'float)) args database db-type)
565 (declare (ignore database db-type))
567 (format nil "FLOAT(~A)" (car args))
570 (defmethod database-get-type-specifier ((type (eql 'long-float)) args database db-type)
571 (declare (ignore database db-type))
573 (format nil "FLOAT(~A)" (car args))
576 (deftype generalized-boolean ()
577 "A type which outputs a SQL boolean value, though any lisp type can be stored in the slot."
580 (defmethod database-get-type-specifier ((type (eql 'boolean)) args database db-type)
581 (declare (ignore args database db-type))
584 (defmethod database-get-type-specifier ((type (eql 'generalized-boolean)) args database db-type)
585 (declare (ignore args database db-type))
588 (defmethod database-get-type-specifier ((type (eql 'number)) args database db-type)
589 (declare (ignore database db-type))
591 ((and (consp args) (= (length args) 2))
592 (format nil "NUMBER(~D,~D)" (first args) (second args)))
593 ((and (consp args) (= (length args) 1))
594 (format nil "NUMBER(~D)" (first args)))
598 (defmethod database-get-type-specifier ((type (eql 'char)) args database db-type)
599 (declare (ignore database db-type))
601 (format nil "CHAR(~D)" (first args))
605 (defmethod database-output-sql-as-type (type val database db-type)
606 (declare (ignore type database db-type))
609 (defmethod database-output-sql-as-type ((type (eql 'list)) val database db-type)
610 (declare (ignore database db-type))
611 (progv '(*print-circle* *print-array*) '(t t)
612 (let ((escaped (prin1-to-string val)))
613 (substitute-char-string
614 escaped #\Null " "))))
616 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database db-type)
617 (declare (ignore database db-type))
620 (package-name (symbol-package val))
625 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database db-type)
626 (declare (ignore database db-type))
631 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database db-type)
632 (declare (ignore database db-type))
633 (progv '(*print-circle* *print-array*) '(t t)
634 (prin1-to-string val)))
636 (defmethod database-output-sql-as-type ((type (eql 'array)) val database db-type)
637 (declare (ignore database db-type))
638 (progv '(*print-circle* *print-array*) '(t t)
639 (prin1-to-string val)))
641 (defmethod database-output-sql-as-type ((type (eql 'boolean)) val database db-type)
642 (declare (ignore database db-type))
645 (defmethod database-output-sql-as-type ((type (eql 'generalized-boolean)) val database db-type)
646 (declare (ignore database db-type))
649 (defmethod database-output-sql-as-type ((type (eql 'string)) val database db-type)
650 (declare (ignore database db-type))
653 (defmethod database-output-sql-as-type ((type (eql 'char)) val database db-type)
654 (declare (ignore database db-type))
656 (character (write-to-string val))
659 (defmethod database-output-sql-as-type ((type (eql 'float)) val database db-type)
660 (declare (ignore database db-type))
661 (if (eq (type-of val) 'null)
663 (let ((*read-default-float-format* (type-of val)))
664 (format nil "~F" val))))
666 (defmethod read-sql-value (val type database db-type)
667 (declare (ignore database db-type))
669 ((null type) val) ;;we have no desired type, just give the value
670 ((typep val type) val) ;;check that it hasn't already been converted.
671 ((typep val 'string) (read-from-string val)) ;;maybe read will just take care of it?
672 (T (error "Unable to read-sql-value ~a as type ~a" val type))))
674 (defmethod read-sql-value (val (type (eql 'string)) database db-type)
675 (declare (ignore database db-type))
678 (defmethod read-sql-value (val (type (eql 'varchar)) database db-type)
679 (declare (ignore database db-type))
682 (defmethod read-sql-value (val (type (eql 'char)) database db-type)
683 (declare (ignore database db-type))
686 (defmethod read-sql-value (val (type (eql 'keyword)) database db-type)
687 (declare (ignore database db-type))
688 (when (< 0 (length val))
689 (intern (symbol-name-default-case val)
690 (find-package '#:keyword))))
692 (defmethod read-sql-value (val (type (eql 'symbol)) database db-type)
693 (declare (ignore database db-type))
694 (when (< 0 (length val))
695 (unless (string= val (symbol-name-default-case "NIL"))
696 (read-from-string val))))
698 (defmethod read-sql-value (val (type (eql 'integer)) database db-type)
699 (declare (ignore database db-type))
702 (unless (string-equal "NIL" val)
703 (parse-integer val)))
706 (defmethod read-sql-value (val (type (eql 'smallint)) database db-type)
707 (declare (ignore database db-type))
710 (unless (string-equal "NIL" val)
711 (parse-integer val)))
714 (defmethod read-sql-value (val (type (eql 'bigint)) database db-type)
715 (declare (ignore database db-type))
718 (unless (string-equal "NIL" val)
719 (parse-integer val)))
722 (defmethod read-sql-value (val (type (eql 'float)) database db-type)
723 (declare (ignore database db-type))
724 ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
726 (string (float (read-from-string val)))
729 (defmethod read-sql-value (val (type (eql 'double-float)) database db-type)
730 (declare (ignore database db-type))
731 ;; writing 1.0 writes 1, so if we *really* want a float, must do (float ...)
734 (let ((*read-default-float-format* 'double-float))
735 (read-from-string val))
738 (float (coerce val 'double-float))))
740 (defmethod read-sql-value (val (type (eql 'boolean)) database db-type)
741 (declare (ignore database db-type))
744 (defmethod read-sql-value (val (type (eql 'generalized-boolean)) database db-type)
745 (declare (ignore database db-type))
748 (defmethod read-sql-value (val (type (eql 'number)) database db-type)
749 (declare (ignore database db-type))
752 (unless (string-equal "NIL" val)
753 (read-from-string val)))
756 (defmethod read-sql-value (val (type (eql 'universal-time)) database db-type)
757 (declare (ignore database db-type))
758 (unless (eq 'NULL val)
764 (defmethod read-sql-value (val (type (eql 'wall-time)) database db-type)
765 (declare (ignore database db-type))
766 (unless (eq 'NULL val)
767 (parse-timestring val)))
769 (defmethod read-sql-value (val (type (eql 'date)) database db-type)
770 (declare (ignore database db-type))
771 (unless (eq 'NULL val)
772 (parse-datestring val)))
774 (defmethod read-sql-value (val (type (eql 'duration)) database db-type)
775 (declare (ignore database db-type))
776 (unless (or (eq 'NULL val)
778 (parse-timestring val)))
780 ;; ------------------------------------------------------------
781 ;; Logic for 'faulting in' :join slots
783 ;; this works, but is inefficient requiring (+ 1 n-rows)
786 (defun fault-join-target-slot (class object slot-def)
787 (let* ((res (fault-join-slot-raw class object slot-def))
788 (dbi (view-class-slot-db-info slot-def))
789 (target-name (gethash :target-slot dbi))
790 (target-class (find-class target-name)))
792 (mapcar (lambda (obj)
798 (find target-name (class-slots (class-of obj))
799 :key #'slot-definition-name)))
802 #+ignore ;; this doesn't work when attempting to call slot-value
803 (mapcar (lambda (obj)
804 (cons obj (slot-value obj ts))) res))))
806 (defun fault-join-target-slot (class object slot-def)
807 (let* ((dbi (view-class-slot-db-info slot-def))
808 (ts (gethash :target-slot dbi))
809 (jc (gethash :join-class dbi))
810 (jc-view-table (view-table (find-class jc)))
811 (tdbi (view-class-slot-db-info
812 (find ts (class-slots (find-class jc))
813 :key #'slot-definition-name)))
814 (retrieval (gethash :retrieval tdbi))
815 (tsc (gethash :join-class tdbi))
816 (ts-view-table (view-table (find-class tsc)))
817 (jq (join-qualifier class object slot-def))
818 (key (slot-value object (gethash :home-key dbi))))
825 :inner-join (sql-expression :table jc-view-table)
829 :attribute (gethash :foreign-key tdbi)
830 :table ts-view-table)
832 :attribute (gethash :home-key tdbi)
833 :table jc-view-table))
836 :database (choose-database-for-instance object))))
837 (mapcar #'(lambda (i)
838 (let* ((instance (car i))
839 (jcc (make-instance jc :view-database (choose-database-for-instance instance))))
840 (setf (slot-value jcc (gethash :foreign-key dbi))
842 (setf (slot-value jcc (gethash :home-key tdbi))
843 (slot-value instance (gethash :foreign-key tdbi)))
844 (list instance jcc)))
847 ;; just fill in minimal slots
850 (let ((instance (make-instance tsc :view-database (choose-database-for-instance object)))
851 (jcc (make-instance jc :view-database (choose-database-for-instance object)))
853 (setf (slot-value instance (gethash :home-key tdbi)) fk)
854 (setf (slot-value jcc (gethash :foreign-key dbi))
856 (setf (slot-value jcc (gethash :home-key tdbi))
858 (list instance jcc)))
859 (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
860 :from (sql-expression :table jc-view-table)
862 :database (choose-database-for-instance object))))))))
867 (defvar *default-update-objects-max-len* nil
868 "The default value to use for the MAX-LEN keyword argument to
869 UPDATE-OBJECT-JOINS.")
871 (defun update-objects-joins (objects &key (slots t) (force-p t)
873 *default-update-objects-max-len*))
874 "Updates from the records of the appropriate database tables
875 the join slots specified by SLOTS in the supplied list of View
876 Class instances OBJECTS. SLOTS is t by default which means that
877 all join slots with :retrieval :immediate are updated. CLASS-NAME
878 is used to specify the View Class of all instance in OBJECTS and
879 default to nil which means that the class of the first instance
880 in OBJECTS is used. FORCE-P is t by default which means that all
881 join slots are updated whereas a value of nil means that only
882 unbound join slots are updated. MAX-LEN defaults to
883 *DEFAULT-UPDATE-OBJECTS-MAX-LEN* and when non-nil specifies that
884 UPDATE-OBJECT-JOINS may issue multiple database queries with a
885 maximum of MAX-LEN instances updated in each query."
886 (assert (or (null max-len) (plusp max-len)))
889 (setq class-name (class-name (class-of (first objects)))))
890 (let* ((class (find-class class-name))
891 (class-slots (ordered-class-slots class))
894 (generate-retrieval-joins-list class :deferred)
896 (mapcar #'(lambda (name)
897 (let ((slotdef (find name class-slots :key #'slot-definition-name)))
899 (warn "Unable to find slot named ~S in class ~S." name class))
902 (dolist (slotdef slotdefs)
903 (let* ((dbi (view-class-slot-db-info slotdef))
904 (slotdef-name (slot-definition-name slotdef))
905 (foreign-key (gethash :foreign-key dbi))
906 (home-key (gethash :home-key dbi))
910 (mapcar #'(lambda (o) (slot-value o home-key)) objects)
913 #'(lambda (o) (if (slot-boundp o slotdef-name)
915 (slot-value o home-key)))
917 (n-object-keys (length object-keys))
918 (query-len (or max-len n-object-keys)))
920 (do ((i 0 (+ i query-len)))
921 ((>= i n-object-keys))
922 (let* ((keys (if max-len
923 (subseq object-keys i (min (+ i query-len) n-object-keys))
925 (results (unless (gethash :target-slot dbi)
926 (find-all (list (gethash :join-class dbi))
927 :where (make-instance 'sql-relational-exp
929 :sub-expressions (list (sql-expression :attribute foreign-key)
934 (dolist (object objects)
935 (when (or force-p (not (slot-boundp object slotdef-name)))
936 (let ((res (if results
937 (remove-if-not #'(lambda (obj)
938 (equal obj (slot-value
947 (when (gethash :target-slot dbi)
948 (fault-join-target-slot class object slotdef))))))
950 (setf (slot-value object slotdef-name)
951 (if (gethash :set dbi) res (car res)))))))))))))
954 (defun fault-join-slot-raw (class object slot-def)
955 (let* ((dbi (view-class-slot-db-info slot-def))
956 (jc (gethash :join-class dbi)))
957 (let ((jq (join-qualifier class object slot-def)))
959 (select jc :where jq :flatp t :result-types nil
960 :database (choose-database-for-instance object))))))
964 (defun fault-join-slot (class object slot-def)
965 (let* ((dbi (view-class-slot-db-info slot-def))
966 (ts (gethash :target-slot dbi))
967 (dbi-set (gethash :set dbi)))
969 (fault-join-target-slot class object slot-def)
970 (let ((res (fault-join-slot-raw class object slot-def)))
973 ((and ts (not dbi-set))
974 (mapcar (lambda (obj) (slot-value obj ts)) res))
975 ((and (not ts) (not dbi-set))
977 ((and (not ts) dbi-set)
980 (defun update-fault-join-normalized-slot (class object slot-def)
981 (if (and (normalizedp class) (key-slot-p slot-def))
982 (setf (easy-slot-value object slot-def)
983 (normalized-key-value object))
984 (update-slot-from-record object slot-def)))
986 (defun join-qualifier (class object slot-def)
987 (declare (ignore class))
988 (let* ((dbi (view-class-slot-db-info slot-def))
989 (jc (find-class (gethash :join-class dbi)))
990 ;;(ts (gethash :target-slot dbi))
991 ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
992 (foreign-keys (gethash :foreign-key dbi))
993 (home-keys (gethash :home-key dbi)))
994 (when (every #'(lambda (slt)
995 (and (slot-boundp object slt)
996 (not (null (slot-value object slt)))))
997 (if (listp home-keys) home-keys (list home-keys)))
999 (mapcar #'(lambda (hk fk)
1000 (let ((fksd (slotdef-for-slot-with-class fk jc)))
1006 (database-identifier fksd nil)
1007 :table (database-identifier jc nil)))
1011 (slot-value object hk))
1014 (if (listp home-keys)
1017 (if (listp foreign-keys)
1019 (list foreign-keys)))))
1021 (if (> (length jc) 1)
1022 (apply #'sql-and jc)
1025 ;; FIXME: add retrieval immediate for efficiency
1026 ;; For example, for (select 'employee-address) in test suite =>
1027 ;; select addr.*,ea_join.* FROM addr,ea_join WHERE ea_join.aaddressid=addr.addressid\g
1029 (defun build-objects (vals sclasses immediate-join-classes sels immediate-joins database refresh flatp instances)
1030 "Used by find-all to build objects."
1031 (labels ((build-object (vals vclass jclasses selects immediate-selects instance)
1032 (let* ((db-vals (butlast vals (- (list-length vals)
1033 (list-length selects))))
1034 (obj (if instance instance (make-instance (class-name vclass) :view-database database)))
1035 (join-vals (subseq vals (list-length selects)))
1036 (joins (mapcar #'(lambda (c) (when c (make-instance c :view-database database)))
1039 ;;(format t "joins: ~S~%db-vals: ~S~%join-values: ~S~%selects: ~S~%immediate-selects: ~S~%"
1040 ;;joins db-vals join-vals selects immediate-selects)
1042 ;; use refresh keyword here
1043 (setf obj (get-slot-values-from-view obj (mapcar #'car selects) db-vals))
1044 (mapc #'(lambda (jo)
1045 ;; find all immediate-select slots and join-vals for this object
1046 (let* ((jo-class (class-of jo))
1047 (slots (slots-for-possibly-normalized-class jo-class))
1048 (pos-list (remove-if #'null
1051 (position s immediate-selects
1055 (get-slot-values-from-view jo
1057 (mapcar #'(lambda (pos)
1058 (nth pos immediate-selects))
1060 (mapcar #'(lambda (pos) (nth pos join-vals))
1066 (class-slots vclass))
1067 (slot (find (class-name (class-of jc)) vslots
1068 :key #'(lambda (slot)
1069 (when (and (eq :join (view-class-slot-db-kind slot))
1070 (eq (slot-definition-name slot)
1071 (gethash :join-class (view-class-slot-db-info slot))))
1072 (slot-definition-name slot))))))
1074 (setf (slot-value obj (slot-definition-name slot)) jc))))
1076 (when refresh (instance-refreshed obj))
1079 (mapcar #'(lambda (sclass jclass sel immediate-join instance)
1081 (build-object vals sclass jclass sel immediate-join instance)
1082 (setf vals (nthcdr (+ (list-length sel) (list-length immediate-join))
1084 sclasses immediate-join-classes sels immediate-joins instances)))
1085 (if (and flatp (= (length sclasses) 1))
1089 (defmethod select-table-sql-expr ((table T))
1090 "Turns an object representing a table into the :from part of the sql expression that will be executed "
1091 (sql-expression :table (view-table table)))
1094 (defun find-all (view-classes
1096 &key all set-operation distinct from where group-by having
1097 order-by offset limit refresh flatp result-types
1099 (database *default-database*)
1100 instances parameters)
1101 "Called by SELECT to generate object query results when the
1102 View Classes VIEW-CLASSES are passed as arguments to SELECT."
1103 (declare (ignore all set-operation group-by having offset limit inner-join on parameters)
1104 (dynamic-extent args))
1105 (flet ((ref-equal (ref1 ref2)
1106 (string= (sql-output ref1 database)
1107 (sql-output ref2 database))))
1108 (declare (dynamic-extent (function ref-equal)))
1109 (let ((args (filter-plist args :from :where :flatp :additional-fields :result-types :instances)))
1110 (let* ((*db-deserializing* t)
1111 (sclasses (mapcar #'find-class view-classes))
1112 (immediate-join-slots
1113 (mapcar #'(lambda (c) (generate-retrieval-joins-list c :immediate)) sclasses))
1114 (immediate-join-classes
1115 (mapcar #'(lambda (jcs)
1116 (mapcar #'(lambda (slotdef)
1117 (find-class (gethash :join-class (view-class-slot-db-info slotdef))))
1119 immediate-join-slots))
1120 (immediate-join-sels (mapcar #'generate-immediate-joins-selection-list sclasses))
1121 (sels (mapcar #'generate-selection-list sclasses))
1122 (fullsels (apply #'append (mapcar #'append sels immediate-join-sels)))
1123 (sel-tables (collect-table-refs where))
1124 (tables (remove-if #'null
1126 (append (mapcar #'select-table-sql-expr sclasses)
1127 (mapcan #'(lambda (jc-list)
1129 #'(lambda (jc) (when jc (select-table-sql-expr jc)))
1131 immediate-join-classes)
1133 :test #'database-identifier-equal)))
1134 (order-by-slots (mapcar #'(lambda (ob) (if (atom ob) ob (car ob)))
1135 (listify order-by)))
1138 ;;(format t "sclasses: ~W~%ijc: ~W~%tables: ~W~%" sclasses immediate-join-classes tables)
1140 (dolist (ob order-by-slots)
1141 (when (and ob (not (member ob (mapcar #'cdr fullsels)
1142 :test #'ref-equal)))
1144 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1146 (dolist (ob (listify distinct))
1147 (when (and (typep ob 'sql-ident)
1148 (not (member ob (mapcar #'cdr fullsels)
1149 :test #'ref-equal)))
1151 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1153 (mapcar #'(lambda (vclass jclasses jslots)
1156 #'(lambda (jclass jslot)
1157 (let ((dbi (view-class-slot-db-info jslot)))
1160 (list (sql-operation '==
1162 :attribute (gethash :foreign-key dbi)
1163 :table (view-table jclass))
1165 :attribute (gethash :home-key dbi)
1166 :table (view-table vclass))))
1167 (when join-where (listify join-where))))))
1169 sclasses immediate-join-classes immediate-join-slots)
1170 ;; Reported buggy on clsql-devel
1171 ;; (when where (setq where (listify where)))
1173 ((and where join-where)
1174 (setq where (list (apply #'sql-and where join-where))))
1175 ((and (null where) (> (length join-where) 1))
1176 (setq where (list (apply #'sql-and join-where)))))
1178 (let* ((rows (apply #'select
1179 (append (mapcar #'cdr fullsels)
1181 (list (append (when from (listify from))
1183 (list :result-types result-types)
1185 (list :where where))
1187 (instances-to-add (- (length rows) (length instances)))
1188 (perhaps-extended-instances
1189 (if (plusp instances-to-add)
1190 (append instances (do ((i 0 (1+ i))
1192 ((= i instances-to-add) res)
1193 (push (make-list (length sclasses) :initial-element nil) res)))
1196 #'(lambda (row instance)
1197 (build-objects row sclasses immediate-join-classes sels
1198 immediate-join-sels database refresh flatp
1199 (if (and flatp (atom instance))
1202 rows perhaps-extended-instances)))
1205 (defmethod instance-refreshed ((instance standard-db-object)))
1207 (defvar *default-caching* t
1208 "Controls whether SELECT caches objects by default. The CommonSQL
1209 specification states caching is on by default.")
1211 (defun select (&rest select-all-args)
1212 "Executes a query on DATABASE, which has a default value of
1213 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
1214 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
1215 argument can be used to generate queries in both functional and
1216 object oriented contexts.
1218 In the functional case, the required arguments specify the
1219 columns selected by the query and may be symbolic SQL expressions
1220 or strings representing attribute identifiers. Type modified
1221 identifiers indicate that the values selected from the specified
1222 column are converted to the specified lisp type. The keyword
1223 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
1224 SET-OPERATION and WHERE are used to specify, using the symbolic
1225 SQL syntax, the corresponding components of the SQL query
1226 generated by the call to SELECT. RESULT-TYPES is a list of
1227 symbols which specifies the lisp type for each field returned by
1228 the query. If RESULT-TYPES is nil all results are returned as
1229 strings whereas the default value of :auto means that the lisp
1230 types are automatically computed for each field. FIELD-NAMES is t
1231 by default which means that the second value returned is a list
1232 of strings representing the columns selected by the query. If
1233 FIELD-NAMES is nil, the list of column names is not returned as a
1236 In the object oriented case, the required arguments to SELECT are
1237 symbols denoting View Classes which specify the database tables
1238 to query. In this case, SELECT returns a list of View Class
1239 instances whose slots are set from the attribute values of the
1240 records in the specified table. Slot-value is a legal operator
1241 which can be employed as part of the symbolic SQL syntax used in
1242 the WHERE keyword argument to SELECT. REFRESH is nil by default
1243 which means that the View Class instances returned are retrieved
1244 from a cache if an equivalent call to SELECT has previously been
1245 issued. If REFRESH is true, the View Class instances returned are
1246 updated as necessary from the database and the generic function
1247 INSTANCE-REFRESHED is called to perform any necessary operations
1248 on the updated instances.
1250 In both object oriented and functional contexts, FLATP has a
1251 default value of nil which means that the results are returned as
1252 a list of lists. If FLATP is t and only one result is returned
1253 for each record selected in the query, the results are returned
1254 as elements of a list."
1255 (multiple-value-bind (target-args qualifier-args)
1256 (query-get-selections select-all-args)
1257 (unless (or *default-database* (getf qualifier-args :database))
1258 (signal-no-database-error nil))
1260 (let ((caching (getf qualifier-args :caching *default-caching*))
1261 (result-types (getf qualifier-args :result-types :auto))
1262 (refresh (getf qualifier-args :refresh nil))
1263 (database (getf qualifier-args :database *default-database*)))
1267 (every #'(lambda (arg)
1269 (find-class arg nil)))
1272 (setf qualifier-args (filter-plist qualifier-args :caching :refresh :result-types))
1274 ;; Add explicity table name to order-by if not specified and only
1275 ;; one selected table. This is required so FIND-ALL won't duplicate
1277 (let ((order-by (getf qualifier-args :order-by)))
1278 (when (and order-by (= 1 (length target-args)))
1279 (let ((table-name (view-table (find-class (car target-args))))
1280 (order-by-list (copy-seq (listify order-by))))
1281 (labels ((sv (val name) (ignore-errors (slot-value val name)))
1282 (set-table-if-needed (val)
1284 (sql-ident-attribute
1286 (if (sv val 'qualifier)
1288 (make-instance 'sql-ident-attribute
1289 :name (sv val 'name)
1290 :qualifier table-name))
1292 ;; TODO: Check for a specific error we expect
1294 (cons (cons (set-table-if-needed (car val))
1298 (loop for i from 0 below (length order-by-list)
1299 for id in order-by-list
1300 collect (set-table-if-needed id))))
1301 (setf (getf qualifier-args :order-by) order-by-list))))
1305 (apply #'find-all target-args :result-types result-types :refresh refresh qualifier-args))
1307 (let ((cached (records-cache-results target-args qualifier-args database)))
1308 (if (and cached (not refresh))
1310 (let ((results (apply #'find-all target-args
1311 :result-types :auto :refresh refresh
1314 (setf (records-cache-results target-args qualifier-args database) results)
1318 (let* ((expr (apply #'make-query select-all-args))
1319 (parameters (second (member :parameters select-all-args)))
1321 (mapcar #'(lambda (attrib)
1322 (if (typep attrib 'sql-ident-attribute)
1323 (let ((type (slot-value attrib 'type)))
1328 (slot-value expr 'selections)))
1329 (flatp (getf qualifier-args :flatp))
1330 (field-names (getf qualifier-args :field-names t)))
1333 (setf expr (command-object (sql-output expr database) parameters)))
1334 (query expr :flatp flatp
1336 ;; specifying a type for an attribute overrides result-types
1337 (if (some #'(lambda (x) (not (eq t x))) specified-types)
1340 :field-names field-names
1341 :database database)))))))
1343 (defun compute-records-cache-key (targets qualifiers)
1345 (do ((args *select-arguments* (cdr args))
1347 ((null args) results)
1348 (let* ((arg (car args))
1349 (value (getf qualifiers arg)))
1353 (cons (cons (sql (car value)) (cdr value)))
1354 (%sql-expression (sql value))
1358 (defun records-cache-results (targets qualifiers database)
1359 (when (record-caches database)
1360 (gethash (compute-records-cache-key targets qualifiers) (record-caches database))))
1362 (defun (setf records-cache-results) (results targets qualifiers database)
1363 (unless (record-caches database)
1364 (setf (record-caches database)
1365 (make-weak-hash-table :test 'equal)))
1366 (setf (gethash (compute-records-cache-key (copy-list targets) qualifiers)
1367 (record-caches database)) results)
1372 ;;; Serialization functions
1374 (defun write-instance-to-stream (obj stream)
1375 "Writes an instance to a stream where it can be later be read.
1376 NOTE: an error will occur if a slot holds a value which can not be written readably."
1377 (let* ((class (class-of obj))
1379 (dolist (slot (ordered-class-slots (class-of obj)))
1380 (let ((name (slot-definition-name slot)))
1381 (when (and (not (eq 'view-database name))
1382 (slot-boundp obj name))
1383 (push (cons name (slot-value obj name)) alist))))
1384 (setq alist (reverse alist))
1385 (write (cons (class-name class) alist) :stream stream :readably t))
1388 (defun read-instance-from-stream (stream)
1389 (let ((raw (read stream nil nil)))
1391 (let ((obj (make-instance (car raw))))
1392 (dolist (pair (cdr raw))
1393 (setf (slot-value obj (car pair)) (cdr pair)))