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 ;;;; *************************************************************************
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 view in DATABASE based on VIEW-CLASS-NAME which defines
76 the view. The argument DATABASE has a default value of
78 (let ((tclass (find-class view-class-name)))
80 (let ((*default-database* database))
81 (%install-class tclass database))
82 (error "Class ~s not found." view-class-name)))
85 (defmethod %install-class ((self standard-db-class) database &aux schemadef)
86 (dolist (slotdef (ordered-class-slots self))
87 (let ((res (database-generate-column-definition (class-name self)
90 (push res schemadef))))
92 (error "Class ~s has no :base slots" self))
93 (create-table (sql-expression :table (view-table self)) schemadef
95 :constraints (database-pkey-constraint self database))
96 (push self (database-view-classes database))
99 (defmethod database-pkey-constraint ((class standard-db-class) database)
100 (let ((keylist (mapcar #'view-class-slot-column (keyslots-for-class class))))
102 (convert-to-db-default-case
103 (format nil "CONSTRAINT ~APK PRIMARY KEY~A"
104 (database-output-sql (view-table class) database)
105 (database-output-sql keylist database))
108 (defmethod database-generate-column-definition (class slotdef database)
109 (declare (ignore database class))
110 (when (member (view-class-slot-db-kind slotdef) '(:base :key))
112 (list (sql-expression :attribute (view-class-slot-column slotdef))
113 (specified-type slotdef))))
114 (setf cdef (append cdef (list (view-class-slot-db-type slotdef))))
115 (let ((const (view-class-slot-db-constraints slotdef)))
117 (setq cdef (append cdef (list const)))))
122 ;; Drop the tables which store the given view class
125 (defun drop-view-from-class (view-class-name &key (database *default-database*))
126 "Deletes a view or base table from DATABASE based on VIEW-CLASS-NAME
127 which defines that view. The argument DATABASE has a default value of
129 (let ((tclass (find-class view-class-name)))
131 (let ((*default-database* database))
132 (%uninstall-class tclass))
133 (error "Class ~s not found." view-class-name)))
136 (defun %uninstall-class (self &key (database *default-database*))
137 (drop-table (sql-expression :table (view-table self))
138 :if-does-not-exist :ignore
140 (setf (database-view-classes database)
141 (remove self (database-view-classes database))))
145 ;; List all known view classes
148 (defun list-classes (&key (test #'identity)
149 (root-class (find-class 'standard-db-object))
150 (database *default-database*))
151 "The LIST-CLASSES function collects all the classes below
152 ROOT-CLASS, which defaults to standard-db-object, that are connected
153 to the supplied DATABASE and which satisfy the TEST function. The
154 default for the TEST argument is identity. By default, LIST-CLASSES
155 returns a list of all the classes connected to the default database,
157 (flet ((find-superclass (class)
158 (member root-class (class-precedence-list class))))
159 (let ((view-classes (and database (database-view-classes database))))
161 (remove-if #'(lambda (c) (or (not (funcall test c))
162 (not (find-superclass c))))
166 ;; Define a new view class
169 (defmacro def-view-class (class supers slots &rest cl-options)
170 "Extends the syntax of defclass to allow special slots to be mapped
171 onto the attributes of database views. The macro DEF-VIEW-CLASS
172 creates a class called CLASS which maps onto a database view. Such a
173 class is called a View Class. The macro DEF-VIEW-CLASS extends the
174 syntax of DEFCLASS to allow special base slots to be mapped onto the
175 attributes of database views (presently single tables). When a select
176 query that names a View Class is submitted, then the corresponding
177 database view is queried, and the slots in the resulting View Class
178 instances are filled with attribute values from the database. If
179 SUPERS is nil then STANDARD-DB-OBJECT automatically becomes the
180 superclass of the newly-defined View Class."
182 (defclass ,class ,supers ,slots
183 ,@(if (find :metaclass `,cl-options :key #'car)
185 (cons '(:metaclass clsql::standard-db-class) `,cl-options)))
186 (finalize-inheritance (find-class ',class))
187 (find-class ',class)))
189 (defun keyslots-for-class (class)
190 (slot-value class 'key-slots))
192 (defun key-qualifier-for-instance (obj &key (database *default-database*))
193 (let ((tb (view-table (class-of obj))))
196 (sql-expression :attribute
197 (view-class-slot-column k)
201 (slot-value obj (slot-definition-name k))
203 (let* ((keys (keyslots-for-class (class-of obj)))
204 (keyxprs (mapcar #'qfk (reverse keys))))
206 ((= (length keyxprs) 0) nil)
207 ((= (length keyxprs) 1) (car keyxprs))
208 ((> (length keyxprs) 1) (apply #'sql-operation 'and keyxprs)))))))
211 ;; Function used by 'generate-selection-list'
214 (defun generate-attribute-reference (vclass slotdef)
216 ((eq (view-class-slot-db-kind slotdef) :base)
217 (sql-expression :attribute (view-class-slot-column slotdef)
218 :table (view-table vclass)))
219 ((eq (view-class-slot-db-kind slotdef) :key)
220 (sql-expression :attribute (view-class-slot-column slotdef)
221 :table (view-table vclass)))
225 ;; Function used by 'find-all'
228 (defun generate-selection-list (vclass)
230 (dolist (slotdef (ordered-class-slots vclass))
231 (let ((res (generate-attribute-reference vclass slotdef)))
233 (push (cons slotdef res) sels))))
236 (error "No slots of type :base in view-class ~A" (class-name vclass)))))
240 (defun generate-retrieval-joins-list (vclass retrieval-method)
241 "Returns list of immediate join slots for a class."
242 (let ((join-slotdefs nil))
243 (dolist (slotdef (ordered-class-slots vclass) join-slotdefs)
244 (when (and (eq :join (view-class-slot-db-kind slotdef))
245 (eq retrieval-method (gethash :retrieval (view-class-slot-db-info slotdef))))
246 (push slotdef join-slotdefs)))))
248 (defun generate-immediate-joins-selection-list (vclass)
249 "Returns list of immediate join slots for a class."
251 (dolist (joined-slot (generate-retrieval-joins-list vclass :immediate) sels)
252 (let* ((join-class-name (gethash :join-class (view-class-slot-db-info joined-slot)))
253 (join-class (when join-class-name (find-class join-class-name))))
254 (dolist (slotdef (ordered-class-slots join-class))
255 (let ((res (generate-attribute-reference join-class slotdef)))
257 (push (cons slotdef res) sels))))))
261 ;; Called by 'get-slot-values-from-view'
264 (defvar *update-context* nil)
266 (defmethod update-slot-from-db ((instance standard-db-object) slotdef value)
267 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
268 (let* ((slot-reader (view-class-slot-db-reader slotdef))
269 (slot-name (slot-definition-name slotdef))
270 (slot-type (specified-type slotdef))
271 (*update-context* (cons (type-of instance) slot-name)))
272 (cond ((and value (null slot-reader))
273 (setf (slot-value instance slot-name)
274 (read-sql-value value (delistify slot-type)
275 (view-database instance))))
277 (update-slot-with-null instance slot-name slotdef))
278 ((typep slot-reader 'string)
279 (setf (slot-value instance slot-name)
280 (format nil slot-reader value)))
281 ((typep slot-reader 'function)
282 (setf (slot-value instance slot-name)
283 (apply slot-reader (list value))))
285 (error "Slot reader is of an unusual type.")))))
287 (defmethod key-value-from-db (slotdef value database)
288 (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
289 (let ((slot-reader (view-class-slot-db-reader slotdef))
290 (slot-type (specified-type slotdef)))
291 (cond ((and value (null slot-reader))
292 (read-sql-value value (delistify slot-type) database))
295 ((typep slot-reader 'string)
296 (format nil slot-reader value))
297 ((typep slot-reader 'function)
298 (apply slot-reader (list value)))
300 (error "Slot reader is of an unusual type.")))))
302 (defun db-value-from-slot (slotdef val database)
303 (let ((dbwriter (view-class-slot-db-writer slotdef))
304 (dbtype (specified-type slotdef)))
306 (string (format nil dbwriter val))
307 (function (apply dbwriter (list val)))
311 (database-output-sql-as-type (car dbtype) val database))
313 (database-output-sql-as-type dbtype val database)))))))
315 (defun check-slot-type (slotdef val)
316 (let* ((slot-type (specified-type slotdef))
317 (basetype (if (listp slot-type) (car slot-type) slot-type)))
318 (when (and slot-type val)
319 (unless (typep val basetype)
320 (error 'clsql-type-error
321 :slotname (slot-definition-name slotdef)
326 ;; Called by find-all
329 (defmethod get-slot-values-from-view (obj slotdeflist values)
330 (flet ((update-slot (slot-def values)
331 (update-slot-from-db obj slot-def values)))
332 (mapc #'update-slot slotdeflist values)
335 (defmethod update-record-from-slot ((obj standard-db-object) slot &key
336 (database *default-database*))
337 (let* ((database (or (view-database obj) database))
338 (vct (view-table (class-of obj)))
339 (sd (slotdef-for-slot-with-class slot (class-of obj))))
340 (check-slot-type sd (slot-value obj slot))
341 (let* ((att (view-class-slot-column sd))
342 (val (db-value-from-slot sd (slot-value obj slot) database)))
343 (cond ((and vct sd (view-database obj))
344 (update-records (sql-expression :table vct)
345 :attributes (list (sql-expression :attribute att))
347 :where (key-qualifier-for-instance
348 obj :database database)
350 ((and vct sd (not (view-database obj)))
351 (insert-records :into (sql-expression :table vct)
352 :attributes (list (sql-expression :attribute att))
355 (setf (slot-value obj 'view-database) database))
357 (error "Unable to update record.")))))
360 (defmethod update-record-from-slots ((obj standard-db-object) slots &key
361 (database *default-database*))
362 (let* ((database (or (view-database obj) database))
363 (vct (view-table (class-of obj)))
364 (sds (slotdefs-for-slots-with-class slots (class-of obj)))
365 (avps (mapcar #'(lambda (s)
366 (let ((val (slot-value
367 obj (slot-definition-name s))))
368 (check-slot-type s val)
369 (list (sql-expression
370 :attribute (view-class-slot-column s))
371 (db-value-from-slot s val database))))
373 (cond ((and avps (view-database obj))
374 (update-records (sql-expression :table vct)
376 :where (key-qualifier-for-instance
377 obj :database database)
379 ((and avps (not (view-database obj)))
380 (insert-records :into (sql-expression :table vct)
383 (setf (slot-value obj 'view-database) database))
385 (error "Unable to update records"))))
388 (defmethod update-records-from-instance ((obj standard-db-object)
389 &key (database *default-database*))
390 (let ((database (or (view-database obj) database)))
391 (labels ((slot-storedp (slot)
392 (and (member (view-class-slot-db-kind slot) '(:base :key))
393 (slot-boundp obj (slot-definition-name slot))))
394 (slot-value-list (slot)
395 (let ((value (slot-value obj (slot-definition-name slot))))
396 (check-slot-type slot value)
397 (list (sql-expression :attribute (view-class-slot-column slot))
398 (db-value-from-slot slot value database)))))
399 (let* ((view-class (class-of obj))
400 (view-class-table (view-table view-class))
401 (slots (remove-if-not #'slot-storedp
402 (ordered-class-slots view-class)))
403 (record-values (mapcar #'slot-value-list slots)))
404 (unless record-values
405 (error "No settable slots."))
406 (if (view-database obj)
407 (update-records (sql-expression :table view-class-table)
408 :av-pairs record-values
409 :where (key-qualifier-for-instance
410 obj :database database)
413 (insert-records :into (sql-expression :table view-class-table)
414 :av-pairs record-values
416 (setf (slot-value obj 'view-database) database))))))
419 (defmethod delete-instance-records ((instance standard-db-object))
420 (let ((vt (sql-expression :table (view-table (class-of instance))))
421 (vd (view-database instance)))
423 (let ((qualifier (key-qualifier-for-instance instance :database vd)))
424 (delete-records :from vt :where qualifier :database vd)
425 (setf (slot-value instance 'view-database) nil))
426 (error 'clsql-base::clsql-no-database-error :database nil))))
428 (defmethod update-instance-from-records ((instance standard-db-object)
429 &key (database *default-database*))
430 (let* ((view-class (find-class (class-name (class-of instance))))
431 (view-table (sql-expression :table (view-table view-class)))
432 (vd (or (view-database instance) database))
433 (view-qual (key-qualifier-for-instance instance :database vd))
434 (sels (generate-selection-list view-class))
435 (res (apply #'select (append (mapcar #'cdr sels)
436 (list :from view-table
438 (list :result-types nil)))))
440 (get-slot-values-from-view instance (mapcar #'car sels) (car res)))))
442 (defmethod update-slot-from-record ((instance standard-db-object)
443 slot &key (database *default-database*))
444 (let* ((view-class (find-class (class-name (class-of instance))))
445 (view-table (sql-expression :table (view-table view-class)))
446 (vd (or (view-database instance) database))
447 (view-qual (key-qualifier-for-instance instance :database vd))
448 (slot-def (slotdef-for-slot-with-class slot view-class))
449 (att-ref (generate-attribute-reference view-class slot-def))
450 (res (select att-ref :from view-table :where view-qual
453 (get-slot-values-from-view instance (list slot-def) (car res)))))
456 (defmethod update-slot-with-null ((object standard-db-object)
459 (setf (slot-value object slotname) (slot-value slotdef 'void-value)))
461 (defvar +no-slot-value+ '+no-slot-value+)
463 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
464 (let* ((class (find-class classname))
465 (sld (slotdef-for-slot-with-class slot class)))
467 (if (eq value +no-slot-value+)
468 (sql-expression :attribute (view-class-slot-column sld)
469 :table (view-table class))
474 (error "Unknown slot ~A for class ~A" slot classname))))
476 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
477 (declare (ignore database))
478 (let* ((class (find-class classname)))
479 (unless (view-table class)
480 (error "No view-table for class ~A" classname))
481 (sql-expression :table (view-table class))))
483 (defmethod database-get-type-specifier (type args database)
484 (declare (ignore type args))
485 (if (clsql-base::in (database-underlying-type database)
486 :postgresql :postgresql-socket)
490 (defmethod database-get-type-specifier ((type (eql 'integer)) args database)
491 (declare (ignore database))
494 (format nil "INT(~A)" (car args))
498 "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
501 (defmethod database-get-type-specifier ((type (eql 'bigint)) args database)
502 (declare (ignore args database))
505 (defmethod database-get-type-specifier ((type (eql 'simple-base-string)) args
508 (format nil "VARCHAR(~A)" (car args))
509 (if (clsql-base::in (database-underlying-type database)
510 :postgresql :postgresql-socket)
514 (defmethod database-get-type-specifier ((type (eql 'simple-string)) args
517 (format nil "VARCHAR(~A)" (car args))
518 (if (clsql-base::in (database-underlying-type database)
519 :postgresql :postgresql-socket)
523 (defmethod database-get-type-specifier ((type (eql 'string)) args database)
525 (format nil "VARCHAR(~A)" (car args))
526 (if (clsql-base::in (database-underlying-type database)
527 :postgresql :postgresql-socket)
531 (deftype universal-time ()
532 "A positive integer as returned by GET-UNIVERSAL-TIME."
535 (defmethod database-get-type-specifier ((type (eql 'universal-time)) args database)
536 (declare (ignore args database))
539 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database)
540 (declare (ignore args))
541 (case (database-underlying-type database)
542 ((:postgresql :postgresql-socket)
543 "TIMESTAMP WITHOUT TIME ZONE")
548 (defmethod database-get-type-specifier ((type (eql 'duration)) args database)
549 (declare (ignore database args))
552 (defmethod database-get-type-specifier ((type (eql 'money)) args database)
553 (declare (ignore database args))
556 (deftype raw-string (&optional len)
557 "A string which is not trimmed when retrieved from the database"
560 (defmethod database-get-type-specifier ((type (eql 'raw-string)) args database)
561 (declare (ignore database))
563 (format nil "VARCHAR(~A)" (car args))
566 (defmethod database-get-type-specifier ((type (eql 'float)) args database)
567 (declare (ignore database))
569 (format nil "FLOAT(~A)" (car args))
572 (defmethod database-get-type-specifier ((type (eql 'long-float)) args database)
573 (declare (ignore database))
575 (format nil "FLOAT(~A)" (car args))
578 (defmethod database-get-type-specifier ((type (eql 'boolean)) args database)
579 (declare (ignore args database))
582 (defmethod database-output-sql-as-type (type val database)
583 (declare (ignore type database))
586 (defmethod database-output-sql-as-type ((type (eql 'list)) val database)
587 (declare (ignore database))
588 (progv '(*print-circle* *print-array*) '(t t)
589 (let ((escaped (prin1-to-string val)))
590 (clsql-base::substitute-char-string
591 escaped #\Null " "))))
593 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database)
594 (declare (ignore database))
599 (package-name (symbol-package val))
604 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database)
605 (declare (ignore database))
610 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database)
611 (declare (ignore database))
612 (progv '(*print-circle* *print-array*) '(t t)
613 (prin1-to-string val)))
615 (defmethod database-output-sql-as-type ((type (eql 'array)) val database)
616 (declare (ignore database))
617 (progv '(*print-circle* *print-array*) '(t t)
618 (prin1-to-string val)))
620 (defmethod database-output-sql-as-type ((type (eql 'boolean)) val database)
621 (case (database-underlying-type database)
627 (defmethod database-output-sql-as-type ((type (eql 'string)) val database)
628 (declare (ignore database))
631 (defmethod database-output-sql-as-type ((type (eql 'simple-string))
633 (declare (ignore database))
636 (defmethod database-output-sql-as-type ((type (eql 'simple-base-string))
638 (declare (ignore database))
641 (defmethod read-sql-value (val type database)
642 (declare (ignore type database))
643 (read-from-string val))
645 (defmethod read-sql-value (val (type (eql 'string)) database)
646 (declare (ignore database))
649 (defmethod read-sql-value (val (type (eql 'simple-string)) database)
650 (declare (ignore database))
653 (defmethod read-sql-value (val (type (eql 'simple-base-string)) database)
654 (declare (ignore database))
657 (defmethod read-sql-value (val (type (eql 'raw-string)) database)
658 (declare (ignore database))
661 (defmethod read-sql-value (val (type (eql 'keyword)) database)
662 (declare (ignore database))
663 (when (< 0 (length val))
664 (intern (symbol-name-default-case val)
665 (find-package '#:keyword))))
667 (defmethod read-sql-value (val (type (eql 'symbol)) database)
668 (declare (ignore database))
669 (when (< 0 (length val))
670 (unless (string= val (clsql-base:symbol-name-default-case "NIL"))
671 (intern (clsql-base:symbol-name-default-case val)
672 (symbol-package *update-context*)))))
674 (defmethod read-sql-value (val (type (eql 'integer)) database)
675 (declare (ignore database))
678 (unless (string-equal "NIL" val)
679 (parse-integer val)))
682 (defmethod read-sql-value (val (type (eql 'bigint)) database)
683 (declare (ignore database))
686 (unless (string-equal "NIL" val)
687 (parse-integer val)))
690 (defmethod read-sql-value (val (type (eql 'float)) database)
691 (declare (ignore database))
692 ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
693 (float (read-from-string val)))
695 (defmethod read-sql-value (val (type (eql 'boolean)) database)
696 (case (database-underlying-type database)
699 (string (if (string= "0" val) nil t))
700 (integer (if (zerop val) nil t))))
702 (if (eq :odbc (database-type database))
703 (if (string= "0" val) nil t)
708 (defmethod read-sql-value (val (type (eql 'univeral-time)) database)
709 (declare (ignore database))
710 (unless (eq 'NULL val)
716 (defmethod read-sql-value (val (type (eql 'wall-time)) database)
717 (declare (ignore database))
718 (unless (eq 'NULL val)
719 (parse-timestring val)))
721 (defmethod read-sql-value (val (type (eql 'duration)) database)
722 (declare (ignore database))
723 (unless (or (eq 'NULL val)
725 (parse-timestring val)))
727 ;; ------------------------------------------------------------
728 ;; Logic for 'faulting in' :join slots
730 ;; this works, but is inefficient requiring (+ 1 n-rows)
733 (defun fault-join-target-slot (class object slot-def)
734 (let* ((res (fault-join-slot-raw class object slot-def))
735 (dbi (view-class-slot-db-info slot-def))
736 (target-name (gethash :target-slot dbi))
737 (target-class (find-class target-name)))
739 (mapcar (lambda (obj)
745 (find target-name (class-slots (class-of obj))
746 :key #'slot-definition-name)))
749 #+ignore ;; this doesn't work when attempting to call slot-value
750 (mapcar (lambda (obj)
751 (cons obj (slot-value obj ts))) res))))
753 (defun fault-join-target-slot (class object slot-def)
754 (let* ((dbi (view-class-slot-db-info slot-def))
755 (ts (gethash :target-slot dbi))
756 (jc (gethash :join-class dbi))
757 (ts-view-table (view-table (find-class ts)))
758 (jc-view-table (view-table (find-class jc)))
759 (tdbi (view-class-slot-db-info
760 (find ts (class-slots (find-class jc))
761 :key #'slot-definition-name)))
762 (retrieval (gethash :retrieval tdbi))
763 (jq (join-qualifier class object slot-def))
764 (key (slot-value object (gethash :home-key dbi))))
770 :inner-join (sql-expression :table jc-view-table)
774 :attribute (gethash :foreign-key tdbi)
775 :table ts-view-table)
777 :attribute (gethash :home-key tdbi)
778 :table jc-view-table))
780 :result-types :auto)))
781 (mapcar #'(lambda (i)
782 (let* ((instance (car i))
783 (jcc (make-instance jc :view-database (view-database instance))))
784 (setf (slot-value jcc (gethash :foreign-key dbi))
786 (setf (slot-value jcc (gethash :home-key tdbi))
787 (slot-value instance (gethash :foreign-key tdbi)))
788 (list instance jcc)))
791 ;; just fill in minimal slots
794 (let ((instance (make-instance ts :view-database (view-database object)))
795 (jcc (make-instance jc :view-database (view-database object)))
797 (setf (slot-value instance (gethash :home-key tdbi)) fk)
798 (setf (slot-value jcc (gethash :foreign-key dbi))
800 (setf (slot-value jcc (gethash :home-key tdbi))
802 (list instance jcc)))
803 (select (sql-expression :attribute (gethash :foreign-key tdbi) :table jc-view-table)
804 :from (sql-expression :table jc-view-table)
807 (defun update-object-joins (objects &key (slots t) (force-p t)
808 class-name (max-len *default-update-objects-max-len*))
809 "Updates the remote join slots, that is those slots defined without :retrieval :immediate."
812 (class-name (class-of (first objects))))
813 (let* ((class (find-class class-name))
814 (deferred-joins (generate-retrieval-joins-list class :deferred)))
816 (warn "not yet implemented.")
820 (defun fault-join-slot-raw (class object slot-def)
821 (let* ((dbi (view-class-slot-db-info slot-def))
822 (jc (gethash :join-class dbi)))
823 (let ((jq (join-qualifier class object slot-def)))
825 (select jc :where jq :flatp t :result-types nil)))))
827 (defun fault-join-slot (class object slot-def)
828 (let* ((dbi (view-class-slot-db-info slot-def))
829 (ts (gethash :target-slot dbi)))
830 (if (and ts (gethash :set dbi))
831 (fault-join-target-slot class object slot-def)
832 (let ((res (fault-join-slot-raw class object slot-def)))
835 ((and ts (not (gethash :set dbi)))
836 (mapcar (lambda (obj) (slot-value obj ts)) res))
837 ((and (not ts) (not (gethash :set dbi)))
839 ((and (not ts) (gethash :set dbi))
842 (defun join-qualifier (class object slot-def)
843 (declare (ignore class))
844 (let* ((dbi (view-class-slot-db-info slot-def))
845 (jc (find-class (gethash :join-class dbi)))
846 ;;(ts (gethash :target-slot dbi))
847 ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
848 (foreign-keys (gethash :foreign-key dbi))
849 (home-keys (gethash :home-key dbi)))
850 (when (every #'(lambda (slt)
851 (and (slot-boundp object slt)
852 (not (null (slot-value object slt)))))
853 (if (listp home-keys) home-keys (list home-keys)))
855 (mapcar #'(lambda (hk fk)
856 (let ((fksd (slotdef-for-slot-with-class fk jc)))
862 (view-class-slot-column fksd)
863 :table (view-table jc)))
867 (slot-value object hk))
870 (if (listp home-keys)
873 (if (listp foreign-keys)
875 (list foreign-keys)))))
877 (if (> (length jc) 1)
881 ;; FIXME: add retrieval immediate for efficiency
882 ;; For example, for (select 'employee-address) in test suite =>
883 ;; select addr.*,ea_join.* FROM addr,ea_join WHERE ea_join.aaddressid=addr.addressid\g
885 (defun build-objects (vals sclasses immediate-join-classes sels immediate-joins database refresh flatp)
886 "Used by find-all to build objects."
887 (labels ((build-object (vals vclass jclasses selects immediate-selects)
888 (let* ((class-name (class-name vclass))
889 (db-vals (butlast vals (- (list-length vals)
890 (list-length selects))))
891 (join-vals (subseq vals (list-length selects)))
892 (obj (make-instance class-name :view-database database))
893 (joins (mapcar #'(lambda (c) (when c (make-instance c :view-database database)))
895 ;;(format t "db-vals: ~S, join-values: ~S~%" db-vals join-vals)
896 ;; use refresh keyword here
897 (setf obj (get-slot-values-from-view obj (mapcar #'car selects)
899 (mapc #'(lambda (jc) (get-slot-values-from-view jc (mapcar #'car immediate-selects) join-vals))
902 #'(lambda (jc) (let ((slot (find (class-name (class-of jc)) (class-slots vclass)
903 :key #'(lambda (slot) (when (and (eq :join (view-class-slot-db-kind slot))
904 (eq (slot-definition-name slot)
905 (gethash :join-class (view-class-slot-db-info slot))))
906 (slot-definition-name slot))))))
908 (setf (slot-value obj (slot-definition-name slot)) jc))))
911 (when refresh (instance-refreshed obj))
913 (let ((objects (mapcar #'(lambda (sclass jclass sel immediate-join)
914 (prog1 (build-object vals sclass jclass sel immediate-join)
915 (setf vals (nthcdr (+ (list-length sel) (list-length immediate-join))
917 sclasses immediate-join-classes sels immediate-joins)))
918 (if (and flatp (= (length sclasses) 1))
922 (defun find-all (view-classes
924 &key all set-operation distinct from where group-by having
925 order-by order-by-descending offset limit refresh
926 flatp result-types inner-join on
927 (database *default-database*))
928 "Called by SELECT to generate object query results when the
929 View Classes VIEW-CLASSES are passed as arguments to SELECT."
930 (declare (ignore all set-operation group-by having offset limit inner-join on)
931 (optimize (debug 3) (speed 1)))
932 (labels ((ref-equal (ref1 ref2)
935 (table-sql-expr (table)
936 (sql-expression :table (view-table table)))
937 (tables-equal (table-a table-b)
938 (when (and table-a table-b)
939 (string= (string (slot-value table-a 'name))
940 (string (slot-value table-b 'name))))))
944 (remf args :additional-fields)
945 (remf args :result-types)
946 (let* ((*db-deserializing* t)
947 (sclasses (mapcar #'find-class view-classes))
948 (immediate-join-slots (mapcar #'(lambda (c) (generate-retrieval-joins-list c :immediate)) sclasses))
949 (immediate-join-classes (mapcar #'(lambda (jcs)
950 (mapcar #'(lambda (slotdef)
951 (find-class (gethash :join-class (view-class-slot-db-info slotdef))))
953 immediate-join-slots))
954 (immediate-join-sels (mapcar #'generate-immediate-joins-selection-list sclasses))
955 (sels (mapcar #'generate-selection-list sclasses))
956 (fullsels (apply #'append (mapcar #'append sels immediate-join-sels)))
957 (sel-tables (collect-table-refs where))
958 (tables (remove-if #'null
959 (remove-duplicates (append (mapcar #'table-sql-expr sclasses)
960 (mapcar #'(lambda (jcs)
961 (mapcan #'(lambda (jc)
962 (when jc (table-sql-expr jc)))
964 immediate-join-classes)
966 :test #'tables-equal)))
968 (dolist (ob (listify order-by))
969 (when (and ob (not (member ob (mapcar #'cdr fullsels)
972 (append fullsels (mapcar #'(lambda (att) (cons nil att))
974 (dolist (ob (listify order-by-descending))
975 (when (and ob (not (member ob (mapcar #'cdr fullsels)
978 (append fullsels (mapcar #'(lambda (att) (cons nil att))
980 (dolist (ob (listify distinct))
981 (when (and (typep ob 'sql-ident)
982 (not (member ob (mapcar #'cdr fullsels)
985 (append fullsels (mapcar #'(lambda (att) (cons nil att))
987 (mapcar #'(lambda (vclass jclasses jslots)
990 #'(lambda (jclass jslot)
991 (let ((dbi (view-class-slot-db-info jslot)))
994 (list (sql-operation '==
996 :attribute (gethash :foreign-key dbi)
997 :table (view-table jclass))
999 :attribute (gethash :home-key dbi)
1000 :table (view-table vclass))))
1001 (when where (listify where))))))
1003 sclasses immediate-join-classes immediate-join-slots)
1006 (append (mapcar #'cdr fullsels)
1008 (list (append (when from (listify from))
1010 (list :result-types result-types)
1011 (when where (list :where where))
1013 (mapcar #'(lambda (r)
1014 (build-objects r sclasses immediate-join-classes sels immediate-join-sels database refresh flatp))
1017 (defmethod instance-refreshed ((instance standard-db-object)))
1019 (defun select (&rest select-all-args)
1020 "The function SELECT selects data from DATABASE, which has a
1021 default value of *DEFAULT-DATABASE*, given the constraints
1022 specified by the rest of the ARGS. It returns a list of objects
1023 as specified by SELECTIONS. By default, the objects will each be
1024 represented as lists of attribute values. The argument SELECTIONS
1025 consists either of database identifiers, type-modified database
1026 identifiers or literal strings. A type-modifed database
1027 identifier is an expression such as [foo :string] which means
1028 that the values in column foo are returned as Lisp strings. The
1029 FLATP argument, which has a default value of nil, specifies if
1030 full bracketed results should be returned for each matched
1031 entry. If FLATP is nil, the results are returned as a list of
1032 lists. If FLATP is t, the results are returned as elements of a
1033 list, only if there is only one result per row. The arguments
1034 ALL, SET-OPERATION, DISTINCT, FROM, WHERE, GROUP-BY, HAVING and
1035 ORDER-by have the same function as the equivalent SQL expression.
1036 The SELECT function is common across both the functional and
1037 object-oriented SQL interfaces. If selections refers to View
1038 Classes then the select operation becomes object-oriented. This
1039 means that SELECT returns a list of View Class instances, and
1040 SLOT-VALUE becomes a valid SQL operator for use within the where
1041 clause. In the View Class case, a second equivalent select call
1042 will return the same View Class instance objects. If REFRESH is
1043 true, then existing instances are updated if necessary, and in
1044 this case you might need to extend the hook INSTANCE-REFRESHED.
1045 The default value of REFRESH is nil. SQL expressions used in the
1046 SELECT function are specified using the square bracket syntax,
1047 once this syntax has been enabled using
1048 ENABLE-SQL-READER-SYNTAX."
1050 (flet ((select-objects (target-args)
1052 (every #'(lambda (arg)
1054 (find-class arg nil)))
1056 (multiple-value-bind (target-args qualifier-args)
1057 (query-get-selections select-all-args)
1058 (if (select-objects target-args)
1059 (apply #'find-all target-args qualifier-args)
1060 (let* ((expr (apply #'make-query select-all-args))
1062 (mapcar #'(lambda (attrib)
1063 (if (typep attrib 'sql-ident-attribute)
1064 (let ((type (slot-value attrib 'type)))
1069 (slot-value expr 'selections))))
1070 (destructuring-bind (&key (flatp nil)
1071 (result-types :auto)
1073 (database *default-database*)
1076 (query expr :flatp flatp
1078 ;; specifying a type for an attribute overrides result-types
1079 (if (some #'(lambda (x) (not (eq t x))) specified-types)
1082 :field-names field-names
1083 :database database)))))))