1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
6 ;;;; The CLSQL Object Oriented Data Definitional Language (OODDL)
7 ;;;; and Object Oriented Data Manipulation Language (OODML).
9 ;;;; This file is part of CLSQL.
11 ;;;; CLSQL users are granted the rights to distribute and use this software
12 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
13 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
14 ;;;; *************************************************************************
16 (in-package #:clsql-sys)
18 (defclass standard-db-object ()
19 ((view-database :initform nil :initarg :view-database :reader view-database
21 (:metaclass standard-db-class)
22 (:documentation "Superclass for all CLSQL View Classes."))
24 (defvar *db-auto-sync* nil
25 "A non-nil value means that creating View Class instances or
26 setting their slots automatically creates/updates the
27 corresponding records in the underlying database.")
29 (defvar *db-deserializing* nil)
30 (defvar *db-initializing* nil)
32 (defmethod slot-value-using-class ((class standard-db-class) instance slot-def)
33 (declare (optimize (speed 3)))
34 (unless *db-deserializing*
35 (let* ((slot-name (%svuc-slot-name slot-def))
36 (slot-object (%svuc-slot-object slot-def class))
37 (slot-kind (view-class-slot-db-kind slot-object)))
38 (when (and (eql slot-kind :join)
39 (not (slot-boundp instance slot-name)))
40 (let ((*db-deserializing* t))
41 (if (view-database instance)
42 (setf (slot-value instance slot-name)
43 (fault-join-slot class instance slot-object))
44 (setf (slot-value instance slot-name) nil))))))
47 (defmethod (setf slot-value-using-class) (new-value (class standard-db-class)
49 (declare (ignore new-value))
50 (let* ((slot-name (%svuc-slot-name slot-def))
51 (slot-object (%svuc-slot-object slot-def class))
52 (slot-kind (view-class-slot-db-kind slot-object)))
54 (when (and *db-auto-sync*
55 (not *db-initializing*)
56 (not *db-deserializing*)
57 (not (eql slot-kind :virtual)))
58 (update-record-from-slot instance slot-name))))
60 (defmethod initialize-instance ((object standard-db-object)
61 &rest all-keys &key &allow-other-keys)
62 (declare (ignore all-keys))
63 (let ((*db-initializing* t))
65 (when (and *db-auto-sync*
66 (not *db-deserializing*))
67 (update-records-from-instance object))))
70 ;; Build the database tables required to store the given view class
73 (defun create-view-from-class (view-class-name
74 &key (database *default-database*))
75 "Creates a table as defined by the View Class VIEW-CLASS-NAME
76 in DATABASE which defaults to *DEFAULT-DATABASE*."
77 (let ((tclass (find-class view-class-name)))
79 (let ((*default-database* database))
80 (%install-class tclass database))
81 (error "Class ~s not found." view-class-name)))
84 (defmethod %install-class ((self standard-db-class) database &aux schemadef)
85 (dolist (slotdef (ordered-class-slots self))
86 (let ((res (database-generate-column-definition (class-name self)
89 (push res schemadef))))
91 (error "Class ~s has no :base slots" self))
92 (create-table (sql-expression :table (view-table self)) schemadef
94 :constraints (database-pkey-constraint self database))
95 (push self (database-view-classes database))
98 (defmethod database-pkey-constraint ((class standard-db-class) database)
99 (let ((keylist (mapcar #'view-class-slot-column (keyslots-for-class class))))
101 (convert-to-db-default-case
102 (format nil "CONSTRAINT ~APK PRIMARY KEY~A"
103 (database-output-sql (view-table class) database)
104 (database-output-sql keylist database))
107 (defmethod database-generate-column-definition (class slotdef database)
108 (declare (ignore database class))
109 (when (member (view-class-slot-db-kind slotdef) '(:base :key))
111 (list (sql-expression :attribute (view-class-slot-column slotdef))
112 (specified-type slotdef))))
113 (setf cdef (append cdef (list (view-class-slot-db-type slotdef))))
114 (let ((const (view-class-slot-db-constraints slotdef)))
116 (setq cdef (append cdef (list const)))))
121 ;; Drop the tables which store the given view class
124 (defun drop-view-from-class (view-class-name &key (database *default-database*))
125 "Removes a table defined by the View Class VIEW-CLASS-NAME from
126 DATABASE which defaults to *DEFAULT-DATABASE*."
127 (let ((tclass (find-class view-class-name)))
129 (let ((*default-database* database))
130 (%uninstall-class tclass))
131 (error "Class ~s not found." view-class-name)))
134 (defun %uninstall-class (self &key (database *default-database*))
135 (drop-table (sql-expression :table (view-table self))
136 :if-does-not-exist :ignore
138 (setf (database-view-classes database)
139 (remove self (database-view-classes database))))
143 ;; List all known view classes
146 (defun list-classes (&key (test #'identity)
147 (root-class (find-class 'standard-db-object))
148 (database *default-database*))
149 "Returns a list of all the View Classes which are connected to
150 DATABASE, which defaults to *DEFAULT-DATABASE*, and which descend
151 from the class ROOT-CLASS and which satisfy the function TEST. By
152 default ROOT-CLASS is STANDARD-DB-OBJECT and TEST is IDENTITY."
153 (flet ((find-superclass (class)
154 (member root-class (class-precedence-list class))))
155 (let ((view-classes (and database (database-view-classes database))))
157 (remove-if #'(lambda (c) (or (not (funcall test c))
158 (not (find-superclass c))))
162 ;; Define a new view class
165 (defmacro def-view-class (class supers slots &rest cl-options)
166 "Creates a View Class called CLASS whose slots SLOTS can map
167 onto the attributes of a table in a database. If SUPERS is nil
168 then the superclass of CLASS will be STANDARD-DB-OBJECT,
169 otherwise SUPERS is a list of superclasses for CLASS which must
170 include STANDARD-DB-OBJECT or a descendent of this class. The
171 syntax of DEFCLASS is extended through the addition of a class
172 option :base-table which defines the database table onto which
173 the View Class maps and which defaults to CLASS. The DEFCLASS
174 syntax is also extended through additional slot
175 options. The :db-kind slot option specifies the kind of DB
176 mapping which is performed for this slot and defaults to :base
177 which indicates that the slot maps to an ordinary column of the
178 database table. A :db-kind value of :key indicates that this slot
179 is a special kind of :base slot which maps onto a column which is
180 one of the unique keys for the database table, the value :join
181 indicates this slot represents a join onto another View Class
182 which contains View Class objects, and the value :virtual
183 indicates a standard CLOS slot which does not map onto columns of
184 the database table. If a slot is specified with :db-kind :join,
185 the slot option :db-info contains a list which specifies the
186 nature of the join. For slots of :db-kind :base or :key,
187 the :type slot option has a special interpretation such that Lisp
188 types, such as string, integer and float are automatically
189 converted into appropriate SQL types for the column onto which
190 the slot maps. This behaviour may be over-ridden using
191 the :db-type slot option which is a string specifying the
192 vendor-specific database type for this slot's column definition
193 in the database. The :column slot option specifies the name of
194 the SQL column which the slot maps onto, if :db-kind is
195 not :virtual, and defaults to the slot name. The :void-value slot
196 option specifies the value to store if the SQL value is NULL and
197 defaults to NIL. The :db-constraints slot option is a string
198 representing an SQL table constraint expression or a list of such
201 (defclass ,class ,supers ,slots
202 ,@(if (find :metaclass `,cl-options :key #'car)
204 (cons '(:metaclass clsql-sys::standard-db-class) `,cl-options)))
205 (finalize-inheritance (find-class ',class))
206 (find-class ',class)))
208 (defun keyslots-for-class (class)
209 (slot-value class 'key-slots))
211 (defun key-qualifier-for-instance (obj &key (database *default-database*))
212 (let ((tb (view-table (class-of obj))))
215 (sql-expression :attribute
216 (view-class-slot-column k)
220 (slot-value obj (slot-definition-name k))
222 (let* ((keys (keyslots-for-class (class-of obj)))
223 (keyxprs (mapcar #'qfk (reverse keys))))
225 ((= (length keyxprs) 0) nil)
226 ((= (length keyxprs) 1) (car keyxprs))
227 ((> (length keyxprs) 1) (apply #'sql-operation 'and keyxprs)))))))
230 ;; Function used by 'generate-selection-list'
233 (defun generate-attribute-reference (vclass slotdef)
235 ((eq (view-class-slot-db-kind slotdef) :base)
236 (sql-expression :attribute (view-class-slot-column slotdef)
237 :table (view-table vclass)))
238 ((eq (view-class-slot-db-kind slotdef) :key)
239 (sql-expression :attribute (view-class-slot-column slotdef)
240 :table (view-table vclass)))
244 ;; Function used by 'find-all'
247 (defun generate-selection-list (vclass)
249 (dolist (slotdef (ordered-class-slots vclass))
250 (let ((res (generate-attribute-reference vclass slotdef)))
252 (push (cons slotdef res) sels))))
255 (error "No slots of type :base in view-class ~A" (class-name vclass)))))
259 (defun generate-retrieval-joins-list (vclass retrieval-method)
260 "Returns list of immediate join slots for a class."
261 (let ((join-slotdefs nil))
262 (dolist (slotdef (ordered-class-slots vclass) join-slotdefs)
263 (when (and (eq :join (view-class-slot-db-kind slotdef))
264 (eq retrieval-method (gethash :retrieval (view-class-slot-db-info slotdef))))
265 (push slotdef join-slotdefs)))))
267 (defun generate-immediate-joins-selection-list (vclass)
268 "Returns list of immediate join slots for a class."
270 (dolist (joined-slot (generate-retrieval-joins-list vclass :immediate) sels)
271 (let* ((join-class-name (gethash :join-class (view-class-slot-db-info joined-slot)))
272 (join-class (when join-class-name (find-class join-class-name))))
273 (dolist (slotdef (ordered-class-slots join-class))
274 (let ((res (generate-attribute-reference join-class slotdef)))
276 (push (cons slotdef res) sels))))))
280 ;; Called by 'get-slot-values-from-view'
283 (defvar *update-context* nil)
285 (defmethod update-slot-from-db ((instance standard-db-object) slotdef value)
286 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
287 (let* ((slot-reader (view-class-slot-db-reader slotdef))
288 (slot-name (slot-definition-name slotdef))
289 (slot-type (specified-type slotdef))
290 (*update-context* (cons (type-of instance) slot-name)))
291 (cond ((and value (null slot-reader))
292 (setf (slot-value instance slot-name)
293 (read-sql-value value (delistify slot-type)
294 (view-database instance)
295 (database-underlying-type
296 (view-database instance)))))
298 (update-slot-with-null instance slot-name slotdef))
299 ((typep slot-reader 'string)
300 (setf (slot-value instance slot-name)
301 (format nil slot-reader value)))
302 ((typep slot-reader 'function)
303 (setf (slot-value instance slot-name)
304 (apply slot-reader (list value))))
306 (error "Slot reader is of an unusual type.")))))
308 (defmethod key-value-from-db (slotdef value database)
309 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
310 (let ((slot-reader (view-class-slot-db-reader slotdef))
311 (slot-type (specified-type slotdef)))
312 (cond ((and value (null slot-reader))
313 (read-sql-value value (delistify slot-type) database
314 (database-underlying-type database)))
317 ((typep slot-reader 'string)
318 (format nil slot-reader value))
319 ((typep slot-reader 'function)
320 (apply slot-reader (list value)))
322 (error "Slot reader is of an unusual type.")))))
324 (defun db-value-from-slot (slotdef val database)
325 (let ((dbwriter (view-class-slot-db-writer slotdef))
326 (dbtype (specified-type slotdef)))
328 (string (format nil dbwriter val))
329 (function (apply dbwriter (list val)))
331 (database-output-sql-as-type
335 val database (database-underlying-type database))))))
337 (defun check-slot-type (slotdef val)
338 (let* ((slot-type (specified-type slotdef))
339 (basetype (if (listp slot-type) (car slot-type) slot-type)))
340 (when (and slot-type val)
341 (unless (typep val basetype)
342 (error 'sql-user-error
344 (format nil "Invalid value ~A in slot ~A, not of type ~A."
345 val (slot-definition-name slotdef) slot-type))))))
348 ;; Called by find-all
351 (defmethod get-slot-values-from-view (obj slotdeflist values)
352 (flet ((update-slot (slot-def values)
353 (update-slot-from-db obj slot-def values)))
354 (mapc #'update-slot slotdeflist values)
357 (defmethod update-record-from-slot ((obj standard-db-object) slot &key
358 (database *default-database*))
359 (let* ((database (or (view-database obj) database))
360 (vct (view-table (class-of obj)))
361 (sd (slotdef-for-slot-with-class slot (class-of obj))))
362 (check-slot-type sd (slot-value obj slot))
363 (let* ((att (view-class-slot-column sd))
364 (val (db-value-from-slot sd (slot-value obj slot) database)))
365 (cond ((and vct sd (view-database obj))
366 (update-records (sql-expression :table vct)
367 :attributes (list (sql-expression :attribute att))
369 :where (key-qualifier-for-instance
370 obj :database database)
372 ((and vct sd (not (view-database obj)))
373 (insert-records :into (sql-expression :table vct)
374 :attributes (list (sql-expression :attribute att))
377 (setf (slot-value obj 'view-database) database))
379 (error "Unable to update record.")))))
382 (defmethod update-record-from-slots ((obj standard-db-object) slots &key
383 (database *default-database*))
384 (let* ((database (or (view-database obj) database))
385 (vct (view-table (class-of obj)))
386 (sds (slotdefs-for-slots-with-class slots (class-of obj)))
387 (avps (mapcar #'(lambda (s)
388 (let ((val (slot-value
389 obj (slot-definition-name s))))
390 (check-slot-type s val)
391 (list (sql-expression
392 :attribute (view-class-slot-column s))
393 (db-value-from-slot s val database))))
395 (cond ((and avps (view-database obj))
396 (update-records (sql-expression :table vct)
398 :where (key-qualifier-for-instance
399 obj :database database)
401 ((and avps (not (view-database obj)))
402 (insert-records :into (sql-expression :table vct)
405 (setf (slot-value obj 'view-database) database))
407 (error "Unable to update records"))))
410 (defmethod update-records-from-instance ((obj standard-db-object)
411 &key (database *default-database*))
412 (let ((database (or (view-database obj) database)))
413 (labels ((slot-storedp (slot)
414 (and (member (view-class-slot-db-kind slot) '(:base :key))
415 (slot-boundp obj (slot-definition-name slot))))
416 (slot-value-list (slot)
417 (let ((value (slot-value obj (slot-definition-name slot))))
418 (check-slot-type slot value)
419 (list (sql-expression :attribute (view-class-slot-column slot))
420 (db-value-from-slot slot value database)))))
421 (let* ((view-class (class-of obj))
422 (view-class-table (view-table view-class))
423 (slots (remove-if-not #'slot-storedp
424 (ordered-class-slots view-class)))
425 (record-values (mapcar #'slot-value-list slots)))
426 (unless record-values
427 (error "No settable slots."))
428 (if (view-database obj)
429 (update-records (sql-expression :table view-class-table)
430 :av-pairs record-values
431 :where (key-qualifier-for-instance
432 obj :database database)
435 (insert-records :into (sql-expression :table view-class-table)
436 :av-pairs record-values
438 (setf (slot-value obj 'view-database) database))))))
441 (defmethod delete-instance-records ((instance standard-db-object))
442 (let ((vt (sql-expression :table (view-table (class-of instance))))
443 (vd (view-database instance)))
445 (let ((qualifier (key-qualifier-for-instance instance :database vd)))
446 (delete-records :from vt :where qualifier :database vd)
447 (setf (slot-value instance 'view-database) nil))
448 (signal-no-database-error vd))))
450 (defmethod update-instance-from-records ((instance standard-db-object)
451 &key (database *default-database*))
452 (let* ((view-class (find-class (class-name (class-of instance))))
453 (view-table (sql-expression :table (view-table view-class)))
454 (vd (or (view-database instance) database))
455 (view-qual (key-qualifier-for-instance instance :database vd))
456 (sels (generate-selection-list view-class))
457 (res (apply #'select (append (mapcar #'cdr sels)
458 (list :from view-table
460 (list :result-types nil)))))
462 (get-slot-values-from-view instance (mapcar #'car sels) (car res)))))
464 (defmethod update-slot-from-record ((instance standard-db-object)
465 slot &key (database *default-database*))
466 (let* ((view-class (find-class (class-name (class-of instance))))
467 (view-table (sql-expression :table (view-table view-class)))
468 (vd (or (view-database instance) database))
469 (view-qual (key-qualifier-for-instance instance :database vd))
470 (slot-def (slotdef-for-slot-with-class slot view-class))
471 (att-ref (generate-attribute-reference view-class slot-def))
472 (res (select att-ref :from view-table :where view-qual
475 (get-slot-values-from-view instance (list slot-def) (car res)))))
478 (defmethod update-slot-with-null ((object standard-db-object)
481 (setf (slot-value object slotname) (slot-value slotdef 'void-value)))
483 (defvar +no-slot-value+ '+no-slot-value+)
485 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
486 (let* ((class (find-class classname))
487 (sld (slotdef-for-slot-with-class slot class)))
489 (if (eq value +no-slot-value+)
490 (sql-expression :attribute (view-class-slot-column sld)
491 :table (view-table class))
496 (error "Unknown slot ~A for class ~A" slot classname))))
498 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
499 (declare (ignore database))
500 (let* ((class (find-class classname)))
501 (unless (view-table class)
502 (error "No view-table for class ~A" classname))
503 (sql-expression :table (view-table class))))
505 (defmethod database-get-type-specifier (type args database db-type)
506 (declare (ignore type args database db-type))
509 (defmethod database-get-type-specifier ((type (eql 'integer)) args database db-type)
510 (declare (ignore database db-type))
512 (format nil "INT(~A)" (car args))
516 "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
519 (defmethod database-get-type-specifier ((type (eql 'bigint)) args database db-type)
520 (declare (ignore args database db-type))
523 (defmethod database-get-type-specifier ((type (eql 'simple-base-string)) args
525 (declare (ignore database db-type))
527 (format nil "VARCHAR(~A)" (car args))
530 (defmethod database-get-type-specifier ((type (eql 'simple-string)) args
532 (declare (ignore database db-type))
534 (format nil "VARCHAR(~A)" (car args))
537 (defmethod database-get-type-specifier ((type (eql 'string)) args database db-type)
538 (declare (ignore database db-type))
540 (format nil "VARCHAR(~A)" (car args))
543 (deftype universal-time ()
544 "A positive integer as returned by GET-UNIVERSAL-TIME."
547 (defmethod database-get-type-specifier ((type (eql 'universal-time)) args database db-type)
548 (declare (ignore args database db-type))
551 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database db-type)
552 (declare (ignore args database db-type))
555 (defmethod database-get-type-specifier ((type (eql 'duration)) args database db-type)
556 (declare (ignore database args db-type))
559 (defmethod database-get-type-specifier ((type (eql 'money)) args database db-type)
560 (declare (ignore database args db-type))
563 (deftype raw-string (&optional len)
564 "A string which is not trimmed when retrieved from the database"
567 (defmethod database-get-type-specifier ((type (eql 'raw-string)) args database db-type)
568 (declare (ignore database db-type))
570 (format nil "VARCHAR(~A)" (car args))
573 (defmethod database-get-type-specifier ((type (eql 'float)) args database db-type)
574 (declare (ignore database db-type))
576 (format nil "FLOAT(~A)" (car args))
579 (defmethod database-get-type-specifier ((type (eql 'long-float)) args database db-type)
580 (declare (ignore database db-type))
582 (format nil "FLOAT(~A)" (car args))
585 (defmethod database-get-type-specifier ((type (eql 'boolean)) args database db-type)
586 (declare (ignore args database db-type))
589 (defmethod database-output-sql-as-type (type val database db-type)
590 (declare (ignore type database db-type))
593 (defmethod database-output-sql-as-type ((type (eql 'list)) val database db-type)
594 (declare (ignore database db-type))
595 (progv '(*print-circle* *print-array*) '(t t)
596 (let ((escaped (prin1-to-string val)))
597 (substitute-char-string
598 escaped #\Null " "))))
600 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database db-type)
601 (declare (ignore database db-type))
606 (package-name (symbol-package val))
611 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database db-type)
612 (declare (ignore database db-type))
617 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database db-type)
618 (declare (ignore database db-type))
619 (progv '(*print-circle* *print-array*) '(t t)
620 (prin1-to-string val)))
622 (defmethod database-output-sql-as-type ((type (eql 'array)) val database db-type)
623 (declare (ignore database db-type))
624 (progv '(*print-circle* *print-array*) '(t t)
625 (prin1-to-string val)))
627 (defmethod database-output-sql-as-type ((type (eql 'boolean)) val database db-type)
628 (declare (ignore database db-type))
631 (defmethod database-output-sql-as-type ((type (eql 'string)) val database db-type)
632 (declare (ignore database db-type))
635 (defmethod database-output-sql-as-type ((type (eql 'simple-string))
636 val database db-type)
637 (declare (ignore database db-type))
640 (defmethod database-output-sql-as-type ((type (eql 'simple-base-string))
641 val database db-type)
642 (declare (ignore database db-type))
645 (defmethod read-sql-value (val type database db-type)
646 (declare (ignore type database db-type))
647 (read-from-string val))
649 (defmethod read-sql-value (val (type (eql 'string)) database db-type)
650 (declare (ignore database db-type))
653 (defmethod read-sql-value (val (type (eql 'simple-string)) database db-type)
654 (declare (ignore database db-type))
657 (defmethod read-sql-value (val (type (eql 'simple-base-string)) database db-type)
658 (declare (ignore database db-type))
661 (defmethod read-sql-value (val (type (eql 'raw-string)) database db-type)
662 (declare (ignore database db-type))
665 (defmethod read-sql-value (val (type (eql 'keyword)) database db-type)
666 (declare (ignore database db-type))
667 (when (< 0 (length val))
668 (intern (symbol-name-default-case val)
669 (find-package '#:keyword))))
671 (defmethod read-sql-value (val (type (eql 'symbol)) database db-type)
672 (declare (ignore database db-type))
673 (when (< 0 (length val))
674 (unless (string= val (symbol-name-default-case "NIL"))
675 (intern (symbol-name-default-case val)
676 (symbol-package *update-context*)))))
678 (defmethod read-sql-value (val (type (eql 'integer)) database db-type)
679 (declare (ignore database db-type))
682 (unless (string-equal "NIL" val)
683 (parse-integer val)))
686 (defmethod read-sql-value (val (type (eql 'bigint)) 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 'float)) database db-type)
695 (declare (ignore database db-type))
696 ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
699 (float (read-from-string val)))
703 (defmethod read-sql-value (val (type (eql 'boolean)) database db-type)
704 (declare (ignore database db-type))
707 (defmethod read-sql-value (val (type (eql 'univeral-time)) database db-type)
708 (declare (ignore database db-type))
709 (unless (eq 'NULL val)
715 (defmethod read-sql-value (val (type (eql 'wall-time)) database db-type)
716 (declare (ignore database db-type))
717 (unless (eq 'NULL val)
718 (parse-timestring val)))
720 (defmethod read-sql-value (val (type (eql 'duration)) database db-type)
721 (declare (ignore database db-type))
722 (unless (or (eq 'NULL val)
724 (parse-timestring val)))
726 ;; ------------------------------------------------------------
727 ;; Logic for 'faulting in' :join slots
729 ;; this works, but is inefficient requiring (+ 1 n-rows)
732 (defun fault-join-target-slot (class object slot-def)
733 (let* ((res (fault-join-slot-raw class object slot-def))
734 (dbi (view-class-slot-db-info slot-def))
735 (target-name (gethash :target-slot dbi))
736 (target-class (find-class target-name)))
738 (mapcar (lambda (obj)
744 (find target-name (class-slots (class-of obj))
745 :key #'slot-definition-name)))
748 #+ignore ;; this doesn't work when attempting to call slot-value
749 (mapcar (lambda (obj)
750 (cons obj (slot-value obj ts))) res))))
752 (defun fault-join-target-slot (class object slot-def)
753 (let* ((dbi (view-class-slot-db-info slot-def))
754 (ts (gethash :target-slot dbi))
755 (jc (gethash :join-class dbi))
756 (ts-view-table (view-table (find-class ts)))
757 (jc-view-table (view-table (find-class jc)))
758 (tdbi (view-class-slot-db-info
759 (find ts (class-slots (find-class jc))
760 :key #'slot-definition-name)))
761 (retrieval (gethash :retrieval tdbi))
762 (jq (join-qualifier class object slot-def))
763 (key (slot-value object (gethash :home-key dbi))))
769 :inner-join (sql-expression :table jc-view-table)
773 :attribute (gethash :foreign-key tdbi)
774 :table ts-view-table)
776 :attribute (gethash :home-key tdbi)
777 :table jc-view-table))
779 :result-types :auto)))
780 (mapcar #'(lambda (i)
781 (let* ((instance (car i))
782 (jcc (make-instance jc :view-database (view-database instance))))
783 (setf (slot-value jcc (gethash :foreign-key dbi))
785 (setf (slot-value jcc (gethash :home-key tdbi))
786 (slot-value instance (gethash :foreign-key tdbi)))
787 (list instance jcc)))
790 ;; just fill in minimal slots
793 (let ((instance (make-instance ts :view-database (view-database object)))
794 (jcc (make-instance jc :view-database (view-database object)))
796 (setf (slot-value instance (gethash :home-key tdbi)) fk)
797 (setf (slot-value jcc (gethash :foreign-key dbi))
799 (setf (slot-value jcc (gethash :home-key tdbi))
801 (list instance jcc)))
802 (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
803 :from (sql-expression :table jc-view-table)
809 (defvar *default-update-objects-max-len* nil
810 "The default value to use for the MAX-LEN keyword argument to
811 UPDATE-OBJECT-JOINS.")
813 (defun update-objects-joins (objects &key (slots t) (force-p t)
815 *default-update-objects-max-len*))
816 "Updates from the records of the appropriate database tables
817 the join slots specified by SLOTS in the supplied list of View
818 Class instances OBJECTS. SLOTS is t by default which means that
819 all join slots with :retrieval :immediate are updated. CLASS-NAME
820 is used to specify the View Class of all instance in OBJECTS and
821 default to nil which means that the class of the first instance
822 in OBJECTS is used. FORCE-P is t by default which means that all
823 join slots are updated whereas a value of nil means that only
824 unbound join slots are updated. MAX-LEN defaults to
825 *DEFAULT-UPDATE-OBJECTS-MAX-LEN* and when non-nil specifies that
826 UPDATE-OBJECT-JOINS may issue multiple database queries with a
827 maximum of MAX-LEN instances updated in each query."
828 (assert (or (null max-len) (plusp max-len)))
831 (setq class-name (class-name (class-of (first objects)))))
832 (let* ((class (find-class class-name))
833 (class-slots (ordered-class-slots class))
836 (generate-retrieval-joins-list class :deferred)
838 (mapcar #'(lambda (name)
839 (let ((slotdef (find name class-slots :key #'slot-definition-name)))
841 (warn "Unable to find slot named ~S in class ~S." name class))
844 (dolist (slotdef slotdefs)
845 (let* ((dbi (view-class-slot-db-info slotdef))
846 (slotdef-name (slot-definition-name slotdef))
847 (foreign-key (gethash :foreign-key dbi))
848 (home-key (gethash :home-key dbi))
852 (mapcar #'(lambda (o) (slot-value o home-key)) objects)
855 #'(lambda (o) (if (slot-boundp o slotdef-name)
857 (slot-value o home-key)))
859 (n-object-keys (length object-keys))
860 (query-len (or max-len n-object-keys)))
862 (do ((i 0 (+ i query-len)))
863 ((>= i n-object-keys))
864 (let* ((keys (if max-len
865 (subseq object-keys i (min (+ i query-len) n-object-keys))
867 (results (find-all (list (gethash :join-class dbi))
868 :where (make-instance 'sql-relational-exp
870 :sub-expressions (list (sql-expression :attribute foreign-key)
874 (dolist (object objects)
875 (when (or force-p (not (slot-boundp object slotdef-name)))
876 (let ((res (find (slot-value object home-key) results
877 :key #'(lambda (res) (slot-value res foreign-key))
880 (setf (slot-value object slotdef-name) res)))))))))))
883 (defun fault-join-slot-raw (class object slot-def)
884 (let* ((dbi (view-class-slot-db-info slot-def))
885 (jc (gethash :join-class dbi)))
886 (let ((jq (join-qualifier class object slot-def)))
888 (select jc :where jq :flatp t :result-types nil)))))
890 (defun fault-join-slot (class object slot-def)
891 (let* ((dbi (view-class-slot-db-info slot-def))
892 (ts (gethash :target-slot dbi)))
893 (if (and ts (gethash :set dbi))
894 (fault-join-target-slot class object slot-def)
895 (let ((res (fault-join-slot-raw class object slot-def)))
898 ((and ts (not (gethash :set dbi)))
899 (mapcar (lambda (obj) (slot-value obj ts)) res))
900 ((and (not ts) (not (gethash :set dbi)))
902 ((and (not ts) (gethash :set dbi))
905 (defun join-qualifier (class object slot-def)
906 (declare (ignore class))
907 (let* ((dbi (view-class-slot-db-info slot-def))
908 (jc (find-class (gethash :join-class dbi)))
909 ;;(ts (gethash :target-slot dbi))
910 ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
911 (foreign-keys (gethash :foreign-key dbi))
912 (home-keys (gethash :home-key dbi)))
913 (when (every #'(lambda (slt)
914 (and (slot-boundp object slt)
915 (not (null (slot-value object slt)))))
916 (if (listp home-keys) home-keys (list home-keys)))
918 (mapcar #'(lambda (hk fk)
919 (let ((fksd (slotdef-for-slot-with-class fk jc)))
925 (view-class-slot-column fksd)
926 :table (view-table jc)))
930 (slot-value object hk))
933 (if (listp home-keys)
936 (if (listp foreign-keys)
938 (list foreign-keys)))))
940 (if (> (length jc) 1)
944 ;; FIXME: add retrieval immediate for efficiency
945 ;; For example, for (select 'employee-address) in test suite =>
946 ;; select addr.*,ea_join.* FROM addr,ea_join WHERE ea_join.aaddressid=addr.addressid\g
948 (defun build-objects (vals sclasses immediate-join-classes sels immediate-joins database refresh flatp instances)
949 "Used by find-all to build objects."
950 (labels ((build-object (vals vclass jclasses selects immediate-selects instance)
951 (let* ((db-vals (butlast vals (- (list-length vals)
952 (list-length selects))))
953 (obj (if instance instance (make-instance (class-name vclass) :view-database database)))
954 (join-vals (subseq vals (list-length selects)))
955 (joins (mapcar #'(lambda (c) (when c (make-instance c :view-database database)))
957 ;;(format t "db-vals: ~S, join-values: ~S~%" db-vals join-vals)
958 ;; use refresh keyword here
959 (setf obj (get-slot-values-from-view obj (mapcar #'car selects) db-vals))
960 (mapc #'(lambda (jc) (get-slot-values-from-view jc (mapcar #'car immediate-selects) join-vals))
964 (let ((slot (find (class-name (class-of jc)) (class-slots vclass)
965 :key #'(lambda (slot)
966 (when (and (eq :join (view-class-slot-db-kind slot))
967 (eq (slot-definition-name slot)
968 (gethash :join-class (view-class-slot-db-info slot))))
969 (slot-definition-name slot))))))
971 (setf (slot-value obj (slot-definition-name slot)) jc))))
973 (when refresh (instance-refreshed obj))
976 (mapcar #'(lambda (sclass jclass sel immediate-join instance)
978 (build-object vals sclass jclass sel immediate-join instance)
979 (setf vals (nthcdr (+ (list-length sel) (list-length immediate-join))
981 sclasses immediate-join-classes sels immediate-joins instances)))
982 (if (and flatp (= (length sclasses) 1))
986 (defun find-all (view-classes
988 &key all set-operation distinct from where group-by having
989 order-by offset limit refresh flatp result-types
991 (database *default-database*)
993 "Called by SELECT to generate object query results when the
994 View Classes VIEW-CLASSES are passed as arguments to SELECT."
995 (declare (ignore all set-operation group-by having offset limit inner-join on)
996 (optimize (debug 3) (speed 1)))
997 (labels ((ref-equal (ref1 ref2)
1000 (table-sql-expr (table)
1001 (sql-expression :table (view-table table)))
1002 (tables-equal (table-a table-b)
1003 (when (and table-a table-b)
1004 (string= (string (slot-value table-a 'name))
1005 (string (slot-value table-b 'name))))))
1009 (remf args :additional-fields)
1010 (remf args :result-types)
1011 (remf args :instances)
1012 (let* ((*db-deserializing* t)
1013 (sclasses (mapcar #'find-class view-classes))
1014 (immediate-join-slots
1015 (mapcar #'(lambda (c) (generate-retrieval-joins-list c :immediate)) sclasses))
1016 (immediate-join-classes
1017 (mapcar #'(lambda (jcs)
1018 (mapcar #'(lambda (slotdef)
1019 (find-class (gethash :join-class (view-class-slot-db-info slotdef))))
1021 immediate-join-slots))
1022 (immediate-join-sels (mapcar #'generate-immediate-joins-selection-list sclasses))
1023 (sels (mapcar #'generate-selection-list sclasses))
1024 (fullsels (apply #'append (mapcar #'append sels immediate-join-sels)))
1025 (sel-tables (collect-table-refs where))
1026 (tables (remove-if #'null
1027 (remove-duplicates (append (mapcar #'table-sql-expr sclasses)
1028 (mapcar #'(lambda (jcs)
1029 (mapcan #'(lambda (jc)
1030 (when jc (table-sql-expr jc)))
1032 immediate-join-classes)
1034 :test #'tables-equal)))
1035 (order-by-slots (mapcar #'(lambda (ob) (if (atom ob) ob (car ob)))
1036 (listify order-by))))
1038 (dolist (ob order-by-slots)
1039 (when (and ob (not (member ob (mapcar #'cdr fullsels)
1040 :test #'ref-equal)))
1042 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1044 (dolist (ob (listify distinct))
1045 (when (and (typep ob 'sql-ident)
1046 (not (member ob (mapcar #'cdr fullsels)
1047 :test #'ref-equal)))
1049 (append fullsels (mapcar #'(lambda (att) (cons nil att))
1051 (mapcar #'(lambda (vclass jclasses jslots)
1054 #'(lambda (jclass jslot)
1055 (let ((dbi (view-class-slot-db-info jslot)))
1058 (list (sql-operation '==
1060 :attribute (gethash :foreign-key dbi)
1061 :table (view-table jclass))
1063 :attribute (gethash :home-key dbi)
1064 :table (view-table vclass))))
1065 (when where (listify where))))))
1067 sclasses immediate-join-classes immediate-join-slots)
1068 (let* ((rows (apply #'select
1069 (append (mapcar #'cdr fullsels)
1071 (list (append (when from (listify from))
1073 (list :result-types result-types)
1074 (when where (list :where where))
1076 (instances-to-add (- (length rows) (length instances)))
1077 (perhaps-extended-instances
1078 (if (plusp instances-to-add)
1079 (append instances (do ((i 0 (1+ i))
1081 ((= i instances-to-add) res)
1082 (push (make-list (length sclasses) :initial-element nil) res)))
1085 #'(lambda (row instance)
1086 (build-objects row sclasses immediate-join-classes sels
1087 immediate-join-sels database refresh flatp
1088 (if (and flatp (atom instance))
1091 rows perhaps-extended-instances)))
1094 (defmethod instance-refreshed ((instance standard-db-object)))
1096 (defun select (&rest select-all-args)
1097 "Executes a query on DATABASE, which has a default value of
1098 *DEFAULT-DATABASE*, specified by the SQL expressions supplied
1099 using the remaining arguments in SELECT-ALL-ARGS. The SELECT
1100 argument can be used to generate queries in both functional and
1101 object oriented contexts.
1103 In the functional case, the required arguments specify the
1104 columns selected by the query and may be symbolic SQL expressions
1105 or strings representing attribute identifiers. Type modified
1106 identifiers indicate that the values selected from the specified
1107 column are converted to the specified lisp type. The keyword
1108 arguments ALL, DISTINCT, FROM, GROUP-by, HAVING, ORDER-BY,
1109 SET-OPERATION and WHERE are used to specify, using the symbolic
1110 SQL syntax, the corresponding components of the SQL query
1111 generated by the call to SELECT. RESULT-TYPES is a list of
1112 symbols which specifies the lisp type for each field returned by
1113 the query. If RESULT-TYPES is nil all results are returned as
1114 strings whereas the default value of :auto means that the lisp
1115 types are automatically computed for each field. FIELD-NAMES is t
1116 by default which means that the second value returned is a list
1117 of strings representing the columns selected by the query. If
1118 FIELD-NAMES is nil, the list of column names is not returned as a
1121 In the object oriented case, the required arguments to SELECT are
1122 symbols denoting View Classes which specify the database tables
1123 to query. In this case, SELECT returns a list of View Class
1124 instances whose slots are set from the attribute values of the
1125 records in the specified table. Slot-value is a legal operator
1126 which can be employed as part of the symbolic SQL syntax used in
1127 the WHERE keyword argument to SELECT. REFRESH is nil by default
1128 which means that the View Class instances returned are retrieved
1129 from a cache if an equivalent call to SELECT has previously been
1130 issued. If REFRESH is true, the View Class instances returned are
1131 updated as necessary from the database and the generic function
1132 INSTANCE-REFRESHED is called to perform any necessary operations
1133 on the updated instances.
1135 In both object oriented and functional contexts, FLATP has a
1136 default value of nil which means that the results are returned as
1137 a list of lists. If FLATP is t and only one result is returned
1138 for each record selected in the query, the results are returned
1139 as elements of a list."
1141 (flet ((select-objects (target-args)
1143 (every #'(lambda (arg)
1145 (find-class arg nil)))
1147 (multiple-value-bind (target-args qualifier-args)
1148 (query-get-selections select-all-args)
1149 (unless (or *default-database* (getf qualifier-args :database))
1150 (signal-no-database-error nil))
1153 ((select-objects target-args)
1154 (let ((caching (getf qualifier-args :caching t))
1155 (result-types (getf qualifier-args :result-types :auto))
1156 (refresh (getf qualifier-args :refresh nil))
1157 (database (or (getf qualifier-args :database) *default-database*))
1158 (order-by (getf qualifier-args :order-by)))
1159 (remf qualifier-args :caching)
1160 (remf qualifier-args :refresh)
1161 (remf qualifier-args :result-types)
1164 ;; Add explicity table name to order-by if not specified and only
1165 ;; one selected table. This is required so FIND-ALL won't duplicate
1167 (when (and order-by (= 1 (length target-args)))
1168 (let ((table-name (view-table (find-class (car target-args))))
1169 (order-by-list (copy-seq (listify order-by))))
1171 (loop for i from 0 below (length order-by-list)
1172 do (etypecase (nth i order-by-list)
1173 (sql-ident-attribute
1174 (unless (slot-value (nth i order-by-list) 'qualifier)
1175 (setf (slot-value (nth i order-by-list) 'qualifier) table-name)))
1177 (unless (slot-value (car (nth i order-by-list)) 'qualifier)
1178 (setf (slot-value (car (nth i order-by-list)) 'qualifier) table-name)))))
1179 (setf (getf qualifier-args :order-by) order-by-list)))
1183 (apply #'find-all target-args
1184 (append qualifier-args (list :result-types result-types))))
1186 (let ((cached (records-cache-results target-args qualifier-args database)))
1188 ((and cached (not refresh))
1190 ((and cached refresh)
1191 (let ((results (apply #'find-all (append (list target-args) qualifier-args `(:instances ,cached :result-types :auto)))))
1192 (setf (records-cache-results target-args qualifier-args database) results)
1195 (let ((results (apply #'find-all target-args (append qualifier-args
1196 '(:result-types :auto)))))
1197 (setf (records-cache-results target-args qualifier-args database) results)
1200 (let* ((expr (apply #'make-query select-all-args))
1202 (mapcar #'(lambda (attrib)
1203 (if (typep attrib 'sql-ident-attribute)
1204 (let ((type (slot-value attrib 'type)))
1209 (slot-value expr 'selections))))
1210 (destructuring-bind (&key (flatp nil)
1211 (result-types :auto)
1213 (database *default-database*)
1216 (query expr :flatp flatp
1218 ;; specifying a type for an attribute overrides result-types
1219 (if (some #'(lambda (x) (not (eq t x))) specified-types)
1222 :field-names field-names
1223 :database database))))))))
1225 (defun compute-records-cache-key (targets qualifiers)
1227 (do ((args *select-arguments* (cdr args))
1229 ((null args) results)
1230 (let* ((arg (car args))
1231 (value (getf qualifiers arg)))
1235 (cons (cons (sql (car value)) (cdr value)))
1236 (%sql-expression (sql value))
1240 (defun records-cache-results (targets qualifiers database)
1241 (when (record-caches database)
1242 (gethash (compute-records-cache-key targets qualifiers) (record-caches database))))
1244 (defun (setf records-cache-results) (results targets qualifiers database)
1245 (unless (record-caches database)
1246 (setf (record-caches database)
1247 (make-hash-table :test 'equal
1248 #+allegro :values #+allegro :weak)))
1249 (setf (gethash (compute-records-cache-key targets qualifiers)
1250 (record-caches database)) results)
1253 (defun update-cached-results (targets qualifiers database)
1254 ;; FIXME: this routine will need to update slots in cached objects, perhaps adding or removing objects from cached
1255 ;; for now, dump cache entry and perform fresh search
1256 (let ((res (apply #'find-all targets qualifiers)))
1257 (setf (gethash (compute-records-cache-key targets qualifiers)
1258 (record-caches database)) res)