events.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  1. # sqlalchemy/events.py
  2. # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  7. """Core event interfaces."""
  8. from . import event, exc
  9. from .pool import Pool
  10. from .engine import Connectable, Engine, Dialect
  11. from .sql.base import SchemaEventTarget
  12. class DDLEvents(event.Events):
  13. """
  14. Define event listeners for schema objects,
  15. that is, :class:`.SchemaItem` and other :class:`.SchemaEventTarget`
  16. subclasses, including :class:`.MetaData`, :class:`.Table`,
  17. :class:`.Column`.
  18. :class:`.MetaData` and :class:`.Table` support events
  19. specifically regarding when CREATE and DROP
  20. DDL is emitted to the database.
  21. Attachment events are also provided to customize
  22. behavior whenever a child schema element is associated
  23. with a parent, such as, when a :class:`.Column` is associated
  24. with its :class:`.Table`, when a :class:`.ForeignKeyConstraint`
  25. is associated with a :class:`.Table`, etc.
  26. Example using the ``after_create`` event::
  27. from sqlalchemy import event
  28. from sqlalchemy import Table, Column, Metadata, Integer
  29. m = MetaData()
  30. some_table = Table('some_table', m, Column('data', Integer))
  31. def after_create(target, connection, **kw):
  32. connection.execute("ALTER TABLE %s SET name=foo_%s" %
  33. (target.name, target.name))
  34. event.listen(some_table, "after_create", after_create)
  35. DDL events integrate closely with the
  36. :class:`.DDL` class and the :class:`.DDLElement` hierarchy
  37. of DDL clause constructs, which are themselves appropriate
  38. as listener callables::
  39. from sqlalchemy import DDL
  40. event.listen(
  41. some_table,
  42. "after_create",
  43. DDL("ALTER TABLE %(table)s SET name=foo_%(table)s")
  44. )
  45. The methods here define the name of an event as well
  46. as the names of members that are passed to listener
  47. functions.
  48. See also:
  49. :ref:`event_toplevel`
  50. :class:`.DDLElement`
  51. :class:`.DDL`
  52. :ref:`schema_ddl_sequences`
  53. """
  54. _target_class_doc = "SomeSchemaClassOrObject"
  55. _dispatch_target = SchemaEventTarget
  56. def before_create(self, target, connection, **kw):
  57. r"""Called before CREATE statements are emitted.
  58. :param target: the :class:`.MetaData` or :class:`.Table`
  59. object which is the target of the event.
  60. :param connection: the :class:`.Connection` where the
  61. CREATE statement or statements will be emitted.
  62. :param \**kw: additional keyword arguments relevant
  63. to the event. The contents of this dictionary
  64. may vary across releases, and include the
  65. list of tables being generated for a metadata-level
  66. event, the checkfirst flag, and other
  67. elements used by internal events.
  68. """
  69. def after_create(self, target, connection, **kw):
  70. r"""Called after CREATE statements are emitted.
  71. :param target: the :class:`.MetaData` or :class:`.Table`
  72. object which is the target of the event.
  73. :param connection: the :class:`.Connection` where the
  74. CREATE statement or statements have been emitted.
  75. :param \**kw: additional keyword arguments relevant
  76. to the event. The contents of this dictionary
  77. may vary across releases, and include the
  78. list of tables being generated for a metadata-level
  79. event, the checkfirst flag, and other
  80. elements used by internal events.
  81. """
  82. def before_drop(self, target, connection, **kw):
  83. r"""Called before DROP statements are emitted.
  84. :param target: the :class:`.MetaData` or :class:`.Table`
  85. object which is the target of the event.
  86. :param connection: the :class:`.Connection` where the
  87. DROP statement or statements will be emitted.
  88. :param \**kw: additional keyword arguments relevant
  89. to the event. The contents of this dictionary
  90. may vary across releases, and include the
  91. list of tables being generated for a metadata-level
  92. event, the checkfirst flag, and other
  93. elements used by internal events.
  94. """
  95. def after_drop(self, target, connection, **kw):
  96. r"""Called after DROP statements are emitted.
  97. :param target: the :class:`.MetaData` or :class:`.Table`
  98. object which is the target of the event.
  99. :param connection: the :class:`.Connection` where the
  100. DROP statement or statements have been emitted.
  101. :param \**kw: additional keyword arguments relevant
  102. to the event. The contents of this dictionary
  103. may vary across releases, and include the
  104. list of tables being generated for a metadata-level
  105. event, the checkfirst flag, and other
  106. elements used by internal events.
  107. """
  108. def before_parent_attach(self, target, parent):
  109. """Called before a :class:`.SchemaItem` is associated with
  110. a parent :class:`.SchemaItem`.
  111. :param target: the target object
  112. :param parent: the parent to which the target is being attached.
  113. :func:`.event.listen` also accepts a modifier for this event:
  114. :param propagate=False: When True, the listener function will
  115. be established for any copies made of the target object,
  116. i.e. those copies that are generated when
  117. :meth:`.Table.tometadata` is used.
  118. """
  119. def after_parent_attach(self, target, parent):
  120. """Called after a :class:`.SchemaItem` is associated with
  121. a parent :class:`.SchemaItem`.
  122. :param target: the target object
  123. :param parent: the parent to which the target is being attached.
  124. :func:`.event.listen` also accepts a modifier for this event:
  125. :param propagate=False: When True, the listener function will
  126. be established for any copies made of the target object,
  127. i.e. those copies that are generated when
  128. :meth:`.Table.tometadata` is used.
  129. """
  130. def column_reflect(self, inspector, table, column_info):
  131. """Called for each unit of 'column info' retrieved when
  132. a :class:`.Table` is being reflected.
  133. The dictionary of column information as returned by the
  134. dialect is passed, and can be modified. The dictionary
  135. is that returned in each element of the list returned
  136. by :meth:`.reflection.Inspector.get_columns`:
  137. * ``name`` - the column's name
  138. * ``type`` - the type of this column, which should be an instance
  139. of :class:`~sqlalchemy.types.TypeEngine`
  140. * ``nullable`` - boolean flag if the column is NULL or NOT NULL
  141. * ``default`` - the column's server default value. This is
  142. normally specified as a plain string SQL expression, however the
  143. event can pass a :class:`.FetchedValue`, :class:`.DefaultClause`,
  144. or :func:`.sql.expression.text` object as well.
  145. .. versionchanged:: 1.1.6
  146. The :meth:`.DDLEvents.column_reflect` event allows a non
  147. string :class:`.FetchedValue`,
  148. :func:`.sql.expression.text`, or derived object to be
  149. specified as the value of ``default`` in the column
  150. dictionary.
  151. * ``attrs`` - dict containing optional column attributes
  152. The event is called before any action is taken against
  153. this dictionary, and the contents can be modified.
  154. The :class:`.Column` specific arguments ``info``, ``key``,
  155. and ``quote`` can also be added to the dictionary and
  156. will be passed to the constructor of :class:`.Column`.
  157. Note that this event is only meaningful if either
  158. associated with the :class:`.Table` class across the
  159. board, e.g.::
  160. from sqlalchemy.schema import Table
  161. from sqlalchemy import event
  162. def listen_for_reflect(inspector, table, column_info):
  163. "receive a column_reflect event"
  164. # ...
  165. event.listen(
  166. Table,
  167. 'column_reflect',
  168. listen_for_reflect)
  169. ...or with a specific :class:`.Table` instance using
  170. the ``listeners`` argument::
  171. def listen_for_reflect(inspector, table, column_info):
  172. "receive a column_reflect event"
  173. # ...
  174. t = Table(
  175. 'sometable',
  176. autoload=True,
  177. listeners=[
  178. ('column_reflect', listen_for_reflect)
  179. ])
  180. This because the reflection process initiated by ``autoload=True``
  181. completes within the scope of the constructor for :class:`.Table`.
  182. """
  183. class PoolEvents(event.Events):
  184. """Available events for :class:`.Pool`.
  185. The methods here define the name of an event as well
  186. as the names of members that are passed to listener
  187. functions.
  188. e.g.::
  189. from sqlalchemy import event
  190. def my_on_checkout(dbapi_conn, connection_rec, connection_proxy):
  191. "handle an on checkout event"
  192. event.listen(Pool, 'checkout', my_on_checkout)
  193. In addition to accepting the :class:`.Pool` class and
  194. :class:`.Pool` instances, :class:`.PoolEvents` also accepts
  195. :class:`.Engine` objects and the :class:`.Engine` class as
  196. targets, which will be resolved to the ``.pool`` attribute of the
  197. given engine or the :class:`.Pool` class::
  198. engine = create_engine("postgresql://scott:tiger@localhost/test")
  199. # will associate with engine.pool
  200. event.listen(engine, 'checkout', my_on_checkout)
  201. """
  202. _target_class_doc = "SomeEngineOrPool"
  203. _dispatch_target = Pool
  204. @classmethod
  205. def _accept_with(cls, target):
  206. if isinstance(target, type):
  207. if issubclass(target, Engine):
  208. return Pool
  209. elif issubclass(target, Pool):
  210. return target
  211. elif isinstance(target, Engine):
  212. return target.pool
  213. else:
  214. return target
  215. def connect(self, dbapi_connection, connection_record):
  216. """Called at the moment a particular DBAPI connection is first
  217. created for a given :class:`.Pool`.
  218. This event allows one to capture the point directly after which
  219. the DBAPI module-level ``.connect()`` method has been used in order
  220. to produce a new DBAPI connection.
  221. :param dbapi_connection: a DBAPI connection.
  222. :param connection_record: the :class:`._ConnectionRecord` managing the
  223. DBAPI connection.
  224. """
  225. def first_connect(self, dbapi_connection, connection_record):
  226. """Called exactly once for the first time a DBAPI connection is
  227. checked out from a particular :class:`.Pool`.
  228. The rationale for :meth:`.PoolEvents.first_connect` is to determine
  229. information about a particular series of database connections based
  230. on the settings used for all connections. Since a particular
  231. :class:`.Pool` refers to a single "creator" function (which in terms
  232. of a :class:`.Engine` refers to the URL and connection options used),
  233. it is typically valid to make observations about a single connection
  234. that can be safely assumed to be valid about all subsequent
  235. connections, such as the database version, the server and client
  236. encoding settings, collation settings, and many others.
  237. :param dbapi_connection: a DBAPI connection.
  238. :param connection_record: the :class:`._ConnectionRecord` managing the
  239. DBAPI connection.
  240. """
  241. def checkout(self, dbapi_connection, connection_record, connection_proxy):
  242. """Called when a connection is retrieved from the Pool.
  243. :param dbapi_connection: a DBAPI connection.
  244. :param connection_record: the :class:`._ConnectionRecord` managing the
  245. DBAPI connection.
  246. :param connection_proxy: the :class:`._ConnectionFairy` object which
  247. will proxy the public interface of the DBAPI connection for the
  248. lifespan of the checkout.
  249. If you raise a :class:`~sqlalchemy.exc.DisconnectionError`, the current
  250. connection will be disposed and a fresh connection retrieved.
  251. Processing of all checkout listeners will abort and restart
  252. using the new connection.
  253. .. seealso:: :meth:`.ConnectionEvents.engine_connect` - a similar event
  254. which occurs upon creation of a new :class:`.Connection`.
  255. """
  256. def checkin(self, dbapi_connection, connection_record):
  257. """Called when a connection returns to the pool.
  258. Note that the connection may be closed, and may be None if the
  259. connection has been invalidated. ``checkin`` will not be called
  260. for detached connections. (They do not return to the pool.)
  261. :param dbapi_connection: a DBAPI connection.
  262. :param connection_record: the :class:`._ConnectionRecord` managing the
  263. DBAPI connection.
  264. """
  265. def reset(self, dbapi_connection, connection_record):
  266. """Called before the "reset" action occurs for a pooled connection.
  267. This event represents
  268. when the ``rollback()`` method is called on the DBAPI connection
  269. before it is returned to the pool. The behavior of "reset" can
  270. be controlled, including disabled, using the ``reset_on_return``
  271. pool argument.
  272. The :meth:`.PoolEvents.reset` event is usually followed by the
  273. :meth:`.PoolEvents.checkin` event is called, except in those
  274. cases where the connection is discarded immediately after reset.
  275. :param dbapi_connection: a DBAPI connection.
  276. :param connection_record: the :class:`._ConnectionRecord` managing the
  277. DBAPI connection.
  278. .. versionadded:: 0.8
  279. .. seealso::
  280. :meth:`.ConnectionEvents.rollback`
  281. :meth:`.ConnectionEvents.commit`
  282. """
  283. def invalidate(self, dbapi_connection, connection_record, exception):
  284. """Called when a DBAPI connection is to be "invalidated".
  285. This event is called any time the :meth:`._ConnectionRecord.invalidate`
  286. method is invoked, either from API usage or via "auto-invalidation",
  287. without the ``soft`` flag.
  288. The event occurs before a final attempt to call ``.close()`` on the
  289. connection occurs.
  290. :param dbapi_connection: a DBAPI connection.
  291. :param connection_record: the :class:`._ConnectionRecord` managing the
  292. DBAPI connection.
  293. :param exception: the exception object corresponding to the reason
  294. for this invalidation, if any. May be ``None``.
  295. .. versionadded:: 0.9.2 Added support for connection invalidation
  296. listening.
  297. .. seealso::
  298. :ref:`pool_connection_invalidation`
  299. """
  300. def soft_invalidate(self, dbapi_connection, connection_record, exception):
  301. """Called when a DBAPI connection is to be "soft invalidated".
  302. This event is called any time the :meth:`._ConnectionRecord.invalidate`
  303. method is invoked with the ``soft`` flag.
  304. Soft invalidation refers to when the connection record that tracks
  305. this connection will force a reconnect after the current connection
  306. is checked in. It does not actively close the dbapi_connection
  307. at the point at which it is called.
  308. .. versionadded:: 1.0.3
  309. """
  310. def close(self, dbapi_connection, connection_record):
  311. """Called when a DBAPI connection is closed.
  312. The event is emitted before the close occurs.
  313. The close of a connection can fail; typically this is because
  314. the connection is already closed. If the close operation fails,
  315. the connection is discarded.
  316. The :meth:`.close` event corresponds to a connection that's still
  317. associated with the pool. To intercept close events for detached
  318. connections use :meth:`.close_detached`.
  319. .. versionadded:: 1.1
  320. """
  321. def detach(self, dbapi_connection, connection_record):
  322. """Called when a DBAPI connection is "detached" from a pool.
  323. This event is emitted after the detach occurs. The connection
  324. is no longer associated with the given connection record.
  325. .. versionadded:: 1.1
  326. """
  327. def close_detached(self, dbapi_connection):
  328. """Called when a detached DBAPI connection is closed.
  329. The event is emitted before the close occurs.
  330. The close of a connection can fail; typically this is because
  331. the connection is already closed. If the close operation fails,
  332. the connection is discarded.
  333. .. versionadded:: 1.1
  334. """
  335. class ConnectionEvents(event.Events):
  336. """Available events for :class:`.Connectable`, which includes
  337. :class:`.Connection` and :class:`.Engine`.
  338. The methods here define the name of an event as well as the names of
  339. members that are passed to listener functions.
  340. An event listener can be associated with any :class:`.Connectable`
  341. class or instance, such as an :class:`.Engine`, e.g.::
  342. from sqlalchemy import event, create_engine
  343. def before_cursor_execute(conn, cursor, statement, parameters, context,
  344. executemany):
  345. log.info("Received statement: %s", statement)
  346. engine = create_engine('postgresql://scott:tiger@localhost/test')
  347. event.listen(engine, "before_cursor_execute", before_cursor_execute)
  348. or with a specific :class:`.Connection`::
  349. with engine.begin() as conn:
  350. @event.listens_for(conn, 'before_cursor_execute')
  351. def before_cursor_execute(conn, cursor, statement, parameters,
  352. context, executemany):
  353. log.info("Received statement: %s", statement)
  354. When the methods are called with a `statement` parameter, such as in
  355. :meth:`.after_cursor_execute`, :meth:`.before_cursor_execute` and
  356. :meth:`.dbapi_error`, the statement is the exact SQL string that was
  357. prepared for transmission to the DBAPI ``cursor`` in the connection's
  358. :class:`.Dialect`.
  359. The :meth:`.before_execute` and :meth:`.before_cursor_execute`
  360. events can also be established with the ``retval=True`` flag, which
  361. allows modification of the statement and parameters to be sent
  362. to the database. The :meth:`.before_cursor_execute` event is
  363. particularly useful here to add ad-hoc string transformations, such
  364. as comments, to all executions::
  365. from sqlalchemy.engine import Engine
  366. from sqlalchemy import event
  367. @event.listens_for(Engine, "before_cursor_execute", retval=True)
  368. def comment_sql_calls(conn, cursor, statement, parameters,
  369. context, executemany):
  370. statement = statement + " -- some comment"
  371. return statement, parameters
  372. .. note:: :class:`.ConnectionEvents` can be established on any
  373. combination of :class:`.Engine`, :class:`.Connection`, as well
  374. as instances of each of those classes. Events across all
  375. four scopes will fire off for a given instance of
  376. :class:`.Connection`. However, for performance reasons, the
  377. :class:`.Connection` object determines at instantiation time
  378. whether or not its parent :class:`.Engine` has event listeners
  379. established. Event listeners added to the :class:`.Engine`
  380. class or to an instance of :class:`.Engine` *after* the instantiation
  381. of a dependent :class:`.Connection` instance will usually
  382. *not* be available on that :class:`.Connection` instance. The newly
  383. added listeners will instead take effect for :class:`.Connection`
  384. instances created subsequent to those event listeners being
  385. established on the parent :class:`.Engine` class or instance.
  386. :param retval=False: Applies to the :meth:`.before_execute` and
  387. :meth:`.before_cursor_execute` events only. When True, the
  388. user-defined event function must have a return value, which
  389. is a tuple of parameters that replace the given statement
  390. and parameters. See those methods for a description of
  391. specific return arguments.
  392. .. versionchanged:: 0.8 :class:`.ConnectionEvents` can now be associated
  393. with any :class:`.Connectable` including :class:`.Connection`,
  394. in addition to the existing support for :class:`.Engine`.
  395. """
  396. _target_class_doc = "SomeEngine"
  397. _dispatch_target = Connectable
  398. @classmethod
  399. def _listen(cls, event_key, retval=False):
  400. target, identifier, fn = \
  401. event_key.dispatch_target, event_key.identifier, \
  402. event_key._listen_fn
  403. target._has_events = True
  404. if not retval:
  405. if identifier == 'before_execute':
  406. orig_fn = fn
  407. def wrap_before_execute(conn, clauseelement,
  408. multiparams, params):
  409. orig_fn(conn, clauseelement, multiparams, params)
  410. return clauseelement, multiparams, params
  411. fn = wrap_before_execute
  412. elif identifier == 'before_cursor_execute':
  413. orig_fn = fn
  414. def wrap_before_cursor_execute(conn, cursor, statement,
  415. parameters, context,
  416. executemany):
  417. orig_fn(conn, cursor, statement,
  418. parameters, context, executemany)
  419. return statement, parameters
  420. fn = wrap_before_cursor_execute
  421. elif retval and \
  422. identifier not in ('before_execute',
  423. 'before_cursor_execute', 'handle_error'):
  424. raise exc.ArgumentError(
  425. "Only the 'before_execute', "
  426. "'before_cursor_execute' and 'handle_error' engine "
  427. "event listeners accept the 'retval=True' "
  428. "argument.")
  429. event_key.with_wrapper(fn).base_listen()
  430. def before_execute(self, conn, clauseelement, multiparams, params):
  431. """Intercept high level execute() events, receiving uncompiled
  432. SQL constructs and other objects prior to rendering into SQL.
  433. This event is good for debugging SQL compilation issues as well
  434. as early manipulation of the parameters being sent to the database,
  435. as the parameter lists will be in a consistent format here.
  436. This event can be optionally established with the ``retval=True``
  437. flag. The ``clauseelement``, ``multiparams``, and ``params``
  438. arguments should be returned as a three-tuple in this case::
  439. @event.listens_for(Engine, "before_execute", retval=True)
  440. def before_execute(conn, conn, clauseelement, multiparams, params):
  441. # do something with clauseelement, multiparams, params
  442. return clauseelement, multiparams, params
  443. :param conn: :class:`.Connection` object
  444. :param clauseelement: SQL expression construct, :class:`.Compiled`
  445. instance, or string statement passed to :meth:`.Connection.execute`.
  446. :param multiparams: Multiple parameter sets, a list of dictionaries.
  447. :param params: Single parameter set, a single dictionary.
  448. See also:
  449. :meth:`.before_cursor_execute`
  450. """
  451. def after_execute(self, conn, clauseelement, multiparams, params, result):
  452. """Intercept high level execute() events after execute.
  453. :param conn: :class:`.Connection` object
  454. :param clauseelement: SQL expression construct, :class:`.Compiled`
  455. instance, or string statement passed to :meth:`.Connection.execute`.
  456. :param multiparams: Multiple parameter sets, a list of dictionaries.
  457. :param params: Single parameter set, a single dictionary.
  458. :param result: :class:`.ResultProxy` generated by the execution.
  459. """
  460. def before_cursor_execute(self, conn, cursor, statement,
  461. parameters, context, executemany):
  462. """Intercept low-level cursor execute() events before execution,
  463. receiving the string SQL statement and DBAPI-specific parameter list to
  464. be invoked against a cursor.
  465. This event is a good choice for logging as well as late modifications
  466. to the SQL string. It's less ideal for parameter modifications except
  467. for those which are specific to a target backend.
  468. This event can be optionally established with the ``retval=True``
  469. flag. The ``statement`` and ``parameters`` arguments should be
  470. returned as a two-tuple in this case::
  471. @event.listens_for(Engine, "before_cursor_execute", retval=True)
  472. def before_cursor_execute(conn, cursor, statement,
  473. parameters, context, executemany):
  474. # do something with statement, parameters
  475. return statement, parameters
  476. See the example at :class:`.ConnectionEvents`.
  477. :param conn: :class:`.Connection` object
  478. :param cursor: DBAPI cursor object
  479. :param statement: string SQL statement, as to be passed to the DBAPI
  480. :param parameters: Dictionary, tuple, or list of parameters being
  481. passed to the ``execute()`` or ``executemany()`` method of the
  482. DBAPI ``cursor``. In some cases may be ``None``.
  483. :param context: :class:`.ExecutionContext` object in use. May
  484. be ``None``.
  485. :param executemany: boolean, if ``True``, this is an ``executemany()``
  486. call, if ``False``, this is an ``execute()`` call.
  487. See also:
  488. :meth:`.before_execute`
  489. :meth:`.after_cursor_execute`
  490. """
  491. def after_cursor_execute(self, conn, cursor, statement,
  492. parameters, context, executemany):
  493. """Intercept low-level cursor execute() events after execution.
  494. :param conn: :class:`.Connection` object
  495. :param cursor: DBAPI cursor object. Will have results pending
  496. if the statement was a SELECT, but these should not be consumed
  497. as they will be needed by the :class:`.ResultProxy`.
  498. :param statement: string SQL statement, as passed to the DBAPI
  499. :param parameters: Dictionary, tuple, or list of parameters being
  500. passed to the ``execute()`` or ``executemany()`` method of the
  501. DBAPI ``cursor``. In some cases may be ``None``.
  502. :param context: :class:`.ExecutionContext` object in use. May
  503. be ``None``.
  504. :param executemany: boolean, if ``True``, this is an ``executemany()``
  505. call, if ``False``, this is an ``execute()`` call.
  506. """
  507. def dbapi_error(self, conn, cursor, statement, parameters,
  508. context, exception):
  509. """Intercept a raw DBAPI error.
  510. This event is called with the DBAPI exception instance
  511. received from the DBAPI itself, *before* SQLAlchemy wraps the
  512. exception with it's own exception wrappers, and before any
  513. other operations are performed on the DBAPI cursor; the
  514. existing transaction remains in effect as well as any state
  515. on the cursor.
  516. The use case here is to inject low-level exception handling
  517. into an :class:`.Engine`, typically for logging and
  518. debugging purposes.
  519. .. warning::
  520. Code should **not** modify
  521. any state or throw any exceptions here as this will
  522. interfere with SQLAlchemy's cleanup and error handling
  523. routines. For exception modification, please refer to the
  524. new :meth:`.ConnectionEvents.handle_error` event.
  525. Subsequent to this hook, SQLAlchemy may attempt any
  526. number of operations on the connection/cursor, including
  527. closing the cursor, rolling back of the transaction in the
  528. case of connectionless execution, and disposing of the entire
  529. connection pool if a "disconnect" was detected. The
  530. exception is then wrapped in a SQLAlchemy DBAPI exception
  531. wrapper and re-thrown.
  532. :param conn: :class:`.Connection` object
  533. :param cursor: DBAPI cursor object
  534. :param statement: string SQL statement, as passed to the DBAPI
  535. :param parameters: Dictionary, tuple, or list of parameters being
  536. passed to the ``execute()`` or ``executemany()`` method of the
  537. DBAPI ``cursor``. In some cases may be ``None``.
  538. :param context: :class:`.ExecutionContext` object in use. May
  539. be ``None``.
  540. :param exception: The **unwrapped** exception emitted directly from the
  541. DBAPI. The class here is specific to the DBAPI module in use.
  542. .. deprecated:: 0.9.7 - replaced by
  543. :meth:`.ConnectionEvents.handle_error`
  544. """
  545. def handle_error(self, exception_context):
  546. r"""Intercept all exceptions processed by the :class:`.Connection`.
  547. This includes all exceptions emitted by the DBAPI as well as
  548. within SQLAlchemy's statement invocation process, including
  549. encoding errors and other statement validation errors. Other areas
  550. in which the event is invoked include transaction begin and end,
  551. result row fetching, cursor creation.
  552. Note that :meth:`.handle_error` may support new kinds of exceptions
  553. and new calling scenarios at *any time*. Code which uses this
  554. event must expect new calling patterns to be present in minor
  555. releases.
  556. To support the wide variety of members that correspond to an exception,
  557. as well as to allow extensibility of the event without backwards
  558. incompatibility, the sole argument received is an instance of
  559. :class:`.ExceptionContext`. This object contains data members
  560. representing detail about the exception.
  561. Use cases supported by this hook include:
  562. * read-only, low-level exception handling for logging and
  563. debugging purposes
  564. * exception re-writing
  565. * Establishing or disabling whether a connection or the owning
  566. connection pool is invalidated or expired in response to a
  567. specific exception.
  568. The hook is called while the cursor from the failed operation
  569. (if any) is still open and accessible. Special cleanup operations
  570. can be called on this cursor; SQLAlchemy will attempt to close
  571. this cursor subsequent to this hook being invoked. If the connection
  572. is in "autocommit" mode, the transaction also remains open within
  573. the scope of this hook; the rollback of the per-statement transaction
  574. also occurs after the hook is called.
  575. The user-defined event handler has two options for replacing
  576. the SQLAlchemy-constructed exception into one that is user
  577. defined. It can either raise this new exception directly, in
  578. which case all further event listeners are bypassed and the
  579. exception will be raised, after appropriate cleanup as taken
  580. place::
  581. @event.listens_for(Engine, "handle_error")
  582. def handle_exception(context):
  583. if isinstance(context.original_exception,
  584. psycopg2.OperationalError) and \
  585. "failed" in str(context.original_exception):
  586. raise MySpecialException("failed operation")
  587. .. warning:: Because the :meth:`.ConnectionEvents.handle_error`
  588. event specifically provides for exceptions to be re-thrown as
  589. the ultimate exception raised by the failed statement,
  590. **stack traces will be misleading** if the user-defined event
  591. handler itself fails and throws an unexpected exception;
  592. the stack trace may not illustrate the actual code line that
  593. failed! It is advised to code carefully here and use
  594. logging and/or inline debugging if unexpected exceptions are
  595. occurring.
  596. Alternatively, a "chained" style of event handling can be
  597. used, by configuring the handler with the ``retval=True``
  598. modifier and returning the new exception instance from the
  599. function. In this case, event handling will continue onto the
  600. next handler. The "chained" exception is available using
  601. :attr:`.ExceptionContext.chained_exception`::
  602. @event.listens_for(Engine, "handle_error", retval=True)
  603. def handle_exception(context):
  604. if context.chained_exception is not None and \
  605. "special" in context.chained_exception.message:
  606. return MySpecialException("failed",
  607. cause=context.chained_exception)
  608. Handlers that return ``None`` may remain within this chain; the
  609. last non-``None`` return value is the one that continues to be
  610. passed to the next handler.
  611. When a custom exception is raised or returned, SQLAlchemy raises
  612. this new exception as-is, it is not wrapped by any SQLAlchemy
  613. object. If the exception is not a subclass of
  614. :class:`sqlalchemy.exc.StatementError`,
  615. certain features may not be available; currently this includes
  616. the ORM's feature of adding a detail hint about "autoflush" to
  617. exceptions raised within the autoflush process.
  618. :param context: an :class:`.ExceptionContext` object. See this
  619. class for details on all available members.
  620. .. versionadded:: 0.9.7 Added the
  621. :meth:`.ConnectionEvents.handle_error` hook.
  622. .. versionchanged:: 1.1 The :meth:`.handle_error` event will now
  623. receive all exceptions that inherit from ``BaseException``, including
  624. ``SystemExit`` and ``KeyboardInterrupt``. The setting for
  625. :attr:`.ExceptionContext.is_disconnect` is ``True`` in this case
  626. and the default for :attr:`.ExceptionContext.invalidate_pool_on_disconnect`
  627. is ``False``.
  628. .. versionchanged:: 1.0.0 The :meth:`.handle_error` event is now
  629. invoked when an :class:`.Engine` fails during the initial
  630. call to :meth:`.Engine.connect`, as well as when a
  631. :class:`.Connection` object encounters an error during a
  632. reconnect operation.
  633. .. versionchanged:: 1.0.0 The :meth:`.handle_error` event is
  634. not fired off when a dialect makes use of the
  635. ``skip_user_error_events`` execution option. This is used
  636. by dialects which intend to catch SQLAlchemy-specific exceptions
  637. within specific operations, such as when the MySQL dialect detects
  638. a table not present within the ``has_table()`` dialect method.
  639. Prior to 1.0.0, code which implements :meth:`.handle_error` needs
  640. to ensure that exceptions thrown in these scenarios are re-raised
  641. without modification.
  642. """
  643. def engine_connect(self, conn, branch):
  644. """Intercept the creation of a new :class:`.Connection`.
  645. This event is called typically as the direct result of calling
  646. the :meth:`.Engine.connect` method.
  647. It differs from the :meth:`.PoolEvents.connect` method, which
  648. refers to the actual connection to a database at the DBAPI level;
  649. a DBAPI connection may be pooled and reused for many operations.
  650. In contrast, this event refers only to the production of a higher level
  651. :class:`.Connection` wrapper around such a DBAPI connection.
  652. It also differs from the :meth:`.PoolEvents.checkout` event
  653. in that it is specific to the :class:`.Connection` object, not the
  654. DBAPI connection that :meth:`.PoolEvents.checkout` deals with, although
  655. this DBAPI connection is available here via the
  656. :attr:`.Connection.connection` attribute. But note there can in fact
  657. be multiple :meth:`.PoolEvents.checkout` events within the lifespan
  658. of a single :class:`.Connection` object, if that :class:`.Connection`
  659. is invalidated and re-established. There can also be multiple
  660. :class:`.Connection` objects generated for the same already-checked-out
  661. DBAPI connection, in the case that a "branch" of a :class:`.Connection`
  662. is produced.
  663. :param conn: :class:`.Connection` object.
  664. :param branch: if True, this is a "branch" of an existing
  665. :class:`.Connection`. A branch is generated within the course
  666. of a statement execution to invoke supplemental statements, most
  667. typically to pre-execute a SELECT of a default value for the purposes
  668. of an INSERT statement.
  669. .. versionadded:: 0.9.0
  670. .. seealso::
  671. :ref:`pool_disconnects_pessimistic` - illustrates how to use
  672. :meth:`.ConnectionEvents.engine_connect`
  673. to transparently ensure pooled connections are connected to the
  674. database.
  675. :meth:`.PoolEvents.checkout` the lower-level pool checkout event
  676. for an individual DBAPI connection
  677. :meth:`.ConnectionEvents.set_connection_execution_options` - a copy
  678. of a :class:`.Connection` is also made when the
  679. :meth:`.Connection.execution_options` method is called.
  680. """
  681. def set_connection_execution_options(self, conn, opts):
  682. """Intercept when the :meth:`.Connection.execution_options`
  683. method is called.
  684. This method is called after the new :class:`.Connection` has been
  685. produced, with the newly updated execution options collection, but
  686. before the :class:`.Dialect` has acted upon any of those new options.
  687. Note that this method is not called when a new :class:`.Connection`
  688. is produced which is inheriting execution options from its parent
  689. :class:`.Engine`; to intercept this condition, use the
  690. :meth:`.ConnectionEvents.engine_connect` event.
  691. :param conn: The newly copied :class:`.Connection` object
  692. :param opts: dictionary of options that were passed to the
  693. :meth:`.Connection.execution_options` method.
  694. .. versionadded:: 0.9.0
  695. .. seealso::
  696. :meth:`.ConnectionEvents.set_engine_execution_options` - event
  697. which is called when :meth:`.Engine.execution_options` is called.
  698. """
  699. def set_engine_execution_options(self, engine, opts):
  700. """Intercept when the :meth:`.Engine.execution_options`
  701. method is called.
  702. The :meth:`.Engine.execution_options` method produces a shallow
  703. copy of the :class:`.Engine` which stores the new options. That new
  704. :class:`.Engine` is passed here. A particular application of this
  705. method is to add a :meth:`.ConnectionEvents.engine_connect` event
  706. handler to the given :class:`.Engine` which will perform some per-
  707. :class:`.Connection` task specific to these execution options.
  708. :param conn: The newly copied :class:`.Engine` object
  709. :param opts: dictionary of options that were passed to the
  710. :meth:`.Connection.execution_options` method.
  711. .. versionadded:: 0.9.0
  712. .. seealso::
  713. :meth:`.ConnectionEvents.set_connection_execution_options` - event
  714. which is called when :meth:`.Connection.execution_options` is
  715. called.
  716. """
  717. def engine_disposed(self, engine):
  718. """Intercept when the :meth:`.Engine.dispose` method is called.
  719. The :meth:`.Engine.dispose` method instructs the engine to
  720. "dispose" of it's connection pool (e.g. :class:`.Pool`), and
  721. replaces it with a new one. Disposing of the old pool has the
  722. effect that existing checked-in connections are closed. The new
  723. pool does not establish any new connections until it is first used.
  724. This event can be used to indicate that resources related to the
  725. :class:`.Engine` should also be cleaned up, keeping in mind that the
  726. :class:`.Engine` can still be used for new requests in which case
  727. it re-acquires connection resources.
  728. .. versionadded:: 1.0.5
  729. """
  730. def begin(self, conn):
  731. """Intercept begin() events.
  732. :param conn: :class:`.Connection` object
  733. """
  734. def rollback(self, conn):
  735. """Intercept rollback() events, as initiated by a
  736. :class:`.Transaction`.
  737. Note that the :class:`.Pool` also "auto-rolls back"
  738. a DBAPI connection upon checkin, if the ``reset_on_return``
  739. flag is set to its default value of ``'rollback'``.
  740. To intercept this
  741. rollback, use the :meth:`.PoolEvents.reset` hook.
  742. :param conn: :class:`.Connection` object
  743. .. seealso::
  744. :meth:`.PoolEvents.reset`
  745. """
  746. def commit(self, conn):
  747. """Intercept commit() events, as initiated by a
  748. :class:`.Transaction`.
  749. Note that the :class:`.Pool` may also "auto-commit"
  750. a DBAPI connection upon checkin, if the ``reset_on_return``
  751. flag is set to the value ``'commit'``. To intercept this
  752. commit, use the :meth:`.PoolEvents.reset` hook.
  753. :param conn: :class:`.Connection` object
  754. """
  755. def savepoint(self, conn, name):
  756. """Intercept savepoint() events.
  757. :param conn: :class:`.Connection` object
  758. :param name: specified name used for the savepoint.
  759. """
  760. def rollback_savepoint(self, conn, name, context):
  761. """Intercept rollback_savepoint() events.
  762. :param conn: :class:`.Connection` object
  763. :param name: specified name used for the savepoint.
  764. :param context: :class:`.ExecutionContext` in use. May be ``None``.
  765. """
  766. def release_savepoint(self, conn, name, context):
  767. """Intercept release_savepoint() events.
  768. :param conn: :class:`.Connection` object
  769. :param name: specified name used for the savepoint.
  770. :param context: :class:`.ExecutionContext` in use. May be ``None``.
  771. """
  772. def begin_twophase(self, conn, xid):
  773. """Intercept begin_twophase() events.
  774. :param conn: :class:`.Connection` object
  775. :param xid: two-phase XID identifier
  776. """
  777. def prepare_twophase(self, conn, xid):
  778. """Intercept prepare_twophase() events.
  779. :param conn: :class:`.Connection` object
  780. :param xid: two-phase XID identifier
  781. """
  782. def rollback_twophase(self, conn, xid, is_prepared):
  783. """Intercept rollback_twophase() events.
  784. :param conn: :class:`.Connection` object
  785. :param xid: two-phase XID identifier
  786. :param is_prepared: boolean, indicates if
  787. :meth:`.TwoPhaseTransaction.prepare` was called.
  788. """
  789. def commit_twophase(self, conn, xid, is_prepared):
  790. """Intercept commit_twophase() events.
  791. :param conn: :class:`.Connection` object
  792. :param xid: two-phase XID identifier
  793. :param is_prepared: boolean, indicates if
  794. :meth:`.TwoPhaseTransaction.prepare` was called.
  795. """
  796. class DialectEvents(event.Events):
  797. """event interface for execution-replacement functions.
  798. These events allow direct instrumentation and replacement
  799. of key dialect functions which interact with the DBAPI.
  800. .. note::
  801. :class:`.DialectEvents` hooks should be considered **semi-public**
  802. and experimental.
  803. These hooks are not for general use and are only for those situations
  804. where intricate re-statement of DBAPI mechanics must be injected onto
  805. an existing dialect. For general-use statement-interception events,
  806. please use the :class:`.ConnectionEvents` interface.
  807. .. seealso::
  808. :meth:`.ConnectionEvents.before_cursor_execute`
  809. :meth:`.ConnectionEvents.before_execute`
  810. :meth:`.ConnectionEvents.after_cursor_execute`
  811. :meth:`.ConnectionEvents.after_execute`
  812. .. versionadded:: 0.9.4
  813. """
  814. _target_class_doc = "SomeEngine"
  815. _dispatch_target = Dialect
  816. @classmethod
  817. def _listen(cls, event_key, retval=False):
  818. target, identifier, fn = \
  819. event_key.dispatch_target, event_key.identifier, event_key.fn
  820. target._has_events = True
  821. event_key.base_listen()
  822. @classmethod
  823. def _accept_with(cls, target):
  824. if isinstance(target, type):
  825. if issubclass(target, Engine):
  826. return Dialect
  827. elif issubclass(target, Dialect):
  828. return target
  829. elif isinstance(target, Engine):
  830. return target.dialect
  831. else:
  832. return target
  833. def do_connect(self, dialect, conn_rec, cargs, cparams):
  834. """Receive connection arguments before a connection is made.
  835. Return a DBAPI connection to halt further events from invoking;
  836. the returned connection will be used.
  837. Alternatively, the event can manipulate the cargs and/or cparams
  838. collections; cargs will always be a Python list that can be mutated
  839. in-place and cparams a Python dictionary. Return None to
  840. allow control to pass to the next event handler and ultimately
  841. to allow the dialect to connect normally, given the updated
  842. arguments.
  843. .. versionadded:: 1.0.3
  844. """
  845. def do_executemany(self, cursor, statement, parameters, context):
  846. """Receive a cursor to have executemany() called.
  847. Return the value True to halt further events from invoking,
  848. and to indicate that the cursor execution has already taken
  849. place within the event handler.
  850. """
  851. def do_execute_no_params(self, cursor, statement, context):
  852. """Receive a cursor to have execute() with no parameters called.
  853. Return the value True to halt further events from invoking,
  854. and to indicate that the cursor execution has already taken
  855. place within the event handler.
  856. """
  857. def do_execute(self, cursor, statement, parameters, context):
  858. """Receive a cursor to have execute() called.
  859. Return the value True to halt further events from invoking,
  860. and to indicate that the cursor execution has already taken
  861. place within the event handler.
  862. """