r9467: add properties
[clsql.git] / sql / ooddl.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;;
4 ;;;; $Id$
5 ;;;;
6 ;;;; The CLSQL Object Oriented Data Definitional Language (OODDL)
7 ;;;;
8 ;;;; This file is part of CLSQL.
9 ;;;;
10 ;;;; CLSQL users are granted the rights to distribute and use this software
11 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
12 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
13 ;;;; *************************************************************************
14
15
16 (in-package #:clsql-sys)
17
18 (defclass standard-db-object ()
19   ((view-database :initform nil :initarg :view-database :reader view-database
20     :db-kind :virtual))
21   (:metaclass standard-db-class)
22   (:documentation "Superclass for all CLSQL View Classes."))
23
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.")
28
29 (defvar *db-deserializing* nil)
30 (defvar *db-initializing* nil)
31
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))))))
45   (call-next-method))
46
47 (defmethod (setf slot-value-using-class) (new-value (class standard-db-class)
48                                           instance slot-def)
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)))
53     (call-next-method)
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))))
59
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))
64     (call-next-method)
65     (when (and *db-auto-sync*
66                (not *db-deserializing*))
67       (update-records-from-instance object))))
68
69 ;;
70 ;; Build the database tables required to store the given view class
71 ;;
72
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)))
78     (if tclass
79         (let ((*default-database* database))
80           (%install-class tclass database))
81         (error "Class ~s not found." view-class-name)))
82   (values))
83
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)
87                                                     slotdef database)))
88       (when res 
89         (push res schemadef))))
90   (unless schemadef
91     (error "Class ~s has no :base slots" self))
92   (create-table (sql-expression :table (view-table self)) (nreverse schemadef)
93                 :database database
94                 :constraints (database-pkey-constraint self database))
95   (push self (database-view-classes database))
96   t)
97
98 (defmethod database-pkey-constraint ((class standard-db-class) database)
99   (let ((keylist (mapcar #'view-class-slot-column (keyslots-for-class class))))
100     (when keylist 
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))
105        database))))
106
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))
110     (let ((cdef
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)))
115         (when const 
116           (setq cdef (append cdef (list const)))))
117       cdef)))
118
119
120 ;;
121 ;; Drop the tables which store the given view class
122 ;;
123
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)))
128     (if tclass
129         (let ((*default-database* database))
130           (%uninstall-class tclass))
131         (error "Class ~s not found." view-class-name)))
132   (values))
133
134 (defun %uninstall-class (self &key (database *default-database*))
135   (drop-table (sql-expression :table (view-table self))
136               :if-does-not-exist :ignore
137               :database database)
138   (setf (database-view-classes database)
139         (remove self (database-view-classes database))))
140
141
142 ;;
143 ;; List all known view classes
144 ;;
145
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))))
156       (when view-classes
157         (remove-if #'(lambda (c) (or (not (funcall test c))
158                                      (not (find-superclass c))))
159                    view-classes)))))
160
161 ;;
162 ;; Define a new view class
163 ;;
164
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
199 strings."
200   `(progn
201     (defclass ,class ,supers ,slots 
202       ,@(if (find :metaclass `,cl-options :key #'car)
203             `,cl-options
204             (cons '(:metaclass clsql-sys::standard-db-class) `,cl-options)))
205     (finalize-inheritance (find-class ',class))
206     (find-class ',class)))
207
208 (defun keyslots-for-class (class)
209   (slot-value class 'key-slots))