082b1d3c111079a487953b643751d1ad5a8cd231
[clsql.git] / sql / metaclasses.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;;
4 ;;;; $Id$
5 ;;;;
6 ;;;; CLSQL metaclass for standard-db-objects created in the 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 (in-package #:clsql)
16
17 (eval-when (:compile-toplevel :load-toplevel :execute)
18   (when (>= (length (generic-function-lambda-list
19                      (ensure-generic-function
20                       'compute-effective-slot-definition)))
21             3)
22     (pushnew :kmr-normal-cesd cl:*features*))
23   
24   (when (>= (length (generic-function-lambda-list
25                      (ensure-generic-function
26                       'direct-slot-definition-class)))
27             3)
28     (pushnew :kmr-normal-dsdc cl:*features*))
29   
30   (when (>= (length (generic-function-lambda-list
31                      (ensure-generic-function
32                       'effective-slot-definition-class)))
33             3)
34     (pushnew :kmr-normal-esdc cl:*features*)))
35
36
37 ;; ------------------------------------------------------------
38 ;; metaclass: view-class
39
40 (defclass standard-db-class (standard-class)
41   ((view-table
42     :accessor view-table
43     :initarg :view-table)
44    (definition
45     :accessor object-definition
46     :initarg :definition
47     :initform nil)
48    (key-slots
49     :accessor key-slots
50     :initform nil)
51    (class-qualifier
52     :accessor view-class-qualifier
53     :initarg :qualifier
54     :initform nil))
55   (:documentation "VIEW-CLASS metaclass."))
56
57 ;;; Lispworks 4.2 and before requires special processing of extra slot and class options
58
59 (defvar +extra-slot-options+ '(:column :db-kind :db-type :db-reader :void-value :db-constraints
60                                :db-writer :db-info))
61 (defvar +extra-class-options+ '(:base-table))
62
63 (dolist (slot-option +extra-slot-options+)
64   (process-slot-option standard-db-class slot-option))
65
66 (dolist (class-option +extra-class-options+)
67   (process-class-option standard-db-class class-option))
68
69 (defmethod validate-superclass ((class standard-db-class)
70                                 (superclass standard-class))
71   t)
72
73 (defun table-name-from-arg (arg)
74   (cond ((symbolp arg)
75          arg)
76         ((typep arg 'sql-ident)
77          (slot-value arg 'name))
78         ((stringp arg)
79          (intern (symbol-name-default-case arg)))))
80
81 (defun column-name-from-arg (arg)
82   (cond ((symbolp arg)
83          arg)
84         ((typep arg 'sql-ident)
85          (slot-value arg 'name))
86         ((stringp arg)
87          (intern (symbol-name-default-case arg)))))
88
89
90 (defun remove-keyword-arg (arglist akey)
91   (let ((mylist arglist)
92         (newlist ()))
93     (labels ((pop-arg (alist)
94              (let ((arg (pop alist))
95                    (val (pop alist)))
96                (unless (equal arg akey)
97                  (setf newlist (append (list arg val) newlist)))
98                (when alist (pop-arg alist)))))
99       (pop-arg mylist))
100     newlist))
101
102 (defmethod initialize-instance :around ((class standard-db-class)
103                                         &rest all-keys
104                                         &key direct-superclasses base-table
105                                         qualifier
106                                         &allow-other-keys)
107   (let ((root-class (find-class 'standard-db-object nil))
108         (vmc (find-class 'standard-db-class)))
109     (setf (view-class-qualifier class)
110           (car qualifier))
111     (if root-class
112         (if (member-if #'(lambda (super)
113                            (eq (class-of super) vmc)) direct-superclasses)
114             (call-next-method)
115             (apply #'call-next-method
116                    class
117                    :direct-superclasses (append (list root-class)
118                                                 direct-superclasses)
119                    (remove-keyword-arg all-keys :direct-superclasses)))
120         (call-next-method))
121     (setf (view-table class)
122           (table-name-from-arg (sql-escape (or (and base-table
123                                                     (if (listp base-table)
124                                                         (car base-table)
125                                                         base-table))
126                                                (class-name class)))))
127     (register-metaclass class (nth (1+ (position :direct-slots all-keys))
128                                    all-keys))))
129
130 (defmethod reinitialize-instance :around ((class standard-db-class)
131                                           &rest all-keys
132                                           &key base-table 
133                                           direct-superclasses qualifier
134                                           &allow-other-keys)
135   (let ((root-class (find-class 'standard-db-object nil))
136         (vmc (find-class 'standard-db-class)))
137     (setf (view-table class)
138           (table-name-from-arg (sql-escape (or (and base-table
139                                                     (if (listp base-table)
140                                                         (car base-table)
141                                                         base-table))
142                                                (class-name class)))))
143     (setf (view-class-qualifier class)
144           (car qualifier))
145     (if (and root-class (not (equal class root-class)))
146         (if (member-if #'(lambda (super)
147                            (eq (class-of super) vmc)) direct-superclasses)
148             (call-next-method)
149             (apply #'call-next-method
150                    class
151                    :direct-superclasses (append (list root-class)
152                                                 direct-superclasses)
153                    (remove-keyword-arg all-keys :direct-superclasses)))
154         (call-next-method)))
155   (register-metaclass class (nth (1+ (position :direct-slots all-keys))
156                                  all-keys)))
157
158
159 (defun get-keywords (keys list)
160   (flet ((extract (key)
161            (let ((pos (position key list)))
162              (when pos
163                (nth (1+ pos) list)))))
164     (mapcar #'extract keys)))
165
166 (defun describe-db-layout (class)
167   (flet ((not-db-col (col)
168            (not (member (nth 2 col)  '(nil :base :key))))
169          (frob-slot (slot)
170            (let ((type (slot-value slot 'type)))
171              (if (eq type t)
172                  (setq type nil))
173              (list (slot-value slot 'name)
174                    type
175                    (slot-value slot 'db-kind)
176                    (and (slot-boundp slot 'column)
177                         (slot-value slot 'column))))))
178     (let ((all-slots (mapcar #'frob-slot (ordered-class-slots class))))
179       (setq all-slots (remove-if #'not-db-col all-slots))
180       (setq all-slots (stable-sort all-slots #'string< :key #'car))
181       ;;(mapcar #'dink-type all-slots)
182       all-slots)))
183
184 (defun register-metaclass (class slots)
185   (labels ((not-db-col (col)
186              (not (member (nth 2 col)  '(nil :base :key))))
187            (frob-slot (slot)
188              (get-keywords '(:name :type :db-kind :column) slot)))
189     (let ((all-slots (mapcar #'frob-slot slots)))
190       (setq all-slots (remove-if #'not-db-col all-slots))
191       (setq all-slots (stable-sort all-slots #'string< :key #'car))
192       (setf (object-definition class) all-slots))
193     #-(or allegro openmcl)
194     (setf (key-slots class) (remove-if-not (lambda (slot)
195                                              (eql (slot-value slot 'db-kind)
196                                                   :key))
197                                            (ordered-class-slots class)))))
198
199 #+(or allegro openmcl)
200 (defmethod finalize-inheritance :after ((class standard-db-class))
201   (setf (key-slots class) (remove-if-not (lambda (slot)
202                                            (eql (slot-value slot 'db-kind)
203                                                 :key))
204                                          (ordered-class-slots class))))
205
206 ;; return the deepest view-class ancestor for a given view class
207
208 (defun base-db-class (classname)
209   (let* ((class (find-class classname))
210          (db-class (find-class 'standard-db-object)))
211     (loop
212      (let ((cds (class-direct-superclasses class)))
213        (cond ((null cds)
214               (error "not a db class"))
215              ((member db-class cds)
216               (return (class-name class))))
217        (setq class (car cds))))))
218
219 (defun db-ancestors (classname)
220   (let ((class (find-class classname))
221         (db-class (find-class 'standard-db-object)))
222     (labels ((ancestors (class)
223              (let ((scs (class-direct-superclasses class)))
224                (if (member db-class scs)
225                    (list class)
226                    (append (list class) (mapcar #'ancestors scs))))))
227       (ancestors class))))
228
229 (defclass view-class-slot-definition-mixin ()
230   ((column
231     :accessor view-class-slot-column
232     :initarg :column
233     :documentation
234     "The name of the SQL column this slot is stored in.  Defaults to
235 the slot name.")
236    (db-kind
237     :accessor view-class-slot-db-kind
238     :initarg :db-kind
239     :initform :base
240     :type keyword
241     :documentation
242     "The kind of DB mapping which is performed for this slot.  :base
243 indicates the slot maps to an ordinary column of the DB view.  :key
244 indicates that this slot corresponds to part of the unique keys for
245 this view, :join indicates ... and :virtual indicates that this slot
246 is an ordinary CLOS slot.  Defaults to :base.")
247    (db-reader
248     :accessor view-class-slot-db-reader
249     :initarg :db-reader
250     :initform nil
251     :documentation
252     "If a string, then when reading values from the DB, the string
253 will be used for a format string, with the only value being the value
254 from the database.  The resulting string will be used as the slot
255 value.  If a function then it will take one argument, the value from
256 the database, and return the value that should be put into the slot.")
257    (db-writer
258     :accessor view-class-slot-db-writer
259     :initarg :db-writer
260     :initform nil
261     :documentation
262     "If a string, then when reading values from the slot for the DB,
263 the string will be used for a format string, with the only value being
264 the value of the slot.  The resulting string will be used as the
265 column value in the DB.  If a function then it will take one argument,
266 the value of the slot, and return the value that should be put into
267 the database.")
268    (db-type
269     :accessor view-class-slot-db-type
270     :initarg :db-type
271     :initform nil
272     :documentation
273     "A string which will be used as the type specifier for this slots
274 column definition in the database.")
275    (db-constraints
276     :accessor view-class-slot-db-constraints
277     :initarg :db-constraints
278     :initform nil
279     :documentation
280     "A single constraint or list of constraints for this column")
281    (void-value
282     :accessor view-class-slot-void-value
283     :initarg :void-value
284     :initform nil
285     :documentation
286     "Value to store is the SQL value is NULL. Default is NIL.")
287    (db-info
288     :accessor view-class-slot-db-info
289     :initarg :db-info
290     :documentation "Description of the join.")
291    (specified-type
292     :accessor specified-type
293     :initform nil
294     :documentation "KMR: Internal slot storing the :type specified by user.")))
295
296 (defparameter *db-info-lambda-list*
297   '(&key join-class
298          home-key
299          foreign-key
300          (key-join nil)
301          (target-slot nil)
302          (retrieval :immmediate)
303          (set nil)))
304           
305 (defun parse-db-info (db-info-list)
306   (destructuring-bind
307         (&key join-class home-key key-join foreign-key (delete-rule nil)
308               (target-slot nil) (retrieval :deferred) (set nil))
309       db-info-list
310     (let ((ih (make-hash-table :size 6)))
311       (if join-class
312           (setf (gethash :join-class ih) join-class)
313           (error "Must specify :join-class in :db-info"))
314       (if home-key
315           (setf (gethash :home-key ih) home-key)
316           (error "Must specify :home-key in :db-info"))
317       (when delete-rule
318         (setf (gethash :delete-rule ih) delete-rule))
319       (if foreign-key
320           (setf (gethash :foreign-key ih) foreign-key)
321           (error "Must specify :foreign-key in :db-info"))
322       (when key-join
323         (setf (gethash :key-join ih) t))
324       (when target-slot
325         (setf (gethash :target-slot ih) target-slot))
326       (when set
327         (setf (gethash :set ih) set))
328       (when retrieval
329         (progn
330           (setf (gethash :retrieval ih) retrieval)
331           (if (eql retrieval :immediate)
332               (setf (gethash :set ih) nil))))
333       ih)))
334
335 (defclass view-class-direct-slot-definition (view-class-slot-definition-mixin
336                                              standard-direct-slot-definition)
337   ())
338
339 (defclass view-class-effective-slot-definition (view-class-slot-definition-mixin
340                                                 standard-effective-slot-definition)
341   ())
342
343 (defmethod direct-slot-definition-class ((class standard-db-class)
344                                          #+kmr-normal-dsdc &rest
345                                          initargs)
346   (declare (ignore initargs))
347   (find-class 'view-class-direct-slot-definition))
348
349 (defmethod effective-slot-definition-class ((class standard-db-class)
350                                             #+kmr-normal-esdc &rest
351                                             initargs)
352   (declare (ignore initargs))
353   (find-class 'view-class-effective-slot-definition))
354
355 #+openmcl
356 (defun compute-class-precedence-list (class)
357   ;; safe to call this in openmcl
358   (class-precedence-list class))
359
360 #-(or sbcl cmu)
361 (defmethod compute-slots ((class standard-db-class))
362   "Need to sort order of class slots so they are the same across
363 implementations."
364   (let ((slots (call-next-method))
365         desired-sequence
366         output-slots)
367     (dolist (c (compute-class-precedence-list class))
368       (dolist (s (class-direct-slots c))
369         (let ((name (slot-definition-name s)))
370           (unless (find name desired-sequence)
371             (push name desired-sequence)))))
372     (dolist (desired desired-sequence)
373       (let ((slot (find desired slots :key #'slot-definition-name)))
374         (assert slot)
375         (push slot output-slots)))
376     output-slots))
377
378 (defun compute-lisp-type-from-slot-specification (slotd specified-type)
379   "Computes the Lisp type for a user-specified type. Needed for OpenMCL
380 which does type checking before storing a value in a slot."
381   (declare (ignore slotd))
382   ;; This function is called after the base compute-effective-slots is called.
383   ;; OpenMCL sets the type-predicate based on the initial value of the slots type.
384   ;; so we have to override the type-predicates here
385   (cond
386     ((consp specified-type)
387      (cond
388        ((and (symbolp (car specified-type))
389              (string-equal (symbol-name (car specified-type)) "string"))
390         'string)
391        (t
392         specified-type)))
393     ((eq (ensure-keyword specified-type) :bigint)
394      'integer)
395     #+openmcl
396     ((null specified-type)
397      t)
398     (t
399      specified-type)))
400
401 ;; Compute the slot definition for slots in a view-class.  Figures out
402 ;; what kind of database value (if any) is stored there, generates and
403 ;; verifies the column name.
404
405 (defmethod compute-effective-slot-definition ((class standard-db-class)
406                                               #+kmr-normal-cesd slot-name
407                                               direct-slots)
408   #+kmr-normal-cesd (declare (ignore slot-name))
409   
410   ;; KMR: store the user-specified type and then compute
411   ;; real Lisp type and store it
412   (let ((dsd (car direct-slots)))
413     (when (and (typep dsd 'view-class-slot-definition-mixin)
414                (null (specified-type dsd)))
415       (setf (specified-type dsd)
416         (slot-definition-type dsd))
417       (setf (slot-value dsd 'type)
418         (compute-lisp-type-from-slot-specification 
419          dsd (slot-definition-type dsd))))
420       
421     (let ((esd (call-next-method)))
422       (typecase dsd
423         (view-class-slot-definition-mixin
424          ;; Use the specified :column argument if it is supplied, otherwise
425          ;; the column slot is filled in with the slot-name,  but transformed
426          ;; to be sql safe, - to _ and such.
427          (setf (slot-value esd 'column)
428            (column-name-from-arg
429             (if (slot-boundp dsd 'column)
430                 (view-class-slot-column dsd)
431               (column-name-from-arg
432                (sql-escape (slot-definition-name dsd))))))
433          
434          (setf (slot-value esd 'db-type)
435            (when (slot-boundp dsd 'db-type)
436              (view-class-slot-db-type dsd)))
437          
438          (setf (slot-value esd 'void-value)
439            (view-class-slot-void-value dsd))
440          
441          ;; :db-kind slot value defaults to :base (store slot value in
442          ;; database)
443          
444          (setf (slot-value esd 'db-kind)
445            (if (slot-boundp dsd 'db-kind)
446                (view-class-slot-db-kind dsd)
447              :base))
448          
449          (setf (slot-value esd 'db-writer)
450            (when (slot-boundp dsd 'db-writer)
451              (view-class-slot-db-writer dsd)))
452          (setf (slot-value esd 'db-constraints)
453            (when (slot-boundp dsd 'db-constraints)
454              (view-class-slot-db-constraints dsd)))
455          
456          ;; I wonder if this slot option and the previous could be merged,
457          ;; so that :base and :key remain keyword options, but :db-kind
458          ;; :join becomes :db-kind (:join <db info .... >)?
459          
460          (setf (slot-value esd 'db-info)
461            (when (slot-boundp dsd 'db-info)
462              (if (listp (view-class-slot-db-info dsd))
463                  (parse-db-info (view-class-slot-db-info dsd))
464                (view-class-slot-db-info dsd))))
465          
466          (setf (specified-type esd) (specified-type dsd))
467          
468          )
469         ;; all other slots
470         (t
471          (change-class esd 'view-class-effective-slot-definition
472                        #+allegro :name 
473                        #+allegro (slot-definition-name dsd))
474          
475          (setf (slot-value esd 'column)
476            (column-name-from-arg
477             (sql-escape (slot-definition-name dsd))))
478          
479          (setf (slot-value esd 'db-info) nil)
480          (setf (slot-value esd 'db-kind)
481            :virtual)))
482       esd)))
483   
484 (defun slotdefs-for-slots-with-class (slots class)
485   (let ((result nil))
486     (dolist (s slots)
487       (let ((c (slotdef-for-slot-with-class s class)))
488         (if c (setf result (cons c result)))))
489     result))
490
491 (defun slotdef-for-slot-with-class (slot class)
492   (find-if #'(lambda (d) (eql slot (slot-definition-name d)))
493            (class-slots class)))
494
495 #+ignore
496 (eval-when (:compile-toplevel :load-toplevel :execute)
497   #+kmr-normal-cesd
498   (setq cl:*features* (delete :kmr-normal-cesd cl:*features*))
499   #+kmr-normal-dsdc
500   (setq cl:*features* (delete :kmr-normal-dsdc cl:*features*))
501   #+kmr-normal-esdc
502   (setq cl:*features* (delete :kmr-normal-esdc cl:*features*))
503   )