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 RowUpdateSignal(Signal):
0119    """
0120    Called when an instance is updated through a call to ``.set()``
0121    (or a column attribute assignment).  The arguments are
0122    ``(instance, kwargs)``.  ``kwargs`` can be modified.  This is run
0123    *before* the instance is updated; if you want to look at the
0124    current values, simply look at ``instance``.
0125    """
0126
0127class AddColumnSignal(Signal):
0128    """
0129    Called when a column is added to a class, with arguments ``(cls,
0130    connection, column_name, column_definition, changeSchema,
0131    post_funcs)``.  This is called *after* the column has been added,
0132    and is called for each column after class creation.
0133
0134    post_funcs are called with ``(cls, so_column_obj)``
0135    """
0136
0137class DeleteColumnSignal(Signal):
0138    """
0139    Called when a column is removed from a class, with the arguments
0140    ``(cls, connection, column_name, so_column_obj, post_funcs)``.
0141    Like ``AddColumnSignal`` this is called after the action has been
0142    performed, and is called for subclassing (when a column is
0143    implicitly removed by setting it to ``None``).
0144
0145    post_funcs are called with ``(cls, so_column_obj)``
0146    """
0147
0148# @@: Signals for indexes and joins?  These are mostly event consumers,
0149# though.
0150
0151class CreateTableSignal(Signal):
0152    """
0153    Called when a table is created.  If ``ifNotExists==True`` and the
0154    table exists, this event is not called.
0155
0156    Called with ``(cls, connection, extra_sql, post_funcs)``.
0157    ``extra_sql`` is a list (which can be appended to) of extra SQL
0158    statements to be run after the table is created.  ``post_funcs``
0159    functions are called with ``(cls, connection)`` after the table
0160    has been created.  Those functions are *not* called simply when
0161    constructing the SQL.
0162    """
0163
0164class DropTableSignal(Signal):
0165    """
0166    Called when a table is dropped.  If ``ifExists==True`` and the
0167    table doesn't exist, this event is not called.
0168
0169    Called with ``(cls, connection, extra_sql, post_funcs)``.
0170    ``post_funcs`` functions are called with ``(cls, connection)``
0171    after the table has been dropped.
0172    """
0173
0174############################################################
0175## Event Debugging
0176############################################################
0177
0178def summarize_events_by_sender(sender=None, output=None, indent=0):
0179    """
0180    Prints out a summary of the senders and listeners in the system,
0181    for debugging purposes.
0182    """
0183    if output is None:
0184        output = sys.stdout
0185    if sender is None:
0186        send_list = [
0187            (deref(dispatcher.senders.get(sid)), listeners)
0188            for sid, listeners in dispatcher.connections.items()
0189            if deref(dispatcher.senders.get(sid))]
0190        for sender, listeners in sorted_items(send_list):
0191            real_sender = deref(sender)
0192            if not real_sender:
0193                continue
0194            header = 'Sender: %r' % real_sender
0195            print >> output, (' '*indent) + header
0196            print >> output, (' '*indent) + '='*len(header)
0197            summarize_events_by_sender(real_sender, output=output, indent=indent+2)
0198    else:
0199        for signal, receivers in sorted_items(dispatcher.connections.get(id(sender), [])):
0200            receivers = [deref(r) for r in receivers if deref(r)]
0201            header = 'Signal: %s (%i receivers)' % (sort_name(signal),
0202                                                    len(receivers))
0203            print >> output, (' '*indent) + header
0204            print >> output, (' '*indent) + '-'*len(header)
0205            for receiver in sorted(receivers, key=sort_name):
0206                print >> output, (' '*indent) + '  ' + nice_repr(receiver)
0207
0208def deref(value):
0209    if isinstance(value, dispatcher.WEAKREF_TYPES):
0210        return value()
0211    else:
0212        return value
0213
0214def sorted_items(a_dict):
0215    if isinstance(a_dict, dict):
0216        a_dict = a_dict.items()
0217    return sorted(a_dict, key=lambda t: sort_name(t[0]))
0218
0219def sort_name(value):
0220    if isinstance(value, type):
0221        return value.__name__
0222    elif isinstance(value, types.FunctionType):
0223        return value.func_name
0224    else:
0225        return str(value)
0226
0227_real_dispatcher_send = dispatcher.send
0228_real_dispatcher_sendExact = dispatcher.sendExact
0229_real_dispatcher_disconnect = dispatcher.disconnect
0230_real_dispatcher_connect = dispatcher.connect
0231_debug_enabled = False
0232def debug_events():
0233    global _debug_enabled, send
0234    if _debug_enabled:
0235        return
0236    _debug_enabled = True
0237    dispatcher.send = send = _debug_send
0238    dispatcher.sendExact = _debug_sendExact
0239    dispatcher.disconnect = _debug_disconnect
0240    dispatcher.connect = _debug_connect
0241
0242def _debug_send(signal=dispatcher.Any, sender=dispatcher.Anonymous,
0243                *arguments, **named):
0244    print "send %s from %s: %s" % (
0245        nice_repr(signal), nice_repr(sender), fmt_args(*arguments, **named))
0246    return _real_dispatcher_send(signal, sender, *arguments, **named)
0247
0248def _debug_sendExact(signal=dispatcher.Any, sender=dispatcher.Anonymous,
0249                     *arguments, **named):
0250    print "sendExact %s from %s: %s" % (
0251        nice_repr(signal), nice_repr(sender), fmt_args(*arguments, **name))
0252    return _real_dispatcher_sendExact(signal, sender, *arguments, **named)
0253
0254def _debug_connect(receiver, signal=dispatcher.Any, sender=dispatcher.Any,
0255                   weak=True):
0256    print "connect %s to %s signal %s" % (
0257        nice_repr(receiver), nice_repr(signal), nice_repr(sender))
0258    return _real_dispatcher_connect(receiver, signal, sender, weak)
0259
0260def _debug_disconnect(receiver, signal=dispatcher.Any, sender=dispatcher.Any,
0261                      weak=True):
0262    print "disconnecting %s from %s signal %s" % (
0263        nice_repr(receiver), nice_repr(signal), nice_repr(sender))
0264    return disconnect(receiver, signal, sender, weak)
0265
0266def fmt_args(*arguments, **name):
0267    args = [repr(a) for a in arguments]
0268    args.extend([
0269        '%s=%r' % (n, v) for n, v in sorted(name.items())])
0270    return ', '.join(args)
0271
0272def nice_repr(v):
0273    """
0274    Like repr(), but nicer for debugging here.
0275    """
0276    if isinstance(v, (types.ClassType, type)):
0277        return v.__module__ + '.' + v.__name__
0278    elif isinstance(v, types.FunctionType):
0279        if '__name__' in v.func_globals:
0280            if getattr(sys.modules[v.func_globals['__name__']],
0281                       v.func_name, None) is v:
0282                return '%s.%s' % (v.func_globals['__name__'], v.func_name)
0283        return repr(v)
0284    elif isinstance(v, types.MethodType):
0285        return '%s.%s of %s' % (
0286            nice_repr(v.im_class), v.im_func.func_name,
0287            nice_repr(v.im_self))
0288    else:
0289        return repr(v)
0290
0291try:
0292    sorted
0293except NameError:
0294    # For Python 2.2 and 2.3:
0295    def sorted(lst, cmp=None, key=None, reverse=False):
0296        if key:
0297            lst = [(key(i), i) for i in lst]
0298        lst = lst[:]
0299        if cmp:
0300            lst.sort(cmp)
0301        else:
0302            lst.sort()
0303        if key:
0304            lst = [i for k, i in lst]
0305        if reverse:
0306            lst.reverse()
0307        return lst
0308
0309__all__ = ['listen', 'send']
0310for name, value in globals().items():
0311    if isinstance(value, type) and issubclass(value, Signal):
0312        __all__.append(name)