introduced slot-def kind predicates (eg: join-slot-p key-slot-p)
[clsql.git] / sql / ooddl.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;;
4 ;;;; The CLSQL Object Oriented Data Definitional Language (OODDL)
5 ;;;;
6 ;;;; This file is part of CLSQL.
7 ;;;;
8 ;;;; CLSQL users are granted the rights to distribute and use this software
9 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
10 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
11 ;;;; *************************************************************************
12
13
14 (in-package #:clsql-sys)
15
16 (defclass standard-db-object ()
17   ((view-database :initform nil :initarg :view-database :reader view-database
18                   :db-kind :virtual))
19   (:metaclass standard-db-class)
20   (:documentation "Superclass for all CLSQL View Classes."))
21
22 (defparameter *default-string-length* 255
23   "The length of a string which does not have a user-specified length.")
24
25 (defvar *db-auto-sync* nil
26   "A non-nil value means that creating View Class instances or
27   setting their slots automatically creates/updates the
28   corresponding records in the underlying database.")
29
30 (defvar *db-deserializing* nil)
31 (defvar *db-initializing* nil)
32
33 (defmethod slot-value-using-class ((class standard-db-class) instance slot-def)
34   (declare (optimize (speed 3)))
35   (unless *db-deserializing*
36     (let* ((slot-name (%svuc-slot-name slot-def))
37            (slot-object (%svuc-slot-object slot-def class))
38            (slot-kind (view-class-slot-db-kind slot-object)))
39       (if (and (eql slot-kind :join)
40                (not (slot-boundp instance slot-name)))
41           (let ((*db-deserializing* t))
42             (if (view-database instance)
43                 (setf (slot-value instance slot-name)
44                       (fault-join-slot class instance slot-object))
45                 (setf (slot-value instance slot-name) nil)))
46           (when (and (normalizedp class)
47                      (not (member slot-name
48                                   (mapcar #'(lambda (esd) (slot-definition-name esd))
49                                           (ordered-class-direct-slots class))))
50                      (not (slot-boundp instance slot-name)))
51             (let ((*db-deserializing* t))
52               (if (view-database instance)
53                   (setf (slot-value instance slot-name)
54                         (fault-join-normalized-slot class instance slot-object))
55                   (setf (slot-value instance slot-name) nil)))))))
56   (call-next-method))
57
58 (defmethod (setf slot-value-using-class) (new-value (class standard-db-class)
59                                           instance slot-def)
60   (declare (ignore new-value))
61   (let* ((slot-name (%svuc-slot-name slot-def))
62          (slot-object (%svuc-slot-object slot-def class))
63          (slot-kind (view-class-slot-db-kind slot-object)))
64     (prog1
65         (call-next-method)
66       (when (and *db-auto-sync*
67                  (not *db-initializing*)
68                  (not *db-deserializing*)
69                  (not (eql slot-kind :virtual)))
70         (update-record-from-slot instance slot-name)))))
71
72 (defmethod initialize-instance ((object standard-db-object)
73                                 &rest all-keys &key &allow-other-keys)
74   (declare (ignore all-keys))
75   (let ((*db-initializing* t))
76     (call-next-method)
77     (when (and *db-auto-sync*
78                (not *db-deserializing*))
79       (update-records-from-instance object))))
80
81 ;;
82 ;; Build the database tables required to store the given view class
83 ;;
84
85 (defun create-view-from-class (view-class-name
86                                &key (database *default-database*)
87                                (transactions t))
88   "Creates a table as defined by the View Class VIEW-CLASS-NAME
89 in DATABASE which defaults to *DEFAULT-DATABASE*."
90   (let ((tclass (find-class view-class-name)))
91     (if tclass
92         (let ((*default-database* database)
93               (pclass (car (class-direct-superclasses tclass))))
94           (when (and (normalizedp tclass) (not (table-exists-p pclass)))
95             (create-view-from-class (class-name pclass)
96                                     :database database :transactions transactions))
97           (%install-class tclass database :transactions transactions))
98         (error "Class ~s not found." view-class-name)))
99   (values))
100
101 (defmethod auto-increment-column-p (slotdef &optional (database clsql-sys:*default-database*))
102   (declare (ignore database))
103   (or (member :auto-increment (listify (view-class-slot-db-constraints slotdef)))
104       (slot-value slotdef 'autoincrement-sequence)))
105
106 (defmethod %install-class ((self standard-db-class) database
107                            &key (transactions t))
108   (let ((schemadef '())
109         (ordered-slots (slots-for-possibly-normalized-class self)))
110     (dolist (slotdef ordered-slots)
111       (let ((res (database-generate-column-definition self slotdef database)))
112         (when res
113           (push res schemadef))))
114     (if (not schemadef)
115         (unless (normalizedp self)
116           (error "Class ~s has no :base slots" self))
117         (progn
118           (database-add-autoincrement-sequence self database)
119           (create-table (sql-expression :table (database-identifier self database))
120                         (nreverse schemadef)
121                         :database database
122                         :transactions transactions
123                         :constraints (database-pkey-constraint self database))
124           (push self (database-view-classes database)))))
125   t)
126
127 (defmethod database-pkey-constraint ((class standard-db-class) database)
128   ;; Keylist will always be a list of escaped-indentifier
129   (let ((keylist (mapcar #'(lambda (x) (escaped-database-identifier x database))
130                          (keyslots-for-class class)))
131         (table (escaped (combine-database-identifiers
132                          (list class 'PK)
133                          database))))
134     (when keylist
135       (format nil "CONSTRAINT ~A PRIMARY KEY (~{~A~^,~})" table
136               keylist))))
137
138 (defmethod database-generate-column-definition (class slotdef database)
139   (declare (ignore class))
140   (when (key-or-base-slot-p slotdef)
141     (let ((cdef
142            (list (sql-expression :attribute (database-identifier slotdef database))
143                  (specified-type slotdef))))
144       (setf cdef (append cdef (list (view-class-slot-db-type slotdef))))
145       (let ((const (view-class-slot-db-constraints slotdef)))
146         (when const
147           (setq cdef (append cdef (listify const)))))
148       cdef)))
149
150
151 ;;
152 ;; Drop the tables which store the given view class
153 ;;
154
155 (defun drop-view-from-class (view-class-name &key (database *default-database*)
156                              (owner nil))
157   "Removes a table defined by the View Class VIEW-CLASS-NAME from
158 DATABASE which defaults to *DEFAULT-DATABASE*."
159   (let ((tclass (find-class view-class-name)))
160     (if tclass
161         (let ((*default-database* database))
162           (%uninstall-class tclass :owner owner))
163         (error "Class ~s not found." view-class-name)))
164   (values))
165
166 (defun %uninstall-class (self &key
167                          (database *default-database*)
168                          (owner nil))
169   (drop-table (sql-expression :table (database-identifier self database))
170               :if-does-not-exist :ignore
171               :database database
172               :owner owner)
173   (database-remove-autoincrement-sequence self database)
174   (setf (database-view-classes database)
175         (remove self (database-view-classes database))))
176
177
178 ;;
179 ;; List all known view classes
180 ;;
181
182 (defun list-classes (&key (test #'identity)
183                      (root-class (find-class 'standard-db-object))
184                      (database *default-database*))
185   "Returns a list of all the View Classes which are connected to
186 DATABASE, which defaults to *DEFAULT-DATABASE*, and which descend
187 from the class ROOT-CLASS and which satisfy the function TEST. By
188 default ROOT-CLASS is STANDARD-DB-OBJECT and TEST is IDENTITY."
189   (flet ((find-superclass (class)
190            (member root-class (class-precedence-list class))))
191     (let ((view-classes (and database (database-view-classes database))))
192       (when view-classes
193         (remove-if #'(lambda (c) (or (not (funcall test c))
194                                      (not (find-superclass c))))
195                    view-classes)))))
196
197 ;;
198 ;; Define a new view class
199 ;;
200
201 (defmacro def-view-class (class supers slots &rest cl-options)
202   "Creates a View Class called CLASS whose slots SLOTS can map
203 onto the attributes of a table in a database. If SUPERS is nil
204 then the superclass of CLASS will be STANDARD-DB-OBJECT,
205 otherwise SUPERS is a list of superclasses for CLASS which must
206 include STANDARD-DB-OBJECT or a descendent of this class. The
207 syntax of DEFCLASS is extended through the addition of a class
208 option :base-table which defines the database table onto which
209 the View Class maps and which defaults to CLASS. The DEFCLASS
210 syntax is also extended through additional slot
211 options. The :db-kind slot option specifies the kind of DB
212 mapping which is performed for this slot and defaults to :base
213 which indicates that the slot maps to an ordinary column of the
214 database table. A :db-kind value of :key indicates that this slot
215 is a special kind of :base slot which maps onto a column which is
216 one of the unique keys for the database table, the value :join
217 indicates this slot represents a join onto another View Class
218 which contains View Class objects, and the value :virtual
219 indicates a standard CLOS slot which does not map onto columns of
220 the database table. If a slot is specified with :db-kind :join,
221 the slot option :db-info contains a list which specifies the
222 nature of the join. For slots of :db-kind :base or :key,
223 the :type slot option has a special interpretation such that Lisp
224 types, such as string, integer and float are automatically
225 converted into appropriate SQL types for the column onto which
226 the slot maps. This behaviour may be over-ridden using
227 the :db-type slot option which is a string specifying the
228 vendor-specific database type for this slot's column definition
229 in the database. The :column slot option specifies the name of
230 the SQL column which the slot maps onto, if :db-kind is
231 not :virtual, and defaults to the slot name. The :void-value slot
232 option specifies the value to store if the SQL value is NULL and
233 defaults to NIL. The :db-constraints slot option is a string
234 representing an SQL table constraint expression or a list of such
235 strings."
236   `(progn
237      (defclass ,class ,supers ,slots
238        ,@(if (find :metaclass `,cl-options :key #'car)
239              `,cl-options
240              (cons '(:metaclass clsql-sys::standard-db-class) `,cl-options)))
241      (finalize-inheritance (find-class ',class))
242      (find-class ',class)))
243
244 (defun keyslots-for-class (class)
245   (slot-value class 'key-slots))