r10512: 05 May 2005 Kevin Rosenberg <kevin@rosenberg.net>
[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 (defparameter *default-string-length* 255
25   "The length of a string which does not have a user-specified length.")
26
27 (defvar *db-auto-sync* nil 
28   "A non-nil value means that creating View Class instances or
29   setting their slots automatically creates/updates the
30   corresponding records in the underlying database.")
31
32 (defvar *db-deserializing* nil)
33 (defvar *db-initializing* nil)
34
35 (defmethod slot-value-using-class ((class standard-db-class) instance slot-def)
36   (declare (optimize (speed 3)))
37   (unless *db-deserializing*
38     (let* ((slot-name (%svuc-slot-name slot-def))
39            (slot-object (%svuc-slot-object slot-def class))
40            (slot-kind (view-class-slot-db-kind slot-object)))
41       (when (and (eql slot-kind :join)
42                  (not (slot-boundp instance slot-name)))
43         (let ((*db-deserializing* t))
44           (if (view-database instance)
45               (setf (slot-value instance slot-name)
46                     (fault-join-slot class instance slot-object))
47               (setf (slot-value instance slot-name) nil))))))
48   (call-next-method))
49
50 (defmethod (setf slot-value-using-class) (new-value (class standard-db-class)
51                                           instance slot-def)
52   (declare (ignore new-value))
53   (let* ((slot-name (%svuc-slot-name slot-def))
54          (slot-object (%svuc-slot-object slot-def class))
55          (slot-kind (view-class-slot-db-kind slot-object)))
56     (prog1
57       (call-next-method)
58       (when (and *db-auto-sync* 
59                  (not *db-initializing*)
60                  (not *db-deserializing*)
61                  (not (eql slot-kind :virtual)))
62         (update-record-from-slot instance slot-name)))))
63
64 (defmethod initialize-instance ((object standard-db-object)
65                                         &rest all-keys &key &allow-other-keys)
66   (declare (ignore all-keys))
67   (let ((*db-initializing* t))
68     (call-next-method)
69     (when (and *db-auto-sync*
70                (not *db-deserializing*))
71       (update-records-from-instance object))))
72
73 ;;
74 ;; Build the database tables required to store the given view class
75 ;;
76
77 (defun create-view-from-class (view-class-name
78                                &key (database *default-database*)
79                                (transactions t))
80   "Creates a table as defined by the View Class VIEW-CLASS-NAME
81 in DATABASE which defaults to *DEFAULT-DATABASE*."
82   (let ((tclass (find-class view-class-name)))
83     (if tclass
84         (let ((*default-database* database))
85           (%install-class tclass database :transactions transactions))
86         (error "Class ~s not found." view-class-name)))
87   (values))
88
89 (defmethod %install-class ((self standard-db-class) database
90                            &key (transactions t))
91   (let ((schemadef '()))
92     (dolist (slotdef (ordered-class-slots self))
93       (let ((res (database-generate-column-definition (class-name self)
94                                                       slotdef database)))
95         (when res 
96           (push res schemadef))))
97     (unless schemadef
98       (error "Class ~s has no :base slots" self))
99     (create-table (sql-expression :table (view-table self)) (nreverse schemadef)
100                   :database database
101                   :transactions transactions
102                   :constraints (database-pkey-constraint self database))
103     (push self (database-view-classes database)))
104   t)
105
106 (defmethod database-pkey-constraint ((class standard-db-class) database)
107   (let ((keylist (mapcar #'view-class-slot-column (keyslots-for-class class))))
108     (when keylist 
109       (convert-to-db-default-case
110        (format nil "CONSTRAINT ~APK PRIMARY KEY~A"
111                (sql-output (view-table class) database)
112                (sql-output keylist database))
113        database))))
114
115 (defmethod database-generate-column-definition (class slotdef database)
116   (declare (ignore database class))
117   (when (member (view-class-slot-db-kind slotdef) '(:base :key))
118     (let ((cdef
119            (list (sql-expression :attribute (view-class-slot-column slotdef))
120                  (specified-type slotdef))))
121       (setf cdef (append cdef (list (view-class-slot-db-type slotdef))))
122       (let ((const (view-class-slot-db-constraints slotdef)))
123         (when const 
124           (setq cdef (append cdef (listify const)))))
125       cdef)))
126
127
128 ;;
129 ;; Drop the tables which store the given view class
130 ;;
131
132 (defun drop-view-from-class (view-class-name &key (database *default-database*))
133   "Removes a table defined by the View Class VIEW-CLASS-NAME from
134 DATABASE which defaults to *DEFAULT-DATABASE*."
135   (let ((tclass (find-class view-class-name)))
136     (if tclass
137         (let ((*default-database* database))
138           (%uninstall-class tclass))
139         (error "Class ~s not found." view-class-name)))
140   (values))
141
142 (defun %uninstall-class (self &key (database *default-database*))
143   (drop-table (sql-expression :table (view-table self))
144               :if-does-not-exist :ignore
145               :database database)
146   (setf (database-view-classes database)
147         (remove self (database-view-classes database))))
148
149
150 ;;
151 ;; List all known view classes
152 ;;
153
154 (defun list-classes (&key (test #'identity)
155                      (root-class (find-class 'standard-db-object))
156                      (database *default-database*))
157   "Returns a list of all the View Classes which are connected to
158 DATABASE, which defaults to *DEFAULT-DATABASE*, and which descend
159 from the class ROOT-CLASS and which satisfy the function TEST. By
160 default ROOT-CLASS is STANDARD-DB-OBJECT and TEST is IDENTITY."
161   (flet ((find-superclass (class) 
162            (member root-class (class-precedence-list class))))
163     (let ((view-classes (and database (database-view-classes database))))
164       (when view-classes
165         (remove-if #'(lambda (c) (or (not (funcall test c))
166                                      (not (find-superclass c))))
167                    view-classes)))))
168
169 ;;
170 ;; Define a new view class
171 ;;
172
173 (defmacro def-view-class (class supers slots &rest cl-options)
174   "Creates a View Class called CLASS whose slots SLOTS can map
175 onto the attributes of a table in a database. If SUPERS is nil
176 then the superclass of CLASS will be STANDARD-DB-OBJECT,
177 otherwise SUPERS is a list of superclasses for CLASS which must
178 include STANDARD-DB-OBJECT or a descendent of this class. The
179 syntax of DEFCLASS is extended through the addition of a class
180 option :base-table which defines the database table onto which
181 the View Class maps and which defaults to CLASS. The DEFCLASS
182 syntax is also extended through additional slot
183 options. The :db-kind slot option specifies the kind of DB
184 mapping which is performed for this slot and defaults to :base
185 which indicates that the slot maps to an ordinary column of the
186 database table. A :db-kind value of :key indicates that this slot
187 is a special kind of :base slot which maps onto a column which is
188 one of the unique keys for the database table, the value :join
189 indicates this slot represents a join onto another View Class
190 which contains View Class objects, and the value :virtual
191 indicates a standard CLOS slot which does not map onto columns of
192 the database table. If a slot is specified with :db-kind :join,
193 the slot option :db-info contains a list which specifies the
194 nature of the join. For slots of :db-kind :base or :key,
195 the :type slot option has a special interpretation such that Lisp
196 types, such as string, integer and float are automatically
197 converted into appropriate SQL types for the column onto which
198 the slot maps. This behaviour may be over-ridden using
199 the :db-type slot option which is a string specifying the
200 vendor-specific database type for this slot's column definition
201 in the database. The :column slot option specifies the name of
202 the SQL column which the slot maps onto, if :db-kind is
203 not :virtual, and defaults to the slot name. The :void-value slot
204 option specifies the value to store if the SQL value is NULL and
205 defaults to NIL. The :db-constraints slot option is a string
206 representing an SQL table constraint expression or a list of such
207 strings."
208   `(progn
209     (defclass ,class ,supers ,slots 
210       ,@(if (find :metaclass `,cl-options :key #'car)
211             `,cl-options
212             (cons '(:metaclass clsql-sys::standard-db-class) `,cl-options)))
213     (finalize-inheritance (find-class ',class))
214     (find-class ',class)))
215
216 (defun keyslots-for-class (class)
217   (slot-value class 'key-slots))