This section describes some key functions used within the migration process, particularly those referenced within a migration environment’s env.py file.
The three main objects in use are the EnvironmentContext, MigrationContext, and Operations classes, pictured below.
An Alembic command begins by instantiating an EnvironmentContext object, then making it available via the alembic.context proxy module. The env.py script, representing a user-configurable migration environment, is then invoked. The env.py script is then responsible for calling upon the EnvironmentContext.configure(), whose job it is to create a MigrationContext object.
Before this method is called, there’s not yet any database connection or dialect-specific state set up. While many methods on EnvironmentContext are usable at this stage, those which require database access, or at least access to the kind of database dialect in use, are not. Once the EnvironmentContext.configure() method is called, the EnvironmentContext is said to be configured with database connectivity, available via a new MigrationContext object. The MigrationContext is associated with the EnvironmentContext object via the EnvironmentContext.get_context() method.
Finally, env.py calls upon the EnvironmentContext.run_migrations() method. Within this method, a new Operations object, which provides an API for individual database migration operations, is established within the alembic.op proxy module. The Operations object uses the MigrationContext object ultimately as a source of database connectivity, though in such a way that it does not care if the MigrationContext is talking to a real database or just writing out SQL to a file.
This section covers the objects that are generally used within an env.py environmental configuration script. Alembic normally generates this script for you; it is however made available locally within the migrations environment so that it can be customized.
In particular, the key method used within env.py is EnvironmentContext.configure(), which establishes all the details about how the database will be accessed.
Create a new Engine instance using a configuration dictionary.
The dictionary is typically produced from a config file where keys are prefixed, such as sqlalchemy.url, sqlalchemy.echo, etc. The ‘prefix’ argument indicates the prefix to be searched for.
A select set of keyword arguments will be “coerced” to their expected type based on string values. In a future release, this functionality will be expanded and include dialect-specific arguments.
Represent the state made available to an env.py script.
EnvironmentContext is normally instantiated by the commands present in the alembic.command module. From within an env.py script, the current EnvironmentContext is available via the alembic.context datamember.
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()
begin_transaction() is intended to “do the right thing” regardless of calling context:
Note that a custom env.py script which has more specific transactional needs can of course manipulate the Connection directly to produce transactional state in “online” mode.
An instance of Config representing the configuration file contents as well as other variables set programmatically within it.
Configure a MigrationContext within this EnvironmentContext which will provide database connectivity and other configuration to a series of migration scripts.
Many methods on 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 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 MigrationContext is to be used in “online” mode.
If the is_offline_mode() function returns True, then no connection is needed here. Otherwise, the connection parameter should be present as an instance of sqlalchemy.engine.base.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 Connection for which it was called is the one that will be operated upon by the next call to run_migrations().
General parameters:
Parameters: |
|
---|
Parameters specific to the autogenerate feature, when alembic revision is run with the --autogenerate feature:
Parameters: |
|
---|
Parameters specific to individual backends:
Parameters: | 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. |
---|
Execute the given SQL using the current change context.
The behavior of execute() is the same as that of Operations.execute(). Please see that function’s documentation for full detail including caveats and limitations.
This function requires that a MigrationContext has first been made available via configure().
Return the current ‘bind’.
In “online” mode, this is the sqlalchemy.engine.base.Connection currently being used to emit SQL to the database.
This function requires that a MigrationContext has first been made available via configure().
Return the current MigrationContext object.
If EnvironmentContext.configure() has not been called yet, raises an exception.
Return the hex identifier of the ‘head’ revision.
This function does not require that the MigrationContext has been configured.
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 MigrationContext has been configured.
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 MigrationContext has been configured.
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 MigrationContext has been configured.
Return True if the current migrations environment is running in “offline mode”.
This is True or False depending on the the --sql flag passed.
This function does not require that the MigrationContext has been configured.
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 configure()
This function requires that a MigrationContext has first been made available via configure().
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 MigrationContext has first been made available via configure().
An instance of ScriptDirectory which provides programmatic access to version files within the versions/ directory.
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.
alias of EnvironmentContext
Represent the state made available to a migration script, or otherwise a series of migration operations.
Mediates the relationship between an env.py environment script, a ScriptDirectory instance, and a DefaultImpl instance.
The MigrationContext that’s established for a duration of a migration command is available via the EnvironmentContext.get_context() method, which is available at alembic.context:
from alembic import context
migration_context = context.get_context()
A MigrationContext can be created programmatically for usage outside of the usual Alembic migrations flow, using the MigrationContext.configure() method:
conn = myengine.connect()
ctx = MigrationContext.configure(conn)
The above context can then be used to produce Alembic migration operations with an Operations instance.
Return the current “bind”.
In online mode, this is an instance of sqlalchemy.engine.base.Connection, and is suitable for ad-hoc execution of any kind of usage described in SQL Expression Language Tutorial as well as for usage with the sqlalchemy.schema.Table.create() and sqlalchemy.schema.MetaData.create_all() methods of Table, MetaData.
Note that when “standard output” mode is enabled, this bind will be a “mock” connection handler that cannot return results and is only appropriate for a very limited subset of commands.
Create a new MigrationContext.
This is a factory method usually called by EnvironmentContext.configure().
Parameters: |
|
---|
Alembic commands are all represented by functions in the alembic.command package. They all accept the same style of usage, being sent the Config object as the first argument.
Commands can be run programmatically, by first constructing a Config object, as in:
from alembic.config import Config
from alembic import command
alembic_cfg = Config("/path/to/yourapp/alembic.ini")
command.upgrade(alembic_cfg, "head")
Show current un-spliced branch points
Display the current revision for each database.
Revert to a previous version.
List changeset scripts in chronological order.
Initialize a new scripts directory.
List available templates
Create a new revision file.
‘splice’ two branches, creating a new revision file.
this command isn’t implemented right now.
‘stamp’ the revision table with the given revision; don’t run any migrations.
Upgrade to a later version.
Represent an Alembic configuration.
Within an env.py script, this is available via the EnvironmentContext.config attribute, which in turn is available at alembic.context:
from alembic import context
some_param = context.config.get_main_option("my option")
When invoking Alembic programatically, a new Config can be created by passing the name of an .ini file to the constructor:
from alembic.config import Config
alembic_cfg = Config("/path/to/yourapp/alembic.ini")
With a Config object, you can then run Alembic commands programmatically using the directives in alembic.command.
The Config object can also be constructed without a filename. Values can be set programmatically, and new sections will be created as needed:
from alembic.config import Config
alembic_cfg = Config()
alembic_cfg.set_main_option("url", "postgresql://foo/bar")
alembic_cfg.set_section_option("mysection", "foo", "bar")
Parameters: |
|
---|
Filesystem path to the .ini file in use.
Name of the config file section to read basic configuration from. Defaults to alembic, that is the [alembic] section of the .ini file. This value is modified using the -n/--name option to the Alembic runnier.
Return an option from the ‘main’ section of the .ini file.
This defaults to being a key from the [alembic] section, unless the -n/--name flag were used to indicate a different section.
Return all the configuration options from a given .ini file section as a dictionary.
Return an option from the given section of the .ini file.
Return the directory where Alembic setup templates are found.
This method is used by the alembic init and list_templates commands.
Set an option programmatically within the ‘main’ section.
This overrides whatever was in the .ini file.
Set an option programmatically within the given section.
The section is created if it doesn’t exist already. The value here will override whatever was in the .ini file.
The console runner function for Alembic.
Represent a single revision file in a versions/ directory.
Provides operations upon an Alembic script directory.
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 alembic.command.
Iterate through all revisions.
This is actually a breadth-first tree traversal, with leaf nodes being heads.
Represent an ALTER TABLE statement.
Only the string name and optional schema name of the table is required, not a full Table object.
quote the elements of a dotted name
Provide the entrypoint for major migration operations, including database-specific behavioral variances.
While individual SQL/DDL constructs already provide for database-specific implementations, variances here allow for entirely different sequences of operations to take place for a particular migration, such as SQL Server’s special ‘IDENTITY INSERT’ step for bulk inserts.
Emit the string BEGIN, or the backend-specific equivalent, on the current connection context.
This is used in offline mode and typically via EnvironmentContext.begin_transaction().
Emit the string COMMIT, or the backend-specific equivalent, on the current connection context.
This is used in offline mode and typically via EnvironmentContext.begin_transaction().
A hook called when EnvironmentContext.run_migrations() is called.
Implementations can set up per-migration-run state here.
Bases: alembic.ddl.base.AlterColumn
Bases: alembic.ddl.impl.DefaultImpl
Bases: alembic.ddl.impl.DefaultImpl
Bases: alembic.ddl.impl.DefaultImpl
Bases: alembic.ddl.impl.DefaultImpl