context.pyi 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. # ### this file stubs are generated by tools/write_pyi.py - do not edit ###
  2. # ### imports are manually managed
  3. from __future__ import annotations
  4. from typing import Any
  5. from typing import Callable
  6. from typing import Collection
  7. from typing import Dict
  8. from typing import Iterable
  9. from typing import List
  10. from typing import Literal
  11. from typing import Mapping
  12. from typing import MutableMapping
  13. from typing import Optional
  14. from typing import overload
  15. from typing import Sequence
  16. from typing import TextIO
  17. from typing import Tuple
  18. from typing import TYPE_CHECKING
  19. from typing import Union
  20. from typing_extensions import ContextManager
  21. if TYPE_CHECKING:
  22. from sqlalchemy.engine.base import Connection
  23. from sqlalchemy.engine.url import URL
  24. from sqlalchemy.sql import Executable
  25. from sqlalchemy.sql.schema import Column
  26. from sqlalchemy.sql.schema import FetchedValue
  27. from sqlalchemy.sql.schema import MetaData
  28. from sqlalchemy.sql.schema import SchemaItem
  29. from sqlalchemy.sql.type_api import TypeEngine
  30. from .autogenerate.api import AutogenContext
  31. from .config import Config
  32. from .operations.ops import MigrationScript
  33. from .runtime.migration import _ProxyTransaction
  34. from .runtime.migration import MigrationContext
  35. from .runtime.migration import MigrationInfo
  36. from .script import ScriptDirectory
  37. ### end imports ###
  38. def begin_transaction() -> (
  39. Union[_ProxyTransaction, ContextManager[None, Optional[bool]]]
  40. ):
  41. """Return a context manager that will
  42. enclose an operation within a "transaction",
  43. as defined by the environment's offline
  44. and transactional DDL settings.
  45. e.g.::
  46. with context.begin_transaction():
  47. context.run_migrations()
  48. :meth:`.begin_transaction` is intended to
  49. "do the right thing" regardless of
  50. calling context:
  51. * If :meth:`.is_transactional_ddl` is ``False``,
  52. returns a "do nothing" context manager
  53. which otherwise produces no transactional
  54. state or directives.
  55. * If :meth:`.is_offline_mode` is ``True``,
  56. returns a context manager that will
  57. invoke the :meth:`.DefaultImpl.emit_begin`
  58. and :meth:`.DefaultImpl.emit_commit`
  59. methods, which will produce the string
  60. directives ``BEGIN`` and ``COMMIT`` on
  61. the output stream, as rendered by the
  62. target backend (e.g. SQL Server would
  63. emit ``BEGIN TRANSACTION``).
  64. * Otherwise, calls :meth:`sqlalchemy.engine.Connection.begin`
  65. on the current online connection, which
  66. returns a :class:`sqlalchemy.engine.Transaction`
  67. object. This object demarcates a real
  68. transaction and is itself a context manager,
  69. which will roll back if an exception
  70. is raised.
  71. Note that a custom ``env.py`` script which
  72. has more specific transactional needs can of course
  73. manipulate the :class:`~sqlalchemy.engine.Connection`
  74. directly to produce transactional state in "online"
  75. mode.
  76. """
  77. config: Config
  78. def configure(
  79. connection: Optional[Connection] = None,
  80. url: Union[str, URL, None] = None,
  81. dialect_name: Optional[str] = None,
  82. dialect_opts: Optional[Dict[str, Any]] = None,
  83. transactional_ddl: Optional[bool] = None,
  84. transaction_per_migration: bool = False,
  85. output_buffer: Optional[TextIO] = None,
  86. starting_rev: Optional[str] = None,
  87. tag: Optional[str] = None,
  88. template_args: Optional[Dict[str, Any]] = None,
  89. render_as_batch: bool = False,
  90. target_metadata: Union[MetaData, Sequence[MetaData], None] = None,
  91. include_name: Optional[
  92. Callable[
  93. [
  94. Optional[str],
  95. Literal[
  96. "schema",
  97. "table",
  98. "column",
  99. "index",
  100. "unique_constraint",
  101. "foreign_key_constraint",
  102. ],
  103. MutableMapping[
  104. Literal[
  105. "schema_name",
  106. "table_name",
  107. "schema_qualified_table_name",
  108. ],
  109. Optional[str],
  110. ],
  111. ],
  112. bool,
  113. ]
  114. ] = None,
  115. include_object: Optional[
  116. Callable[
  117. [
  118. SchemaItem,
  119. Optional[str],
  120. Literal[
  121. "schema",
  122. "table",
  123. "column",
  124. "index",
  125. "unique_constraint",
  126. "foreign_key_constraint",
  127. ],
  128. bool,
  129. Optional[SchemaItem],
  130. ],
  131. bool,
  132. ]
  133. ] = None,
  134. include_schemas: bool = False,
  135. process_revision_directives: Optional[
  136. Callable[
  137. [
  138. MigrationContext,
  139. Union[str, Iterable[Optional[str]], Iterable[str]],
  140. List[MigrationScript],
  141. ],
  142. None,
  143. ]
  144. ] = None,
  145. compare_type: Union[
  146. bool,
  147. Callable[
  148. [
  149. MigrationContext,
  150. Column[Any],
  151. Column[Any],
  152. TypeEngine[Any],
  153. TypeEngine[Any],
  154. ],
  155. Optional[bool],
  156. ],
  157. ] = True,
  158. compare_server_default: Union[
  159. bool,
  160. Callable[
  161. [
  162. MigrationContext,
  163. Column[Any],
  164. Column[Any],
  165. Optional[str],
  166. Optional[FetchedValue],
  167. Optional[str],
  168. ],
  169. Optional[bool],
  170. ],
  171. ] = False,
  172. render_item: Optional[
  173. Callable[[str, Any, AutogenContext], Union[str, Literal[False]]]
  174. ] = None,
  175. literal_binds: bool = False,
  176. upgrade_token: str = "upgrades",
  177. downgrade_token: str = "downgrades",
  178. alembic_module_prefix: str = "op.",
  179. sqlalchemy_module_prefix: str = "sa.",
  180. user_module_prefix: Optional[str] = None,
  181. on_version_apply: Optional[
  182. Callable[
  183. [
  184. MigrationContext,
  185. MigrationInfo,
  186. Collection[Any],
  187. Mapping[str, Any],
  188. ],
  189. None,
  190. ]
  191. ] = None,
  192. **kw: Any,
  193. ) -> None:
  194. """Configure a :class:`.MigrationContext` within this
  195. :class:`.EnvironmentContext` which will provide database
  196. connectivity and other configuration to a series of
  197. migration scripts.
  198. Many methods on :class:`.EnvironmentContext` require that
  199. this method has been called in order to function, as they
  200. ultimately need to have database access or at least access
  201. to the dialect in use. Those which do are documented as such.
  202. The important thing needed by :meth:`.configure` is a
  203. means to determine what kind of database dialect is in use.
  204. An actual connection to that database is needed only if
  205. the :class:`.MigrationContext` is to be used in
  206. "online" mode.
  207. If the :meth:`.is_offline_mode` function returns ``True``,
  208. then no connection is needed here. Otherwise, the
  209. ``connection`` parameter should be present as an
  210. instance of :class:`sqlalchemy.engine.Connection`.
  211. This function is typically called from the ``env.py``
  212. script within a migration environment. It can be called
  213. multiple times for an invocation. The most recent
  214. :class:`~sqlalchemy.engine.Connection`
  215. for which it was called is the one that will be operated upon
  216. by the next call to :meth:`.run_migrations`.
  217. General parameters:
  218. :param connection: a :class:`~sqlalchemy.engine.Connection`
  219. to use
  220. for SQL execution in "online" mode. When present, is also
  221. used to determine the type of dialect in use.
  222. :param url: a string database url, or a
  223. :class:`sqlalchemy.engine.url.URL` object.
  224. The type of dialect to be used will be derived from this if
  225. ``connection`` is not passed.
  226. :param dialect_name: string name of a dialect, such as
  227. "postgresql", "mssql", etc.
  228. The type of dialect to be used will be derived from this if
  229. ``connection`` and ``url`` are not passed.
  230. :param dialect_opts: dictionary of options to be passed to dialect
  231. constructor.
  232. :param transactional_ddl: Force the usage of "transactional"
  233. DDL on or off;
  234. this otherwise defaults to whether or not the dialect in
  235. use supports it.
  236. :param transaction_per_migration: if True, nest each migration script
  237. in a transaction rather than the full series of migrations to
  238. run.
  239. :param output_buffer: a file-like object that will be used
  240. for textual output
  241. when the ``--sql`` option is used to generate SQL scripts.
  242. Defaults to
  243. ``sys.stdout`` if not passed here and also not present on
  244. the :class:`.Config`
  245. object. The value here overrides that of the :class:`.Config`
  246. object.
  247. :param output_encoding: when using ``--sql`` to generate SQL
  248. scripts, apply this encoding to the string output.
  249. :param literal_binds: when using ``--sql`` to generate SQL
  250. scripts, pass through the ``literal_binds`` flag to the compiler
  251. so that any literal values that would ordinarily be bound
  252. parameters are converted to plain strings.
  253. .. warning:: Dialects can typically only handle simple datatypes
  254. like strings and numbers for auto-literal generation. Datatypes
  255. like dates, intervals, and others may still require manual
  256. formatting, typically using :meth:`.Operations.inline_literal`.
  257. .. note:: the ``literal_binds`` flag is ignored on SQLAlchemy
  258. versions prior to 0.8 where this feature is not supported.
  259. .. seealso::
  260. :meth:`.Operations.inline_literal`
  261. :param starting_rev: Override the "starting revision" argument
  262. when using ``--sql`` mode.
  263. :param tag: a string tag for usage by custom ``env.py`` scripts.
  264. Set via the ``--tag`` option, can be overridden here.
  265. :param template_args: dictionary of template arguments which
  266. will be added to the template argument environment when
  267. running the "revision" command. Note that the script environment
  268. is only run within the "revision" command if the --autogenerate
  269. option is used, or if the option "revision_environment=true"
  270. is present in the alembic.ini file.
  271. :param version_table: The name of the Alembic version table.
  272. The default is ``'alembic_version'``.
  273. :param version_table_schema: Optional schema to place version
  274. table within.
  275. :param version_table_pk: boolean, whether the Alembic version table
  276. should use a primary key constraint for the "value" column; this
  277. only takes effect when the table is first created.
  278. Defaults to True; setting to False should not be necessary and is
  279. here for backwards compatibility reasons.
  280. :param on_version_apply: a callable or collection of callables to be
  281. run for each migration step.
  282. The callables will be run in the order they are given, once for
  283. each migration step, after the respective operation has been
  284. applied but before its transaction is finalized.
  285. Each callable accepts no positional arguments and the following
  286. keyword arguments:
  287. * ``ctx``: the :class:`.MigrationContext` running the migration,
  288. * ``step``: a :class:`.MigrationInfo` representing the
  289. step currently being applied,
  290. * ``heads``: a collection of version strings representing the
  291. current heads,
  292. * ``run_args``: the ``**kwargs`` passed to :meth:`.run_migrations`.
  293. Parameters specific to the autogenerate feature, when
  294. ``alembic revision`` is run with the ``--autogenerate`` feature:
  295. :param target_metadata: a :class:`sqlalchemy.schema.MetaData`
  296. object, or a sequence of :class:`~sqlalchemy.schema.MetaData`
  297. objects, that will be consulted during autogeneration.
  298. The tables present in each :class:`~sqlalchemy.schema.MetaData`
  299. will be compared against
  300. what is locally available on the target
  301. :class:`~sqlalchemy.engine.Connection`
  302. to produce candidate upgrade/downgrade operations.
  303. :param compare_type: Indicates type comparison behavior during
  304. an autogenerate
  305. operation. Defaults to ``True`` turning on type comparison, which
  306. has good accuracy on most backends. See :ref:`compare_types`
  307. for an example as well as information on other type
  308. comparison options. Set to ``False`` which disables type
  309. comparison. A callable can also be passed to provide custom type
  310. comparison, see :ref:`compare_types` for additional details.
  311. .. versionchanged:: 1.12.0 The default value of
  312. :paramref:`.EnvironmentContext.configure.compare_type` has been
  313. changed to ``True``.
  314. .. seealso::
  315. :ref:`compare_types`
  316. :paramref:`.EnvironmentContext.configure.compare_server_default`
  317. :param compare_server_default: Indicates server default comparison
  318. behavior during
  319. an autogenerate operation. Defaults to ``False`` which disables
  320. server default
  321. comparison. Set to ``True`` to turn on server default comparison,
  322. which has
  323. varied accuracy depending on backend.
  324. To customize server default comparison behavior, a callable may
  325. be specified
  326. which can filter server default comparisons during an
  327. autogenerate operation.
  328. defaults during an autogenerate operation. The format of this
  329. callable is::
  330. def my_compare_server_default(context, inspected_column,
  331. metadata_column, inspected_default, metadata_default,
  332. rendered_metadata_default):
  333. # return True if the defaults are different,
  334. # False if not, or None to allow the default implementation
  335. # to compare these defaults
  336. return None
  337. context.configure(
  338. # ...
  339. compare_server_default = my_compare_server_default
  340. )
  341. ``inspected_column`` is a dictionary structure as returned by
  342. :meth:`sqlalchemy.engine.reflection.Inspector.get_columns`, whereas
  343. ``metadata_column`` is a :class:`sqlalchemy.schema.Column` from
  344. the local model environment.
  345. A return value of ``None`` indicates to allow default server default
  346. comparison
  347. to proceed. Note that some backends such as Postgresql actually
  348. execute
  349. the two defaults on the database side to compare for equivalence.
  350. .. seealso::
  351. :paramref:`.EnvironmentContext.configure.compare_type`
  352. :param include_name: A callable function which is given
  353. the chance to return ``True`` or ``False`` for any database reflected
  354. object based on its name, including database schema names when
  355. the :paramref:`.EnvironmentContext.configure.include_schemas` flag
  356. is set to ``True``.
  357. The function accepts the following positional arguments:
  358. * ``name``: the name of the object, such as schema name or table name.
  359. Will be ``None`` when indicating the default schema name of the
  360. database connection.
  361. * ``type``: a string describing the type of object; currently
  362. ``"schema"``, ``"table"``, ``"column"``, ``"index"``,
  363. ``"unique_constraint"``, or ``"foreign_key_constraint"``
  364. * ``parent_names``: a dictionary of "parent" object names, that are
  365. relative to the name being given. Keys in this dictionary may
  366. include: ``"schema_name"``, ``"table_name"`` or
  367. ``"schema_qualified_table_name"``.
  368. E.g.::
  369. def include_name(name, type_, parent_names):
  370. if type_ == "schema":
  371. return name in ["schema_one", "schema_two"]
  372. else:
  373. return True
  374. context.configure(
  375. # ...
  376. include_schemas = True,
  377. include_name = include_name
  378. )
  379. .. seealso::
  380. :ref:`autogenerate_include_hooks`
  381. :paramref:`.EnvironmentContext.configure.include_object`
  382. :paramref:`.EnvironmentContext.configure.include_schemas`
  383. :param include_object: A callable function which is given
  384. the chance to return ``True`` or ``False`` for any object,
  385. indicating if the given object should be considered in the
  386. autogenerate sweep.
  387. The function accepts the following positional arguments:
  388. * ``object``: a :class:`~sqlalchemy.schema.SchemaItem` object such
  389. as a :class:`~sqlalchemy.schema.Table`,
  390. :class:`~sqlalchemy.schema.Column`,
  391. :class:`~sqlalchemy.schema.Index`
  392. :class:`~sqlalchemy.schema.UniqueConstraint`,
  393. or :class:`~sqlalchemy.schema.ForeignKeyConstraint` object
  394. * ``name``: the name of the object. This is typically available
  395. via ``object.name``.
  396. * ``type``: a string describing the type of object; currently
  397. ``"table"``, ``"column"``, ``"index"``, ``"unique_constraint"``,
  398. or ``"foreign_key_constraint"``
  399. * ``reflected``: ``True`` if the given object was produced based on
  400. table reflection, ``False`` if it's from a local :class:`.MetaData`
  401. object.
  402. * ``compare_to``: the object being compared against, if available,
  403. else ``None``.
  404. E.g.::
  405. def include_object(object, name, type_, reflected, compare_to):
  406. if (type_ == "column" and
  407. not reflected and
  408. object.info.get("skip_autogenerate", False)):
  409. return False
  410. else:
  411. return True
  412. context.configure(
  413. # ...
  414. include_object = include_object
  415. )
  416. For the use case of omitting specific schemas from a target database
  417. when :paramref:`.EnvironmentContext.configure.include_schemas` is
  418. set to ``True``, the :attr:`~sqlalchemy.schema.Table.schema`
  419. attribute can be checked for each :class:`~sqlalchemy.schema.Table`
  420. object passed to the hook, however it is much more efficient
  421. to filter on schemas before reflection of objects takes place
  422. using the :paramref:`.EnvironmentContext.configure.include_name`
  423. hook.
  424. .. seealso::
  425. :ref:`autogenerate_include_hooks`
  426. :paramref:`.EnvironmentContext.configure.include_name`
  427. :paramref:`.EnvironmentContext.configure.include_schemas`
  428. :param render_as_batch: if True, commands which alter elements
  429. within a table will be placed under a ``with batch_alter_table():``
  430. directive, so that batch migrations will take place.
  431. .. seealso::
  432. :ref:`batch_migrations`
  433. :param include_schemas: If True, autogenerate will scan across
  434. all schemas located by the SQLAlchemy
  435. :meth:`~sqlalchemy.engine.reflection.Inspector.get_schema_names`
  436. method, and include all differences in tables found across all
  437. those schemas. When using this option, you may want to also
  438. use the :paramref:`.EnvironmentContext.configure.include_name`
  439. parameter to specify a callable which
  440. can filter the tables/schemas that get included.
  441. .. seealso::
  442. :ref:`autogenerate_include_hooks`
  443. :paramref:`.EnvironmentContext.configure.include_name`
  444. :paramref:`.EnvironmentContext.configure.include_object`
  445. :param render_item: Callable that can be used to override how
  446. any schema item, i.e. column, constraint, type,
  447. etc., is rendered for autogenerate. The callable receives a
  448. string describing the type of object, the object, and
  449. the autogen context. If it returns False, the
  450. default rendering method will be used. If it returns None,
  451. the item will not be rendered in the context of a Table
  452. construct, that is, can be used to skip columns or constraints
  453. within op.create_table()::
  454. def my_render_column(type_, col, autogen_context):
  455. if type_ == "column" and isinstance(col, MySpecialCol):
  456. return repr(col)
  457. else:
  458. return False
  459. context.configure(
  460. # ...
  461. render_item = my_render_column
  462. )
  463. Available values for the type string include: ``"column"``,
  464. ``"primary_key"``, ``"foreign_key"``, ``"unique"``, ``"check"``,
  465. ``"type"``, ``"server_default"``.
  466. .. seealso::
  467. :ref:`autogen_render_types`
  468. :param upgrade_token: When autogenerate completes, the text of the
  469. candidate upgrade operations will be present in this template
  470. variable when ``script.py.mako`` is rendered. Defaults to
  471. ``upgrades``.
  472. :param downgrade_token: When autogenerate completes, the text of the
  473. candidate downgrade operations will be present in this
  474. template variable when ``script.py.mako`` is rendered. Defaults to
  475. ``downgrades``.
  476. :param alembic_module_prefix: When autogenerate refers to Alembic
  477. :mod:`alembic.operations` constructs, this prefix will be used
  478. (i.e. ``op.create_table``) Defaults to "``op.``".
  479. Can be ``None`` to indicate no prefix.
  480. :param sqlalchemy_module_prefix: When autogenerate refers to
  481. SQLAlchemy
  482. :class:`~sqlalchemy.schema.Column` or type classes, this prefix
  483. will be used
  484. (i.e. ``sa.Column("somename", sa.Integer)``) Defaults to "``sa.``".
  485. Can be ``None`` to indicate no prefix.
  486. Note that when dialect-specific types are rendered, autogenerate
  487. will render them using the dialect module name, i.e. ``mssql.BIT()``,
  488. ``postgresql.UUID()``.
  489. :param user_module_prefix: When autogenerate refers to a SQLAlchemy
  490. type (e.g. :class:`.TypeEngine`) where the module name is not
  491. under the ``sqlalchemy`` namespace, this prefix will be used
  492. within autogenerate. If left at its default of
  493. ``None``, the ``__module__`` attribute of the type is used to
  494. render the import module. It's a good practice to set this
  495. and to have all custom types be available from a fixed module space,
  496. in order to future-proof migration files against reorganizations
  497. in modules.
  498. .. seealso::
  499. :ref:`autogen_module_prefix`
  500. :param process_revision_directives: a callable function that will
  501. be passed a structure representing the end result of an autogenerate
  502. or plain "revision" operation, which can be manipulated to affect
  503. how the ``alembic revision`` command ultimately outputs new
  504. revision scripts. The structure of the callable is::
  505. def process_revision_directives(context, revision, directives):
  506. pass
  507. The ``directives`` parameter is a Python list containing
  508. a single :class:`.MigrationScript` directive, which represents
  509. the revision file to be generated. This list as well as its
  510. contents may be freely modified to produce any set of commands.
  511. The section :ref:`customizing_revision` shows an example of
  512. doing this. The ``context`` parameter is the
  513. :class:`.MigrationContext` in use,
  514. and ``revision`` is a tuple of revision identifiers representing the
  515. current revision of the database.
  516. The callable is invoked at all times when the ``--autogenerate``
  517. option is passed to ``alembic revision``. If ``--autogenerate``
  518. is not passed, the callable is invoked only if the
  519. ``revision_environment`` variable is set to True in the Alembic
  520. configuration, in which case the given ``directives`` collection
  521. will contain empty :class:`.UpgradeOps` and :class:`.DowngradeOps`
  522. collections for ``.upgrade_ops`` and ``.downgrade_ops``. The
  523. ``--autogenerate`` option itself can be inferred by inspecting
  524. ``context.config.cmd_opts.autogenerate``.
  525. The callable function may optionally be an instance of
  526. a :class:`.Rewriter` object. This is a helper object that
  527. assists in the production of autogenerate-stream rewriter functions.
  528. .. seealso::
  529. :ref:`customizing_revision`
  530. :ref:`autogen_rewriter`
  531. :paramref:`.command.revision.process_revision_directives`
  532. Parameters specific to individual backends:
  533. :param mssql_batch_separator: The "batch separator" which will
  534. be placed between each statement when generating offline SQL Server
  535. migrations. Defaults to ``GO``. Note this is in addition to the
  536. customary semicolon ``;`` at the end of each statement; SQL Server
  537. considers the "batch separator" to denote the end of an
  538. individual statement execution, and cannot group certain
  539. dependent operations in one step.
  540. :param oracle_batch_separator: The "batch separator" which will
  541. be placed between each statement when generating offline
  542. Oracle migrations. Defaults to ``/``. Oracle doesn't add a
  543. semicolon between statements like most other backends.
  544. """
  545. def execute(
  546. sql: Union[Executable, str],
  547. execution_options: Optional[Dict[str, Any]] = None,
  548. ) -> None:
  549. """Execute the given SQL using the current change context.
  550. The behavior of :meth:`.execute` is the same
  551. as that of :meth:`.Operations.execute`. Please see that
  552. function's documentation for full detail including
  553. caveats and limitations.
  554. This function requires that a :class:`.MigrationContext` has
  555. first been made available via :meth:`.configure`.
  556. """
  557. def get_bind() -> Connection:
  558. """Return the current 'bind'.
  559. In "online" mode, this is the
  560. :class:`sqlalchemy.engine.Connection` currently being used
  561. to emit SQL to the database.
  562. This function requires that a :class:`.MigrationContext`
  563. has first been made available via :meth:`.configure`.
  564. """
  565. def get_context() -> MigrationContext:
  566. """Return the current :class:`.MigrationContext` object.
  567. If :meth:`.EnvironmentContext.configure` has not been
  568. called yet, raises an exception.
  569. """
  570. def get_head_revision() -> Union[str, Tuple[str, ...], None]:
  571. """Return the hex identifier of the 'head' script revision.
  572. If the script directory has multiple heads, this
  573. method raises a :class:`.CommandError`;
  574. :meth:`.EnvironmentContext.get_head_revisions` should be preferred.
  575. This function does not require that the :class:`.MigrationContext`
  576. has been configured.
  577. .. seealso:: :meth:`.EnvironmentContext.get_head_revisions`
  578. """
  579. def get_head_revisions() -> Union[str, Tuple[str, ...], None]:
  580. """Return the hex identifier of the 'heads' script revision(s).
  581. This returns a tuple containing the version number of all
  582. heads in the script directory.
  583. This function does not require that the :class:`.MigrationContext`
  584. has been configured.
  585. """
  586. def get_revision_argument() -> Union[str, Tuple[str, ...], None]:
  587. """Get the 'destination' revision argument.
  588. This is typically the argument passed to the
  589. ``upgrade`` or ``downgrade`` command.
  590. If it was specified as ``head``, the actual
  591. version number is returned; if specified
  592. as ``base``, ``None`` is returned.
  593. This function does not require that the :class:`.MigrationContext`
  594. has been configured.
  595. """
  596. def get_starting_revision_argument() -> Union[str, Tuple[str, ...], None]:
  597. """Return the 'starting revision' argument,
  598. if the revision was passed using ``start:end``.
  599. This is only meaningful in "offline" mode.
  600. Returns ``None`` if no value is available
  601. or was configured.
  602. This function does not require that the :class:`.MigrationContext`
  603. has been configured.
  604. """
  605. def get_tag_argument() -> Optional[str]:
  606. """Return the value passed for the ``--tag`` argument, if any.
  607. The ``--tag`` argument is not used directly by Alembic,
  608. but is available for custom ``env.py`` configurations that
  609. wish to use it; particularly for offline generation scripts
  610. that wish to generate tagged filenames.
  611. This function does not require that the :class:`.MigrationContext`
  612. has been configured.
  613. .. seealso::
  614. :meth:`.EnvironmentContext.get_x_argument` - a newer and more
  615. open ended system of extending ``env.py`` scripts via the command
  616. line.
  617. """
  618. @overload
  619. def get_x_argument(as_dictionary: Literal[False]) -> List[str]: ...
  620. @overload
  621. def get_x_argument(as_dictionary: Literal[True]) -> Dict[str, str]: ...
  622. @overload
  623. def get_x_argument(
  624. as_dictionary: bool = ...,
  625. ) -> Union[List[str], Dict[str, str]]:
  626. """Return the value(s) passed for the ``-x`` argument, if any.
  627. The ``-x`` argument is an open ended flag that allows any user-defined
  628. value or values to be passed on the command line, then available
  629. here for consumption by a custom ``env.py`` script.
  630. The return value is a list, returned directly from the ``argparse``
  631. structure. If ``as_dictionary=True`` is passed, the ``x`` arguments
  632. are parsed using ``key=value`` format into a dictionary that is
  633. then returned. If there is no ``=`` in the argument, value is an empty
  634. string.
  635. .. versionchanged:: 1.13.1 Support ``as_dictionary=True`` when
  636. arguments are passed without the ``=`` symbol.
  637. For example, to support passing a database URL on the command line,
  638. the standard ``env.py`` script can be modified like this::
  639. cmd_line_url = context.get_x_argument(
  640. as_dictionary=True).get('dbname')
  641. if cmd_line_url:
  642. engine = create_engine(cmd_line_url)
  643. else:
  644. engine = engine_from_config(
  645. config.get_section(config.config_ini_section),
  646. prefix='sqlalchemy.',
  647. poolclass=pool.NullPool)
  648. This then takes effect by running the ``alembic`` script as::
  649. alembic -x dbname=postgresql://user:pass@host/dbname upgrade head
  650. This function does not require that the :class:`.MigrationContext`
  651. has been configured.
  652. .. seealso::
  653. :meth:`.EnvironmentContext.get_tag_argument`
  654. :attr:`.Config.cmd_opts`
  655. """
  656. def is_offline_mode() -> bool:
  657. """Return True if the current migrations environment
  658. is running in "offline mode".
  659. This is ``True`` or ``False`` depending
  660. on the ``--sql`` flag passed.
  661. This function does not require that the :class:`.MigrationContext`
  662. has been configured.
  663. """
  664. def is_transactional_ddl() -> bool:
  665. """Return True if the context is configured to expect a
  666. transactional DDL capable backend.
  667. This defaults to the type of database in use, and
  668. can be overridden by the ``transactional_ddl`` argument
  669. to :meth:`.configure`
  670. This function requires that a :class:`.MigrationContext`
  671. has first been made available via :meth:`.configure`.
  672. """
  673. def run_migrations(**kw: Any) -> None:
  674. """Run migrations as determined by the current command line
  675. configuration
  676. as well as versioning information present (or not) in the current
  677. database connection (if one is present).
  678. The function accepts optional ``**kw`` arguments. If these are
  679. passed, they are sent directly to the ``upgrade()`` and
  680. ``downgrade()``
  681. functions within each target revision file. By modifying the
  682. ``script.py.mako`` file so that the ``upgrade()`` and ``downgrade()``
  683. functions accept arguments, parameters can be passed here so that
  684. contextual information, usually information to identify a particular
  685. database in use, can be passed from a custom ``env.py`` script
  686. to the migration functions.
  687. This function requires that a :class:`.MigrationContext` has
  688. first been made available via :meth:`.configure`.
  689. """
  690. script: ScriptDirectory
  691. def static_output(text: str) -> None:
  692. """Emit text directly to the "offline" SQL stream.
  693. Typically this is for emitting comments that
  694. start with --. The statement is not treated
  695. as a SQL execution, no ; or batch separator
  696. is added, etc.
  697. """