alembic API Reference
Full documentation for alembic (1.18.5)
alembic.autogenerate
Python Library Documentation: package alembic.autogenerate in alembic
NAME
alembic.autogenerate
PACKAGE CONTENTS
api
compare (package)
render
rewriter
DATA
comparators = <alembic.util.langhelpers.PriorityDispatcher object>
renderers = <alembic.util.langhelpers.Dispatcher object>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\alembic\autogenerate\__init__.py
alembic.context
Python Library Documentation: module alembic.context in alembic
NAME
alembic.context
FUNCTIONS
begin_transaction(*args, **kw)
Return a context manager that will
enclose an operation within a "transaction",
as defined by the environment's offline
and transactional DDL settings.
e.g.::
with context.begin_transaction():
context.run_migrations()
:meth:`.begin_transaction` is intended to
"do the right thing" regardless of
calling context:
* If :meth:`.is_transactional_ddl` is ``False``,
returns a "do nothing" context manager
which otherwise produces no transactional
state or directives.
* If :meth:`.is_offline_mode` is ``True``,
returns a context manager that will
invoke the :meth:`.DefaultImpl.emit_begin`
and :meth:`.DefaultImpl.emit_commit`
methods, which will produce the string
directives ``BEGIN`` and ``COMMIT`` on
the output stream, as rendered by the
target backend (e.g. SQL Server would
emit ``BEGIN TRANSACTION``).
* Otherwise, calls :meth:`sqlalchemy.engine.Connection.begin`
on the current online connection, which
returns a :class:`sqlalchemy.engine.Transaction`
object. This object demarcates a real
transaction and is itself a context manager,
which will roll back if an exception
is raised.
Note that a custom ``env.py`` script which
has more specific transactional needs can of course
manipulate the :class:`~sqlalchemy.engine.Connection`
directly to produce transactional state in "online"
mode.
configure(*args, **kw)
Configure a :class:`.MigrationContext` within this
:class:`.EnvironmentContext` which will provide database
connectivity and other configuration to a series of
migration scripts.
Many methods on :class:`.EnvironmentContext` require that
this method has been called in order to function, as they
ultimately need to have database access or at least access
to the dialect in use. Those which do are documented as such.
The important thing needed by :meth:`.configure` is a
means to determine what kind of database dialect is in use.
An actual connection to that database is needed only if
the :class:`.MigrationContext` is to be used in
"online" mode.
If the :meth:`.is_offline_mode` function returns ``True``,
then no connection is needed here. Otherwise, the
``connection`` parameter should be present as an
instance of :class:`sqlalchemy.engine.Connection`.
This function is typically called from the ``env.py``
script within a migration environment. It can be called
multiple times for an invocation. The most recent
:class:`~sqlalchemy.engine.Connection`
for which it was called is the one that will be operated upon
by the next call to :meth:`.run_migrations`.
General parameters:
:param connection: a :class:`~sqlalchemy.engine.Connection`
to use
for SQL execution in "online" mode. When present, is also
used to determine the type of dialect in use.
:param url: a string database url, or a
:class:`sqlalchemy.engine.url.URL` object.
The type of dialect to be used will be derived from this if
``connection`` is not passed.
:param dialect_name: string name of a dialect, such as
"postgresql", "mssql", etc.
The type of dialect to be used will be derived from this if
``connection`` and ``url`` are not passed.
:param dialect_opts: dictionary of options to be passed to dialect
constructor.
:param transactional_ddl: Force the usage of "transactional"
DDL on or off;
this otherwise defaults to whether or not the dialect in
use supports it.
:param transaction_per_migration: if True, nest each migration script
in a transaction rather than the full series of migrations to
run.
:param output_buffer: a file-like object that will be used
for textual output
when the ``--sql`` option is used to generate SQL scripts.
Defaults to
``sys.stdout`` if not passed here and also not present on
the :class:`.Config`
object. The value here overrides that of the :class:`.Config`
object.
:param output_encoding: when using ``--sql`` to generate SQL
scripts, apply this encoding to the string output.
:param literal_binds: when using ``--sql`` to generate SQL
scripts, pass through the ``literal_binds`` flag to the compiler
so that any literal values that would ordinarily be bound
parameters are converted to plain strings.
.. warning:: Dialects can typically only handle simple datatypes
like strings and numbers for auto-literal generation. Datatypes
like dates, intervals, and others may still require manual
formatting, typically using :meth:`.Operations.inline_literal`.
.. note:: the ``literal_binds`` flag is ignored on SQLAlchemy
versions prior to 0.8 where this feature is not supported.
.. seealso::
:meth:`.Operations.inline_literal`
:param starting_rev: Override the "starting revision" argument
when using ``--sql`` mode.
:param tag: a string tag for usage by custom ``env.py`` scripts.
Set via the ``--tag`` option, can be overridden here.
:param template_args: dictionary of template arguments which
will be added to the template argument environment when
running the "revision" command. Note that the script environment
is only run within the "revision" command if the --autogenerate
option is used, or if the option "revision_environment=true"
is present in the alembic.ini file.
:param version_table: The name of the Alembic version table.
The default is ``'alembic_version'``.
:param version_table_schema: Optional schema to place version
table within.
:param version_table_pk: boolean, whether the Alembic version table
should use a primary key constraint for the "value" column; this
only takes effect when the table is first created.
Defaults to True; setting to False should not be necessary and is
here for backwards compatibility reasons.
:param on_version_apply: a callable or collection of callables to be
run for each migration step.
The callables will be run in the order they are given, once for
each migration step, after the respective operation has been
applied but before its transaction is finalized.
Each callable accepts no positional arguments and the following
keyword arguments:
* ``ctx``: the :class:`.MigrationContext` running the migration,
* ``step``: a :class:`.MigrationInfo` representing the
step currently being applied,
* ``heads``: a collection of version strings representing the
current heads,
* ``run_args``: the ``**kwargs`` passed to :meth:`.run_migrations`.
Parameters specific to the autogenerate feature, when
``alembic revision`` is run with the ``--autogenerate`` feature:
:param target_metadata: a :class:`sqlalchemy.schema.MetaData`
object, or a sequence of :class:`~sqlalchemy.schema.MetaData`
objects, that will be consulted during autogeneration.
The tables present in each :class:`~sqlalchemy.schema.MetaData`
will be compared against
what is locally available on the target
:class:`~sqlalchemy.engine.Connection`
to produce candidate upgrade/downgrade operations.
:param compare_type: Indicates type comparison behavior during
an autogenerate
operation. Defaults to ``True`` turning on type comparison, which
has good accuracy on most backends. See :ref:`compare_types`
for an example as well as information on other type
comparison options. Set to ``False`` which disables type
comparison. A callable can also be passed to provide custom type
comparison, see :ref:`compare_types` for additional details.
.. versionchanged:: 1.12.0 The default value of
:paramref:`.EnvironmentContext.configure.compare_type` has been
changed to ``True``.
.. seealso::
:ref:`compare_types`
:paramref:`.EnvironmentContext.configure.compare_server_default`
:param compare_server_default: Indicates server default comparison
behavior during
an autogenerate operation. Defaults to ``False`` which disables
server default
comparison. Set to ``True`` to turn on server default comparison,
which has
varied accuracy depending on backend.
To customize server default comparison behavior, a callable may
be specified
which can filter server default comparisons during an
autogenerate operation.
defaults during an autogenerate operation. The format of this
callable is::
def my_compare_server_default(context, inspected_column,
metadata_column, inspected_default, metadata_default,
rendered_metadata_default):
# return True if the defaults are different,
# False if not, or None to allow the default implementation
# to compare these defaults
return None
context.configure(
# ...
compare_server_default = my_compare_server_default
)
``inspected_column`` is a dictionary structure as returned by
:meth:`sqlalchemy.engine.reflection.Inspector.get_columns`, whereas
``metadata_column`` is a :class:`sqlalchemy.schema.Column` from
the local model environment.
A return value of ``None`` indicates to allow default server default
comparison
to proceed. Note that some backends such as Postgresql actually
execute
the two defaults on the database side to compare for equivalence.
.. seealso::
:paramref:`.EnvironmentContext.configure.compare_type`
:param include_name: A callable function which is given
the chance to return ``True`` or ``False`` for any database reflected
object based on its name, including database schema names when
the :paramref:`.EnvironmentContext.configure.include_schemas` flag
is set to ``True``.
The function accepts the following positional arguments:
* ``name``: the name of the object, such as schema name or table name.
Will be ``None`` when indicating the default schema name of the
database connection.
* ``type``: a string describing the type of object; currently
``"schema"``, ``"table"``, ``"column"``, ``"index"``,
``"unique_constraint"``, or ``"foreign_key_constraint"``
* ``parent_names``: a dictionary of "parent" object names, that are
relative to the name being given. Keys in this dictionary may
include: ``"schema_name"``, ``"table_name"`` or
``"schema_qualified_table_name"``.
E.g.::
def include_name(name, type_, parent_names):
if type_ == "schema":
return name in ["schema_one", "schema_two"]
else:
return True
context.configure(
# ...
include_schemas = True,
include_name = include_name
)
.. seealso::
:ref:`autogenerate_include_hooks`
:paramref:`.EnvironmentContext.configure.include_object`
:paramref:`.EnvironmentContext.configure.include_schemas`
:param include_object: A callable function which is given
the chance to return ``True`` or ``False`` for any object,
indicating if the given object should be considered in the
autogenerate sweep.
The function accepts the following positional arguments:
* ``object``: a :class:`~sqlalchemy.schema.SchemaItem` object such
as a :class:`~sqlalchemy.schema.Table`,
:class:`~sqlalchemy.schema.Column`,
:class:`~sqlalchemy.schema.Index`
:class:`~sqlalchemy.schema.UniqueConstraint`,
or :class:`~sqlalchemy.schema.ForeignKeyConstraint` object
* ``name``: the name of the object. This is typically available
via ``object.name``.
* ``type``: a string describing the type of object; currently
``"table"``, ``"column"``, ``"index"``, ``"unique_constraint"``,
or ``"foreign_key_constraint"``
* ``reflected``: ``True`` if the given object was produced based on
table reflection, ``False`` if it's from a local :class:`.MetaData`
object.
* ``compare_to``: the object being compared against, if available,
else ``None``.
E.g.::
def include_object(object, name, type_, reflected, compare_to):
if (type_ == "column" and
not reflected and
object.info.get("skip_autogenerate", False)):
return False
else:
return True
context.configure(
# ...
include_object = include_object
)
For the use case of omitting specific schemas from a target database
when :paramref:`.EnvironmentContext.configure.include_schemas` is
set to ``True``, the :attr:`~sqlalchemy.schema.Table.schema`
attribute can be checked for each :class:`~sqlalchemy.schema.Table`
object passed to the hook, however it is much more efficient
to filter on schemas before reflection of objects takes place
using the :paramref:`.EnvironmentContext.configure.include_name`
hook.
.. seealso::
:ref:`autogenerate_include_hooks`
:paramref:`.EnvironmentContext.configure.include_name`
:paramref:`.EnvironmentContext.configure.include_schemas`
:param render_as_batch: if True, commands which alter elements
within a table will be placed under a ``with batch_alter_table():``
directive, so that batch migrations will take place.
.. seealso::
:ref:`batch_migrations`
:param include_schemas: If True, autogenerate will scan across
all schemas located by the SQLAlchemy
:meth:`~sqlalchemy.engine.reflection.Inspector.get_schema_names`
method, and include all differences in tables found across all
those schemas. When using this option, you may want to also
use the :paramref:`.EnvironmentContext.configure.include_name`
parameter to specify a callable which
can filter the tables/schemas that get included.
.. seealso::
:ref:`autogenerate_include_hooks`
:paramref:`.EnvironmentContext.configure.include_name`
:paramref:`.EnvironmentContext.configure.include_object`
:param render_item: Callable that can be used to override how
any schema item, i.e. column, constraint, type,
etc., is rendered for autogenerate. The callable receives a
string describing the type of object, the object, and
the autogen context. If it returns False, the
default rendering method will be used. If it returns None,
the item will not be rendered in the context of a Table
construct, that is, can be used to skip columns or constraints
within op.create_table()::
def my_render_column(type_, col, autogen_context):
if type_ == "column" and isinstance(col, MySpecialCol):
return repr(col)
else:
return False
context.configure(
# ...
render_item = my_render_column
)
Available values for the type string include: ``"column"``,
``"primary_key"``, ``"foreign_key"``, ``"unique"``, ``"check"``,
``"type"``, ``"server_default"``.
.. seealso::
:ref:`autogen_render_types`
:param upgrade_token: When autogenerate completes, the text of the
candidate upgrade operations will be present in this template
variable when ``script.py.mako`` is rendered. Defaults to
``upgrades``.
:param downgrade_token: When autogenerate completes, the text of the
candidate downgrade operations will be present in this
template variable when ``script.py.mako`` is rendered. Defaults to
``downgrades``.
:param alembic_module_prefix: When autogenerate refers to Alembic
:mod:`alembic.operations` constructs, this prefix will be used
(i.e. ``op.create_table``) Defaults to "``op.``".
Can be ``None`` to indicate no prefix.
:param sqlalchemy_module_prefix: When autogenerate refers to
SQLAlchemy
:class:`~sqlalchemy.schema.Column` or type classes, this prefix
will be used
(i.e. ``sa.Column("somename", sa.Integer)``) Defaults to "``sa.``".
Can be ``None`` to indicate no prefix.
Note that when dialect-specific types are rendered, autogenerate
will render them using the dialect module name, i.e. ``mssql.BIT()``,
``postgresql.UUID()``.
:param user_module_prefix: When autogenerate refers to a SQLAlchemy
type (e.g. :class:`.TypeEngine`) where the module name is not
under the ``sqlalchemy`` namespace, this prefix will be used
within autogenerate. If left at its default of
``None``, the ``__module__`` attribute of the type is used to
render the import module. It's a good practice to set this
and to have all custom types be available from a fixed module space,
in order to future-proof migration files against reorganizations
in modules.
.. seealso::
:ref:`autogen_module_prefix`
:param process_revision_directives: a callable function that will
be passed a structure representing the end result of an autogenerate
or plain "revision" operation, which can be manipulated to affect
how the ``alembic revision`` command ultimately outputs new
revision scripts. The structure of the callable is::
def process_revision_directives(context, revision, directives):
pass
The ``directives`` parameter is a Python list containing
a single :class:`.MigrationScript` directive, which represents
the revision file to be generated. This list as well as its
contents may be freely modified to produce any set of commands.
The section :ref:`customizing_revision` shows an example of
doing this. The ``context`` parameter is the
:class:`.MigrationContext` in use,
and ``revision`` is a tuple of revision identifiers representing the
current revision of the database.
The callable is invoked at all times when the ``--autogenerate``
option is passed to ``alembic revision``. If ``--autogenerate``
is not passed, the callable is invoked only if the
``revision_environment`` variable is set to True in the Alembic
configuration, in which case the given ``directives`` collection
will contain empty :class:`.UpgradeOps` and :class:`.DowngradeOps`
collections for ``.upgrade_ops`` and ``.downgrade_ops``. The
``--autogenerate`` option itself can be inferred by inspecting
``context.config.cmd_opts.autogenerate``.
The callable function may optionally be an instance of
a :class:`.Rewriter` object. This is a helper object that
assists in the production of autogenerate-stream rewriter functions.
.. seealso::
:ref:`customizing_revision`
:ref:`autogen_rewriter`
:paramref:`.command.revision.process_revision_directives`
:param autogenerate_plugins: A list of string names of "plugins" that
should participate in this autogenerate run. Defaults to the list
``["alembic.autogenerate.*"]``, which indicates that Alembic's default
autogeneration plugins will be used.
See the section :ref:`plugins_autogenerate` for complete background
on how to use this parameter.
.. versionadded:: 1.18.0 Added a new plugin system for autogenerate
compare directives.
.. seealso::
:ref:`plugins_autogenerate` - background on enabling/disabling
autogenerate plugins
:ref:`alembic.plugins.toplevel` - Introduction and documentation
to the plugin system
Parameters specific to individual backends:
:param mssql_batch_separator: The "batch separator" which will
be placed between each statement when generating offline SQL Server
migrations. Defaults to ``GO``. Note this is in addition to the
customary semicolon ``;`` at the end of each statement; SQL Server
considers the "batch separator" to denote the end of an
individual statement execution, and cannot group certain
dependent operations in one step.
:param oracle_batch_separator: The "batch separator" which will
be placed between each statement when generating offline
Oracle migrations. Defaults to ``/``. Oracle doesn't add a
semicolon between statements like most other backends.
create_module_class_proxy(*args, **kw)
execute(*args, **kw)
Execute the given SQL using the current change context.
The behavior of :meth:`.execute` is the same
as that of :meth:`.Operations.execute`. Please see that
function's documentation for full detail including
caveats and limitations.
This function requires that a :class:`.MigrationContext` has
first been made available via :meth:`.configure`.
get_bind(*args, **kw)
Return the current 'bind'.
In "online" mode, this is the
:class:`sqlalchemy.engine.Connection` currently being used
to emit SQL to the database.
This function requires that a :class:`.MigrationContext`
has first been made available via :meth:`.configure`.
get_context(*args, **kw)
Return the current :class:`.MigrationContext` object.
If :meth:`.EnvironmentContext.configure` has not been
called yet, raises an exception.
get_head_revision(*args, **kw)
Return the hex identifier of the 'head' script revision.
If the script directory has multiple heads, this
method raises a :class:`.CommandError`;
:meth:`.EnvironmentContext.get_head_revisions` should be preferred.
This function does not require that the :class:`.MigrationContext`
has been configured.
.. seealso:: :meth:`.EnvironmentContext.get_head_revisions`
get_head_revisions(*args, **kw)
Return the hex identifier of the 'heads' script revision(s).
This returns a tuple containing the version number of all
heads in the script directory.
This function does not require that the :class:`.MigrationContext`
has been configured.
get_impl(*args, **kw)
get_revision_argument(*args, **kw)
Get the 'destination' revision argument.
This is typically the argument passed to the
``upgrade`` or ``downgrade`` command.
If it was specified as ``head``, the actual
version number is returned; if specified
as ``base``, ``None`` is returned.
This function does not require that the :class:`.MigrationContext`
has been configured.
get_starting_revision_argument(*args, **kw)
Return the 'starting revision' argument,
if the revision was passed using ``start:end``.
This is only meaningful in "offline" mode.
Returns ``None`` if no value is available
or was configured.
This function does not require that the :class:`.MigrationContext`
has been configured.
get_tag_argument(*args, **kw)
Return the value passed for the ``--tag`` argument, if any.
The ``--tag`` argument is not used directly by Alembic,
but is available for custom ``env.py`` configurations that
wish to use it; particularly for offline generation scripts
that wish to generate tagged filenames.
This function does not require that the :class:`.MigrationContext`
has been configured.
.. seealso::
:meth:`.EnvironmentContext.get_x_argument` - a newer and more
open ended system of extending ``env.py`` scripts via the command
line.
get_x_argument(*args, **kw)
Return the value(s) passed for the ``-x`` argument, if any.
The ``-x`` argument is an open ended flag that allows any user-defined
value or values to be passed on the command line, then available
here for consumption by a custom ``env.py`` script.
The return value is a list, returned directly from the ``argparse``
structure. If ``as_dictionary=True`` is passed, the ``x`` arguments
are parsed using ``key=value`` format into a dictionary that is
then returned. If there is no ``=`` in the argument, value is an empty
string.
.. versionchanged:: 1.13.1 Support ``as_dictionary=True`` when
arguments are passed without the ``=`` symbol.
For example, to support passing a database URL on the command line,
the standard ``env.py`` script can be modified like this::
cmd_line_url = context.get_x_argument(
as_dictionary=True).get('dbname')
if cmd_line_url:
engine = create_engine(cmd_line_url)
else:
engine = engine_from_config(
config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool)
This then takes effect by running the ``alembic`` script as::
alembic -x dbname=postgresql://user:pass@host/dbname upgrade head
This function does not require that the :class:`.MigrationContext`
has been configured.
.. seealso::
:meth:`.EnvironmentContext.get_tag_argument`
:attr:`.Config.cmd_opts`
is_offline_mode(*args, **kw)
Return True if the current migrations environment
is running in "offline mode".
This is ``True`` or ``False`` depending
on the ``--sql`` flag passed.
This function does not require that the :class:`.MigrationContext`
has been configured.
is_transactional_ddl(*args, **kw)
Return True if the context is configured to expect a
transactional DDL capable backend.
This defaults to the type of database in use, and
can be overridden by the ``transactional_ddl`` argument
to :meth:`.configure`
This function requires that a :class:`.MigrationContext`
has first been made available via :meth:`.configure`.
requires_connection(*args, **kw)
run_migrations(*args, **kw)
Run migrations as determined by the current command line
configuration
as well as versioning information present (or not) in the current
database connection (if one is present).
The function accepts optional ``**kw`` arguments. If these are
passed, they are sent directly to the ``upgrade()`` and
``downgrade()``
functions within each target revision file. By modifying the
``script.py.mako`` file so that the ``upgrade()`` and ``downgrade()``
functions accept arguments, parameters can be passed here so that
contextual information, usually information to identify a particular
database in use, can be passed from a custom ``env.py`` script
to the migration functions.
This function requires that a :class:`.MigrationContext` has
first been made available via :meth:`.configure`.
static_output(*args, **kw)
Emit text directly to the "offline" SQL stream.
Typically this is for emitting comments that
start with --. The statement is not treated
as a SQL execution, no ; or batch separator
is added, etc.
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\alembic\context.py
alembic.ddl
Python Library Documentation: package alembic.ddl in alembic
NAME
alembic.ddl
PACKAGE CONTENTS
_autogen
base
impl
mssql
mysql
oracle
postgresql
sqlite
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\alembic\ddl\__init__.py
alembic.op
Python Library Documentation: module alembic.op in alembic
NAME
alembic.op
FUNCTIONS
add_column(*args, **kw)
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. Options
also exist for control of single-column primary key and foreign key
constraints to be generated.
.. note::
Not all constraint types may be indicated with this directive.
NOT NULL, FOREIGN KEY, and CHECK are honored, PRIMARY KEY
is conditionally honored, UNIQUE
is currently not.
As of 1.18.2, the following :class:`~sqlalchemy.schema.Column`
parameters are **ignored**:
* :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
**PRIMARY KEY support**
The provided :class:`~sqlalchemy.schema.Column` object may include a
``primary_key=True`` directive, indicating the column intends to be
part of a primary key constraint. However by default, the inline
"PRIMARY KEY" directive is not emitted, and it's assumed that a
separate :meth:`.Operations.create_primary_key` directive will be used
to create this constraint, which may potentially include other columns
as well as have an explicit name. To instead render an inline
"PRIMARY KEY" directive, the
:paramref:`.AddColumnOp.inline_primary_key` parameter may be indicated
at the same time as the ``primary_key`` parameter (both are needed)::
from alembic import op
from sqlalchemy import Column, INTEGER
op.add_column(
"organization",
Column("id", INTEGER, primary_key=True),
inline_primary_key=True
)
The ``primary_key=True`` parameter on
:class:`~sqlalchemy.schema.Column` also indicates behaviors such as
using the ``SERIAL`` datatype with the PostgreSQL database, which is
why two separate, independent parameters are provided to support all
combinations.
.. versionadded:: 1.18.4 Added
:paramref:`.AddColumnOp.inline_primary_key`
to control use of the ``PRIMARY KEY`` inline directive.
**FOREIGN KEY support**
The provided :class:`~sqlalchemy.schema.Column` object may include a
:class:`~sqlalchemy.schema.ForeignKey` constraint directive,
referencing a remote table name. By default, 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")),
)
To render the FOREIGN KEY constraint inline within the ADD COLUMN
directive, use the ``inline_references`` parameter. This can improve
performance on large tables since the constraint is marked as valid
immediately for nullable columns::
from alembic import op
from sqlalchemy import Column, INTEGER, ForeignKey
op.add_column(
"organization",
Column("account_id", INTEGER, ForeignKey("accounts.id")),
inline_references=True,
)
**Indicating server side defaults**
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`.
:param if_not_exists: If True, adds ``IF NOT EXISTS`` operator
when creating the new column for compatible dialects
.. versionadded:: 1.16.0
:param inline_references: If True, renders ``FOREIGN KEY`` constraints
inline within the ``ADD COLUMN`` directive using ``REFERENCES``
syntax, rather than as a separate ``ALTER TABLE ADD CONSTRAINT``
statement. This is supported by PostgreSQL, Oracle, MySQL 5.7+, and
MariaDB 10.5+.
.. versionadded:: 1.18.2
:param inline_primary_key: If True, renders the ``PRIMARY KEY`` phrase
inline within the ``ADD COLUMN`` directive. When not present or
False, ``PRIMARY KEY`` is not emitted; it is assumed that the
migration script will include an additional
:meth:`.Operations.create_primary_key` directive to create a full
primary key constraint.
.. versionadded:: 1.18.4
alter_column(*args, **kw)
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.
batch_alter_table(*args, **kw)
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`
bulk_insert(*args, **kw)
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.
context(*args, **kw)
create_check_constraint(*args, **kw)
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`.
create_exclude_constraint(*args, **kw)
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.
create_foreign_key(*args, **kw)
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.
create_index(*args, **kw)
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.
create_module_class_proxy(*args, **kw)
create_primary_key(*args, **kw)
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`.
create_table(*args, **kw)
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.
create_table_comment(*args, **kw)
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`
create_unique_constraint(*args, **kw)
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`.
drop_column(*args, **kw)
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 if_exists: If True, adds IF EXISTS operator when
dropping the new column for compatible dialects
.. versionadded:: 1.16.0
: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.
drop_constraint(*args, **kw)
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`.
:param if_exists: If True, adds IF EXISTS operator when
dropping the constraint
.. versionadded:: 1.16.0
drop_index(*args, **kw)
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.
drop_table(*args, **kw)
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.
drop_table_comment(*args, **kw)
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`
execute(*args, **kw)
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`.
f(*args, **kw)
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.
get_bind(*args, **kw)
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]
get_context(*args, **kw)
Return the :class:`.MigrationContext` object that's
currently in use.
implementation_for(*args, **kw)
Register an implementation for a given :class:`.MigrateOperation`.
:param replace: when True, allows replacement of an already
registered implementation for the given operation class. This
enables customization of built-in operations such as
:class:`.CreateTableOp` by providing an alternate implementation
that can augment, modify, or conditionally invoke the default
behavior.
.. versionadded:: 1.17.2
This is part of the operation extensibility API.
.. seealso::
:ref:`operation_plugins`
:ref:`operations_extending_builtin`
inline_literal(*args, **kw)
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`
invoke(*args, **kw)
Given a :class:`.MigrateOperation`, invoke it in terms of
this :class:`.Operations` instance.
register_operation(*args, **kw)
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`
rename_table(*args, **kw)
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`.
run_async(*args, **kw)
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.
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\alembic\op.py
alembic.operations
Python Library Documentation: package alembic.operations in alembic
NAME
alembic.operations
PACKAGE CONTENTS
base
batch
ops
schemaobj
toimpl
CLASSES
alembic.util.langhelpers.ModuleClsProxy(builtins.object)
alembic.operations.base.AbstractOperations
alembic.operations.base.BatchOperations
alembic.operations.base.Operations
builtins.object
alembic.operations.ops.MigrateOperation
alembic.operations.ops.MigrationScript
class AbstractOperations(alembic.util.langhelpers.ModuleClsProxy)
| AbstractOperations(migration_context: 'MigrationContext', impl: 'Optional[BatchOperationsImpl]' = None) -> 'None'
|
| Base class for Operations and BatchOperations.
|
| .. versionadded:: 1.11.0
|
| Method resolution order:
| AbstractOperations
| alembic.util.langhelpers.ModuleClsProxy
| builtins.object
|
| Methods defined here:
|
| __init__(self, migration_context: 'MigrationContext', impl: 'Optional[BatchOperationsImpl]' = None) -> 'None'
| Construct a new :class:`.Operations`
|
| :param migration_context: a :class:`.MigrationContext`
| instance.
|
| batch_alter_table(self, table_name: 'str', schema: 'Optional[str]' = None, recreate: "Literal['auto', 'always', 'never']" = 'auto', partial_reordering: 'list[tuple[str, ...]] | None' = None, copy_from: 'Optional[Table]' = None, table_args: 'Tuple[Any, ...]' = (), table_kwargs: 'Mapping[str, Any]' = immutabledict({}), reflect_args: 'Tuple[Any, ...]' = (), reflect_kwargs: 'Mapping[str, Any]' = 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`
|
| 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.
|
| 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]
|
| get_context(self) -> 'MigrationContext'
| Return the :class:`.MigrationContext` object that's
| currently in use.
|
| inline_literal(self, value: 'Union[str, int]', type_: 'Optional[TypeEngine[Any]]' = None) -> '_literal_bindparam'
| 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`
|
| invoke(self, operation: 'MigrateOperation') -> 'Any'
| Given a :class:`.MigrateOperation`, invoke it in terms of
| this :class:`.Operations` instance.
|
| 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.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| context(migration_context: 'MigrationContext') -> 'Iterator[Operations]'
|
| implementation_for(op_cls: 'Any', replace: 'bool' = False) -> 'Callable[[_C], _C]'
| Register an implementation for a given :class:`.MigrateOperation`.
|
| :param replace: when True, allows replacement of an already
| registered implementation for the given operation class. This
| enables customization of built-in operations such as
| :class:`.CreateTableOp` by providing an alternate implementation
| that can augment, modify, or conditionally invoke the default
| behavior.
|
| .. versionadded:: 1.17.2
|
| This is part of the operation extensibility API.
|
| .. seealso::
|
| :ref:`operation_plugins`
|
| :ref:`operations_extending_builtin`
|
| register_operation(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`
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'impl': 'Union[DefaultImpl, BatchOperationsImpl]'}
|
| ----------------------------------------------------------------------
| Class methods inherited from alembic.util.langhelpers.ModuleClsProxy:
|
| create_module_class_proxy(globals_: 'MutableMapping[str, Any]', locals_: 'MutableMapping[str, Any]') -> 'None'
|
| ----------------------------------------------------------------------
| Data descriptors inherited from alembic.util.langhelpers.ModuleClsProxy:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class BatchOperations(AbstractOperations)
| BatchOperations(migration_context: 'MigrationContext', impl: 'Optional[BatchOperationsImpl]' = None) -> 'None'
|
| 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.
|
| Method resolution order:
| BatchOperations
| AbstractOperations
| alembic.util.langhelpers.ModuleClsProxy
| builtins.object
|
| Methods defined here:
|
| add_column(self, column: 'Column[Any]', *, insert_before: 'Optional[str]' = None, insert_after: 'Optional[str]' = None, if_not_exists: 'Optional[bool]' = None, inline_references: 'Optional[bool]' = None, inline_primary_key: 'Optional[bool]' = None) -> 'None' from alembic.operations.base
| Issue an "add column" instruction using the current
| batch migration context.
|
| .. seealso::
|
| :meth:`.Operations.add_column`
|
| alter_column(self, column_name: 'str', *, nullable: 'Optional[bool]' = None, comment: 'Optional[Union[str, Literal[False]]]' = False, server_default: 'Union[_ServerDefaultType, None, Literal[False]]' = False, new_column_name: 'Optional[str]' = None, type_: 'Optional[Union[TypeEngine[Any], Type[TypeEngine[Any]]]]' = None, existing_type: 'Optional[Union[TypeEngine[Any], Type[TypeEngine[Any]]]]' = None, existing_server_default: 'Union[_ServerDefaultType, None, Literal[False]]' = False, existing_nullable: 'Optional[bool]' = None, existing_comment: 'Optional[str]' = None, insert_before: 'Optional[str]' = None, insert_after: 'Optional[str]' = None, **kw: 'Any') -> 'None' from alembic.operations.base
| 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`
|
| create_check_constraint(self, constraint_name: 'str', condition: 'Union[str, ColumnElement[bool], TextClause]', **kw: 'Any') -> 'None' from alembic.operations.base
| 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`
|
| create_exclude_constraint(self, constraint_name: 'str', *elements: 'Any', **kw: 'Any') -> 'Optional[Table]' from alembic.operations.base
| 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`
|
| 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' from alembic.operations.base
| 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`
|
| create_index(self, index_name: 'str', columns: 'List[str]', **kw: 'Any') -> 'None' from alembic.operations.base
| Issue a "create index" instruction using the
| current batch migration context.
|
| .. seealso::
|
| :meth:`.Operations.create_index`
|
| create_primary_key(self, constraint_name: 'Optional[str]', columns: 'List[str]') -> 'None' from alembic.operations.base
| 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`
|
| create_table_comment(self, comment: 'Optional[str]', *, existing_comment: 'Optional[str]' = None) -> 'None' from alembic.operations.base
| 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.
|
| create_unique_constraint(self, constraint_name: 'str', columns: 'Sequence[str]', **kw: 'Any') -> 'Any' from alembic.operations.base
| 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`
|
| drop_column(self, column_name: 'str', **kw: 'Any') -> 'None' from alembic.operations.base
| Issue a "drop column" instruction using the current
| batch migration context.
|
| .. seealso::
|
| :meth:`.Operations.drop_column`
|
| drop_constraint(self, constraint_name: 'str', type_: 'Optional[str]' = None) -> 'None' from alembic.operations.base
| 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`
|
| drop_index(self, index_name: 'str', **kw: 'Any') -> 'None' from alembic.operations.base
| Issue a "drop index" instruction using the
| current batch migration context.
|
| .. seealso::
|
| :meth:`.Operations.drop_index`
|
| drop_table_comment(self, *, existing_comment: 'Optional[str]' = None) -> 'None' from alembic.operations.base
| 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.
|
| execute(self, sqltext: 'Union[Executable, str]', *, execution_options: 'Optional[dict[str, Any]]' = None) -> 'None' from alembic.operations.base
| Execute the given SQL using the current migration context.
|
| .. seealso::
|
| :meth:`.Operations.execute`
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'impl': 'BatchOperationsImpl'}
|
| ----------------------------------------------------------------------
| Methods inherited from AbstractOperations:
|
| __init__(self, migration_context: 'MigrationContext', impl: 'Optional[BatchOperationsImpl]' = None) -> 'None'
| Construct a new :class:`.Operations`
|
| :param migration_context: a :class:`.MigrationContext`
| instance.
|
| batch_alter_table(self, table_name: 'str', schema: 'Optional[str]' = None, recreate: "Literal['auto', 'always', 'never']" = 'auto', partial_reordering: 'list[tuple[str, ...]] | None' = None, copy_from: 'Optional[Table]' = None, table_args: 'Tuple[Any, ...]' = (), table_kwargs: 'Mapping[str, Any]' = immutabledict({}), reflect_args: 'Tuple[Any, ...]' = (), reflect_kwargs: 'Mapping[str, Any]' = 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`
|
| 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.
|
| 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]
|
| get_context(self) -> 'MigrationContext'
| Return the :class:`.MigrationContext` object that's
| currently in use.
|
| inline_literal(self, value: 'Union[str, int]', type_: 'Optional[TypeEngine[Any]]' = None) -> '_literal_bindparam'
| 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`
|
| invoke(self, operation: 'MigrateOperation') -> 'Any'
| Given a :class:`.MigrateOperation`, invoke it in terms of
| this :class:`.Operations` instance.
|
| 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.
|
| ----------------------------------------------------------------------
| Class methods inherited from AbstractOperations:
|
| context(migration_context: 'MigrationContext') -> 'Iterator[Operations]'
|
| implementation_for(op_cls: 'Any', replace: 'bool' = False) -> 'Callable[[_C], _C]'
| Register an implementation for a given :class:`.MigrateOperation`.
|
| :param replace: when True, allows replacement of an already
| registered implementation for the given operation class. This
| enables customization of built-in operations such as
| :class:`.CreateTableOp` by providing an alternate implementation
| that can augment, modify, or conditionally invoke the default
| behavior.
|
| .. versionadded:: 1.17.2
|
| This is part of the operation extensibility API.
|
| .. seealso::
|
| :ref:`operation_plugins`
|
| :ref:`operations_extending_builtin`
|
| register_operation(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`
|
| ----------------------------------------------------------------------
| Class methods inherited from alembic.util.langhelpers.ModuleClsProxy:
|
| create_module_class_proxy(globals_: 'MutableMapping[str, Any]', locals_: 'MutableMapping[str, Any]') -> 'None'
|
| ----------------------------------------------------------------------
| Data descriptors inherited from alembic.util.langhelpers.ModuleClsProxy:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class MigrateOperation(builtins.object)
| base class for migration command and organization objects.
|
| This system is part of the operation extensibility API.
|
| .. seealso::
|
| :ref:`operation_objects`
|
| :ref:`operation_plugins`
|
| :ref:`customizing_revision`
|
| Methods defined here:
|
| info(...)
| A dictionary that may be used to store arbitrary information
| along with this :class:`.MigrateOperation` object.
|
| reverse(self) -> 'MigrateOperation'
|
| to_diff_tuple(self) -> 'Tuple[Any, ...]'
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_mutations': 'FrozenSet[Rewriter]'}
class MigrationScript(MigrateOperation)
| MigrationScript(rev_id: 'Optional[str]', upgrade_ops: 'UpgradeOps', downgrade_ops: 'DowngradeOps', *, message: 'Optional[str]' = None, imports: 'Set[str]' = set(), head: 'Optional[str]' = None, splice: 'Optional[bool]' = None, branch_label: 'Optional[_RevIdType]' = None, version_path: 'Union[str, os.PathLike[str], None]' = None, depends_on: 'Optional[_RevIdType]' = None) -> 'None'
|
| represents a migration script.
|
| E.g. when autogenerate encounters this object, this corresponds to the
| production of an actual script file.
|
| A normal :class:`.MigrationScript` object would contain a single
| :class:`.UpgradeOps` and a single :class:`.DowngradeOps` directive.
| These are accessible via the ``.upgrade_ops`` and ``.downgrade_ops``
| attributes.
|
| In the case of an autogenerate operation that runs multiple times,
| such as the multiple database example in the "multidb" template,
| the ``.upgrade_ops`` and ``.downgrade_ops`` attributes are disabled,
| and instead these objects should be accessed via the ``.upgrade_ops_list``
| and ``.downgrade_ops_list`` list-based attributes. These latter
| attributes are always available at the very least as single-element lists.
|
| .. seealso::
|
| :ref:`customizing_revision`
|
| Method resolution order:
| MigrationScript
| MigrateOperation
| builtins.object
|
| Methods defined here:
|
| __init__(self, rev_id: 'Optional[str]', upgrade_ops: 'UpgradeOps', downgrade_ops: 'DowngradeOps', *, message: 'Optional[str]' = None, imports: 'Set[str]' = set(), head: 'Optional[str]' = None, splice: 'Optional[bool]' = None, branch_label: 'Optional[_RevIdType]' = None, version_path: 'Union[str, os.PathLike[str], None]' = None, depends_on: 'Optional[_RevIdType]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| downgrade_ops_list
| A list of :class:`.DowngradeOps` instances.
|
| This is used in place of the :attr:`.MigrationScript.downgrade_ops`
| attribute when dealing with a revision operation that does
| multiple autogenerate passes.
|
| upgrade_ops_list
| A list of :class:`.UpgradeOps` instances.
|
| This is used in place of the :attr:`.MigrationScript.upgrade_ops`
| attribute when dealing with a revision operation that does
| multiple autogenerate passes.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| downgrade_ops
| An instance of :class:`.DowngradeOps`.
|
| .. seealso::
|
| :attr:`.MigrationScript.downgrade_ops_list`
|
| upgrade_ops
| An instance of :class:`.UpgradeOps`.
|
| .. seealso::
|
| :attr:`.MigrationScript.upgrade_ops_list`
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_downgrade_ops': 'List[DowngradeOps]', '_needs_ren...
|
| ----------------------------------------------------------------------
| Methods inherited from MigrateOperation:
|
| info(...)
| A dictionary that may be used to store arbitrary information
| along with this :class:`.MigrateOperation` object.
|
| reverse(self) -> 'MigrateOperation'
|
| to_diff_tuple(self) -> 'Tuple[Any, ...]'
|
| ----------------------------------------------------------------------
| Data descriptors inherited from MigrateOperation:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class Operations(AbstractOperations)
| Operations(migration_context: 'MigrationContext', impl: 'Optional[BatchOperationsImpl]' = None) -> 'None'
|
| 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.
|
| Method resolution order:
| Operations
| AbstractOperations
| alembic.util.langhelpers.ModuleClsProxy
| builtins.object
|
| Methods defined here:
|
| add_column(self, table_name: 'str', column: 'Column[Any]', *, schema: 'Optional[str]' = None, if_not_exists: 'Optional[bool]' = None, inline_references: 'Optional[bool]' = None, inline_primary_key: 'Optional[bool]' = None) -> 'None' from alembic.operations.base
| 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. Options
| also exist for control of single-column primary key and foreign key
| constraints to be generated.
|
| .. note::
|
| Not all constraint types may be indicated with this directive.
| NOT NULL, FOREIGN KEY, and CHECK are honored, PRIMARY KEY
| is conditionally honored, UNIQUE
| is currently not.
|
| As of 1.18.2, the following :class:`~sqlalchemy.schema.Column`
| parameters are **ignored**:
|
| * :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
|
| **PRIMARY KEY support**
|
| The provided :class:`~sqlalchemy.schema.Column` object may include a
| ``primary_key=True`` directive, indicating the column intends to be
| part of a primary key constraint. However by default, the inline
| "PRIMARY KEY" directive is not emitted, and it's assumed that a
| separate :meth:`.Operations.create_primary_key` directive will be used
| to create this constraint, which may potentially include other columns
| as well as have an explicit name. To instead render an inline
| "PRIMARY KEY" directive, the
| :paramref:`.AddColumnOp.inline_primary_key` parameter may be indicated
| at the same time as the ``primary_key`` parameter (both are needed)::
|
| from alembic import op
| from sqlalchemy import Column, INTEGER
|
| op.add_column(
| "organization",
| Column("id", INTEGER, primary_key=True),
| inline_primary_key=True
| )
|
| The ``primary_key=True`` parameter on
| :class:`~sqlalchemy.schema.Column` also indicates behaviors such as
| using the ``SERIAL`` datatype with the PostgreSQL database, which is
| why two separate, independent parameters are provided to support all
| combinations.
|
| .. versionadded:: 1.18.4 Added
| :paramref:`.AddColumnOp.inline_primary_key`
| to control use of the ``PRIMARY KEY`` inline directive.
|
| **FOREIGN KEY support**
|
| The provided :class:`~sqlalchemy.schema.Column` object may include a
| :class:`~sqlalchemy.schema.ForeignKey` constraint directive,
| referencing a remote table name. By default, 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")),
| )
|
| To render the FOREIGN KEY constraint inline within the ADD COLUMN
| directive, use the ``inline_references`` parameter. This can improve
| performance on large tables since the constraint is marked as valid
| immediately for nullable columns::
|
| from alembic import op
| from sqlalchemy import Column, INTEGER, ForeignKey
|
| op.add_column(
| "organization",
| Column("account_id", INTEGER, ForeignKey("accounts.id")),
| inline_references=True,
| )
|
| **Indicating server side defaults**
|
| 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`.
| :param if_not_exists: If True, adds ``IF NOT EXISTS`` operator
| when creating the new column for compatible dialects
|
| .. versionadded:: 1.16.0
|
| :param inline_references: If True, renders ``FOREIGN KEY`` constraints
| inline within the ``ADD COLUMN`` directive using ``REFERENCES``
| syntax, rather than as a separate ``ALTER TABLE ADD CONSTRAINT``
| statement. This is supported by PostgreSQL, Oracle, MySQL 5.7+, and
| MariaDB 10.5+.
|
| .. versionadded:: 1.18.2
|
| :param inline_primary_key: If True, renders the ``PRIMARY KEY`` phrase
| inline within the ``ADD COLUMN`` directive. When not present or
| False, ``PRIMARY KEY`` is not emitted; it is assumed that the
| migration script will include an additional
| :meth:`.Operations.create_primary_key` directive to create a full
| primary key constraint.
|
| .. versionadded:: 1.18.4
|
| alter_column(self, table_name: 'str', column_name: 'str', *, nullable: 'Optional[bool]' = None, comment: 'Optional[Union[str, Literal[False]]]' = False, server_default: 'Union[_ServerDefaultType, None, Literal[False]]' = False, new_column_name: 'Optional[str]' = None, type_: 'Optional[Union[TypeEngine[Any], Type[TypeEngine[Any]]]]' = None, existing_type: 'Optional[Union[TypeEngine[Any], Type[TypeEngine[Any]]]]' = None, existing_server_default: 'Union[_ServerDefaultType, None, Literal[False]]' = False, existing_nullable: 'Optional[bool]' = None, existing_comment: 'Optional[str]' = None, schema: 'Optional[str]' = None, **kw: 'Any') -> 'None' from alembic.operations.base
| 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.
|
| bulk_insert(self, table: 'Union[Table, TableClause]', rows: 'List[Dict[str, Any]]', *, multiinsert: 'bool' = True) -> 'None' from alembic.operations.base
| 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.
|
| create_check_constraint(self, constraint_name: 'Optional[str]', table_name: 'str', condition: 'Union[str, ColumnElement[bool], TextClause]', *, schema: 'Optional[str]' = None, **kw: 'Any') -> 'None' from alembic.operations.base
| 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`.
|
| create_exclude_constraint(self, constraint_name: 'str', table_name: 'str', *elements: 'Any', **kw: 'Any') -> 'Optional[Table]' from alembic.operations.base
| 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.
|
| 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' from alembic.operations.base
| 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.
|
| 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' from alembic.operations.base
| 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.
|
| create_primary_key(self, constraint_name: 'Optional[str]', table_name: 'str', columns: 'List[str]', *, schema: 'Optional[str]' = None) -> 'None' from alembic.operations.base
| 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`.
|
| create_table(self, table_name: 'str', *columns: 'SchemaItem', if_not_exists: 'Optional[bool]' = None, **kw: 'Any') -> 'Table' from alembic.operations.base
| 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.
|
| create_table_comment(self, table_name: 'str', comment: 'Optional[str]', *, existing_comment: 'Optional[str]' = None, schema: 'Optional[str]' = None) -> 'None' from alembic.operations.base
| 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`
|
| create_unique_constraint(self, constraint_name: 'Optional[str]', table_name: 'str', columns: 'Sequence[str]', *, schema: 'Optional[str]' = None, **kw: 'Any') -> 'Any' from alembic.operations.base
| 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`.
|
| drop_column(self, table_name: 'str', column_name: 'str', *, schema: 'Optional[str]' = None, **kw: 'Any') -> 'None' from alembic.operations.base
| 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 if_exists: If True, adds IF EXISTS operator when
| dropping the new column for compatible dialects
|
| .. versionadded:: 1.16.0
|
| :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.
|
| drop_constraint(self, constraint_name: 'str', table_name: 'str', type_: 'Optional[str]' = None, *, schema: 'Optional[str]' = None, if_exists: 'Optional[bool]' = None) -> 'None' from alembic.operations.base
| 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`.
| :param if_exists: If True, adds IF EXISTS operator when
| dropping the constraint
|
| .. versionadded:: 1.16.0
|
| drop_index(self, index_name: 'str', table_name: 'Optional[str]' = None, *, schema: 'Optional[str]' = None, if_exists: 'Optional[bool]' = None, **kw: 'Any') -> 'None' from alembic.operations.base
| 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.
|
| drop_table(self, table_name: 'str', *, schema: 'Optional[str]' = None, if_exists: 'Optional[bool]' = None, **kw: 'Any') -> 'None' from alembic.operations.base
| 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.
|
| drop_table_comment(self, table_name: 'str', *, existing_comment: 'Optional[str]' = None, schema: 'Optional[str]' = None) -> 'None' from alembic.operations.base
| 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`
|
| execute(self, sqltext: 'Union[Executable, str]', *, execution_options: 'Optional[dict[str, Any]]' = None) -> 'None' from alembic.operations.base
| 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`.
|
| rename_table(self, old_table_name: 'str', new_table_name: 'str', *, schema: 'Optional[str]' = None) -> 'None' from alembic.operations.base
| 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`.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from AbstractOperations:
|
| __init__(self, migration_context: 'MigrationContext', impl: 'Optional[BatchOperationsImpl]' = None) -> 'None'
| Construct a new :class:`.Operations`
|
| :param migration_context: a :class:`.MigrationContext`
| instance.
|
| batch_alter_table(self, table_name: 'str', schema: 'Optional[str]' = None, recreate: "Literal['auto', 'always', 'never']" = 'auto', partial_reordering: 'list[tuple[str, ...]] | None' = None, copy_from: 'Optional[Table]' = None, table_args: 'Tuple[Any, ...]' = (), table_kwargs: 'Mapping[str, Any]' = immutabledict({}), reflect_args: 'Tuple[Any, ...]' = (), reflect_kwargs: 'Mapping[str, Any]' = 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`
|
| 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.
|
| 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]
|
| get_context(self) -> 'MigrationContext'
| Return the :class:`.MigrationContext` object that's
| currently in use.
|
| inline_literal(self, value: 'Union[str, int]', type_: 'Optional[TypeEngine[Any]]' = None) -> '_literal_bindparam'
| 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`
|
| invoke(self, operation: 'MigrateOperation') -> 'Any'
| Given a :class:`.MigrateOperation`, invoke it in terms of
| this :class:`.Operations` instance.
|
| 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.
|
| ----------------------------------------------------------------------
| Class methods inherited from AbstractOperations:
|
| context(migration_context: 'MigrationContext') -> 'Iterator[Operations]'
|
| implementation_for(op_cls: 'Any', replace: 'bool' = False) -> 'Callable[[_C], _C]'
| Register an implementation for a given :class:`.MigrateOperation`.
|
| :param replace: when True, allows replacement of an already
| registered implementation for the given operation class. This
| enables customization of built-in operations such as
| :class:`.CreateTableOp` by providing an alternate implementation
| that can augment, modify, or conditionally invoke the default
| behavior.
|
| .. versionadded:: 1.17.2
|
| This is part of the operation extensibility API.
|
| .. seealso::
|
| :ref:`operation_plugins`
|
| :ref:`operations_extending_builtin`
|
| register_operation(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`
|
| ----------------------------------------------------------------------
| Class methods inherited from alembic.util.langhelpers.ModuleClsProxy:
|
| create_module_class_proxy(globals_: 'MutableMapping[str, Any]', locals_: 'MutableMapping[str, Any]') -> 'None'
|
| ----------------------------------------------------------------------
| Data descriptors inherited from alembic.util.langhelpers.ModuleClsProxy:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
DATA
__all__ = ['AbstractOperations', 'Operations', 'BatchOperations', 'Mig...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\alembic\operations\__init__.py
alembic.plugins
Python Library Documentation: module alembic.runtime.plugins in alembic.runtime
NAME
alembic.runtime.plugins
CLASSES
builtins.object
Plugin
class Plugin(builtins.object)
| Plugin(name: 'str')
|
| Describe a series of functions that are pulled in as a plugin.
|
| This is initially to provide for portable lists of autogenerate
| comparison functions, however the setup for a plugin can run any
| other kinds of global registration as well.
|
| .. versionadded:: 1.18.0
|
| Methods defined here:
|
| __init__(self, name: 'str')
| Initialize self. See help(type(self)) for accurate signature.
|
| add_autogenerate_comparator(self, fn: 'Callable[..., PriorityDispatchResult]', compare_target: 'str', compare_element: 'str | None' = None, *, qualifier: 'str' = 'default', priority: 'DispatchPriority' = <DispatchPriority.MEDIUM: 25>) -> 'None'
| Register an autogenerate comparison function.
|
| See the section :ref:`plugins_registering_autogenerate` for detailed
| examples on how to use this method.
|
| :param fn: The comparison function to register. The function receives
| arguments specific to the type of comparison being performed and
| should return a :class:`.PriorityDispatchResult` value.
|
| :param compare_target: The type of comparison being performed
| (e.g., ``"table"``, ``"column"``, ``"type"``).
|
| :param compare_element: Optional sub-element being compared within
| the target type.
|
| :param qualifier: Database dialect qualifier. Use ``"default"`` for
| all dialects, or specify a dialect name like ``"postgresql"`` to
| register a dialect-specific handler. Defaults to ``"default"``.
|
| :param priority: Execution priority for this comparison function.
| Functions are executed in priority order from
| :attr:`.DispatchPriority.FIRST` to :attr:`.DispatchPriority.LAST`.
| Defaults to :attr:`.DispatchPriority.MEDIUM`.
|
| remove(self) -> 'None'
| remove this plugin
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| populate_autogenerate_priority_dispatch(comparators: 'PriorityDispatcher', include_plugins: 'list[str]') -> 'None'
| Populate all current autogenerate comparison functions into
| a given PriorityDispatcher.
|
| setup_plugin_from_module(module: 'ModuleType', name: 'str') -> 'None'
| Call the ``setup()`` function of a plugin module, identified by
| passing the module object itself.
|
| E.g.::
|
| from alembic.runtime.plugins import Plugin
| import myproject.alembic_plugin
|
| # Register the plugin manually
| Plugin.setup_plugin_from_module(
| myproject.alembic_plugin,
| "myproject.custom_operations"
| )
|
| This will generate a new :class:`.Plugin` object with the given
| name, which will register itself in the global list of plugins.
| Then the module's ``setup()`` function is invoked, passing that
| :class:`.Plugin` object.
|
| This exact process is invoked automatically at import time for any
| plugin module that is published via the ``alembic.plugins`` entrypoint.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
DATA
Callable = typing.Callable
Deprecated alias to collections.abc.Callable.
Callable[[int], str] signifies a function that takes a single
parameter of type int and returns a str.
The subscription syntax must always be used with exactly two
values: the argument list and the return type.
The argument list must be a list of types, a ParamSpec,
Concatenate or ellipsis. The return type must be a single type.
There is no syntax to indicate optional or keyword arguments;
such function types are rarely used as callback types.
Pattern = typing.Pattern
A generic version of re.Pattern.
TYPE_CHECKING = False
__annotations__ = {'_all_plugins': 'dict[str, Plugin]'}
log = <Logger alembic.runtime.plugins (WARNING)>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\alembic\runtime\plugins.py
alembic.runtime
Python Library Documentation: package alembic.runtime in alembic
NAME
alembic.runtime
PACKAGE CONTENTS
environment
migration
plugins
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\alembic\runtime\__init__.py
alembic.script
Python Library Documentation: package alembic.script in alembic
NAME
alembic.script
PACKAGE CONTENTS
base
revision
write_hooks
CLASSES
alembic.script.revision.Revision(builtins.object)
alembic.script.base.Script
builtins.object
alembic.script.base.ScriptDirectory
class Script(alembic.script.revision.Revision)
| Script(module: 'ModuleType', rev_id: 'str', path: 'Union[str, os.PathLike[str]]')
|
| Represent a single revision file in a ``versions/`` directory.
|
| The :class:`.Script` instance is returned by methods
| such as :meth:`.ScriptDirectory.iterate_revisions`.
|
| Method resolution order:
| Script
| alembic.script.revision.Revision
| builtins.object
|
| Methods defined here:
|
| __init__(self, module: 'ModuleType', rev_id: 'str', path: 'Union[str, os.PathLike[str]]')
| Initialize self. See help(type(self)) for accurate signature.
|
| __str__(self) -> 'str'
| Return str(self).
|
| cmd_format(self, verbose: 'bool', include_branches: 'bool' = False, include_doc: 'bool' = False, include_parents: 'bool' = False, tree_indicators: 'bool' = True) -> 'str'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| doc
| Return the docstring given in the script.
|
| log_entry
|
| longdoc
| Return the docstring given in the script.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_db_current_indicator': 'Optional[bool]', 'module'...
|
| ----------------------------------------------------------------------
| Methods inherited from alembic.script.revision.Revision:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| add_nextrev(self, revision: 'Revision') -> 'None'
|
| ----------------------------------------------------------------------
| Class methods inherited from alembic.script.revision.Revision:
|
| verify_rev_id(revision: 'str') -> 'None'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from alembic.script.revision.Revision:
|
| is_base
| Return True if this :class:`.Revision` is a 'base' revision.
|
| is_branch_point
| Return True if this :class:`.Script` is a branch point.
|
| A branchpoint is defined as a :class:`.Script` which is referred
| to by more than one succeeding :class:`.Script`, that is more
| than one :class:`.Script` has a `down_revision` identifier pointing
| here.
|
| is_head
| Return True if this :class:`.Revision` is a 'head' revision.
|
| This is determined based on whether any other :class:`.Script`
| within the :class:`.ScriptDirectory` refers to this
| :class:`.Script`. Multiple heads can be present.
|
| is_merge_point
| Return True if this :class:`.Script` is a merge point.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from alembic.script.revision.Revision:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from alembic.script.revision.Revision:
|
| branch_labels = None
|
| dependencies = None
|
| down_revision = None
|
| nextrev = frozenset()
|
| revision = None
class ScriptDirectory(builtins.object)
| ScriptDirectory(dir: 'Union[str, os.PathLike[str]]', file_template: 'str' = '%(rev)s_%(slug)s', truncate_slug_length: 'Optional[int]' = 40, version_locations: 'Optional[Sequence[Union[str, os.PathLike[str]]]]' = None, sourceless: 'bool' = False, output_encoding: 'str' = 'utf-8', timezone: 'Optional[str]' = None, hooks: 'list[PostWriteHookConfig]' = [], recursive_version_locations: 'bool' = False, messaging_opts: 'MessagingOptions' = immutabledict({})) -> 'None'
|
| Provides operations upon an Alembic script directory.
|
| This object is useful to get information as to current revisions,
| most notably being able to get at the "head" revision, for schemes
| that want to test if the current revision in the database is the most
| recent::
|
| from alembic.script import ScriptDirectory
| from alembic.config import Config
| config = Config()
| config.set_main_option("script_location", "myapp:migrations")
| script = ScriptDirectory.from_config(config)
|
| head_revision = script.get_current_head()
|
| Methods defined here:
|
| __init__(self, dir: 'Union[str, os.PathLike[str]]', file_template: 'str' = '%(rev)s_%(slug)s', truncate_slug_length: 'Optional[int]' = 40, version_locations: 'Optional[Sequence[Union[str, os.PathLike[str]]]]' = None, sourceless: 'bool' = False, output_encoding: 'str' = 'utf-8', timezone: 'Optional[str]' = None, hooks: 'list[PostWriteHookConfig]' = [], recursive_version_locations: 'bool' = False, messaging_opts: 'MessagingOptions' = immutabledict({})) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| as_revision_number(self, id_: 'Optional[str]') -> 'Optional[Union[str, Tuple[str, ...]]]'
| Convert a symbolic revision, i.e. 'head' or 'base', into
| an actual revision number.
|
| generate_revision(self, revid: 'str', message: 'Optional[str]', head: 'Optional[_RevIdType]' = None, splice: 'Optional[bool]' = False, branch_labels: 'Optional[_RevIdType]' = None, version_path: 'Union[str, os.PathLike[str], None]' = None, file_template: 'Optional[str]' = None, depends_on: 'Optional[_RevIdType]' = None, **kw: 'Any') -> 'Optional[Script]'
| Generate a new revision file.
|
| This runs the ``script.py.mako`` template, given
| template arguments, and creates a new file.
|
| :param revid: String revision id. Typically this
| comes from ``alembic.util.rev_id()``.
| :param message: the revision message, the one passed
| by the -m argument to the ``revision`` command.
| :param head: the head revision to generate against. Defaults
| to the current "head" if no branches are present, else raises
| an exception.
| :param splice: if True, allow the "head" version to not be an
| actual head; otherwise, the selected head must be a head
| (e.g. endpoint) revision.
|
| get_all_current(self, id_: 'Tuple[str, ...]') -> 'Set[Script]'
|
| get_base(self) -> 'Optional[str]'
| Return the "base" revision as a string.
|
| This is the revision number of the script that
| has a ``down_revision`` of None.
|
| If the script directory has multiple bases, an error is raised;
| :meth:`.ScriptDirectory.get_bases` should be
| preferred.
|
| get_bases(self) -> 'List[str]'
| return all "base" revisions as strings.
|
| This is the revision number of all scripts that
| have a ``down_revision`` of None.
|
| get_current_head(self) -> 'Optional[str]'
| Return the current head revision.
|
| If the script directory has multiple heads
| due to branching, an error is raised;
| :meth:`.ScriptDirectory.get_heads` should be
| preferred.
|
| :return: a string revision number.
|
| .. seealso::
|
| :meth:`.ScriptDirectory.get_heads`
|
| get_heads(self, consider_depends_on: 'bool' = False) -> 'List[str]'
| Return all "versioned head" revisions as strings.
|
| This is normally a list of length one,
| unless branches are present. The
| :meth:`.ScriptDirectory.get_current_head()` method
| can be used normally when a script directory
| has only one head.
|
| :param consider_depends_on: if True, head revisions that are
| also a dependency of another revision via
| :paramref:`.Operations.create_revision.depends_on` will not
| be included in the returned list, matching the effective heads
| that would be present in the ``alembic_version`` table after
| running all upgrades.
|
| .. versionadded:: 1.18.5
|
| :return: a list of string revision numbers.
|
| get_revision(self, id_: 'str') -> 'Script'
| Return the :class:`.Script` instance with the given rev id.
|
| .. seealso::
|
| :meth:`.ScriptDirectory.get_revisions`
|
| get_revisions(self, id_: '_GetRevArg') -> 'Tuple[Script, ...]'
| Return the :class:`.Script` instance with the given rev identifier,
| symbolic name, or sequence of identifiers.
|
| iterate_revisions(self, upper: 'Union[str, Tuple[str, ...], None]', lower: 'Union[str, Tuple[str, ...], None]', **kw: 'Any') -> 'Iterator[Script]'
| Iterate through script revisions, starting at the given
| upper revision identifier and ending at the lower.
|
| The traversal uses strictly the `down_revision`
| marker inside each migration script, so
| it is a requirement that upper >= lower,
| else you'll get nothing back.
|
| The iterator yields :class:`.Script` objects.
|
| .. seealso::
|
| :meth:`.RevisionMap.iterate_revisions`
|
| run_env(self) -> 'None'
| Run the script environment.
|
| This basically runs the ``env.py`` script present
| in the migration environment. It is called exclusively
| by the command functions in :mod:`alembic.command`.
|
| walk_revisions(self, base: 'str' = 'base', head: 'str' = 'heads') -> 'Iterator[Script]'
| Iterate through all revisions.
|
| :param base: the base revision, or "base" to start from the
| empty revision.
|
| :param head: the head revision; defaults to "heads" to indicate
| all head revisions. May also be "head" to indicate a single
| head revision.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_config(config: 'Config') -> 'ScriptDirectory'
| Produce a new :class:`.ScriptDirectory` given a :class:`.Config`
| instance.
|
| The :class:`.Config` need only have the ``script_location`` key
| present.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| env_py_location
|
| versions
| return a single version location based on the sole path passed
| within version_locations.
|
| If multiple version locations are configured, an error is raised.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
DATA
__all__ = ['ScriptDirectory', 'Script']
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\alembic\script\__init__.py
alembic.util
Python Library Documentation: package alembic.util in alembic
NAME
alembic.util
PACKAGE CONTENTS
compat
editor
exc
langhelpers
messaging
pyfiles
sqla_compat
DATA
EMPTY_DICT = immutabledict({})
sqla_2 = True
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\alembic\util\__init__.py