op.pyi 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321
  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 contextlib import contextmanager
  5. from typing import Any
  6. from typing import Awaitable
  7. from typing import Callable
  8. from typing import Dict
  9. from typing import Iterator
  10. from typing import List
  11. from typing import Literal
  12. from typing import Mapping
  13. from typing import Optional
  14. from typing import overload
  15. from typing import Sequence
  16. from typing import Tuple
  17. from typing import Type
  18. from typing import TYPE_CHECKING
  19. from typing import TypeVar
  20. from typing import Union
  21. if TYPE_CHECKING:
  22. from sqlalchemy.engine import Connection
  23. from sqlalchemy.sql import Executable
  24. from sqlalchemy.sql.elements import ColumnElement
  25. from sqlalchemy.sql.elements import conv
  26. from sqlalchemy.sql.elements import TextClause
  27. from sqlalchemy.sql.expression import TableClause
  28. from sqlalchemy.sql.functions import Function
  29. from sqlalchemy.sql.schema import Column
  30. from sqlalchemy.sql.schema import Computed
  31. from sqlalchemy.sql.schema import Identity
  32. from sqlalchemy.sql.schema import SchemaItem
  33. from sqlalchemy.sql.schema import Table
  34. from sqlalchemy.sql.type_api import TypeEngine
  35. from sqlalchemy.util import immutabledict
  36. from .operations.base import BatchOperations
  37. from .operations.ops import AddColumnOp
  38. from .operations.ops import AddConstraintOp
  39. from .operations.ops import AlterColumnOp
  40. from .operations.ops import AlterTableOp
  41. from .operations.ops import BulkInsertOp
  42. from .operations.ops import CreateIndexOp
  43. from .operations.ops import CreateTableCommentOp
  44. from .operations.ops import CreateTableOp
  45. from .operations.ops import DropColumnOp
  46. from .operations.ops import DropConstraintOp
  47. from .operations.ops import DropIndexOp
  48. from .operations.ops import DropTableCommentOp
  49. from .operations.ops import DropTableOp
  50. from .operations.ops import ExecuteSQLOp
  51. from .operations.ops import MigrateOperation
  52. from .runtime.migration import MigrationContext
  53. from .util.sqla_compat import _literal_bindparam
  54. _T = TypeVar("_T")
  55. _C = TypeVar("_C", bound=Callable[..., Any])
  56. ### end imports ###
  57. def add_column(
  58. table_name: str, column: Column[Any], *, schema: Optional[str] = None
  59. ) -> None:
  60. """Issue an "add column" instruction using the current
  61. migration context.
  62. e.g.::
  63. from alembic import op
  64. from sqlalchemy import Column, String
  65. op.add_column("organization", Column("name", String()))
  66. The :meth:`.Operations.add_column` method typically corresponds
  67. to the SQL command "ALTER TABLE... ADD COLUMN". Within the scope
  68. of this command, the column's name, datatype, nullability,
  69. and optional server-generated defaults may be indicated.
  70. .. note::
  71. With the exception of NOT NULL constraints or single-column FOREIGN
  72. KEY constraints, other kinds of constraints such as PRIMARY KEY,
  73. UNIQUE or CHECK constraints **cannot** be generated using this
  74. method; for these constraints, refer to operations such as
  75. :meth:`.Operations.create_primary_key` and
  76. :meth:`.Operations.create_check_constraint`. In particular, the
  77. following :class:`~sqlalchemy.schema.Column` parameters are
  78. **ignored**:
  79. * :paramref:`~sqlalchemy.schema.Column.primary_key` - SQL databases
  80. typically do not support an ALTER operation that can add
  81. individual columns one at a time to an existing primary key
  82. constraint, therefore it's less ambiguous to use the
  83. :meth:`.Operations.create_primary_key` method, which assumes no
  84. existing primary key constraint is present.
  85. * :paramref:`~sqlalchemy.schema.Column.unique` - use the
  86. :meth:`.Operations.create_unique_constraint` method
  87. * :paramref:`~sqlalchemy.schema.Column.index` - use the
  88. :meth:`.Operations.create_index` method
  89. The provided :class:`~sqlalchemy.schema.Column` object may include a
  90. :class:`~sqlalchemy.schema.ForeignKey` constraint directive,
  91. referencing a remote table name. For this specific type of constraint,
  92. Alembic will automatically emit a second ALTER statement in order to
  93. add the single-column FOREIGN KEY constraint separately::
  94. from alembic import op
  95. from sqlalchemy import Column, INTEGER, ForeignKey
  96. op.add_column(
  97. "organization",
  98. Column("account_id", INTEGER, ForeignKey("accounts.id")),
  99. )
  100. The column argument passed to :meth:`.Operations.add_column` is a
  101. :class:`~sqlalchemy.schema.Column` construct, used in the same way it's
  102. used in SQLAlchemy. In particular, values or functions to be indicated
  103. as producing the column's default value on the database side are
  104. specified using the ``server_default`` parameter, and not ``default``
  105. which only specifies Python-side defaults::
  106. from alembic import op
  107. from sqlalchemy import Column, TIMESTAMP, func
  108. # specify "DEFAULT NOW" along with the column add
  109. op.add_column(
  110. "account",
  111. Column("timestamp", TIMESTAMP, server_default=func.now()),
  112. )
  113. :param table_name: String name of the parent table.
  114. :param column: a :class:`sqlalchemy.schema.Column` object
  115. representing the new column.
  116. :param schema: Optional schema name to operate within. To control
  117. quoting of the schema outside of the default behavior, use
  118. the SQLAlchemy construct
  119. :class:`~sqlalchemy.sql.elements.quoted_name`.
  120. """
  121. def alter_column(
  122. table_name: str,
  123. column_name: str,
  124. *,
  125. nullable: Optional[bool] = None,
  126. comment: Union[str, Literal[False], None] = False,
  127. server_default: Any = False,
  128. new_column_name: Optional[str] = None,
  129. type_: Union[TypeEngine[Any], Type[TypeEngine[Any]], None] = None,
  130. existing_type: Union[TypeEngine[Any], Type[TypeEngine[Any]], None] = None,
  131. existing_server_default: Union[
  132. str, bool, Identity, Computed, None
  133. ] = False,
  134. existing_nullable: Optional[bool] = None,
  135. existing_comment: Optional[str] = None,
  136. schema: Optional[str] = None,
  137. **kw: Any,
  138. ) -> None:
  139. r"""Issue an "alter column" instruction using the
  140. current migration context.
  141. Generally, only that aspect of the column which
  142. is being changed, i.e. name, type, nullability,
  143. default, needs to be specified. Multiple changes
  144. can also be specified at once and the backend should
  145. "do the right thing", emitting each change either
  146. separately or together as the backend allows.
  147. MySQL has special requirements here, since MySQL
  148. cannot ALTER a column without a full specification.
  149. When producing MySQL-compatible migration files,
  150. it is recommended that the ``existing_type``,
  151. ``existing_server_default``, and ``existing_nullable``
  152. parameters be present, if not being altered.
  153. Type changes which are against the SQLAlchemy
  154. "schema" types :class:`~sqlalchemy.types.Boolean`
  155. and :class:`~sqlalchemy.types.Enum` may also
  156. add or drop constraints which accompany those
  157. types on backends that don't support them natively.
  158. The ``existing_type`` argument is
  159. used in this case to identify and remove a previous
  160. constraint that was bound to the type object.
  161. :param table_name: string name of the target table.
  162. :param column_name: string name of the target column,
  163. as it exists before the operation begins.
  164. :param nullable: Optional; specify ``True`` or ``False``
  165. to alter the column's nullability.
  166. :param server_default: Optional; specify a string
  167. SQL expression, :func:`~sqlalchemy.sql.expression.text`,
  168. or :class:`~sqlalchemy.schema.DefaultClause` to indicate
  169. an alteration to the column's default value.
  170. Set to ``None`` to have the default removed.
  171. :param comment: optional string text of a new comment to add to the
  172. column.
  173. :param new_column_name: Optional; specify a string name here to
  174. indicate the new name within a column rename operation.
  175. :param type\_: Optional; a :class:`~sqlalchemy.types.TypeEngine`
  176. type object to specify a change to the column's type.
  177. For SQLAlchemy types that also indicate a constraint (i.e.
  178. :class:`~sqlalchemy.types.Boolean`, :class:`~sqlalchemy.types.Enum`),
  179. the constraint is also generated.
  180. :param autoincrement: set the ``AUTO_INCREMENT`` flag of the column;
  181. currently understood by the MySQL dialect.
  182. :param existing_type: Optional; a
  183. :class:`~sqlalchemy.types.TypeEngine`
  184. type object to specify the previous type. This
  185. is required for all MySQL column alter operations that
  186. don't otherwise specify a new type, as well as for
  187. when nullability is being changed on a SQL Server
  188. column. It is also used if the type is a so-called
  189. SQLAlchemy "schema" type which may define a constraint (i.e.
  190. :class:`~sqlalchemy.types.Boolean`,
  191. :class:`~sqlalchemy.types.Enum`),
  192. so that the constraint can be dropped.
  193. :param existing_server_default: Optional; The existing
  194. default value of the column. Required on MySQL if
  195. an existing default is not being changed; else MySQL
  196. removes the default.
  197. :param existing_nullable: Optional; the existing nullability
  198. of the column. Required on MySQL if the existing nullability
  199. is not being changed; else MySQL sets this to NULL.
  200. :param existing_autoincrement: Optional; the existing autoincrement
  201. of the column. Used for MySQL's system of altering a column
  202. that specifies ``AUTO_INCREMENT``.
  203. :param existing_comment: string text of the existing comment on the
  204. column to be maintained. Required on MySQL if the existing comment
  205. on the column is not being changed.
  206. :param schema: Optional schema name to operate within. To control
  207. quoting of the schema outside of the default behavior, use
  208. the SQLAlchemy construct
  209. :class:`~sqlalchemy.sql.elements.quoted_name`.
  210. :param postgresql_using: String argument which will indicate a
  211. SQL expression to render within the Postgresql-specific USING clause
  212. within ALTER COLUMN. This string is taken directly as raw SQL which
  213. must explicitly include any necessary quoting or escaping of tokens
  214. within the expression.
  215. """
  216. @contextmanager
  217. def batch_alter_table(
  218. table_name: str,
  219. schema: Optional[str] = None,
  220. recreate: Literal["auto", "always", "never"] = "auto",
  221. partial_reordering: Optional[Tuple[Any, ...]] = None,
  222. copy_from: Optional[Table] = None,
  223. table_args: Tuple[Any, ...] = (),
  224. table_kwargs: Mapping[str, Any] = immutabledict({}),
  225. reflect_args: Tuple[Any, ...] = (),
  226. reflect_kwargs: Mapping[str, Any] = immutabledict({}),
  227. naming_convention: Optional[Dict[str, str]] = None,
  228. ) -> Iterator[BatchOperations]:
  229. """Invoke a series of per-table migrations in batch.
  230. Batch mode allows a series of operations specific to a table
  231. to be syntactically grouped together, and allows for alternate
  232. modes of table migration, in particular the "recreate" style of
  233. migration required by SQLite.
  234. "recreate" style is as follows:
  235. 1. A new table is created with the new specification, based on the
  236. migration directives within the batch, using a temporary name.
  237. 2. the data copied from the existing table to the new table.
  238. 3. the existing table is dropped.
  239. 4. the new table is renamed to the existing table name.
  240. The directive by default will only use "recreate" style on the
  241. SQLite backend, and only if directives are present which require
  242. this form, e.g. anything other than ``add_column()``. The batch
  243. operation on other backends will proceed using standard ALTER TABLE
  244. operations.
  245. The method is used as a context manager, which returns an instance
  246. of :class:`.BatchOperations`; this object is the same as
  247. :class:`.Operations` except that table names and schema names
  248. are omitted. E.g.::
  249. with op.batch_alter_table("some_table") as batch_op:
  250. batch_op.add_column(Column("foo", Integer))
  251. batch_op.drop_column("bar")
  252. The operations within the context manager are invoked at once
  253. when the context is ended. When run against SQLite, if the
  254. migrations include operations not supported by SQLite's ALTER TABLE,
  255. the entire table will be copied to a new one with the new
  256. specification, moving all data across as well.
  257. The copy operation by default uses reflection to retrieve the current
  258. structure of the table, and therefore :meth:`.batch_alter_table`
  259. in this mode requires that the migration is run in "online" mode.
  260. The ``copy_from`` parameter may be passed which refers to an existing
  261. :class:`.Table` object, which will bypass this reflection step.
  262. .. note:: The table copy operation will currently not copy
  263. CHECK constraints, and may not copy UNIQUE constraints that are
  264. unnamed, as is possible on SQLite. See the section
  265. :ref:`sqlite_batch_constraints` for workarounds.
  266. :param table_name: name of table
  267. :param schema: optional schema name.
  268. :param recreate: under what circumstances the table should be
  269. recreated. At its default of ``"auto"``, the SQLite dialect will
  270. recreate the table if any operations other than ``add_column()``,
  271. ``create_index()``, or ``drop_index()`` are
  272. present. Other options include ``"always"`` and ``"never"``.
  273. :param copy_from: optional :class:`~sqlalchemy.schema.Table` object
  274. that will act as the structure of the table being copied. If omitted,
  275. table reflection is used to retrieve the structure of the table.
  276. .. seealso::
  277. :ref:`batch_offline_mode`
  278. :paramref:`~.Operations.batch_alter_table.reflect_args`
  279. :paramref:`~.Operations.batch_alter_table.reflect_kwargs`
  280. :param reflect_args: a sequence of additional positional arguments that
  281. will be applied to the table structure being reflected / copied;
  282. this may be used to pass column and constraint overrides to the
  283. table that will be reflected, in lieu of passing the whole
  284. :class:`~sqlalchemy.schema.Table` using
  285. :paramref:`~.Operations.batch_alter_table.copy_from`.
  286. :param reflect_kwargs: a dictionary of additional keyword arguments
  287. that will be applied to the table structure being copied; this may be
  288. used to pass additional table and reflection options to the table that
  289. will be reflected, in lieu of passing the whole
  290. :class:`~sqlalchemy.schema.Table` using
  291. :paramref:`~.Operations.batch_alter_table.copy_from`.
  292. :param table_args: a sequence of additional positional arguments that
  293. will be applied to the new :class:`~sqlalchemy.schema.Table` when
  294. created, in addition to those copied from the source table.
  295. This may be used to provide additional constraints such as CHECK
  296. constraints that may not be reflected.
  297. :param table_kwargs: a dictionary of additional keyword arguments
  298. that will be applied to the new :class:`~sqlalchemy.schema.Table`
  299. when created, in addition to those copied from the source table.
  300. This may be used to provide for additional table options that may
  301. not be reflected.
  302. :param naming_convention: a naming convention dictionary of the form
  303. described at :ref:`autogen_naming_conventions` which will be applied
  304. to the :class:`~sqlalchemy.schema.MetaData` during the reflection
  305. process. This is typically required if one wants to drop SQLite
  306. constraints, as these constraints will not have names when
  307. reflected on this backend. Requires SQLAlchemy **0.9.4** or greater.
  308. .. seealso::
  309. :ref:`dropping_sqlite_foreign_keys`
  310. :param partial_reordering: a list of tuples, each suggesting a desired
  311. ordering of two or more columns in the newly created table. Requires
  312. that :paramref:`.batch_alter_table.recreate` is set to ``"always"``.
  313. Examples, given a table with columns "a", "b", "c", and "d":
  314. Specify the order of all columns::
  315. with op.batch_alter_table(
  316. "some_table",
  317. recreate="always",
  318. partial_reordering=[("c", "d", "a", "b")],
  319. ) as batch_op:
  320. pass
  321. Ensure "d" appears before "c", and "b", appears before "a"::
  322. with op.batch_alter_table(
  323. "some_table",
  324. recreate="always",
  325. partial_reordering=[("d", "c"), ("b", "a")],
  326. ) as batch_op:
  327. pass
  328. The ordering of columns not included in the partial_reordering
  329. set is undefined. Therefore it is best to specify the complete
  330. ordering of all columns for best results.
  331. .. note:: batch mode requires SQLAlchemy 0.8 or above.
  332. .. seealso::
  333. :ref:`batch_migrations`
  334. """
  335. def bulk_insert(
  336. table: Union[Table, TableClause],
  337. rows: List[Dict[str, Any]],
  338. *,
  339. multiinsert: bool = True,
  340. ) -> None:
  341. """Issue a "bulk insert" operation using the current
  342. migration context.
  343. This provides a means of representing an INSERT of multiple rows
  344. which works equally well in the context of executing on a live
  345. connection as well as that of generating a SQL script. In the
  346. case of a SQL script, the values are rendered inline into the
  347. statement.
  348. e.g.::
  349. from alembic import op
  350. from datetime import date
  351. from sqlalchemy.sql import table, column
  352. from sqlalchemy import String, Integer, Date
  353. # Create an ad-hoc table to use for the insert statement.
  354. accounts_table = table(
  355. "account",
  356. column("id", Integer),
  357. column("name", String),
  358. column("create_date", Date),
  359. )
  360. op.bulk_insert(
  361. accounts_table,
  362. [
  363. {
  364. "id": 1,
  365. "name": "John Smith",
  366. "create_date": date(2010, 10, 5),
  367. },
  368. {
  369. "id": 2,
  370. "name": "Ed Williams",
  371. "create_date": date(2007, 5, 27),
  372. },
  373. {
  374. "id": 3,
  375. "name": "Wendy Jones",
  376. "create_date": date(2008, 8, 15),
  377. },
  378. ],
  379. )
  380. When using --sql mode, some datatypes may not render inline
  381. automatically, such as dates and other special types. When this
  382. issue is present, :meth:`.Operations.inline_literal` may be used::
  383. op.bulk_insert(
  384. accounts_table,
  385. [
  386. {
  387. "id": 1,
  388. "name": "John Smith",
  389. "create_date": op.inline_literal("2010-10-05"),
  390. },
  391. {
  392. "id": 2,
  393. "name": "Ed Williams",
  394. "create_date": op.inline_literal("2007-05-27"),
  395. },
  396. {
  397. "id": 3,
  398. "name": "Wendy Jones",
  399. "create_date": op.inline_literal("2008-08-15"),
  400. },
  401. ],
  402. multiinsert=False,
  403. )
  404. When using :meth:`.Operations.inline_literal` in conjunction with
  405. :meth:`.Operations.bulk_insert`, in order for the statement to work
  406. in "online" (e.g. non --sql) mode, the
  407. :paramref:`~.Operations.bulk_insert.multiinsert`
  408. flag should be set to ``False``, which will have the effect of
  409. individual INSERT statements being emitted to the database, each
  410. with a distinct VALUES clause, so that the "inline" values can
  411. still be rendered, rather than attempting to pass the values
  412. as bound parameters.
  413. :param table: a table object which represents the target of the INSERT.
  414. :param rows: a list of dictionaries indicating rows.
  415. :param multiinsert: when at its default of True and --sql mode is not
  416. enabled, the INSERT statement will be executed using
  417. "executemany()" style, where all elements in the list of
  418. dictionaries are passed as bound parameters in a single
  419. list. Setting this to False results in individual INSERT
  420. statements being emitted per parameter set, and is needed
  421. in those cases where non-literal values are present in the
  422. parameter sets.
  423. """
  424. def create_check_constraint(
  425. constraint_name: Optional[str],
  426. table_name: str,
  427. condition: Union[str, ColumnElement[bool], TextClause],
  428. *,
  429. schema: Optional[str] = None,
  430. **kw: Any,
  431. ) -> None:
  432. """Issue a "create check constraint" instruction using the
  433. current migration context.
  434. e.g.::
  435. from alembic import op
  436. from sqlalchemy.sql import column, func
  437. op.create_check_constraint(
  438. "ck_user_name_len",
  439. "user",
  440. func.len(column("name")) > 5,
  441. )
  442. CHECK constraints are usually against a SQL expression, so ad-hoc
  443. table metadata is usually needed. The function will convert the given
  444. arguments into a :class:`sqlalchemy.schema.CheckConstraint` bound
  445. to an anonymous table in order to emit the CREATE statement.
  446. :param name: Name of the check constraint. The name is necessary
  447. so that an ALTER statement can be emitted. For setups that
  448. use an automated naming scheme such as that described at
  449. :ref:`sqla:constraint_naming_conventions`,
  450. ``name`` here can be ``None``, as the event listener will
  451. apply the name to the constraint object when it is associated
  452. with the table.
  453. :param table_name: String name of the source table.
  454. :param condition: SQL expression that's the condition of the
  455. constraint. Can be a string or SQLAlchemy expression language
  456. structure.
  457. :param deferrable: optional bool. If set, emit DEFERRABLE or
  458. NOT DEFERRABLE when issuing DDL for this constraint.
  459. :param initially: optional string. If set, emit INITIALLY <value>
  460. when issuing DDL for this constraint.
  461. :param schema: Optional schema name to operate within. To control
  462. quoting of the schema outside of the default behavior, use
  463. the SQLAlchemy construct
  464. :class:`~sqlalchemy.sql.elements.quoted_name`.
  465. """
  466. def create_exclude_constraint(
  467. constraint_name: str, table_name: str, *elements: Any, **kw: Any
  468. ) -> Optional[Table]:
  469. """Issue an alter to create an EXCLUDE constraint using the
  470. current migration context.
  471. .. note:: This method is Postgresql specific, and additionally
  472. requires at least SQLAlchemy 1.0.
  473. e.g.::
  474. from alembic import op
  475. op.create_exclude_constraint(
  476. "user_excl",
  477. "user",
  478. ("period", "&&"),
  479. ("group", "="),
  480. where=("group != 'some group'"),
  481. )
  482. Note that the expressions work the same way as that of
  483. the ``ExcludeConstraint`` object itself; if plain strings are
  484. passed, quoting rules must be applied manually.
  485. :param name: Name of the constraint.
  486. :param table_name: String name of the source table.
  487. :param elements: exclude conditions.
  488. :param where: SQL expression or SQL string with optional WHERE
  489. clause.
  490. :param deferrable: optional bool. If set, emit DEFERRABLE or
  491. NOT DEFERRABLE when issuing DDL for this constraint.
  492. :param initially: optional string. If set, emit INITIALLY <value>
  493. when issuing DDL for this constraint.
  494. :param schema: Optional schema name to operate within.
  495. """
  496. def create_foreign_key(
  497. constraint_name: Optional[str],
  498. source_table: str,
  499. referent_table: str,
  500. local_cols: List[str],
  501. remote_cols: List[str],
  502. *,
  503. onupdate: Optional[str] = None,
  504. ondelete: Optional[str] = None,
  505. deferrable: Optional[bool] = None,
  506. initially: Optional[str] = None,
  507. match: Optional[str] = None,
  508. source_schema: Optional[str] = None,
  509. referent_schema: Optional[str] = None,
  510. **dialect_kw: Any,
  511. ) -> None:
  512. """Issue a "create foreign key" instruction using the
  513. current migration context.
  514. e.g.::
  515. from alembic import op
  516. op.create_foreign_key(
  517. "fk_user_address",
  518. "address",
  519. "user",
  520. ["user_id"],
  521. ["id"],
  522. )
  523. This internally generates a :class:`~sqlalchemy.schema.Table` object
  524. containing the necessary columns, then generates a new
  525. :class:`~sqlalchemy.schema.ForeignKeyConstraint`
  526. object which it then associates with the
  527. :class:`~sqlalchemy.schema.Table`.
  528. Any event listeners associated with this action will be fired
  529. off normally. The :class:`~sqlalchemy.schema.AddConstraint`
  530. construct is ultimately used to generate the ALTER statement.
  531. :param constraint_name: Name of the foreign key constraint. The name
  532. is necessary so that an ALTER statement can be emitted. For setups
  533. that use an automated naming scheme such as that described at
  534. :ref:`sqla:constraint_naming_conventions`,
  535. ``name`` here can be ``None``, as the event listener will
  536. apply the name to the constraint object when it is associated
  537. with the table.
  538. :param source_table: String name of the source table.
  539. :param referent_table: String name of the destination table.
  540. :param local_cols: a list of string column names in the
  541. source table.
  542. :param remote_cols: a list of string column names in the
  543. remote table.
  544. :param onupdate: Optional string. If set, emit ON UPDATE <value> when
  545. issuing DDL for this constraint. Typical values include CASCADE,
  546. DELETE and RESTRICT.
  547. :param ondelete: Optional string. If set, emit ON DELETE <value> when
  548. issuing DDL for this constraint. Typical values include CASCADE,
  549. DELETE and RESTRICT.
  550. :param deferrable: optional bool. If set, emit DEFERRABLE or NOT
  551. DEFERRABLE when issuing DDL for this constraint.
  552. :param source_schema: Optional schema name of the source table.
  553. :param referent_schema: Optional schema name of the destination table.
  554. """
  555. def create_index(
  556. index_name: Optional[str],
  557. table_name: str,
  558. columns: Sequence[Union[str, TextClause, Function[Any]]],
  559. *,
  560. schema: Optional[str] = None,
  561. unique: bool = False,
  562. if_not_exists: Optional[bool] = None,
  563. **kw: Any,
  564. ) -> None:
  565. r"""Issue a "create index" instruction using the current
  566. migration context.
  567. e.g.::
  568. from alembic import op
  569. op.create_index("ik_test", "t1", ["foo", "bar"])
  570. Functional indexes can be produced by using the
  571. :func:`sqlalchemy.sql.expression.text` construct::
  572. from alembic import op
  573. from sqlalchemy import text
  574. op.create_index("ik_test", "t1", [text("lower(foo)")])
  575. :param index_name: name of the index.
  576. :param table_name: name of the owning table.
  577. :param columns: a list consisting of string column names and/or
  578. :func:`~sqlalchemy.sql.expression.text` constructs.
  579. :param schema: Optional schema name to operate within. To control
  580. quoting of the schema outside of the default behavior, use
  581. the SQLAlchemy construct
  582. :class:`~sqlalchemy.sql.elements.quoted_name`.
  583. :param unique: If True, create a unique index.
  584. :param quote: Force quoting of this column's name on or off,
  585. corresponding to ``True`` or ``False``. When left at its default
  586. of ``None``, the column identifier will be quoted according to
  587. whether the name is case sensitive (identifiers with at least one
  588. upper case character are treated as case sensitive), or if it's a
  589. reserved word. This flag is only needed to force quoting of a
  590. reserved word which is not known by the SQLAlchemy dialect.
  591. :param if_not_exists: If True, adds IF NOT EXISTS operator when
  592. creating the new index.
  593. .. versionadded:: 1.12.0
  594. :param \**kw: Additional keyword arguments not mentioned above are
  595. dialect specific, and passed in the form
  596. ``<dialectname>_<argname>``.
  597. See the documentation regarding an individual dialect at
  598. :ref:`dialect_toplevel` for detail on documented arguments.
  599. """
  600. def create_primary_key(
  601. constraint_name: Optional[str],
  602. table_name: str,
  603. columns: List[str],
  604. *,
  605. schema: Optional[str] = None,
  606. ) -> None:
  607. """Issue a "create primary key" instruction using the current
  608. migration context.
  609. e.g.::
  610. from alembic import op
  611. op.create_primary_key("pk_my_table", "my_table", ["id", "version"])
  612. This internally generates a :class:`~sqlalchemy.schema.Table` object
  613. containing the necessary columns, then generates a new
  614. :class:`~sqlalchemy.schema.PrimaryKeyConstraint`
  615. object which it then associates with the
  616. :class:`~sqlalchemy.schema.Table`.
  617. Any event listeners associated with this action will be fired
  618. off normally. The :class:`~sqlalchemy.schema.AddConstraint`
  619. construct is ultimately used to generate the ALTER statement.
  620. :param constraint_name: Name of the primary key constraint. The name
  621. is necessary so that an ALTER statement can be emitted. For setups
  622. that use an automated naming scheme such as that described at
  623. :ref:`sqla:constraint_naming_conventions`
  624. ``name`` here can be ``None``, as the event listener will
  625. apply the name to the constraint object when it is associated
  626. with the table.
  627. :param table_name: String name of the target table.
  628. :param columns: a list of string column names to be applied to the
  629. primary key constraint.
  630. :param schema: Optional schema name to operate within. To control
  631. quoting of the schema outside of the default behavior, use
  632. the SQLAlchemy construct
  633. :class:`~sqlalchemy.sql.elements.quoted_name`.
  634. """
  635. def create_table(table_name: str, *columns: SchemaItem, **kw: Any) -> Table:
  636. r"""Issue a "create table" instruction using the current migration
  637. context.
  638. This directive receives an argument list similar to that of the
  639. traditional :class:`sqlalchemy.schema.Table` construct, but without the
  640. metadata::
  641. from sqlalchemy import INTEGER, VARCHAR, NVARCHAR, Column
  642. from alembic import op
  643. op.create_table(
  644. "account",
  645. Column("id", INTEGER, primary_key=True),
  646. Column("name", VARCHAR(50), nullable=False),
  647. Column("description", NVARCHAR(200)),
  648. Column("timestamp", TIMESTAMP, server_default=func.now()),
  649. )
  650. Note that :meth:`.create_table` accepts
  651. :class:`~sqlalchemy.schema.Column`
  652. constructs directly from the SQLAlchemy library. In particular,
  653. default values to be created on the database side are
  654. specified using the ``server_default`` parameter, and not
  655. ``default`` which only specifies Python-side defaults::
  656. from alembic import op
  657. from sqlalchemy import Column, TIMESTAMP, func
  658. # specify "DEFAULT NOW" along with the "timestamp" column
  659. op.create_table(
  660. "account",
  661. Column("id", INTEGER, primary_key=True),
  662. Column("timestamp", TIMESTAMP, server_default=func.now()),
  663. )
  664. The function also returns a newly created
  665. :class:`~sqlalchemy.schema.Table` object, corresponding to the table
  666. specification given, which is suitable for
  667. immediate SQL operations, in particular
  668. :meth:`.Operations.bulk_insert`::
  669. from sqlalchemy import INTEGER, VARCHAR, NVARCHAR, Column
  670. from alembic import op
  671. account_table = op.create_table(
  672. "account",
  673. Column("id", INTEGER, primary_key=True),
  674. Column("name", VARCHAR(50), nullable=False),
  675. Column("description", NVARCHAR(200)),
  676. Column("timestamp", TIMESTAMP, server_default=func.now()),
  677. )
  678. op.bulk_insert(
  679. account_table,
  680. [
  681. {"name": "A1", "description": "account 1"},
  682. {"name": "A2", "description": "account 2"},
  683. ],
  684. )
  685. :param table_name: Name of the table
  686. :param \*columns: collection of :class:`~sqlalchemy.schema.Column`
  687. objects within
  688. the table, as well as optional :class:`~sqlalchemy.schema.Constraint`
  689. objects
  690. and :class:`~.sqlalchemy.schema.Index` objects.
  691. :param schema: Optional schema name to operate within. To control
  692. quoting of the schema outside of the default behavior, use
  693. the SQLAlchemy construct
  694. :class:`~sqlalchemy.sql.elements.quoted_name`.
  695. :param \**kw: Other keyword arguments are passed to the underlying
  696. :class:`sqlalchemy.schema.Table` object created for the command.
  697. :return: the :class:`~sqlalchemy.schema.Table` object corresponding
  698. to the parameters given.
  699. """
  700. def create_table_comment(
  701. table_name: str,
  702. comment: Optional[str],
  703. *,
  704. existing_comment: Optional[str] = None,
  705. schema: Optional[str] = None,
  706. ) -> None:
  707. """Emit a COMMENT ON operation to set the comment for a table.
  708. :param table_name: string name of the target table.
  709. :param comment: string value of the comment being registered against
  710. the specified table.
  711. :param existing_comment: String value of a comment
  712. already registered on the specified table, used within autogenerate
  713. so that the operation is reversible, but not required for direct
  714. use.
  715. .. seealso::
  716. :meth:`.Operations.drop_table_comment`
  717. :paramref:`.Operations.alter_column.comment`
  718. """
  719. def create_unique_constraint(
  720. constraint_name: Optional[str],
  721. table_name: str,
  722. columns: Sequence[str],
  723. *,
  724. schema: Optional[str] = None,
  725. **kw: Any,
  726. ) -> Any:
  727. """Issue a "create unique constraint" instruction using the
  728. current migration context.
  729. e.g.::
  730. from alembic import op
  731. op.create_unique_constraint("uq_user_name", "user", ["name"])
  732. This internally generates a :class:`~sqlalchemy.schema.Table` object
  733. containing the necessary columns, then generates a new
  734. :class:`~sqlalchemy.schema.UniqueConstraint`
  735. object which it then associates with the
  736. :class:`~sqlalchemy.schema.Table`.
  737. Any event listeners associated with this action will be fired
  738. off normally. The :class:`~sqlalchemy.schema.AddConstraint`
  739. construct is ultimately used to generate the ALTER statement.
  740. :param name: Name of the unique constraint. The name is necessary
  741. so that an ALTER statement can be emitted. For setups that
  742. use an automated naming scheme such as that described at
  743. :ref:`sqla:constraint_naming_conventions`,
  744. ``name`` here can be ``None``, as the event listener will
  745. apply the name to the constraint object when it is associated
  746. with the table.
  747. :param table_name: String name of the source table.
  748. :param columns: a list of string column names in the
  749. source table.
  750. :param deferrable: optional bool. If set, emit DEFERRABLE or
  751. NOT DEFERRABLE when issuing DDL for this constraint.
  752. :param initially: optional string. If set, emit INITIALLY <value>
  753. when issuing DDL for this constraint.
  754. :param schema: Optional schema name to operate within. To control
  755. quoting of the schema outside of the default behavior, use
  756. the SQLAlchemy construct
  757. :class:`~sqlalchemy.sql.elements.quoted_name`.
  758. """
  759. def drop_column(
  760. table_name: str,
  761. column_name: str,
  762. *,
  763. schema: Optional[str] = None,
  764. **kw: Any,
  765. ) -> None:
  766. """Issue a "drop column" instruction using the current
  767. migration context.
  768. e.g.::
  769. drop_column("organization", "account_id")
  770. :param table_name: name of table
  771. :param column_name: name of column
  772. :param schema: Optional schema name to operate within. To control
  773. quoting of the schema outside of the default behavior, use
  774. the SQLAlchemy construct
  775. :class:`~sqlalchemy.sql.elements.quoted_name`.
  776. :param mssql_drop_check: Optional boolean. When ``True``, on
  777. Microsoft SQL Server only, first
  778. drop the CHECK constraint on the column using a
  779. SQL-script-compatible
  780. block that selects into a @variable from sys.check_constraints,
  781. then exec's a separate DROP CONSTRAINT for that constraint.
  782. :param mssql_drop_default: Optional boolean. When ``True``, on
  783. Microsoft SQL Server only, first
  784. drop the DEFAULT constraint on the column using a
  785. SQL-script-compatible
  786. block that selects into a @variable from sys.default_constraints,
  787. then exec's a separate DROP CONSTRAINT for that default.
  788. :param mssql_drop_foreign_key: Optional boolean. When ``True``, on
  789. Microsoft SQL Server only, first
  790. drop a single FOREIGN KEY constraint on the column using a
  791. SQL-script-compatible
  792. block that selects into a @variable from
  793. sys.foreign_keys/sys.foreign_key_columns,
  794. then exec's a separate DROP CONSTRAINT for that default. Only
  795. works if the column has exactly one FK constraint which refers to
  796. it, at the moment.
  797. """
  798. def drop_constraint(
  799. constraint_name: str,
  800. table_name: str,
  801. type_: Optional[str] = None,
  802. *,
  803. schema: Optional[str] = None,
  804. ) -> None:
  805. r"""Drop a constraint of the given name, typically via DROP CONSTRAINT.
  806. :param constraint_name: name of the constraint.
  807. :param table_name: table name.
  808. :param type\_: optional, required on MySQL. can be
  809. 'foreignkey', 'primary', 'unique', or 'check'.
  810. :param schema: Optional schema name to operate within. To control
  811. quoting of the schema outside of the default behavior, use
  812. the SQLAlchemy construct
  813. :class:`~sqlalchemy.sql.elements.quoted_name`.
  814. """
  815. def drop_index(
  816. index_name: str,
  817. table_name: Optional[str] = None,
  818. *,
  819. schema: Optional[str] = None,
  820. if_exists: Optional[bool] = None,
  821. **kw: Any,
  822. ) -> None:
  823. r"""Issue a "drop index" instruction using the current
  824. migration context.
  825. e.g.::
  826. drop_index("accounts")
  827. :param index_name: name of the index.
  828. :param table_name: name of the owning table. Some
  829. backends such as Microsoft SQL Server require this.
  830. :param schema: Optional schema name to operate within. To control
  831. quoting of the schema outside of the default behavior, use
  832. the SQLAlchemy construct
  833. :class:`~sqlalchemy.sql.elements.quoted_name`.
  834. :param if_exists: If True, adds IF EXISTS operator when
  835. dropping the index.
  836. .. versionadded:: 1.12.0
  837. :param \**kw: Additional keyword arguments not mentioned above are
  838. dialect specific, and passed in the form
  839. ``<dialectname>_<argname>``.
  840. See the documentation regarding an individual dialect at
  841. :ref:`dialect_toplevel` for detail on documented arguments.
  842. """
  843. def drop_table(
  844. table_name: str, *, schema: Optional[str] = None, **kw: Any
  845. ) -> None:
  846. r"""Issue a "drop table" instruction using the current
  847. migration context.
  848. e.g.::
  849. drop_table("accounts")
  850. :param table_name: Name of the table
  851. :param schema: Optional schema name to operate within. To control
  852. quoting of the schema outside of the default behavior, use
  853. the SQLAlchemy construct
  854. :class:`~sqlalchemy.sql.elements.quoted_name`.
  855. :param \**kw: Other keyword arguments are passed to the underlying
  856. :class:`sqlalchemy.schema.Table` object created for the command.
  857. """
  858. def drop_table_comment(
  859. table_name: str,
  860. *,
  861. existing_comment: Optional[str] = None,
  862. schema: Optional[str] = None,
  863. ) -> None:
  864. """Issue a "drop table comment" operation to
  865. remove an existing comment set on a table.
  866. :param table_name: string name of the target table.
  867. :param existing_comment: An optional string value of a comment already
  868. registered on the specified table.
  869. .. seealso::
  870. :meth:`.Operations.create_table_comment`
  871. :paramref:`.Operations.alter_column.comment`
  872. """
  873. def execute(
  874. sqltext: Union[Executable, str],
  875. *,
  876. execution_options: Optional[dict[str, Any]] = None,
  877. ) -> None:
  878. r"""Execute the given SQL using the current migration context.
  879. The given SQL can be a plain string, e.g.::
  880. op.execute("INSERT INTO table (foo) VALUES ('some value')")
  881. Or it can be any kind of Core SQL Expression construct, such as
  882. below where we use an update construct::
  883. from sqlalchemy.sql import table, column
  884. from sqlalchemy import String
  885. from alembic import op
  886. account = table("account", column("name", String))
  887. op.execute(
  888. account.update()
  889. .where(account.c.name == op.inline_literal("account 1"))
  890. .values({"name": op.inline_literal("account 2")})
  891. )
  892. Above, we made use of the SQLAlchemy
  893. :func:`sqlalchemy.sql.expression.table` and
  894. :func:`sqlalchemy.sql.expression.column` constructs to make a brief,
  895. ad-hoc table construct just for our UPDATE statement. A full
  896. :class:`~sqlalchemy.schema.Table` construct of course works perfectly
  897. fine as well, though note it's a recommended practice to at least
  898. ensure the definition of a table is self-contained within the migration
  899. script, rather than imported from a module that may break compatibility
  900. with older migrations.
  901. In a SQL script context, the statement is emitted directly to the
  902. output stream. There is *no* return result, however, as this
  903. function is oriented towards generating a change script
  904. that can run in "offline" mode. Additionally, parameterized
  905. statements are discouraged here, as they *will not work* in offline
  906. mode. Above, we use :meth:`.inline_literal` where parameters are
  907. to be used.
  908. For full interaction with a connected database where parameters can
  909. also be used normally, use the "bind" available from the context::
  910. from alembic import op
  911. connection = op.get_bind()
  912. connection.execute(
  913. account.update()
  914. .where(account.c.name == "account 1")
  915. .values({"name": "account 2"})
  916. )
  917. Additionally, when passing the statement as a plain string, it is first
  918. coerced into a :func:`sqlalchemy.sql.expression.text` construct
  919. before being passed along. In the less likely case that the
  920. literal SQL string contains a colon, it must be escaped with a
  921. backslash, as::
  922. op.execute(r"INSERT INTO table (foo) VALUES ('\:colon_value')")
  923. :param sqltext: Any legal SQLAlchemy expression, including:
  924. * a string
  925. * a :func:`sqlalchemy.sql.expression.text` construct.
  926. * a :func:`sqlalchemy.sql.expression.insert` construct.
  927. * a :func:`sqlalchemy.sql.expression.update` construct.
  928. * a :func:`sqlalchemy.sql.expression.delete` construct.
  929. * Any "executable" described in SQLAlchemy Core documentation,
  930. noting that no result set is returned.
  931. .. note:: when passing a plain string, the statement is coerced into
  932. a :func:`sqlalchemy.sql.expression.text` construct. This construct
  933. considers symbols with colons, e.g. ``:foo`` to be bound parameters.
  934. To avoid this, ensure that colon symbols are escaped, e.g.
  935. ``\:foo``.
  936. :param execution_options: Optional dictionary of
  937. execution options, will be passed to
  938. :meth:`sqlalchemy.engine.Connection.execution_options`.
  939. """
  940. def f(name: str) -> conv:
  941. """Indicate a string name that has already had a naming convention
  942. applied to it.
  943. This feature combines with the SQLAlchemy ``naming_convention`` feature
  944. to disambiguate constraint names that have already had naming
  945. conventions applied to them, versus those that have not. This is
  946. necessary in the case that the ``"%(constraint_name)s"`` token
  947. is used within a naming convention, so that it can be identified
  948. that this particular name should remain fixed.
  949. If the :meth:`.Operations.f` is used on a constraint, the naming
  950. convention will not take effect::
  951. op.add_column("t", "x", Boolean(name=op.f("ck_bool_t_x")))
  952. Above, the CHECK constraint generated will have the name
  953. ``ck_bool_t_x`` regardless of whether or not a naming convention is
  954. in use.
  955. Alternatively, if a naming convention is in use, and 'f' is not used,
  956. names will be converted along conventions. If the ``target_metadata``
  957. contains the naming convention
  958. ``{"ck": "ck_bool_%(table_name)s_%(constraint_name)s"}``, then the
  959. output of the following:
  960. op.add_column("t", "x", Boolean(name="x"))
  961. will be::
  962. CONSTRAINT ck_bool_t_x CHECK (x in (1, 0)))
  963. The function is rendered in the output of autogenerate when
  964. a particular constraint name is already converted.
  965. """
  966. def get_bind() -> Connection:
  967. """Return the current 'bind'.
  968. Under normal circumstances, this is the
  969. :class:`~sqlalchemy.engine.Connection` currently being used
  970. to emit SQL to the database.
  971. In a SQL script context, this value is ``None``. [TODO: verify this]
  972. """
  973. def get_context() -> MigrationContext:
  974. """Return the :class:`.MigrationContext` object that's
  975. currently in use.
  976. """
  977. def implementation_for(op_cls: Any) -> Callable[[_C], _C]:
  978. """Register an implementation for a given :class:`.MigrateOperation`.
  979. This is part of the operation extensibility API.
  980. .. seealso::
  981. :ref:`operation_plugins` - example of use
  982. """
  983. def inline_literal(
  984. value: Union[str, int], type_: Optional[TypeEngine[Any]] = None
  985. ) -> _literal_bindparam:
  986. r"""Produce an 'inline literal' expression, suitable for
  987. using in an INSERT, UPDATE, or DELETE statement.
  988. When using Alembic in "offline" mode, CRUD operations
  989. aren't compatible with SQLAlchemy's default behavior surrounding
  990. literal values,
  991. which is that they are converted into bound values and passed
  992. separately into the ``execute()`` method of the DBAPI cursor.
  993. An offline SQL
  994. script needs to have these rendered inline. While it should
  995. always be noted that inline literal values are an **enormous**
  996. security hole in an application that handles untrusted input,
  997. a schema migration is not run in this context, so
  998. literals are safe to render inline, with the caveat that
  999. advanced types like dates may not be supported directly
  1000. by SQLAlchemy.
  1001. See :meth:`.Operations.execute` for an example usage of
  1002. :meth:`.Operations.inline_literal`.
  1003. The environment can also be configured to attempt to render
  1004. "literal" values inline automatically, for those simple types
  1005. that are supported by the dialect; see
  1006. :paramref:`.EnvironmentContext.configure.literal_binds` for this
  1007. more recently added feature.
  1008. :param value: The value to render. Strings, integers, and simple
  1009. numerics should be supported. Other types like boolean,
  1010. dates, etc. may or may not be supported yet by various
  1011. backends.
  1012. :param type\_: optional - a :class:`sqlalchemy.types.TypeEngine`
  1013. subclass stating the type of this value. In SQLAlchemy
  1014. expressions, this is usually derived automatically
  1015. from the Python type of the value itself, as well as
  1016. based on the context in which the value is used.
  1017. .. seealso::
  1018. :paramref:`.EnvironmentContext.configure.literal_binds`
  1019. """
  1020. @overload
  1021. def invoke(operation: CreateTableOp) -> Table: ...
  1022. @overload
  1023. def invoke(
  1024. operation: Union[
  1025. AddConstraintOp,
  1026. DropConstraintOp,
  1027. CreateIndexOp,
  1028. DropIndexOp,
  1029. AddColumnOp,
  1030. AlterColumnOp,
  1031. AlterTableOp,
  1032. CreateTableCommentOp,
  1033. DropTableCommentOp,
  1034. DropColumnOp,
  1035. BulkInsertOp,
  1036. DropTableOp,
  1037. ExecuteSQLOp,
  1038. ]
  1039. ) -> None: ...
  1040. @overload
  1041. def invoke(operation: MigrateOperation) -> Any:
  1042. """Given a :class:`.MigrateOperation`, invoke it in terms of
  1043. this :class:`.Operations` instance.
  1044. """
  1045. def register_operation(
  1046. name: str, sourcename: Optional[str] = None
  1047. ) -> Callable[[Type[_T]], Type[_T]]:
  1048. """Register a new operation for this class.
  1049. This method is normally used to add new operations
  1050. to the :class:`.Operations` class, and possibly the
  1051. :class:`.BatchOperations` class as well. All Alembic migration
  1052. operations are implemented via this system, however the system
  1053. is also available as a public API to facilitate adding custom
  1054. operations.
  1055. .. seealso::
  1056. :ref:`operation_plugins`
  1057. """
  1058. def rename_table(
  1059. old_table_name: str, new_table_name: str, *, schema: Optional[str] = None
  1060. ) -> None:
  1061. """Emit an ALTER TABLE to rename a table.
  1062. :param old_table_name: old name.
  1063. :param new_table_name: new name.
  1064. :param schema: Optional schema name to operate within. To control
  1065. quoting of the schema outside of the default behavior, use
  1066. the SQLAlchemy construct
  1067. :class:`~sqlalchemy.sql.elements.quoted_name`.
  1068. """
  1069. def run_async(
  1070. async_function: Callable[..., Awaitable[_T]], *args: Any, **kw_args: Any
  1071. ) -> _T:
  1072. """Invoke the given asynchronous callable, passing an asynchronous
  1073. :class:`~sqlalchemy.ext.asyncio.AsyncConnection` as the first
  1074. argument.
  1075. This method allows calling async functions from within the
  1076. synchronous ``upgrade()`` or ``downgrade()`` alembic migration
  1077. method.
  1078. The async connection passed to the callable shares the same
  1079. transaction as the connection running in the migration context.
  1080. Any additional arg or kw_arg passed to this function are passed
  1081. to the provided async function.
  1082. .. versionadded: 1.11
  1083. .. note::
  1084. This method can be called only when alembic is called using
  1085. an async dialect.
  1086. """