~ubuntu-branches/debian/jessie/sqlalchemy/jessie

« back to all changes in this revision

Viewing changes to lib/sqlalchemy/events.py

  • Committer: Package Import Robot
  • Author(s): Piotr Ożarowski, Jakub Wilk, Piotr Ożarowski
  • Date: 2013-07-06 20:53:52 UTC
  • mfrom: (1.4.23) (16.1.17 experimental)
  • Revision ID: package-import@ubuntu.com-20130706205352-ryppl1eto3illd79
Tags: 0.8.2-1
[ Jakub Wilk ]
* Use canonical URIs for Vcs-* fields.

[ Piotr Ożarowski ]
* New upstream release
* Upload to unstable
* Build depend on python3-all instead of -dev, extensions are not built for
  Python 3.X 

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# sqlalchemy/events.py
2
 
# Copyright (C) 2005-2012 the SQLAlchemy authors and contributors <see AUTHORS file>
 
2
# Copyright (C) 2005-2013 the SQLAlchemy authors and contributors <see AUTHORS file>
3
3
#
4
4
# This module is part of SQLAlchemy and is released under
5
5
# the MIT License: http://www.opensource.org/licenses/mit-license.php
6
6
 
7
7
"""Core event interfaces."""
8
8
 
9
 
from sqlalchemy import event, exc, util
 
9
from . import event, exc, util
10
10
engine = util.importlater('sqlalchemy', 'engine')
11
11
pool = util.importlater('sqlalchemy', 'pool')
12
12
 
166
166
 
167
167
        """
168
168
 
169
 
    def column_reflect(self, table, column_info):
 
169
    def column_reflect(self, inspector, table, column_info):
170
170
        """Called for each unit of 'column info' retrieved when
171
171
        a :class:`.Table` is being reflected.
172
172
 
188
188
            from sqlalchemy.schema import Table
189
189
            from sqlalchemy import event
190
190
 
191
 
            def listen_for_reflect(table, column_info):
 
191
            def listen_for_reflect(inspector, table, column_info):
192
192
                "receive a column_reflect event"
193
193
                # ...
194
194
 
200
200
        ...or with a specific :class:`.Table` instance using
201
201
        the ``listeners`` argument::
202
202
 
203
 
            def listen_for_reflect(table, column_info):
 
203
            def listen_for_reflect(inspector, table, column_info):
204
204
                "receive a column_reflect event"
205
205
                # ...
206
206
 
216
216
 
217
217
        """
218
218
 
 
219
 
219
220
class SchemaEventTarget(object):
220
 
    """Base class for elements that are the targets of :class:`.DDLEvents` events.
 
221
    """Base class for elements that are the targets of :class:`.DDLEvents`
 
222
    events.
221
223
 
222
224
    This includes :class:`.SchemaItem` as well as :class:`.SchemaType`.
223
225
 
234
236
        self._set_parent(parent)
235
237
        self.dispatch.after_parent_attach(self, parent)
236
238
 
 
239
 
237
240
class PoolEvents(event.Events):
238
241
    """Available events for :class:`.Pool`.
239
242
 
250
253
 
251
254
        event.listen(Pool, 'checkout', my_on_checkout)
252
255
 
253
 
    In addition to accepting the :class:`.Pool` class and :class:`.Pool` instances,
254
 
    :class:`.PoolEvents` also accepts :class:`.Engine` objects and
255
 
    the :class:`.Engine` class as targets, which will be resolved
256
 
    to the ``.pool`` attribute of the given engine or the :class:`.Pool`
257
 
    class::
 
256
    In addition to accepting the :class:`.Pool` class and
 
257
    :class:`.Pool` instances, :class:`.PoolEvents` also accepts
 
258
    :class:`.Engine` objects and the :class:`.Engine` class as
 
259
    targets, which will be resolved to the ``.pool`` attribute of the
 
260
    given engine or the :class:`.Pool` class::
258
261
 
259
262
        engine = create_engine("postgresql://scott:tiger@localhost/test")
260
263
 
333
336
 
334
337
        """
335
338
 
 
339
    def reset(self, dbapi_con, con_record):
 
340
        """Called before the "reset" action occurs for a pooled connection.
 
341
 
 
342
        This event represents
 
343
        when the ``rollback()`` method is called on the DBAPI connection
 
344
        before it is returned to the pool.  The behavior of "reset" can
 
345
        be controlled, including disabled, using the ``reset_on_return``
 
346
        pool argument.
 
347
 
 
348
 
 
349
        The :meth:`.PoolEvents.reset` event is usually followed by the
 
350
        the :meth:`.PoolEvents.checkin` event is called, except in those
 
351
        cases where the connection is discarded immediately after reset.
 
352
 
 
353
        :param dbapi_con:
 
354
          A raw DB-API connection
 
355
 
 
356
        :param con_record:
 
357
          The ``_ConnectionRecord`` that persistently manages the connection
 
358
 
 
359
        .. versionadded:: 0.8
 
360
 
 
361
        .. seealso::
 
362
 
 
363
            :meth:`.ConnectionEvents.rollback`
 
364
 
 
365
            :meth:`.ConnectionEvents.commit`
 
366
 
 
367
        """
 
368
 
 
369
 
 
370
 
336
371
class ConnectionEvents(event.Events):
337
 
    """Available events for :class:`.Connection`.
338
 
 
339
 
    The methods here define the name of an event as well as the names of members that are passed to listener functions.
340
 
 
341
 
    e.g.::
 
372
    """Available events for :class:`.Connectable`, which includes
 
373
    :class:`.Connection` and :class:`.Engine`.
 
374
 
 
375
    The methods here define the name of an event as well as the names of
 
376
    members that are passed to listener functions.
 
377
 
 
378
    An event listener can be associated with any :class:`.Connectable`
 
379
    class or instance, such as an :class:`.Engine`, e.g.::
342
380
 
343
381
        from sqlalchemy import event, create_engine
344
382
 
345
 
        def before_execute(conn, clauseelement, multiparams, params):
346
 
            log.info("Received statement: %s" % clauseelement)
 
383
        def before_cursor_execute(conn, cursor, statement, parameters, context,
 
384
                                                        executemany):
 
385
            log.info("Received statement: %s" % statement)
347
386
 
348
387
        engine = create_engine('postgresql://scott:tiger@localhost/test')
349
 
        event.listen(engine, "before_execute", before_execute)
350
 
 
351
 
    Some events allow modifiers to the listen() function.
 
388
        event.listen(engine, "before_cursor_execute", before_cursor_execute)
 
389
 
 
390
    or with a specific :class:`.Connection`::
 
391
 
 
392
        with engine.begin() as conn:
 
393
            @event.listens_for(conn, 'before_cursor_execute')
 
394
            def before_cursor_execute(conn, cursor, statement, parameters,
 
395
                                            context, executemany):
 
396
                log.info("Received statement: %s" % statement)
 
397
 
 
398
    The :meth:`.before_execute` and :meth:`.before_cursor_execute`
 
399
    events can also be established with the ``retval=True`` flag, which
 
400
    allows modification of the statement and parameters to be sent
 
401
    to the database.  The :meth:`.before_cursor_execute` event is
 
402
    particularly useful here to add ad-hoc string transformations, such
 
403
    as comments, to all executions::
 
404
 
 
405
        from sqlalchemy.engine import Engine
 
406
        from sqlalchemy import event
 
407
 
 
408
        @event.listens_for(Engine, "before_cursor_execute", retval=True)
 
409
        def comment_sql_calls(conn, cursor, statement, parameters,
 
410
                                            context, executemany):
 
411
            statement = statement + " -- some comment"
 
412
            return statement, parameters
 
413
 
 
414
    .. note:: :class:`.ConnectionEvents` can be established on any
 
415
       combination of :class:`.Engine`, :class:`.Connection`, as well
 
416
       as instances of each of those classes.  Events across all
 
417
       four scopes will fire off for a given instance of
 
418
       :class:`.Connection`.  However, for performance reasons, the
 
419
       :class:`.Connection` object determines at instantiation time
 
420
       whether or not its parent :class:`.Engine` has event listeners
 
421
       established.   Event listeners added to the :class:`.Engine`
 
422
       class or to an instance of :class:`.Engine` *after* the instantiation
 
423
       of a dependent :class:`.Connection` instance will usually
 
424
       *not* be available on that :class:`.Connection` instance.  The newly
 
425
       added listeners will instead take effect for :class:`.Connection`
 
426
       instances created subsequent to those event listeners being
 
427
       established on the parent :class:`.Engine` class or instance.
352
428
 
353
429
    :param retval=False: Applies to the :meth:`.before_execute` and
354
430
      :meth:`.before_cursor_execute` events only.  When True, the
357
433
      and parameters.  See those methods for a description of
358
434
      specific return arguments.
359
435
 
 
436
    .. versionchanged:: 0.8 :class:`.ConnectionEvents` can now be associated
 
437
       with any :class:`.Connectable` including :class:`.Connection`,
 
438
       in addition to the existing support for :class:`.Engine`.
 
439
 
360
440
    """
361
441
 
362
442
    @classmethod
366
446
        if not retval:
367
447
            if identifier == 'before_execute':
368
448
                orig_fn = fn
369
 
                def wrap(conn, clauseelement, multiparams, params):
 
449
 
 
450
                def wrap_before_execute(conn, clauseelement,
 
451
                                                multiparams, params):
370
452
                    orig_fn(conn, clauseelement, multiparams, params)
371
453
                    return clauseelement, multiparams, params
372
 
                fn = wrap
 
454
                fn = wrap_before_execute
373
455
            elif identifier == 'before_cursor_execute':
374
456
                orig_fn = fn
375
 
                def wrap(conn, cursor, statement,
 
457
 
 
458
                def wrap_before_cursor_execute(conn, cursor, statement,
376
459
                        parameters, context, executemany):
377
460
                    orig_fn(conn, cursor, statement,
378
461
                        parameters, context, executemany)
379
462
                    return statement, parameters
380
 
                fn = wrap
 
463
                fn = wrap_before_cursor_execute
381
464
 
382
 
        elif retval and identifier not in ('before_execute', 'before_cursor_execute'):
 
465
        elif retval and \
 
466
            identifier not in ('before_execute', 'before_cursor_execute'):
383
467
            raise exc.ArgumentError(
384
468
                    "Only the 'before_execute' and "
385
469
                    "'before_cursor_execute' engine "
388
472
        event.Events._listen(target, identifier, fn)
389
473
 
390
474
    def before_execute(self, conn, clauseelement, multiparams, params):
391
 
        """Intercept high level execute() events."""
 
475
        """Intercept high level execute() events, receiving uncompiled
 
476
        SQL constructs and other objects prior to rendering into SQL.
 
477
 
 
478
        This event is good for debugging SQL compilation issues as well
 
479
        as early manipulation of the parameters being sent to the database,
 
480
        as the parameter lists will be in a consistent format here.
 
481
 
 
482
        This event can be optionally established with the ``retval=True``
 
483
        flag.  The ``clauseelement``, ``multiparams``, and ``params``
 
484
        arguments should be returned as a three-tuple in this case::
 
485
 
 
486
            @event.listens_for(Engine, "before_execute", retval=True)
 
487
            def before_execute(conn, conn, clauseelement, multiparams, params):
 
488
                # do something with clauseelement, multiparams, params
 
489
                return clauseelement, multiparams, params
 
490
 
 
491
        :param conn: :class:`.Connection` object
 
492
        :param clauseelement: SQL expression construct, :class:`.Compiled`
 
493
         instance, or string statement passed to :meth:`.Connection.execute`.
 
494
        :param multiparams: Multiple parameter sets, a list of dictionaries.
 
495
        :param params: Single parameter set, a single dictionary.
 
496
 
 
497
        See also:
 
498
 
 
499
        :meth:`.before_cursor_execute`
 
500
 
 
501
        """
392
502
 
393
503
    def after_execute(self, conn, clauseelement, multiparams, params, result):
394
 
        """Intercept high level execute() events."""
 
504
        """Intercept high level execute() events after execute.
 
505
 
 
506
 
 
507
        :param conn: :class:`.Connection` object
 
508
        :param clauseelement: SQL expression construct, :class:`.Compiled`
 
509
         instance, or string statement passed to :meth:`.Connection.execute`.
 
510
        :param multiparams: Multiple parameter sets, a list of dictionaries.
 
511
        :param params: Single parameter set, a single dictionary.
 
512
        :param result: :class:`.ResultProxy` generated by the execution.
 
513
 
 
514
        """
395
515
 
396
516
    def before_cursor_execute(self, conn, cursor, statement,
397
517
                        parameters, context, executemany):
398
 
        """Intercept low-level cursor execute() events."""
 
518
        """Intercept low-level cursor execute() events before execution,
 
519
        receiving the string
 
520
        SQL statement and DBAPI-specific parameter list to be invoked
 
521
        against a cursor.
 
522
 
 
523
        This event is a good choice for logging as well as late modifications
 
524
        to the SQL string.  It's less ideal for parameter modifications except
 
525
        for those which are specific to a target backend.
 
526
 
 
527
        This event can be optionally established with the ``retval=True``
 
528
        flag.  The ``statement`` and ``parameters`` arguments should be
 
529
        returned as a two-tuple in this case::
 
530
 
 
531
            @event.listens_for(Engine, "before_cursor_execute", retval=True)
 
532
            def before_cursor_execute(conn, cursor, statement,
 
533
                            parameters, context, executemany):
 
534
                # do something with statement, parameters
 
535
                return statement, parameters
 
536
 
 
537
        See the example at :class:`.ConnectionEvents`.
 
538
 
 
539
        :param conn: :class:`.Connection` object
 
540
        :param cursor: DBAPI cursor object
 
541
        :param statement: string SQL statement
 
542
        :param parameters: Dictionary, tuple, or list of parameters being
 
543
         passed to the ``execute()`` or ``executemany()`` method of the
 
544
         DBAPI ``cursor``.  In some cases may be ``None``.
 
545
        :param context: :class:`.ExecutionContext` object in use.  May
 
546
         be ``None``.
 
547
        :param executemany: boolean, if ``True``, this is an ``executemany()``
 
548
         call, if ``False``, this is an ``execute()`` call.
 
549
 
 
550
        See also:
 
551
 
 
552
        :meth:`.before_execute`
 
553
 
 
554
        :meth:`.after_cursor_execute`
 
555
 
 
556
        """
399
557
 
400
558
    def after_cursor_execute(self, conn, cursor, statement,
401
559
                        parameters, context, executemany):
402
 
        """Intercept low-level cursor execute() events."""
 
560
        """Intercept low-level cursor execute() events after execution.
 
561
 
 
562
        :param conn: :class:`.Connection` object
 
563
        :param cursor: DBAPI cursor object.  Will have results pending
 
564
         if the statement was a SELECT, but these should not be consumed
 
565
         as they will be needed by the :class:`.ResultProxy`.
 
566
        :param statement: string SQL statement
 
567
        :param parameters: Dictionary, tuple, or list of parameters being
 
568
         passed to the ``execute()`` or ``executemany()`` method of the
 
569
         DBAPI ``cursor``.  In some cases may be ``None``.
 
570
        :param context: :class:`.ExecutionContext` object in use.  May
 
571
         be ``None``.
 
572
        :param executemany: boolean, if ``True``, this is an ``executemany()``
 
573
         call, if ``False``, this is an ``execute()`` call.
 
574
 
 
575
        """
403
576
 
404
577
    def dbapi_error(self, conn, cursor, statement, parameters,
405
578
                        context, exception):
427
600
        exception is then wrapped in a SQLAlchemy DBAPI exception
428
601
        wrapper and re-thrown.
429
602
 
 
603
        :param conn: :class:`.Connection` object
 
604
        :param cursor: DBAPI cursor object
 
605
        :param statement: string SQL statement
 
606
        :param parameters: Dictionary, tuple, or list of parameters being
 
607
         passed to the ``execute()`` or ``executemany()`` method of the
 
608
         DBAPI ``cursor``.  In some cases may be ``None``.
 
609
        :param context: :class:`.ExecutionContext` object in use.  May
 
610
         be ``None``.
 
611
        :param exception: The **unwrapped** exception emitted directly from the
 
612
         DBAPI.  The class here is specific to the DBAPI module in use.
 
613
 
430
614
        .. versionadded:: 0.7.7
431
615
 
432
616
        """
433
617
 
434
618
    def begin(self, conn):
435
 
        """Intercept begin() events."""
 
619
        """Intercept begin() events.
 
620
 
 
621
        :param conn: :class:`.Connection` object
 
622
 
 
623
        """
436
624
 
437
625
    def rollback(self, conn):
438
 
        """Intercept rollback() events."""
 
626
        """Intercept rollback() events, as initiated by a
 
627
        :class:`.Transaction`.
 
628
 
 
629
        Note that the :class:`.Pool` also "auto-rolls back"
 
630
        a DBAPI connection upon checkin, if the ``reset_on_return``
 
631
        flag is set to its default value of ``'rollback'``.
 
632
        To intercept this
 
633
        rollback, use the :meth:`.PoolEvents.reset` hook.
 
634
 
 
635
        :param conn: :class:`.Connection` object
 
636
 
 
637
        .. seealso::
 
638
 
 
639
            :meth:`.PoolEvents.reset`
 
640
 
 
641
        """
439
642
 
440
643
    def commit(self, conn):
441
 
        """Intercept commit() events."""
 
644
        """Intercept commit() events, as initiated by a
 
645
        :class:`.Transaction`.
 
646
 
 
647
        Note that the :class:`.Pool` may also "auto-commit"
 
648
        a DBAPI connection upon checkin, if the ``reset_on_return``
 
649
        flag is set to the value ``'commit'``.  To intercept this
 
650
        commit, use the :meth:`.PoolEvents.reset` hook.
 
651
 
 
652
        :param conn: :class:`.Connection` object
 
653
        """
442
654
 
443
655
    def savepoint(self, conn, name=None):
444
 
        """Intercept savepoint() events."""
 
656
        """Intercept savepoint() events.
 
657
 
 
658
        :param conn: :class:`.Connection` object
 
659
        :param name: specified name used for the savepoint.
 
660
 
 
661
        """
445
662
 
446
663
    def rollback_savepoint(self, conn, name, context):
447
 
        """Intercept rollback_savepoint() events."""
 
664
        """Intercept rollback_savepoint() events.
 
665
 
 
666
        :param conn: :class:`.Connection` object
 
667
        :param name: specified name used for the savepoint.
 
668
        :param context: :class:`.ExecutionContext` in use.  May be ``None``.
 
669
 
 
670
        """
448
671
 
449
672
    def release_savepoint(self, conn, name, context):
450
 
        """Intercept release_savepoint() events."""
 
673
        """Intercept release_savepoint() events.
 
674
 
 
675
        :param conn: :class:`.Connection` object
 
676
        :param name: specified name used for the savepoint.
 
677
        :param context: :class:`.ExecutionContext` in use.  May be ``None``.
 
678
 
 
679
        """
451
680
 
452
681
    def begin_twophase(self, conn, xid):
453
 
        """Intercept begin_twophase() events."""
 
682
        """Intercept begin_twophase() events.
 
683
 
 
684
        :param conn: :class:`.Connection` object
 
685
        :param xid: two-phase XID identifier
 
686
 
 
687
        """
454
688
 
455
689
    def prepare_twophase(self, conn, xid):
456
 
        """Intercept prepare_twophase() events."""
 
690
        """Intercept prepare_twophase() events.
 
691
 
 
692
        :param conn: :class:`.Connection` object
 
693
        :param xid: two-phase XID identifier
 
694
        """
457
695
 
458
696
    def rollback_twophase(self, conn, xid, is_prepared):
459
 
        """Intercept rollback_twophase() events."""
 
697
        """Intercept rollback_twophase() events.
 
698
 
 
699
        :param conn: :class:`.Connection` object
 
700
        :param xid: two-phase XID identifier
 
701
        :param is_prepared: boolean, indicates if
 
702
         :meth:`.TwoPhaseTransaction.prepare` was called.
 
703
 
 
704
        """
460
705
 
461
706
    def commit_twophase(self, conn, xid, is_prepared):
462
 
        """Intercept commit_twophase() events."""
463
 
 
 
707
        """Intercept commit_twophase() events.
 
708
 
 
709
        :param conn: :class:`.Connection` object
 
710
        :param xid: two-phase XID identifier
 
711
        :param is_prepared: boolean, indicates if
 
712
         :meth:`.TwoPhaseTransaction.prepare` was called.
 
713
 
 
714
        """