aboutsummaryrefslogtreecommitdiff
path: root/.venv/lib/python3.12/site-packages/alembic/operations/base.py
blob: 456d1c75bb39eca98417bd491c5cdd50384ef440 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
# mypy: allow-untyped-calls

from __future__ import annotations

from contextlib import contextmanager
import re
import textwrap
from typing import Any
from typing import Awaitable
from typing import Callable
from typing import Dict
from typing import Iterator
from typing import List  # noqa
from typing import Mapping
from typing import NoReturn
from typing import Optional
from typing import overload
from typing import Sequence  # noqa
from typing import Tuple
from typing import Type  # noqa
from typing import TYPE_CHECKING
from typing import TypeVar
from typing import Union

from sqlalchemy.sql.elements import conv

from . import batch
from . import schemaobj
from .. import util
from ..util import sqla_compat
from ..util.compat import formatannotation_fwdref
from ..util.compat import inspect_formatargspec
from ..util.compat import inspect_getfullargspec
from ..util.sqla_compat import _literal_bindparam


if TYPE_CHECKING:
    from typing import Literal

    from sqlalchemy import Table
    from sqlalchemy.engine import Connection
    from sqlalchemy.sql import Executable
    from sqlalchemy.sql.expression import ColumnElement
    from sqlalchemy.sql.expression import TableClause
    from sqlalchemy.sql.expression import TextClause
    from sqlalchemy.sql.schema import Column
    from sqlalchemy.sql.schema import Computed
    from sqlalchemy.sql.schema import Identity
    from sqlalchemy.sql.schema import SchemaItem
    from sqlalchemy.types import TypeEngine

    from .batch import BatchOperationsImpl
    from .ops import AddColumnOp
    from .ops import AddConstraintOp
    from .ops import AlterColumnOp
    from .ops import AlterTableOp
    from .ops import BulkInsertOp
    from .ops import CreateIndexOp
    from .ops import CreateTableCommentOp
    from .ops import CreateTableOp
    from .ops import DropColumnOp
    from .ops import DropConstraintOp
    from .ops import DropIndexOp
    from .ops import DropTableCommentOp
    from .ops import DropTableOp
    from .ops import ExecuteSQLOp
    from .ops import MigrateOperation
    from ..ddl import DefaultImpl
    from ..runtime.migration import MigrationContext
__all__ = ("Operations", "BatchOperations")
_T = TypeVar("_T")

_C = TypeVar("_C", bound=Callable[..., Any])


class AbstractOperations(util.ModuleClsProxy):
    """Base class for Operations and BatchOperations.

    .. versionadded:: 1.11.0

    """

    impl: Union[DefaultImpl, BatchOperationsImpl]
    _to_impl = util.Dispatcher()

    def __init__(
        self,
        migration_context: MigrationContext,
        impl: Optional[BatchOperationsImpl] = None,
    ) -> None:
        """Construct a new :class:`.Operations`

        :param migration_context: a :class:`.MigrationContext`
         instance.

        """
        self.migration_context = migration_context
        if impl is None:
            self.impl = migration_context.impl
        else:
            self.impl = impl

        self.schema_obj = schemaobj.SchemaObjects(migration_context)

    @classmethod
    def register_operation(
        cls, name: str, sourcename: Optional[str] = None
    ) -> Callable[[Type[_T]], Type[_T]]:
        """Register a new operation for this class.

        This method is normally used to add new operations
        to the :class:`.Operations` class, and possibly the
        :class:`.BatchOperations` class as well.   All Alembic migration
        operations are implemented via this system, however the system
        is also available as a public API to facilitate adding custom
        operations.

        .. seealso::

            :ref:`operation_plugins`


        """

        def register(op_cls: Type[_T]) -> Type[_T]:
            if sourcename is None:
                fn = getattr(op_cls, name)
                source_name = fn.__name__
            else:
                fn = getattr(op_cls, sourcename)
                source_name = fn.__name__

            spec = inspect_getfullargspec(fn)

            name_args = spec[0]
            assert name_args[0:2] == ["cls", "operations"]

            name_args[0:2] = ["self"]

            args = inspect_formatargspec(
                *spec, formatannotation=formatannotation_fwdref
            )
            num_defaults = len(spec[3]) if spec[3] else 0

            defaulted_vals: Tuple[Any, ...]

            if num_defaults:
                defaulted_vals = tuple(name_args[0 - num_defaults :])
            else:
                defaulted_vals = ()

            defaulted_vals += tuple(spec[4])
            # here, we are using formatargspec in a different way in order
            # to get a string that will re-apply incoming arguments to a new
            # function call

            apply_kw = inspect_formatargspec(
                name_args + spec[4],
                spec[1],
                spec[2],
                defaulted_vals,
                formatvalue=lambda x: "=" + x,
                formatannotation=formatannotation_fwdref,
            )

            args = re.sub(
                r'[_]?ForwardRef\(([\'"].+?[\'"])\)',
                lambda m: m.group(1),
                args,
            )

            func_text = textwrap.dedent(
                """\
            def %(name)s%(args)s:
                %(doc)r
                return op_cls.%(source_name)s%(apply_kw)s
            """
                % {
                    "name": name,
                    "source_name": source_name,
                    "args": args,
                    "apply_kw": apply_kw,
                    "doc": fn.__doc__,
                }
            )

            globals_ = dict(globals())
            globals_.update({"op_cls": op_cls})
            lcl: Dict[str, Any] = {}

            exec(func_text, globals_, lcl)
            setattr(cls, name, lcl[name])
            fn.__func__.__doc__ = (
                "This method is proxied on "
                "the :class:`.%s` class, via the :meth:`.%s.%s` method."
                % (cls.__name__, cls.__name__, name)
            )
            if hasattr(fn, "_legacy_translations"):
                lcl[name]._legacy_translations = fn._legacy_translations
            return op_cls

        return register

    @classmethod
    def implementation_for(cls, op_cls: Any) -> Callable[[_C], _C]:
        """Register an implementation for a given :class:`.MigrateOperation`.

        This is part of the operation extensibility API.

        .. seealso::

            :ref:`operation_plugins` - example of use

        """

        def decorate(fn: _C) -> _C:
            cls._to_impl.dispatch_for(op_cls)(fn)
            return fn

        return decorate

    @classmethod
    @contextmanager
    def context(
        cls, migration_context: MigrationContext
    ) -> Iterator[Operations]:
        op = Operations(migration_context)
        op._install_proxy()
        yield op
        op._remove_proxy()

    @contextmanager
    def batch_alter_table(
        self,
        table_name: str,
        schema: Optional[str] = None,
        recreate: Literal["auto", "always", "never"] = "auto",
        partial_reordering: Optional[Tuple[Any, ...]] = None,
        copy_from: Optional[Table] = None,
        table_args: Tuple[Any, ...] = (),
        table_kwargs: Mapping[str, Any] = util.immutabledict(),
        reflect_args: Tuple[Any, ...] = (),
        reflect_kwargs: Mapping[str, Any] = util.immutabledict(),
        naming_convention: Optional[Dict[str, str]] = None,
    ) -> Iterator[BatchOperations]:
        """Invoke a series of per-table migrations in batch.

        Batch mode allows a series of operations specific to a table
        to be syntactically grouped together, and allows for alternate
        modes of table migration, in particular the "recreate" style of
        migration required by SQLite.

        "recreate" style is as follows:

        1. A new table is created with the new specification, based on the
           migration directives within the batch, using a temporary name.

        2. the data copied from the existing table to the new table.

        3. the existing table is dropped.

        4. the new table is renamed to the existing table name.

        The directive by default will only use "recreate" style on the
        SQLite backend, and only if directives are present which require
        this form, e.g. anything other than ``add_column()``.   The batch
        operation on other backends will proceed using standard ALTER TABLE
        operations.

        The method is used as a context manager, which returns an instance
        of :class:`.BatchOperations`; this object is the same as
        :class:`.Operations` except that table names and schema names
        are omitted.  E.g.::

            with op.batch_alter_table("some_table") as batch_op:
                batch_op.add_column(Column("foo", Integer))
                batch_op.drop_column("bar")

        The operations within the context manager are invoked at once
        when the context is ended.   When run against SQLite, if the
        migrations include operations not supported by SQLite's ALTER TABLE,
        the entire table will be copied to a new one with the new
        specification, moving all data across as well.

        The copy operation by default uses reflection to retrieve the current
        structure of the table, and therefore :meth:`.batch_alter_table`
        in this mode requires that the migration is run in "online" mode.
        The ``copy_from`` parameter may be passed which refers to an existing
        :class:`.Table` object, which will bypass this reflection step.

        .. note::  The table copy operation will currently not copy
           CHECK constraints, and may not copy UNIQUE constraints that are
           unnamed, as is possible on SQLite.   See the section
           :ref:`sqlite_batch_constraints` for workarounds.

        :param table_name: name of table
        :param schema: optional schema name.
        :param recreate: under what circumstances the table should be
         recreated. At its default of ``"auto"``, the SQLite dialect will
         recreate the table if any operations other than ``add_column()``,
         ``create_index()``, or ``drop_index()`` are
         present. Other options include ``"always"`` and ``"never"``.
        :param copy_from: optional :class:`~sqlalchemy.schema.Table` object
         that will act as the structure of the table being copied.  If omitted,
         table reflection is used to retrieve the structure of the table.

         .. seealso::

            :ref:`batch_offline_mode`

            :paramref:`~.Operations.batch_alter_table.reflect_args`

            :paramref:`~.Operations.batch_alter_table.reflect_kwargs`

        :param reflect_args: a sequence of additional positional arguments that
         will be applied to the table structure being reflected / copied;
         this may be used to pass column and constraint overrides to the
         table that will be reflected, in lieu of passing the whole
         :class:`~sqlalchemy.schema.Table` using
         :paramref:`~.Operations.batch_alter_table.copy_from`.
        :param reflect_kwargs: a dictionary of additional keyword arguments
         that will be applied to the table structure being copied; this may be
         used to pass additional table and reflection options to the table that
         will be reflected, in lieu of passing the whole
         :class:`~sqlalchemy.schema.Table` using
         :paramref:`~.Operations.batch_alter_table.copy_from`.
        :param table_args: a sequence of additional positional arguments that
         will be applied to the new :class:`~sqlalchemy.schema.Table` when
         created, in addition to those copied from the source table.
         This may be used to provide additional constraints such as CHECK
         constraints that may not be reflected.
        :param table_kwargs: a dictionary of additional keyword arguments
         that will be applied to the new :class:`~sqlalchemy.schema.Table`
         when created, in addition to those copied from the source table.
         This may be used to provide for additional table options that may
         not be reflected.
        :param naming_convention: a naming convention dictionary of the form
         described at :ref:`autogen_naming_conventions` which will be applied
         to the :class:`~sqlalchemy.schema.MetaData` during the reflection
         process.  This is typically required if one wants to drop SQLite
         constraints, as these constraints will not have names when
         reflected on this backend.  Requires SQLAlchemy **0.9.4** or greater.

         .. seealso::

            :ref:`dropping_sqlite_foreign_keys`

        :param partial_reordering: a list of tuples, each suggesting a desired
         ordering of two or more columns in the newly created table.  Requires
         that :paramref:`.batch_alter_table.recreate` is set to ``"always"``.
         Examples, given a table with columns "a", "b", "c", and "d":

         Specify the order of all columns::

            with op.batch_alter_table(
                "some_table",
                recreate="always",
                partial_reordering=[("c", "d", "a", "b")],
            ) as batch_op:
                pass

         Ensure "d" appears before "c", and "b", appears before "a"::

            with op.batch_alter_table(
                "some_table",
                recreate="always",
                partial_reordering=[("d", "c"), ("b", "a")],
            ) as batch_op:
                pass

         The ordering of columns not included in the partial_reordering
         set is undefined.   Therefore it is best to specify the complete
         ordering of all columns for best results.

        .. note:: batch mode requires SQLAlchemy 0.8 or above.

        .. seealso::

            :ref:`batch_migrations`

        """
        impl = batch.BatchOperationsImpl(
            self,
            table_name,
            schema,
            recreate,
            copy_from,
            table_args,
            table_kwargs,
            reflect_args,
            reflect_kwargs,
            naming_convention,
            partial_reordering,
        )
        batch_op = BatchOperations(self.migration_context, impl=impl)
        yield batch_op
        impl.flush()

    def get_context(self) -> MigrationContext:
        """Return the :class:`.MigrationContext` object that's
        currently in use.

        """

        return self.migration_context

    @overload
    def invoke(self, operation: CreateTableOp) -> Table: ...

    @overload
    def invoke(
        self,
        operation: Union[
            AddConstraintOp,
            DropConstraintOp,
            CreateIndexOp,
            DropIndexOp,
            AddColumnOp,
            AlterColumnOp,
            AlterTableOp,
            CreateTableCommentOp,
            DropTableCommentOp,
            DropColumnOp,
            BulkInsertOp,
            DropTableOp,
            ExecuteSQLOp,
        ],
    ) -> None: ...

    @overload
    def invoke(self, operation: MigrateOperation) -> Any: ...

    def invoke(self, operation: MigrateOperation) -> Any:
        """Given a :class:`.MigrateOperation`, invoke it in terms of
        this :class:`.Operations` instance.

        """
        fn = self._to_impl.dispatch(
            operation, self.migration_context.impl.__dialect__
        )
        return fn(self, operation)

    def f(self, name: str) -> conv:
        """Indicate a string name that has already had a naming convention
        applied to it.

        This feature combines with the SQLAlchemy ``naming_convention`` feature
        to disambiguate constraint names that have already had naming
        conventions applied to them, versus those that have not.  This is
        necessary in the case that the ``"%(constraint_name)s"`` token
        is used within a naming convention, so that it can be identified
        that this particular name should remain fixed.

        If the :meth:`.Operations.f` is used on a constraint, the naming
        convention will not take effect::

            op.add_column("t", "x", Boolean(name=op.f("ck_bool_t_x")))

        Above, the CHECK constraint generated will have the name
        ``ck_bool_t_x`` regardless of whether or not a naming convention is
        in use.

        Alternatively, if a naming convention is in use, and 'f' is not used,
        names will be converted along conventions.  If the ``target_metadata``
        contains the naming convention
        ``{"ck": "ck_bool_%(table_name)s_%(constraint_name)s"}``, then the
        output of the following:

            op.add_column("t", "x", Boolean(name="x"))

        will be::

            CONSTRAINT ck_bool_t_x CHECK (x in (1, 0)))

        The function is rendered in the output of autogenerate when
        a particular constraint name is already converted.

        """
        return conv(name)

    def inline_literal(
        self, value: Union[str, int], type_: Optional[TypeEngine[Any]] = None
    ) -> _literal_bindparam:
        r"""Produce an 'inline literal' expression, suitable for
        using in an INSERT, UPDATE, or DELETE statement.

        When using Alembic in "offline" mode, CRUD operations
        aren't compatible with SQLAlchemy's default behavior surrounding
        literal values,
        which is that they are converted into bound values and passed
        separately into the ``execute()`` method of the DBAPI cursor.
        An offline SQL
        script needs to have these rendered inline.  While it should
        always be noted that inline literal values are an **enormous**
        security hole in an application that handles untrusted input,
        a schema migration is not run in this context, so
        literals are safe to render inline, with the caveat that
        advanced types like dates may not be supported directly
        by SQLAlchemy.

        See :meth:`.Operations.execute` for an example usage of
        :meth:`.Operations.inline_literal`.

        The environment can also be configured to attempt to render
        "literal" values inline automatically, for those simple types
        that are supported by the dialect; see
        :paramref:`.EnvironmentContext.configure.literal_binds` for this
        more recently added feature.

        :param value: The value to render.  Strings, integers, and simple
         numerics should be supported.   Other types like boolean,
         dates, etc. may or may not be supported yet by various
         backends.
        :param type\_: optional - a :class:`sqlalchemy.types.TypeEngine`
         subclass stating the type of this value.  In SQLAlchemy
         expressions, this is usually derived automatically
         from the Python type of the value itself, as well as
         based on the context in which the value is used.

        .. seealso::

            :paramref:`.EnvironmentContext.configure.literal_binds`

        """
        return sqla_compat._literal_bindparam(None, value, type_=type_)

    def get_bind(self) -> Connection:
        """Return the current 'bind'.

        Under normal circumstances, this is the
        :class:`~sqlalchemy.engine.Connection` currently being used
        to emit SQL to the database.

        In a SQL script context, this value is ``None``. [TODO: verify this]

        """
        return self.migration_context.impl.bind  # type: ignore[return-value]

    def run_async(
        self,
        async_function: Callable[..., Awaitable[_T]],
        *args: Any,
        **kw_args: Any,
    ) -> _T:
        """Invoke the given asynchronous callable, passing an asynchronous
        :class:`~sqlalchemy.ext.asyncio.AsyncConnection` as the first
        argument.

        This method allows calling async functions from within the
        synchronous ``upgrade()`` or ``downgrade()`` alembic migration
        method.

        The async connection passed to the callable shares the same
        transaction as the connection running in the migration context.

        Any additional arg or kw_arg passed to this function are passed
        to the provided async function.

        .. versionadded: 1.11

        .. note::

            This method can be called only when alembic is called using
            an async dialect.
        """
        if not sqla_compat.sqla_14_18:
            raise NotImplementedError("SQLAlchemy 1.4.18+ required")
        sync_conn = self.get_bind()
        if sync_conn is None:
            raise NotImplementedError("Cannot call run_async in SQL mode")
        if not sync_conn.dialect.is_async:
            raise ValueError("Cannot call run_async with a sync engine")
        from sqlalchemy.ext.asyncio import AsyncConnection
        from sqlalchemy.util import await_only

        async_conn = AsyncConnection._retrieve_proxy_for_target(sync_conn)
        return await_only(async_function(async_conn, *args, **kw_args))


class Operations(AbstractOperations):
    """Define high level migration operations.

    Each operation corresponds to some schema migration operation,
    executed against a particular :class:`.MigrationContext`
    which in turn represents connectivity to a database,
    or a file output stream.

    While :class:`.Operations` is normally configured as
    part of the :meth:`.EnvironmentContext.run_migrations`
    method called from an ``env.py`` script, a standalone
    :class:`.Operations` instance can be
    made for use cases external to regular Alembic
    migrations by passing in a :class:`.MigrationContext`::

        from alembic.migration import MigrationContext
        from alembic.operations import Operations

        conn = myengine.connect()
        ctx = MigrationContext.configure(conn)
        op = Operations(ctx)

        op.alter_column("t", "c", nullable=True)

    Note that as of 0.8, most of the methods on this class are produced
    dynamically using the :meth:`.Operations.register_operation`
    method.

    """

    if TYPE_CHECKING:
        # START STUB FUNCTIONS: op_cls
        # ### the following stubs are generated by tools/write_pyi.py ###
        # ### do not edit ###

        def add_column(
            self,
            table_name: str,
            column: Column[Any],
            *,
            schema: Optional[str] = None,
        ) -> None:
            """Issue an "add column" instruction using the current
            migration context.

            e.g.::

                from alembic import op
                from sqlalchemy import Column, String

                op.add_column("organization", Column("name", String()))

            The :meth:`.Operations.add_column` method typically corresponds
            to the SQL command "ALTER TABLE... ADD COLUMN".    Within the scope
            of this command, the column's name, datatype, nullability,
            and optional server-generated defaults may be indicated.

            .. note::

                With the exception of NOT NULL constraints or single-column FOREIGN
                KEY constraints, other kinds of constraints such as PRIMARY KEY,
                UNIQUE or CHECK constraints **cannot** be generated using this
                method; for these constraints, refer to operations such as
                :meth:`.Operations.create_primary_key` and
                :meth:`.Operations.create_check_constraint`. In particular, the
                following :class:`~sqlalchemy.schema.Column` parameters are
                **ignored**:

                * :paramref:`~sqlalchemy.schema.Column.primary_key` - SQL databases
                  typically do not support an ALTER operation that can add
                  individual columns one at a time to an existing primary key
                  constraint, therefore it's less ambiguous to use the
                  :meth:`.Operations.create_primary_key` method, which assumes no
                  existing primary key constraint is present.
                * :paramref:`~sqlalchemy.schema.Column.unique` - use the
                  :meth:`.Operations.create_unique_constraint` method
                * :paramref:`~sqlalchemy.schema.Column.index` - use the
                  :meth:`.Operations.create_index` method


            The provided :class:`~sqlalchemy.schema.Column` object may include a
            :class:`~sqlalchemy.schema.ForeignKey` constraint directive,
            referencing a remote table name. For this specific type of constraint,
            Alembic will automatically emit a second ALTER statement in order to
            add the single-column FOREIGN KEY constraint separately::

                from alembic import op
                from sqlalchemy import Column, INTEGER, ForeignKey

                op.add_column(
                    "organization",
                    Column("account_id", INTEGER, ForeignKey("accounts.id")),
                )

            The column argument passed to :meth:`.Operations.add_column` is a
            :class:`~sqlalchemy.schema.Column` construct, used in the same way it's
            used in SQLAlchemy. In particular, values or functions to be indicated
            as producing the column's default value on the database side are
            specified using the ``server_default`` parameter, and not ``default``
            which only specifies Python-side defaults::

                from alembic import op
                from sqlalchemy import Column, TIMESTAMP, func

                # specify "DEFAULT NOW" along with the column add
                op.add_column(
                    "account",
                    Column("timestamp", TIMESTAMP, server_default=func.now()),
                )

            :param table_name: String name of the parent table.
            :param column: a :class:`sqlalchemy.schema.Column` object
             representing the new column.
            :param schema: Optional schema name to operate within.  To control
             quoting of the schema outside of the default behavior, use
             the SQLAlchemy construct
             :class:`~sqlalchemy.sql.elements.quoted_name`.

            """  # noqa: E501
            ...

        def alter_column(
            self,
            table_name: str,
            column_name: str,
            *,
            nullable: Optional[bool] = None,
            comment: Union[str, Literal[False], None] = False,
            server_default: Any = False,
            new_column_name: Optional[str] = None,
            type_: Union[TypeEngine[Any], Type[TypeEngine[Any]], None] = None,
            existing_type: Union[
                TypeEngine[Any], Type[TypeEngine[Any]], None
            ] = None,
            existing_server_default: Union[
                str, bool, Identity, Computed, None
            ] = False,
            existing_nullable: Optional[bool] = None,
            existing_comment: Optional[str] = None,
            schema: Optional[str] = None,
            **kw: Any,
        ) -> None:
            r"""Issue an "alter column" instruction using the
            current migration context.

            Generally, only that aspect of the column which
            is being changed, i.e. name, type, nullability,
            default, needs to be specified.  Multiple changes
            can also be specified at once and the backend should
            "do the right thing", emitting each change either
            separately or together as the backend allows.

            MySQL has special requirements here, since MySQL
            cannot ALTER a column without a full specification.
            When producing MySQL-compatible migration files,
            it is recommended that the ``existing_type``,
            ``existing_server_default``, and ``existing_nullable``
            parameters be present, if not being altered.

            Type changes which are against the SQLAlchemy
            "schema" types :class:`~sqlalchemy.types.Boolean`
            and  :class:`~sqlalchemy.types.Enum` may also
            add or drop constraints which accompany those
            types on backends that don't support them natively.
            The ``existing_type`` argument is
            used in this case to identify and remove a previous
            constraint that was bound to the type object.

            :param table_name: string name of the target table.
            :param column_name: string name of the target column,
             as it exists before the operation begins.
            :param nullable: Optional; specify ``True`` or ``False``
             to alter the column's nullability.
            :param server_default: Optional; specify a string
             SQL expression, :func:`~sqlalchemy.sql.expression.text`,
             or :class:`~sqlalchemy.schema.DefaultClause` to indicate
             an alteration to the column's default value.
             Set to ``None`` to have the default removed.
            :param comment: optional string text of a new comment to add to the
             column.
            :param new_column_name: Optional; specify a string name here to
             indicate the new name within a column rename operation.
            :param type\_: Optional; a :class:`~sqlalchemy.types.TypeEngine`
             type object to specify a change to the column's type.
             For SQLAlchemy types that also indicate a constraint (i.e.
             :class:`~sqlalchemy.types.Boolean`, :class:`~sqlalchemy.types.Enum`),
             the constraint is also generated.
            :param autoincrement: set the ``AUTO_INCREMENT`` flag of the column;
             currently understood by the MySQL dialect.
            :param existing_type: Optional; a
             :class:`~sqlalchemy.types.TypeEngine`
             type object to specify the previous type.   This
             is required for all MySQL column alter operations that
             don't otherwise specify a new type, as well as for
             when nullability is being changed on a SQL Server
             column.  It is also used if the type is a so-called
             SQLAlchemy "schema" type which may define a constraint (i.e.
             :class:`~sqlalchemy.types.Boolean`,
             :class:`~sqlalchemy.types.Enum`),
             so that the constraint can be dropped.
            :param existing_server_default: Optional; The existing
             default value of the column.   Required on MySQL if
             an existing default is not being changed; else MySQL
             removes the default.
            :param existing_nullable: Optional; the existing nullability
             of the column.  Required on MySQL if the existing nullability
             is not being changed; else MySQL sets this to NULL.
            :param existing_autoincrement: Optional; the existing autoincrement
             of the column.  Used for MySQL's system of altering a column
             that specifies ``AUTO_INCREMENT``.
            :param existing_comment: string text of the existing comment on the
             column to be maintained.  Required on MySQL if the existing comment
             on the column is not being changed.
            :param schema: Optional schema name to operate within.  To control
             quoting of the schema outside of the default behavior, use
             the SQLAlchemy construct
             :class:`~sqlalchemy.sql.elements.quoted_name`.
            :param postgresql_using: String argument which will indicate a
             SQL expression to render within the Postgresql-specific USING clause
             within ALTER COLUMN.    This string is taken directly as raw SQL which
             must explicitly include any necessary quoting or escaping of tokens
             within the expression.

            """  # noqa: E501
            ...

        def bulk_insert(
            self,
            table: Union[Table, TableClause],
            rows: List[Dict[str, Any]],
            *,
            multiinsert: bool = True,
        ) -> None:
            """Issue a "bulk insert" operation using the current
            migration context.

            This provides a means of representing an INSERT of multiple rows
            which works equally well in the context of executing on a live
            connection as well as that of generating a SQL script.   In the
            case of a SQL script, the values are rendered inline into the
            statement.

            e.g.::

                from alembic import op
                from datetime import date
                from sqlalchemy.sql import table, column
                from sqlalchemy import String, Integer, Date

                # Create an ad-hoc table to use for the insert statement.
                accounts_table = table(
                    "account",
                    column("id", Integer),
                    column("name", String),
                    column("create_date", Date),
                )

                op.bulk_insert(
                    accounts_table,
                    [
                        {
                            "id": 1,
                            "name": "John Smith",
                            "create_date": date(2010, 10, 5),
                        },
                        {
                            "id": 2,
                            "name": "Ed Williams",
                            "create_date": date(2007, 5, 27),
                        },
                        {
                            "id": 3,
                            "name": "Wendy Jones",
                            "create_date": date(2008, 8, 15),
                        },
                    ],
                )

            When using --sql mode, some datatypes may not render inline
            automatically, such as dates and other special types.   When this
            issue is present, :meth:`.Operations.inline_literal` may be used::

                op.bulk_insert(
                    accounts_table,
                    [
                        {
                            "id": 1,
                            "name": "John Smith",
                            "create_date": op.inline_literal("2010-10-05"),
                        },
                        {
                            "id": 2,
                            "name": "Ed Williams",
                            "create_date": op.inline_literal("2007-05-27"),
                        },
                        {
                            "id": 3,
                            "name": "Wendy Jones",
                            "create_date": op.inline_literal("2008-08-15"),
                        },
                    ],
                    multiinsert=False,
                )

            When using :meth:`.Operations.inline_literal` in conjunction with
            :meth:`.Operations.bulk_insert`, in order for the statement to work
            in "online" (e.g. non --sql) mode, the
            :paramref:`~.Operations.bulk_insert.multiinsert`
            flag should be set to ``False``, which will have the effect of
            individual INSERT statements being emitted to the database, each
            with a distinct VALUES clause, so that the "inline" values can
            still be rendered, rather than attempting to pass the values
            as bound parameters.

            :param table: a table object which represents the target of the INSERT.

            :param rows: a list of dictionaries indicating rows.

            :param multiinsert: when at its default of True and --sql mode is not
               enabled, the INSERT statement will be executed using
               "executemany()" style, where all elements in the list of
               dictionaries are passed as bound parameters in a single
               list.   Setting this to False results in individual INSERT
               statements being emitted per parameter set, and is needed
               in those cases where non-literal values are present in the
               parameter sets.

            """  # noqa: E501
            ...

        def create_check_constraint(
            self,
            constraint_name: Optional[str],
            table_name: str,
            condition: Union[str, ColumnElement[bool], TextClause],
            *,
            schema: Optional[str] = None,
            **kw: Any,
        ) -> None:
            """Issue a "create check constraint" instruction using the
            current migration context.

            e.g.::

                from alembic import op
                from sqlalchemy.sql import column, func

                op.create_check_constraint(
                    "ck_user_name_len",
                    "user",
                    func.len(column("name")) > 5,
                )

            CHECK constraints are usually against a SQL expression, so ad-hoc
            table metadata is usually needed.   The function will convert the given
            arguments into a :class:`sqlalchemy.schema.CheckConstraint` bound
            to an anonymous table in order to emit the CREATE statement.

            :param name: Name of the check constraint.  The name is necessary
             so that an ALTER statement can be emitted.  For setups that
             use an automated naming scheme such as that described at
             :ref:`sqla:constraint_naming_conventions`,
             ``name`` here can be ``None``, as the event listener will
             apply the name to the constraint object when it is associated
             with the table.
            :param table_name: String name of the source table.
            :param condition: SQL expression that's the condition of the
             constraint. Can be a string or SQLAlchemy expression language
             structure.
            :param deferrable: optional bool. If set, emit DEFERRABLE or
             NOT DEFERRABLE when issuing DDL for this constraint.
            :param initially: optional string. If set, emit INITIALLY <value>
             when issuing DDL for this constraint.
            :param schema: Optional schema name to operate within.  To control
             quoting of the schema outside of the default behavior, use
             the SQLAlchemy construct
             :class:`~sqlalchemy.sql.elements.quoted_name`.

            """  # noqa: E501
            ...

        def create_exclude_constraint(
            self,
            constraint_name: str,
            table_name: str,
            *elements: Any,
            **kw: Any,
        ) -> Optional[Table]:
            """Issue an alter to create an EXCLUDE constraint using the
            current migration context.

            .. note::  This method is Postgresql specific, and additionally
               requires at least SQLAlchemy 1.0.

            e.g.::

                from alembic import op

                op.create_exclude_constraint(
                    "user_excl",
                    "user",
                    ("period", "&&"),
                    ("group", "="),
                    where=("group != 'some group'"),
                )

            Note that the expressions work the same way as that of
            the ``ExcludeConstraint`` object itself; if plain strings are
            passed, quoting rules must be applied manually.

            :param name: Name of the constraint.
            :param table_name: String name of the source table.
            :param elements: exclude conditions.
            :param where: SQL expression or SQL string with optional WHERE
             clause.
            :param deferrable: optional bool. If set, emit DEFERRABLE or
             NOT DEFERRABLE when issuing DDL for this constraint.
            :param initially: optional string. If set, emit INITIALLY <value>
             when issuing DDL for this constraint.
            :param schema: Optional schema name to operate within.

            """  # noqa: E501
            ...

        def create_foreign_key(
            self,
            constraint_name: Optional[str],
            source_table: str,
            referent_table: str,
            local_cols: List[str],
            remote_cols: List[str],
            *,
            onupdate: Optional[str] = None,
            ondelete: Optional[str] = None,
            deferrable: Optional[bool] = None,
            initially: Optional[str] = None,
            match: Optional[str] = None,
            source_schema: Optional[str] = None,
            referent_schema: Optional[str] = None,
            **dialect_kw: Any,
        ) -> None:
            """Issue a "create foreign key" instruction using the
            current migration context.

            e.g.::

                from alembic import op

                op.create_foreign_key(
                    "fk_user_address",
                    "address",
                    "user",
                    ["user_id"],
                    ["id"],
                )

            This internally generates a :class:`~sqlalchemy.schema.Table` object
            containing the necessary columns, then generates a new
            :class:`~sqlalchemy.schema.ForeignKeyConstraint`
            object which it then associates with the
            :class:`~sqlalchemy.schema.Table`.
            Any event listeners associated with this action will be fired
            off normally.   The :class:`~sqlalchemy.schema.AddConstraint`
            construct is ultimately used to generate the ALTER statement.

            :param constraint_name: Name of the foreign key constraint.  The name
             is necessary so that an ALTER statement can be emitted.  For setups
             that use an automated naming scheme such as that described at
             :ref:`sqla:constraint_naming_conventions`,
             ``name`` here can be ``None``, as the event listener will
             apply the name to the constraint object when it is associated
             with the table.
            :param source_table: String name of the source table.
            :param referent_table: String name of the destination table.
            :param local_cols: a list of string column names in the
             source table.
            :param remote_cols: a list of string column names in the
             remote table.
            :param onupdate: Optional string. If set, emit ON UPDATE <value> when
             issuing DDL for this constraint. Typical values include CASCADE,
             DELETE and RESTRICT.
            :param ondelete: Optional string. If set, emit ON DELETE <value> when
             issuing DDL for this constraint. Typical values include CASCADE,
             DELETE and RESTRICT.
            :param deferrable: optional bool. If set, emit DEFERRABLE or NOT
             DEFERRABLE when issuing DDL for this constraint.
            :param source_schema: Optional schema name of the source table.
            :param referent_schema: Optional schema name of the destination table.

            """  # noqa: E501
            ...

        def create_index(
            self,
            index_name: Optional[str],
            table_name: str,
            columns: Sequence[Union[str, TextClause, ColumnElement[Any]]],
            *,
            schema: Optional[str] = None,
            unique: bool = False,
            if_not_exists: Optional[bool] = None,
            **kw: Any,
        ) -> None:
            r"""Issue a "create index" instruction using the current
            migration context.

            e.g.::

                from alembic import op

                op.create_index("ik_test", "t1", ["foo", "bar"])

            Functional indexes can be produced by using the
            :func:`sqlalchemy.sql.expression.text` construct::

                from alembic import op
                from sqlalchemy import text

                op.create_index("ik_test", "t1", [text("lower(foo)")])

            :param index_name: name of the index.
            :param table_name: name of the owning table.
            :param columns: a list consisting of string column names and/or
             :func:`~sqlalchemy.sql.expression.text` constructs.
            :param schema: Optional schema name to operate within.  To control
             quoting of the schema outside of the default behavior, use
             the SQLAlchemy construct
             :class:`~sqlalchemy.sql.elements.quoted_name`.
            :param unique: If True, create a unique index.

            :param quote: Force quoting of this column's name on or off,
             corresponding to ``True`` or ``False``. When left at its default
             of ``None``, the column identifier will be quoted according to
             whether the name is case sensitive (identifiers with at least one
             upper case character are treated as case sensitive), or if it's a
             reserved word. This flag is only needed to force quoting of a
             reserved word which is not known by the SQLAlchemy dialect.

            :param if_not_exists: If True, adds IF NOT EXISTS operator when
             creating the new index.

             .. versionadded:: 1.12.0

            :param \**kw: Additional keyword arguments not mentioned above are
             dialect specific, and passed in the form
             ``<dialectname>_<argname>``.
             See the documentation regarding an individual dialect at
             :ref:`dialect_toplevel` for detail on documented arguments.

            """  # noqa: E501
            ...

        def create_primary_key(
            self,
            constraint_name: Optional[str],
            table_name: str,
            columns: List[str],
            *,
            schema: Optional[str] = None,
        ) -> None:
            """Issue a "create primary key" instruction using the current
            migration context.

            e.g.::

                from alembic import op

                op.create_primary_key("pk_my_table", "my_table", ["id", "version"])

            This internally generates a :class:`~sqlalchemy.schema.Table` object
            containing the necessary columns, then generates a new
            :class:`~sqlalchemy.schema.PrimaryKeyConstraint`
            object which it then associates with the
            :class:`~sqlalchemy.schema.Table`.
            Any event listeners associated with this action will be fired
            off normally.   The :class:`~sqlalchemy.schema.AddConstraint`
            construct is ultimately used to generate the ALTER statement.

            :param constraint_name: Name of the primary key constraint.  The name
             is necessary so that an ALTER statement can be emitted.  For setups
             that use an automated naming scheme such as that described at
             :ref:`sqla:constraint_naming_conventions`
             ``name`` here can be ``None``, as the event listener will
             apply the name to the constraint object when it is associated
             with the table.
            :param table_name: String name of the target table.
            :param columns: a list of string column names to be applied to the
             primary key constraint.
            :param schema: Optional schema name to operate within.  To control
             quoting of the schema outside of the default behavior, use
             the SQLAlchemy construct
             :class:`~sqlalchemy.sql.elements.quoted_name`.

            """  # noqa: E501
            ...

        def create_table(
            self,
            table_name: str,
            *columns: SchemaItem,
            if_not_exists: Optional[bool] = None,
            **kw: Any,
        ) -> Table:
            r"""Issue a "create table" instruction using the current migration
            context.

            This directive receives an argument list similar to that of the
            traditional :class:`sqlalchemy.schema.Table` construct, but without the
            metadata::

                from sqlalchemy import INTEGER, VARCHAR, NVARCHAR, Column
                from alembic import op

                op.create_table(
                    "account",
                    Column("id", INTEGER, primary_key=True),
                    Column("name", VARCHAR(50), nullable=False),
                    Column("description", NVARCHAR(200)),
                    Column("timestamp", TIMESTAMP, server_default=func.now()),
                )

            Note that :meth:`.create_table` accepts
            :class:`~sqlalchemy.schema.Column`
            constructs directly from the SQLAlchemy library.  In particular,
            default values to be created on the database side are
            specified using the ``server_default`` parameter, and not
            ``default`` which only specifies Python-side defaults::

                from alembic import op
                from sqlalchemy import Column, TIMESTAMP, func

                # specify "DEFAULT NOW" along with the "timestamp" column
                op.create_table(
                    "account",
                    Column("id", INTEGER, primary_key=True),
                    Column("timestamp", TIMESTAMP, server_default=func.now()),
                )

            The function also returns a newly created
            :class:`~sqlalchemy.schema.Table` object, corresponding to the table
            specification given, which is suitable for
            immediate SQL operations, in particular
            :meth:`.Operations.bulk_insert`::

                from sqlalchemy import INTEGER, VARCHAR, NVARCHAR, Column
                from alembic import op

                account_table = op.create_table(
                    "account",
                    Column("id", INTEGER, primary_key=True),
                    Column("name", VARCHAR(50), nullable=False),
                    Column("description", NVARCHAR(200)),
                    Column("timestamp", TIMESTAMP, server_default=func.now()),
                )

                op.bulk_insert(
                    account_table,
                    [
                        {"name": "A1", "description": "account 1"},
                        {"name": "A2", "description": "account 2"},
                    ],
                )

            :param table_name: Name of the table
            :param \*columns: collection of :class:`~sqlalchemy.schema.Column`
             objects within
             the table, as well as optional :class:`~sqlalchemy.schema.Constraint`
             objects
             and :class:`~.sqlalchemy.schema.Index` objects.
            :param schema: Optional schema name to operate within.  To control
             quoting of the schema outside of the default behavior, use
             the SQLAlchemy construct
             :class:`~sqlalchemy.sql.elements.quoted_name`.
            :param if_not_exists: If True, adds IF NOT EXISTS operator when
             creating the new table.

             .. versionadded:: 1.13.3
            :param \**kw: Other keyword arguments are passed to the underlying
             :class:`sqlalchemy.schema.Table` object created for the command.

            :return: the :class:`~sqlalchemy.schema.Table` object corresponding
             to the parameters given.

            """  # noqa: E501
            ...

        def create_table_comment(
            self,
            table_name: str,
            comment: Optional[str],
            *,
            existing_comment: Optional[str] = None,
            schema: Optional[str] = None,
        ) -> None:
            """Emit a COMMENT ON operation to set the comment for a table.

            :param table_name: string name of the target table.
            :param comment: string value of the comment being registered against
             the specified table.
            :param existing_comment: String value of a comment
             already registered on the specified table, used within autogenerate
             so that the operation is reversible, but not required for direct
             use.

            .. seealso::

                :meth:`.Operations.drop_table_comment`

                :paramref:`.Operations.alter_column.comment`

            """  # noqa: E501
            ...

        def create_unique_constraint(
            self,
            constraint_name: Optional[str],
            table_name: str,
            columns: Sequence[str],
            *,
            schema: Optional[str] = None,
            **kw: Any,
        ) -> Any:
            """Issue a "create unique constraint" instruction using the
            current migration context.

            e.g.::

                from alembic import op
                op.create_unique_constraint("uq_user_name", "user", ["name"])

            This internally generates a :class:`~sqlalchemy.schema.Table` object
            containing the necessary columns, then generates a new
            :class:`~sqlalchemy.schema.UniqueConstraint`
            object which it then associates with the
            :class:`~sqlalchemy.schema.Table`.
            Any event listeners associated with this action will be fired
            off normally.   The :class:`~sqlalchemy.schema.AddConstraint`
            construct is ultimately used to generate the ALTER statement.

            :param name: Name of the unique constraint.  The name is necessary
             so that an ALTER statement can be emitted.  For setups that
             use an automated naming scheme such as that described at
             :ref:`sqla:constraint_naming_conventions`,
             ``name`` here can be ``None``, as the event listener will
             apply the name to the constraint object when it is associated
             with the table.
            :param table_name: String name of the source table.
            :param columns: a list of string column names in the
             source table.
            :param deferrable: optional bool. If set, emit DEFERRABLE or
             NOT DEFERRABLE when issuing DDL for this constraint.
            :param initially: optional string. If set, emit INITIALLY <value>
             when issuing DDL for this constraint.
            :param schema: Optional schema name to operate within.  To control
             quoting of the schema outside of the default behavior, use
             the SQLAlchemy construct
             :class:`~sqlalchemy.sql.elements.quoted_name`.

            """  # noqa: E501
            ...

        def drop_column(
            self,
            table_name: str,
            column_name: str,
            *,
            schema: Optional[str] = None,
            **kw: Any,
        ) -> None:
            """Issue a "drop column" instruction using the current
            migration context.

            e.g.::

                drop_column("organization", "account_id")

            :param table_name: name of table
            :param column_name: name of column
            :param schema: Optional schema name to operate within.  To control
             quoting of the schema outside of the default behavior, use
             the SQLAlchemy construct
             :class:`~sqlalchemy.sql.elements.quoted_name`.
            :param mssql_drop_check: Optional boolean.  When ``True``, on
             Microsoft SQL Server only, first
             drop the CHECK constraint on the column using a
             SQL-script-compatible
             block that selects into a @variable from sys.check_constraints,
             then exec's a separate DROP CONSTRAINT for that constraint.
            :param mssql_drop_default: Optional boolean.  When ``True``, on
             Microsoft SQL Server only, first
             drop the DEFAULT constraint on the column using a
             SQL-script-compatible
             block that selects into a @variable from sys.default_constraints,
             then exec's a separate DROP CONSTRAINT for that default.
            :param mssql_drop_foreign_key: Optional boolean.  When ``True``, on
             Microsoft SQL Server only, first
             drop a single FOREIGN KEY constraint on the column using a
             SQL-script-compatible
             block that selects into a @variable from
             sys.foreign_keys/sys.foreign_key_columns,
             then exec's a separate DROP CONSTRAINT for that default.  Only
             works if the column has exactly one FK constraint which refers to
             it, at the moment.

            """  # noqa: E501
            ...

        def drop_constraint(
            self,
            constraint_name: str,
            table_name: str,
            type_: Optional[str] = None,
            *,
            schema: Optional[str] = None,
        ) -> None:
            r"""Drop a constraint of the given name, typically via DROP CONSTRAINT.

            :param constraint_name: name of the constraint.
            :param table_name: table name.
            :param type\_: optional, required on MySQL.  can be
             'foreignkey', 'primary', 'unique', or 'check'.
            :param schema: Optional schema name to operate within.  To control
             quoting of the schema outside of the default behavior, use
             the SQLAlchemy construct
             :class:`~sqlalchemy.sql.elements.quoted_name`.

            """  # noqa: E501
            ...

        def drop_index(
            self,
            index_name: str,
            table_name: Optional[str] = None,
            *,
            schema: Optional[str] = None,
            if_exists: Optional[bool] = None,
            **kw: Any,
        ) -> None:
            r"""Issue a "drop index" instruction using the current
            migration context.

            e.g.::

                drop_index("accounts")

            :param index_name: name of the index.
            :param table_name: name of the owning table.  Some
             backends such as Microsoft SQL Server require this.
            :param schema: Optional schema name to operate within.  To control
             quoting of the schema outside of the default behavior, use
             the SQLAlchemy construct
             :class:`~sqlalchemy.sql.elements.quoted_name`.

            :param if_exists: If True, adds IF EXISTS operator when
             dropping the index.

             .. versionadded:: 1.12.0

            :param \**kw: Additional keyword arguments not mentioned above are
             dialect specific, and passed in the form
             ``<dialectname>_<argname>``.
             See the documentation regarding an individual dialect at
             :ref:`dialect_toplevel` for detail on documented arguments.

            """  # noqa: E501
            ...

        def drop_table(
            self,
            table_name: str,
            *,
            schema: Optional[str] = None,
            if_exists: Optional[bool] = None,
            **kw: Any,
        ) -> None:
            r"""Issue a "drop table" instruction using the current
            migration context.


            e.g.::

                drop_table("accounts")

            :param table_name: Name of the table
            :param schema: Optional schema name to operate within.  To control
             quoting of the schema outside of the default behavior, use
             the SQLAlchemy construct
             :class:`~sqlalchemy.sql.elements.quoted_name`.
            :param if_exists: If True, adds IF EXISTS operator when
             dropping the table.

             .. versionadded:: 1.13.3
            :param \**kw: Other keyword arguments are passed to the underlying
             :class:`sqlalchemy.schema.Table` object created for the command.

            """  # noqa: E501
            ...

        def drop_table_comment(
            self,
            table_name: str,
            *,
            existing_comment: Optional[str] = None,
            schema: Optional[str] = None,
        ) -> None:
            """Issue a "drop table comment" operation to
            remove an existing comment set on a table.

            :param table_name: string name of the target table.
            :param existing_comment: An optional string value of a comment already
             registered on the specified table.

            .. seealso::

                :meth:`.Operations.create_table_comment`

                :paramref:`.Operations.alter_column.comment`

            """  # noqa: E501
            ...

        def execute(
            self,
            sqltext: Union[Executable, str],
            *,
            execution_options: Optional[dict[str, Any]] = None,
        ) -> None:
            r"""Execute the given SQL using the current migration context.

            The given SQL can be a plain string, e.g.::

                op.execute("INSERT INTO table (foo) VALUES ('some value')")

            Or it can be any kind of Core SQL Expression construct, such as
            below where we use an update construct::

                from sqlalchemy.sql import table, column
                from sqlalchemy import String
                from alembic import op

                account = table("account", column("name", String))
                op.execute(
                    account.update()
                    .where(account.c.name == op.inline_literal("account 1"))
                    .values({"name": op.inline_literal("account 2")})
                )

            Above, we made use of the SQLAlchemy
            :func:`sqlalchemy.sql.expression.table` and
            :func:`sqlalchemy.sql.expression.column` constructs to make a brief,
            ad-hoc table construct just for our UPDATE statement.  A full
            :class:`~sqlalchemy.schema.Table` construct of course works perfectly
            fine as well, though note it's a recommended practice to at least
            ensure the definition of a table is self-contained within the migration
            script, rather than imported from a module that may break compatibility
            with older migrations.

            In a SQL script context, the statement is emitted directly to the
            output stream.   There is *no* return result, however, as this
            function is oriented towards generating a change script
            that can run in "offline" mode.     Additionally, parameterized
            statements are discouraged here, as they *will not work* in offline
            mode.  Above, we use :meth:`.inline_literal` where parameters are
            to be used.

            For full interaction with a connected database where parameters can
            also be used normally, use the "bind" available from the context::

                from alembic import op

                connection = op.get_bind()

                connection.execute(
                    account.update()
                    .where(account.c.name == "account 1")
                    .values({"name": "account 2"})
                )

            Additionally, when passing the statement as a plain string, it is first
            coerced into a :func:`sqlalchemy.sql.expression.text` construct
            before being passed along.  In the less likely case that the
            literal SQL string contains a colon, it must be escaped with a
            backslash, as::

               op.execute(r"INSERT INTO table (foo) VALUES ('\:colon_value')")


            :param sqltext: Any legal SQLAlchemy expression, including:

            * a string
            * a :func:`sqlalchemy.sql.expression.text` construct.
            * a :func:`sqlalchemy.sql.expression.insert` construct.
            * a :func:`sqlalchemy.sql.expression.update` construct.
            * a :func:`sqlalchemy.sql.expression.delete` construct.
            * Any "executable" described in SQLAlchemy Core documentation,
              noting that no result set is returned.

            .. note::  when passing a plain string, the statement is coerced into
               a :func:`sqlalchemy.sql.expression.text` construct. This construct
               considers symbols with colons, e.g. ``:foo`` to be bound parameters.
               To avoid this, ensure that colon symbols are escaped, e.g.
               ``\:foo``.

            :param execution_options: Optional dictionary of
             execution options, will be passed to
             :meth:`sqlalchemy.engine.Connection.execution_options`.
            """  # noqa: E501
            ...

        def rename_table(
            self,
            old_table_name: str,
            new_table_name: str,
            *,
            schema: Optional[str] = None,
        ) -> None:
            """Emit an ALTER TABLE to rename a table.

            :param old_table_name: old name.
            :param new_table_name: new name.
            :param schema: Optional schema name to operate within.  To control
             quoting of the schema outside of the default behavior, use
             the SQLAlchemy construct
             :class:`~sqlalchemy.sql.elements.quoted_name`.

            """  # noqa: E501
            ...

        # END STUB FUNCTIONS: op_cls


class BatchOperations(AbstractOperations):
    """Modifies the interface :class:`.Operations` for batch mode.

    This basically omits the ``table_name`` and ``schema`` parameters
    from associated methods, as these are a given when running under batch
    mode.

    .. seealso::

        :meth:`.Operations.batch_alter_table`

    Note that as of 0.8, most of the methods on this class are produced
    dynamically using the :meth:`.Operations.register_operation`
    method.

    """

    impl: BatchOperationsImpl

    def _noop(self, operation: Any) -> NoReturn:
        raise NotImplementedError(
            "The %s method does not apply to a batch table alter operation."
            % operation
        )

    if TYPE_CHECKING:
        # START STUB FUNCTIONS: batch_op
        # ### the following stubs are generated by tools/write_pyi.py ###
        # ### do not edit ###

        def add_column(
            self,
            column: Column[Any],
            *,
            insert_before: Optional[str] = None,
            insert_after: Optional[str] = None,
        ) -> None:
            """Issue an "add column" instruction using the current
            batch migration context.

            .. seealso::

                :meth:`.Operations.add_column`

            """  # noqa: E501
            ...

        def alter_column(
            self,
            column_name: str,
            *,
            nullable: Optional[bool] = None,
            comment: Union[str, Literal[False], None] = False,
            server_default: Any = False,
            new_column_name: Optional[str] = None,
            type_: Union[TypeEngine[Any], Type[TypeEngine[Any]], None] = None,
            existing_type: Union[
                TypeEngine[Any], Type[TypeEngine[Any]], None
            ] = None,
            existing_server_default: Union[
                str, bool, Identity, Computed, None
            ] = False,
            existing_nullable: Optional[bool] = None,
            existing_comment: Optional[str] = None,
            insert_before: Optional[str] = None,
            insert_after: Optional[str] = None,
            **kw: Any,
        ) -> None:
            """Issue an "alter column" instruction using the current
            batch migration context.

            Parameters are the same as that of :meth:`.Operations.alter_column`,
            as well as the following option(s):

            :param insert_before: String name of an existing column which this
             column should be placed before, when creating the new table.

            :param insert_after: String name of an existing column which this
             column should be placed after, when creating the new table.  If
             both :paramref:`.BatchOperations.alter_column.insert_before`
             and :paramref:`.BatchOperations.alter_column.insert_after` are
             omitted, the column is inserted after the last existing column
             in the table.

            .. seealso::

                :meth:`.Operations.alter_column`


            """  # noqa: E501
            ...

        def create_check_constraint(
            self,
            constraint_name: str,
            condition: Union[str, ColumnElement[bool], TextClause],
            **kw: Any,
        ) -> None:
            """Issue a "create check constraint" instruction using the
            current batch migration context.

            The batch form of this call omits the ``source`` and ``schema``
            arguments from the call.

            .. seealso::

                :meth:`.Operations.create_check_constraint`

            """  # noqa: E501
            ...

        def create_exclude_constraint(
            self, constraint_name: str, *elements: Any, **kw: Any
        ) -> Optional[Table]:
            """Issue a "create exclude constraint" instruction using the
            current batch migration context.

            .. note::  This method is Postgresql specific, and additionally
               requires at least SQLAlchemy 1.0.

            .. seealso::

                :meth:`.Operations.create_exclude_constraint`

            """  # noqa: E501
            ...

        def create_foreign_key(
            self,
            constraint_name: Optional[str],
            referent_table: str,
            local_cols: List[str],
            remote_cols: List[str],
            *,
            referent_schema: Optional[str] = None,
            onupdate: Optional[str] = None,
            ondelete: Optional[str] = None,
            deferrable: Optional[bool] = None,
            initially: Optional[str] = None,
            match: Optional[str] = None,
            **dialect_kw: Any,
        ) -> None:
            """Issue a "create foreign key" instruction using the
            current batch migration context.

            The batch form of this call omits the ``source`` and ``source_schema``
            arguments from the call.

            e.g.::

                with batch_alter_table("address") as batch_op:
                    batch_op.create_foreign_key(
                        "fk_user_address",
                        "user",
                        ["user_id"],
                        ["id"],
                    )

            .. seealso::

                :meth:`.Operations.create_foreign_key`

            """  # noqa: E501
            ...

        def create_index(
            self, index_name: str, columns: List[str], **kw: Any
        ) -> None:
            """Issue a "create index" instruction using the
            current batch migration context.

            .. seealso::

                :meth:`.Operations.create_index`

            """  # noqa: E501
            ...

        def create_primary_key(
            self, constraint_name: Optional[str], columns: List[str]
        ) -> None:
            """Issue a "create primary key" instruction using the
            current batch migration context.

            The batch form of this call omits the ``table_name`` and ``schema``
            arguments from the call.

            .. seealso::

                :meth:`.Operations.create_primary_key`

            """  # noqa: E501
            ...

        def create_table_comment(
            self,
            comment: Optional[str],
            *,
            existing_comment: Optional[str] = None,
        ) -> None:
            """Emit a COMMENT ON operation to set the comment for a table
            using the current batch migration context.

            :param comment: string value of the comment being registered against
             the specified table.
            :param existing_comment: String value of a comment
             already registered on the specified table, used within autogenerate
             so that the operation is reversible, but not required for direct
             use.

            """  # noqa: E501
            ...

        def create_unique_constraint(
            self, constraint_name: str, columns: Sequence[str], **kw: Any
        ) -> Any:
            """Issue a "create unique constraint" instruction using the
            current batch migration context.

            The batch form of this call omits the ``source`` and ``schema``
            arguments from the call.

            .. seealso::

                :meth:`.Operations.create_unique_constraint`

            """  # noqa: E501
            ...

        def drop_column(self, column_name: str, **kw: Any) -> None:
            """Issue a "drop column" instruction using the current
            batch migration context.

            .. seealso::

                :meth:`.Operations.drop_column`

            """  # noqa: E501
            ...

        def drop_constraint(
            self, constraint_name: str, type_: Optional[str] = None
        ) -> None:
            """Issue a "drop constraint" instruction using the
            current batch migration context.

            The batch form of this call omits the ``table_name`` and ``schema``
            arguments from the call.

            .. seealso::

                :meth:`.Operations.drop_constraint`

            """  # noqa: E501
            ...

        def drop_index(self, index_name: str, **kw: Any) -> None:
            """Issue a "drop index" instruction using the
            current batch migration context.

            .. seealso::

                :meth:`.Operations.drop_index`

            """  # noqa: E501
            ...

        def drop_table_comment(
            self, *, existing_comment: Optional[str] = None
        ) -> None:
            """Issue a "drop table comment" operation to
            remove an existing comment set on a table using the current
            batch operations context.

            :param existing_comment: An optional string value of a comment already
             registered on the specified table.

            """  # noqa: E501
            ...

        def execute(
            self,
            sqltext: Union[Executable, str],
            *,
            execution_options: Optional[dict[str, Any]] = None,
        ) -> None:
            """Execute the given SQL using the current migration context.

            .. seealso::

                :meth:`.Operations.execute`

            """  # noqa: E501
            ...

        # END STUB FUNCTIONS: batch_op