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# We export this function:
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# @@: Should there be a class reload event?  This would allow modules
0066# to be reloaded, possibly.  Or it could even be folded into
0067# ClassCreateSignal, since anything that listens to that needs to pay
0068# attention to reloads (or else it is probably buggy).
0069
0070class RowCreateSignal(Signal):
0071    """
0072    Called before an instance is created, with the class as the
0073    sender.  Called with the arguments ``(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 ``(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# @@: An event for getting a row?  But for each row, when doing a
0095# select?  For .sync, .syncUpdate, .expire?
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 without arguments. If
0104    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)``. This is run *after* the instance is updated;
0143    Works better with lazyUpdate = True
0144    """
0145
0146class AddColumnSignal(Signal):
0147    """
0148    Called when a column is added to a class, with arguments ``(cls,
0149    connection, column_name, column_definition, changeSchema,
0150    post_funcs)``.  This is called *after* the column has been added,
0151    and is called for each column after class creation.
0152
0153    post_funcs are called with ``(cls, so_column_obj)``
0154    """
0155
0156class DeleteColumnSignal(Signal):
0157    """
0158    Called when a column is removed from a class, with the arguments
0159    ``(cls, connection, column_name, so_column_obj, post_funcs)``.
0160    Like ``AddColumnSignal`` this is called after the action has been
0161    performed, and is called for subclassing (when a column is
0162    implicitly removed by setting it to ``None``).
0163
0164    post_funcs are called with ``(cls, so_column_obj)``
0165    """
0166
0167# @@: Signals for indexes and joins?  These are mostly event consumers,
0168# though.
0169
0170class CreateTableSignal(Signal):
0171    """
0172    Called when a table is created.  If ``ifNotExists==True`` and the
0173    table exists, this event is not called.
0174
0175    Called with ``(cls, connection, extra_sql, post_funcs)``.
0176    ``extra_sql`` is a list (which can be appended to) of extra SQL
0177    statements to be run after the table is created.  ``post_funcs``
0178    functions are called with ``(cls, connection)`` after the table
0179    has been created.  Those functions are *not* called simply when
0180    constructing the SQL.
0181    """
0182
0183class DropTableSignal(Signal):
0184    """
0185    Called when a table is dropped.  If ``ifExists==True`` and the
0186    table doesn't exist, this event is not called.
0187
0188    Called with ``(cls, connection, extra_sql, post_funcs)``.
0189    ``post_funcs`` functions are called with ``(cls, connection)``
0190    after the table has been dropped.
0191    """
0192
0193############################################################
0194## Event Debugging
0195############################################################
0196
0197def summarize_events_by_sender(sender=None, output=None, indent=0):
0198    """
0199    Prints out a summary of the senders and listeners in the system,
0200    for debugging purposes.
0201    """
0202    if output is None:
0203        output = sys.stdout
0204    if sender is None:
0205        send_list = [
0206            (deref(dispatcher.senders.get(sid)), listeners)
0207            for sid, listeners in dispatcher.connections.items()
0208            if deref(dispatcher.senders.get(sid))]
0209        for sender, listeners in sorted_items(send_list):
0210            real_sender = deref(sender)
0211            if not real_sender:
0212                continue
0213            header = 'Sender: %r' % real_sender
0214            print >> output, (' '*indent) + header
0215            print >> output, (' '*indent) + '='*len(header)
0216            summarize_events_by_sender(real_sender, output=output, indent=indent+2)
0217    else:
0218        for signal, receivers in sorted_items(dispatcher.connections.get(id(sender), [])):
0219            receivers = [deref(r) for r in receivers if deref(r)]
0220            header = 'Signal: %s (%i receivers)' % (sort_name(signal),
0221                                                    len(receivers))
0222            print >> output, (' '*indent) + header
0223            print >> output, (' '*indent) + '-'*len(header)
0224            for receiver in sorted(receivers, key=sort_name):
0225                print >> output, (' '*indent) + '  ' + nice_repr(receiver)
0226
0227def deref(value):
0228    if isinstance(value, dispatcher.WEAKREF_TYPES):
0229        return value()
0230    else:
0231        return value
0232
0233def sorted_items(a_dict):
0234    if isinstance(a_dict, dict):
0235        a_dict = a_dict.items()
0236    return sorted(a_dict, key=lambda t: sort_name(t[0]))
0237
0238def sort_name(value):
0239    if isinstance(value, type):
0240        return value.__name__
0241    elif isinstance(value, types.FunctionType):
0242        return value.func_name
0243    else:
0244        return str(value)
0245
0246_real_dispatcher_send = dispatcher.send
0247_real_dispatcher_sendExact = dispatcher.sendExact
0248_real_dispatcher_disconnect = dispatcher.disconnect
0249_real_dispatcher_connect = dispatcher.connect
0250_debug_enabled = False
0251def debug_events():
0252    global _debug_enabled, send
0253    if _debug_enabled:
0254        return
0255    _debug_enabled = True
0256    dispatcher.send = send = _debug_send
0257    dispatcher.sendExact = _debug_sendExact
0258    dispatcher.disconnect = _debug_disconnect
0259    dispatcher.connect = _debug_connect
0260
0261def _debug_send(signal=dispatcher.Any, sender=dispatcher.Anonymous,
0262                *arguments, **named):
0263    print "send %s from %s: %s" % (
0264        nice_repr(signal), nice_repr(sender), fmt_args(*arguments, **named))
0265    return _real_dispatcher_send(signal, sender, *arguments, **named)
0266
0267def _debug_sendExact(signal=dispatcher.Any, sender=dispatcher.Anonymous,
0268                     *arguments, **named):
0269    print "sendExact %s from %s: %s" % (
0270        nice_repr(signal), nice_repr(sender), fmt_args(*arguments, **name))
0271    return _real_dispatcher_sendExact(signal, sender, *arguments, **named)
0272
0273def _debug_connect(receiver, signal=dispatcher.Any, sender=dispatcher.Any,
0274                   weak=True):
0275    print "connect %s to %s signal %s" % (
0276        nice_repr(receiver), nice_repr(signal), nice_repr(sender))
0277    return _real_dispatcher_connect(receiver, signal, sender, weak)
0278
0279def _debug_disconnect(receiver, signal=dispatcher.Any, sender=dispatcher.Any,
0280                      weak=True):
0281    print "disconnecting %s from %s signal %s" % (
0282        nice_repr(receiver), nice_repr(signal), nice_repr(sender))
0283    return disconnect(receiver, signal, sender, weak)
0284
0285def fmt_args(*arguments, **name):
0286    args = [repr(a) for a in arguments]
0287    args.extend([
0288        '%s=%r' % (n, v) for n, v in sorted(name.items())])
0289    return ', '.join(args)
0290
0291def nice_repr(v):
0292    """
0293    Like repr(), but nicer for debugging here.
0294    """
0295    if isinstance(v, (types.ClassType, type)):
0296        return v.__module__ + '.' + v.__name__
0297    elif isinstance(v, types.FunctionType):
0298        if '__name__' in v.func_globals:
0299            if getattr(sys.modules[v.func_globals['__name__']],
0300                       v.func_name, None) is v:
0301                return '%s.%s' % (v.func_globals['__name__'], v.func_name)
0302        return repr(v)
0303    elif isinstance(v, types.MethodType):
0304        return '%s.%s of %s' % (
0305            nice_repr(v.im_class), v.im_func.func_name,
0306            nice_repr(v.im_self))
0307    else:
0308        return repr(v)
0309
0310
0311__all__ = ['listen', 'send']
0312for name, value in globals().items():
0313    if isinstance(value, type) and issubclass(value, Signal):
0314        __all__.append(name)