0001import sys
0002import types
0003from sqlobject.include.pydispatch import dispatcher
0004from weakref import ref
0005
0006
0007subclassClones = {}
0008
0009def listen(receiver, soClass, signal, alsoSubclasses=True, weak=True):
0010 """
0011 Listen for the given ``signal`` on the SQLObject subclass
0012 ``soClass``, calling ``receiver()`` when ``send(soClass, signal,
0013 ...)`` is called.
0014
0015 If ``alsoSubclasses`` is true, receiver will also be called when
0016 an event is fired on any subclass.
0017 """
0018 dispatcher.connect(receiver, signal=signal, sender=soClass, weak=weak)
0019 weakReceiver = ref(receiver)
0020 subclassClones.setdefault(soClass, []).append((weakReceiver, signal))
0021
0022
0023send = dispatcher.send
0024
0025class Signal(object):
0026 """
0027 Base event for all SQLObject events.
0028
0029 In general the sender for these methods is the class, not the
0030 instance.
0031 """
0032
0033class ClassCreateSignal(Signal):
0034 """
0035 Signal raised after class creation. The sender is the superclass
0036 (in case of multiple superclasses, the first superclass). The
0037 arguments are ``(new_class_name, bases, new_attrs, post_funcs,
0038 early_funcs)``. ``new_attrs`` is a dictionary and may be modified
0039 (but ``new_class_name`` and ``bases`` are immutable).
0040 ``post_funcs`` is an initially-empty list that can have callbacks
0041 appended to it.
0042
0043 Note: at the time this event is called, the new class has not yet
0044 been created. The functions in ``post_funcs`` will be called
0045 after the class is created, with the single arguments of
0046 ``(new_class)``. Also, ``early_funcs`` will be called at the
0047 soonest possible time after class creation (``post_funcs`` is
0048 called after the class's ``__classinit__``).
0049 """
0050
0051def _makeSubclassConnections(new_class_name, bases, new_attrs,
0052 post_funcs, early_funcs):
0053 early_funcs.insert(0, _makeSubclassConnectionsPost)
0054
0055def _makeSubclassConnectionsPost(new_class):
0056 for cls in new_class.__bases__:
0057 for weakReceiver, signal in subclassClones.get(cls, []):
0058 receiver = weakReceiver()
0059 if not receiver:
0060 continue
0061 listen(receiver, new_class, signal)
0062
0063dispatcher.connect(_makeSubclassConnections, signal=ClassCreateSignal)
0064
0065
0066
0067
0068
0069
0070class RowCreateSignal(Signal):
0071 """
0072 Called before an instance is created, with the class as the
0073 sender. Called with the arguments ``(instance, kwargs, post_funcs)``.
0074 There may be a ``connection`` argument. ``kwargs``may be usefully
0075 modified. ``post_funcs`` is a list of callbacks, intended to have
0076 functions appended to it, and are called with the arguments
0077 ``(new_instance)``.
0078
0079 Note: this is not called when an instance is created from an
0080 existing database row.
0081 """
0082class RowCreatedSignal(Signal):
0083 """
0084 Called after an instance is created, with the class as the
0085 sender. Called with the arguments ``(instance, kwargs, post_funcs)``.
0086 There may be a ``connection`` argument. ``kwargs``may be usefully
0087 modified. ``post_funcs`` is a list of callbacks, intended to have
0088 functions appended to it, and are called with the arguments
0089 ``(new_instance)``.
0090
0091 Note: this is not called when an instance is created from an
0092 existing database row.
0093 """
0094
0095
0096
0097class RowDestroySignal(Signal):
0098 """
0099 Called before an instance is deleted. Sender is the instance's
0100 class. Arguments are ``(instance, post_funcs)``.
0101
0102 ``post_funcs`` is a list of callbacks, intended to have
0103 functions appended to it, and are called with arguments ``(instance)``.
0104 If any of the post_funcs raises an exception, the deletion is only
0105 affected if this will prevent a commit.
0106
0107 You cannot cancel the delete, but you can raise an exception (which will
0108 probably cancel the delete, but also cause an uncaught exception if not
0109 expected).
0110
0111 Note: this is not called when an instance is destroyed through
0112 garbage collection.
0113
0114 @@: Should this allow ``instance`` to be a primary key, so that a
0115 row can be deleted without first fetching it?
0116 """
0117
0118class RowDestroyedSignal(Signal):
0119 """
0120 Called after an instance is deleted. Sender is the instance's
0121 class. Arguments are ``(instance)``.
0122
0123 This is called before the post_funcs of RowDestroySignal
0124
0125 Note: this is not called when an instance is destroyed through
0126 garbage collection.
0127 """
0128
0129class RowUpdateSignal(Signal):
0130 """
0131 Called when an instance is updated through a call to ``.set()``
0132 (or a column attribute assignment). The arguments are
0133 ``(instance, kwargs)``. ``kwargs`` can be modified. This is run
0134 *before* the instance is updated; if you want to look at the
0135 current values, simply look at ``instance``.
0136 """
0137
0138class RowUpdatedSignal(Signal):
0139 """
0140 Called when an instance is updated through a call to ``.set()``
0141 (or a column attribute assignment). The arguments are
0142 ``(instance, post_funcs)``. ``post_funcs`` is a list of callbacks,
0143 intended to have functions appended to it, and are called with the
0144 arguments ``(new_instance)``. This is run *after* the instance is
0145 updated; Works better with lazyUpdate = True.
0146 """
0147
0148class AddColumnSignal(Signal):
0149 """
0150 Called when a column is added to a class, with arguments ``(cls,
0151 connection, column_name, column_definition, changeSchema,
0152 post_funcs)``. This is called *after* the column has been added,
0153 and is called for each column after class creation.
0154
0155 post_funcs are called with ``(cls, so_column_obj)``
0156 """
0157
0158class DeleteColumnSignal(Signal):
0159 """
0160 Called when a column is removed from a class, with the arguments
0161 ``(cls, connection, column_name, so_column_obj, post_funcs)``.
0162 Like ``AddColumnSignal`` this is called after the action has been
0163 performed, and is called for subclassing (when a column is
0164 implicitly removed by setting it to ``None``).
0165
0166 post_funcs are called with ``(cls, so_column_obj)``
0167 """
0168
0169
0170
0171
0172class CreateTableSignal(Signal):
0173 """
0174 Called when a table is created. If ``ifNotExists==True`` and the
0175 table exists, this event is not called.
0176
0177 Called with ``(cls, connection, extra_sql, post_funcs)``.
0178 ``extra_sql`` is a list (which can be appended to) of extra SQL
0179 statements to be run after the table is created. ``post_funcs``
0180 functions are called with ``(cls, connection)`` after the table
0181 has been created. Those functions are *not* called simply when
0182 constructing the SQL.
0183 """
0184
0185class DropTableSignal(Signal):
0186 """
0187 Called when a table is dropped. If ``ifExists==True`` and the
0188 table doesn't exist, this event is not called.
0189
0190 Called with ``(cls, connection, extra_sql, post_funcs)``.
0191 ``post_funcs`` functions are called with ``(cls, connection)``
0192 after the table has been dropped.
0193 """
0194
0195
0196
0197
0198
0199def summarize_events_by_sender(sender=None, output=None, indent=0):
0200 """
0201 Prints out a summary of the senders and listeners in the system,
0202 for debugging purposes.
0203 """
0204 if output is None:
0205 output = sys.stdout
0206 if sender is None:
0207 send_list = [
0208 (deref(dispatcher.senders.get(sid)), listeners)
0209 for sid, listeners in dispatcher.connections.items()
0210 if deref(dispatcher.senders.get(sid))]
0211 for sender, listeners in sorted_items(send_list):
0212 real_sender = deref(sender)
0213 if not real_sender:
0214 continue
0215 header = 'Sender: %r' % real_sender
0216 print >> output, (' '*indent) + header
0217 print >> output, (' '*indent) + '='*len(header)
0218 summarize_events_by_sender(real_sender, output=output, indent=indent+2)
0219 else:
0220 for signal, receivers in sorted_items(dispatcher.connections.get(id(sender), [])):
0221 receivers = [deref(r) for r in receivers if deref(r)]
0222 header = 'Signal: %s (%i receivers)' % (sort_name(signal),
0223 len(receivers))
0224 print >> output, (' '*indent) + header
0225 print >> output, (' '*indent) + '-'*len(header)
0226 for receiver in sorted(receivers, key=sort_name):
0227 print >> output, (' '*indent) + ' ' + nice_repr(receiver)
0228
0229def deref(value):
0230 if isinstance(value, dispatcher.WEAKREF_TYPES):
0231 return value()
0232 else:
0233 return value
0234
0235def sorted_items(a_dict):
0236 if isinstance(a_dict, dict):
0237 a_dict = a_dict.items()
0238 return sorted(a_dict, key=lambda t: sort_name(t[0]))
0239
0240def sort_name(value):
0241 if isinstance(value, type):
0242 return value.__name__
0243 elif isinstance(value, types.FunctionType):
0244 return value.func_name
0245 else:
0246 return str(value)
0247
0248_real_dispatcher_send = dispatcher.send
0249_real_dispatcher_sendExact = dispatcher.sendExact
0250_real_dispatcher_disconnect = dispatcher.disconnect
0251_real_dispatcher_connect = dispatcher.connect
0252_debug_enabled = False
0253def debug_events():
0254 global _debug_enabled, send
0255 if _debug_enabled:
0256 return
0257 _debug_enabled = True
0258 dispatcher.send = send = _debug_send
0259 dispatcher.sendExact = _debug_sendExact
0260 dispatcher.disconnect = _debug_disconnect
0261 dispatcher.connect = _debug_connect
0262
0263def _debug_send(signal=dispatcher.Any, sender=dispatcher.Anonymous,
0264 *arguments, **named):
0265 print "send %s from %s: %s" % (
0266 nice_repr(signal), nice_repr(sender), fmt_args(*arguments, **named))
0267 return _real_dispatcher_send(signal, sender, *arguments, **named)
0268
0269def _debug_sendExact(signal=dispatcher.Any, sender=dispatcher.Anonymous,
0270 *arguments, **named):
0271 print "sendExact %s from %s: %s" % (
0272 nice_repr(signal), nice_repr(sender), fmt_args(*arguments, **name))
0273 return _real_dispatcher_sendExact(signal, sender, *arguments, **named)
0274
0275def _debug_connect(receiver, signal=dispatcher.Any, sender=dispatcher.Any,
0276 weak=True):
0277 print "connect %s to %s signal %s" % (
0278 nice_repr(receiver), nice_repr(signal), nice_repr(sender))
0279 return _real_dispatcher_connect(receiver, signal, sender, weak)
0280
0281def _debug_disconnect(receiver, signal=dispatcher.Any, sender=dispatcher.Any,
0282 weak=True):
0283 print "disconnecting %s from %s signal %s" % (
0284 nice_repr(receiver), nice_repr(signal), nice_repr(sender))
0285 return disconnect(receiver, signal, sender, weak)
0286
0287def fmt_args(*arguments, **name):
0288 args = [repr(a) for a in arguments]
0289 args.extend([
0290 '%s=%r' % (n, v) for n, v in sorted(name.items())])
0291 return ', '.join(args)
0292
0293def nice_repr(v):
0294 """
0295 Like repr(), but nicer for debugging here.
0296 """
0297 if isinstance(v, (types.ClassType, type)):
0298 return v.__module__ + '.' + v.__name__
0299 elif isinstance(v, types.FunctionType):
0300 if '__name__' in v.func_globals:
0301 if getattr(sys.modules[v.func_globals['__name__']],
0302 v.func_name, None) is v:
0303 return '%s.%s' % (v.func_globals['__name__'], v.func_name)
0304 return repr(v)
0305 elif isinstance(v, types.MethodType):
0306 return '%s.%s of %s' % (
0307 nice_repr(v.im_class), v.im_func.func_name,
0308 nice_repr(v.im_self))
0309 else:
0310 return repr(v)
0311
0312
0313__all__ = ['listen', 'send']
0314for name, value in globals().items():
0315 if isinstance(value, type) and issubclass(value, Signal):
0316 __all__.append(name)