This section describes some key functions used within the migration process, particularly those referenced within a migration environment’s env.py file.
The alembic.context module contains API features that are generally used within env.py files.
The central object in use is the Context object. This object is made present when the env.py script calls upon the configure() method for the first time. Before this function is called, there’s not yet any database connection or dialect-specific state set up, and those functions which require this state will raise an exception when used, until configure() is called successfully.
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.
Maintains state throughout the migration running process.
Mediates the relationship between an env.py environment script, a ScriptDirectory instance, and a DefaultImpl instance.
The Context is available directly via the get_context() function, though usually it is referenced behind the scenes by the various module level functions within the alembic.context module.
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.
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.
The current Config object.
This is the gateway to the alembic.ini or other .ini file in use for the current command.
This function does not require that the Context has been configured.
Configure the migration environment.
The important thing needed here is first a way to figure out what kind of “dialect” is in use. The second is to pass an actual database connection, if one is required.
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. |
---|
Deprecated; use alembic.context.configure().
Execute the given SQL using the current change context.
The behavior of context.execute() is the same as that of op.execute(). Please see that function’s documentation for full detail including caveats and limitations.
This function requires that a Context has first been made available via configure().
Return the current ‘bind’.
In “online” mode, this is the sqlalchemy.engine.Connection currently being used to emit SQL to the database.
This function requires that a Context has first been made available via configure().
Return the current Context object.
If configure() has not been called yet, raises an exception.
Generally, env.py scripts should access the module-level functions in alebmic.context to get at this object’s functionality.
Return the hex identifier of the ‘head’ revision.
This function does not require that the Context 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 Context 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 Context 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 Context 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 Context 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 Context 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 Context has first been made available via configure().
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.
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 alembic.context.config attribute:
from alembic import context
some_param = context.config.get_main_option("my option")
When invoking Alembic programatically, a new Config can be created simply 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.
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.
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.
As env.py runs context.configure_connection(), the connection environment should be set up first. This is typically achieved using the context.opts().
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 context.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 context.begin_transaction().
A hook called when Context.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