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