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