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