op.pyi 50 KB

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