You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

327 lines
13KB

  1. # sqlalchemy/sql/events.py
  2. # Copyright (C) 2005-2021 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. from .base import SchemaEventTarget
  8. from .. import event
  9. class DDLEvents(event.Events):
  10. """
  11. Define event listeners for schema objects,
  12. that is, :class:`.SchemaItem` and other :class:`.SchemaEventTarget`
  13. subclasses, including :class:`_schema.MetaData`, :class:`_schema.Table`,
  14. :class:`_schema.Column`.
  15. :class:`_schema.MetaData` and :class:`_schema.Table` support events
  16. specifically regarding when CREATE and DROP
  17. DDL is emitted to the database.
  18. Attachment events are also provided to customize
  19. behavior whenever a child schema element is associated
  20. with a parent, such as, when a :class:`_schema.Column` is associated
  21. with its :class:`_schema.Table`, when a
  22. :class:`_schema.ForeignKeyConstraint`
  23. is associated with a :class:`_schema.Table`, etc.
  24. Example using the ``after_create`` event::
  25. from sqlalchemy import event
  26. from sqlalchemy import Table, Column, Metadata, Integer
  27. m = MetaData()
  28. some_table = Table('some_table', m, Column('data', Integer))
  29. def after_create(target, connection, **kw):
  30. connection.execute(text(
  31. "ALTER TABLE %s SET name=foo_%s" % (target.name, target.name)
  32. ))
  33. event.listen(some_table, "after_create", after_create)
  34. DDL events integrate closely with the
  35. :class:`.DDL` class and the :class:`.DDLElement` hierarchy
  36. of DDL clause constructs, which are themselves appropriate
  37. as listener callables::
  38. from sqlalchemy import DDL
  39. event.listen(
  40. some_table,
  41. "after_create",
  42. DDL("ALTER TABLE %(table)s SET name=foo_%(table)s")
  43. )
  44. The methods here define the name of an event as well
  45. as the names of members that are passed to listener
  46. functions.
  47. For all :class:`.DDLEvent` events, the ``propagate=True`` keyword argument
  48. will ensure that a given event handler is propagated to copies of the
  49. object, which are made when using the :meth:`_schema.Table.to_metadata`
  50. method::
  51. from sqlalchemy import DDL
  52. event.listen(
  53. some_table,
  54. "after_create",
  55. DDL("ALTER TABLE %(table)s SET name=foo_%(table)s"),
  56. propagate=True
  57. )
  58. new_table = some_table.to_metadata(new_metadata)
  59. The above :class:`.DDL` object will also be associated with the
  60. :class:`_schema.Table` object represented by ``new_table``.
  61. .. seealso::
  62. :ref:`event_toplevel`
  63. :class:`.DDLElement`
  64. :class:`.DDL`
  65. :ref:`schema_ddl_sequences`
  66. """
  67. _target_class_doc = "SomeSchemaClassOrObject"
  68. _dispatch_target = SchemaEventTarget
  69. def before_create(self, target, connection, **kw):
  70. r"""Called before CREATE statements are emitted.
  71. :param target: the :class:`_schema.MetaData` or :class:`_schema.Table`
  72. object which is the target of the event.
  73. :param connection: the :class:`_engine.Connection` where the
  74. CREATE statement or statements will be 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. :func:`.event.listen` also accepts the ``propagate=True``
  82. modifier for this event; when True, the listener function will
  83. be established for any copies made of the target object,
  84. i.e. those copies that are generated when
  85. :meth:`_schema.Table.to_metadata` is used.
  86. """
  87. def after_create(self, target, connection, **kw):
  88. r"""Called after CREATE statements are emitted.
  89. :param target: the :class:`_schema.MetaData` or :class:`_schema.Table`
  90. object which is the target of the event.
  91. :param connection: the :class:`_engine.Connection` where the
  92. CREATE statement or statements have been emitted.
  93. :param \**kw: additional keyword arguments relevant
  94. to the event. The contents of this dictionary
  95. may vary across releases, and include the
  96. list of tables being generated for a metadata-level
  97. event, the checkfirst flag, and other
  98. elements used by internal events.
  99. :func:`.event.listen` also accepts the ``propagate=True``
  100. modifier for this event; when True, the listener function will
  101. be established for any copies made of the target object,
  102. i.e. those copies that are generated when
  103. :meth:`_schema.Table.to_metadata` is used.
  104. """
  105. def before_drop(self, target, connection, **kw):
  106. r"""Called before DROP statements are emitted.
  107. :param target: the :class:`_schema.MetaData` or :class:`_schema.Table`
  108. object which is the target of the event.
  109. :param connection: the :class:`_engine.Connection` where the
  110. DROP statement or statements will be emitted.
  111. :param \**kw: additional keyword arguments relevant
  112. to the event. The contents of this dictionary
  113. may vary across releases, and include the
  114. list of tables being generated for a metadata-level
  115. event, the checkfirst flag, and other
  116. elements used by internal events.
  117. :func:`.event.listen` also accepts the ``propagate=True``
  118. modifier for this event; when True, the listener function will
  119. be established for any copies made of the target object,
  120. i.e. those copies that are generated when
  121. :meth:`_schema.Table.to_metadata` is used.
  122. """
  123. def after_drop(self, target, connection, **kw):
  124. r"""Called after DROP statements are emitted.
  125. :param target: the :class:`_schema.MetaData` or :class:`_schema.Table`
  126. object which is the target of the event.
  127. :param connection: the :class:`_engine.Connection` where the
  128. DROP statement or statements have been emitted.
  129. :param \**kw: additional keyword arguments relevant
  130. to the event. The contents of this dictionary
  131. may vary across releases, and include the
  132. list of tables being generated for a metadata-level
  133. event, the checkfirst flag, and other
  134. elements used by internal events.
  135. :func:`.event.listen` also accepts the ``propagate=True``
  136. modifier for this event; when True, the listener function will
  137. be established for any copies made of the target object,
  138. i.e. those copies that are generated when
  139. :meth:`_schema.Table.to_metadata` is used.
  140. """
  141. def before_parent_attach(self, target, parent):
  142. """Called before a :class:`.SchemaItem` is associated with
  143. a parent :class:`.SchemaItem`.
  144. :param target: the target object
  145. :param parent: the parent to which the target is being attached.
  146. :func:`.event.listen` also accepts the ``propagate=True``
  147. modifier for this event; when True, the listener function will
  148. be established for any copies made of the target object,
  149. i.e. those copies that are generated when
  150. :meth:`_schema.Table.to_metadata` is used.
  151. """
  152. def after_parent_attach(self, target, parent):
  153. """Called after a :class:`.SchemaItem` is associated with
  154. a parent :class:`.SchemaItem`.
  155. :param target: the target object
  156. :param parent: the parent to which the target is being attached.
  157. :func:`.event.listen` also accepts the ``propagate=True``
  158. modifier for this event; when True, the listener function will
  159. be established for any copies made of the target object,
  160. i.e. those copies that are generated when
  161. :meth:`_schema.Table.to_metadata` is used.
  162. """
  163. def _sa_event_column_added_to_pk_constraint(self, const, col):
  164. """internal event hook used for primary key naming convention
  165. updates.
  166. """
  167. def column_reflect(self, inspector, table, column_info):
  168. """Called for each unit of 'column info' retrieved when
  169. a :class:`_schema.Table` is being reflected.
  170. This event is most easily used by applying it to a specific
  171. :class:`_schema.MetaData` instance, where it will take effect for
  172. all :class:`_schema.Table` objects within that
  173. :class:`_schema.MetaData` that undergo reflection::
  174. metadata = MetaData()
  175. @event.listens_for(metadata, 'column_reflect')
  176. def receive_column_reflect(inspector, table, column_info):
  177. # receives for all Table objects that are reflected
  178. # under this MetaData
  179. # will use the above event hook
  180. my_table = Table("my_table", metadata, autoload_with=some_engine)
  181. .. versionadded:: 1.4.0b2 The :meth:`_events.DDLEvents.column_reflect`
  182. hook may now be applied to a :class:`_schema.MetaData` object as
  183. well as the :class:`_schema.MetaData` class itself where it will
  184. take place for all :class:`_schema.Table` objects associated with
  185. the targeted :class:`_schema.MetaData`.
  186. It may also be applied to the :class:`_schema.Table` class across
  187. the board::
  188. from sqlalchemy import Table
  189. @event.listens_for(Table, 'column_reflect')
  190. def receive_column_reflect(inspector, table, column_info):
  191. # receives for all Table objects that are reflected
  192. It can also be applied to a specific :class:`_schema.Table` at the
  193. point that one is being reflected using the
  194. :paramref:`_schema.Table.listeners` parameter::
  195. t1 = Table(
  196. "my_table",
  197. autoload_with=some_engine,
  198. listeners=[
  199. ('column_reflect', receive_column_reflect)
  200. ]
  201. )
  202. A future release will allow it to be associated with a specific
  203. :class:`_schema.MetaData` object as well.
  204. The dictionary of column information as returned by the
  205. dialect is passed, and can be modified. The dictionary
  206. is that returned in each element of the list returned
  207. by :meth:`.reflection.Inspector.get_columns`:
  208. * ``name`` - the column's name, is applied to the
  209. :paramref:`_schema.Column.name` parameter
  210. * ``type`` - the type of this column, which should be an instance
  211. of :class:`~sqlalchemy.types.TypeEngine`, is applied to the
  212. :paramref:`_schema.Column.type` parameter
  213. * ``nullable`` - boolean flag if the column is NULL or NOT NULL,
  214. is applied to the :paramref:`_schema.Column.nullable` parameter
  215. * ``default`` - the column's server default value. This is
  216. normally specified as a plain string SQL expression, however the
  217. event can pass a :class:`.FetchedValue`, :class:`.DefaultClause`,
  218. or :func:`_expression.text` object as well. Is applied to the
  219. :paramref:`_schema.Column.server_default` parameter
  220. The event is called before any action is taken against
  221. this dictionary, and the contents can be modified; the following
  222. additional keys may be added to the dictionary to further modify
  223. how the :class:`_schema.Column` is constructed:
  224. * ``key`` - the string key that will be used to access this
  225. :class:`_schema.Column` in the ``.c`` collection; will be applied
  226. to the :paramref:`_schema.Column.key` parameter. Is also used
  227. for ORM mapping. See the section
  228. :ref:`mapper_automated_reflection_schemes` for an example.
  229. * ``quote`` - force or un-force quoting on the column name;
  230. is applied to the :paramref:`_schema.Column.quote` parameter.
  231. * ``info`` - a dictionary of arbitrary data to follow along with
  232. the :class:`_schema.Column`, is applied to the
  233. :paramref:`_schema.Column.info` parameter.
  234. :func:`.event.listen` also accepts the ``propagate=True``
  235. modifier for this event; when True, the listener function will
  236. be established for any copies made of the target object,
  237. i.e. those copies that are generated when
  238. :meth:`_schema.Table.to_metadata` is used.
  239. .. seealso::
  240. :ref:`mapper_automated_reflection_schemes` -
  241. in the ORM mapping documentation
  242. :ref:`automap_intercepting_columns` -
  243. in the :ref:`automap_toplevel` documentation
  244. :ref:`metadata_reflection_dbagnostic_types` - in
  245. the :ref:`metadata_reflection_toplevel` documentation
  246. """