The “runtime” of Alembic involves the EnvironmentContext and MigrationContext objects. These are the objects that are in play once the env.py script is loaded up by a command and a migration operation proceeds.
The EnvironmentContext class provides most of the API used within an env.py script. Within env.py, the instantated EnvironmentContext is made available via a special proxy module called alembic.context. That is, you can import alembic.context like a regular Python module, and each name you call upon it is ultimately routed towards the current EnvironmentContext in use.
In particular, the key method used within env.py is EnvironmentContext.configure(), which establishes all the details about how the database will be accessed.
A configurational facade made available in an env.py script.
The EnvironmentContext acts as a facade to the more nuts-and-bolts objects of MigrationContext as well as certain aspects of Config, within the context of the env.py script that is invoked by most Alembic commands.
EnvironmentContext is normally instantiated when a command in alembic.command is run. It then makes itself available in the alembic.context module for the scope of the command. From within an env.py script, the current EnvironmentContext is available by importing this module.
EnvironmentContext also supports programmatic usage. At this level, it acts as a Python context manager, that is, is intended to be used using the with: statement. A typical use of EnvironmentContext:
from alembic.config import Config
from alembic.script import ScriptDirectory
config = Config()
config.set_main_option("script_location", "myapp:migrations")
script = ScriptDirectory.from_config(config)
def my_function(rev, context):
'''do something with revision "rev", which
will be the current database revision,
and "context", which is the MigrationContext
that the env.py will create'''
with EnvironmentContext(
config,
script,
fn = my_function,
as_sql = False,
starting_rev = 'base',
destination_rev = 'head',
tag = "sometag"
):
script.run_env()
The above script will invoke the env.py script within the migration environment. If and when env.py calls MigrationContext.run_migrations(), the my_function() function above will be called by the MigrationContext, given the context itself as well as the current revision in the database.
Note
For most API usages other than full blown invocation of migration scripts, the MigrationContext and ScriptDirectory objects can be created and used directly. The EnvironmentContext object is only needed when you need to actually invoke the env.py module present in the migration environment.
Construct a new EnvironmentContext.
Parameters: |
|
---|
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.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: |
|
---|
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.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’ script revision.
If the script directory has multiple heads, this method raises a CommandError; EnvironmentContext.get_head_revisions() should be preferred.
This function does not require that the MigrationContext has been configured.
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 MigrationContext has been configured.
New in version 0.7.0.
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.
See also
EnvironmentContext.get_x_argument() - a newer and more open ended system of extending env.py scripts via the command line.
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.
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 MigrationContext has been configured.
New in version 0.6.0.
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.
The MigrationContext handles the actual work to be performed against a database backend as migration operations proceed. It is generally not exposed to the end-user.
Represent the database state made available to a migration script.
MigrationContext is the front end to an actual database connection, or alternatively a string output stream given a particular database dialect, from an Alembic perspective.
When inside the env.py script, the MigrationContext is available via the EnvironmentContext.get_context() method, which is available at alembic.context:
# from within env.py script
from alembic import context
migration_context = context.get_context()
For usage outside of an env.py script, such as for utility routines that want to check the current version in the database, the MigrationContext.configure() method to create new MigrationContext objects. For example, to get at the current revision in the database using MigrationContext.get_current_revision():
# in any application, outside of an env.py script
from alembic.migration import MigrationContext
from sqlalchemy import create_engine
engine = create_engine("postgresql://mydatabase")
conn = engine.connect()
context = MigrationContext.configure(conn)
current_rev = context.get_current_revision()
The above context can also be used to produce Alembic migration operations with an Operations instance:
# in any application, outside of the normal Alembic environment
from alembic.operations import Operations
op = Operations(context)
op.alter_column("mytable", "somecolumn", nullable=True)
Return the current “bind”.
In online mode, this is an instance of sqlalchemy.engine.Connection, and is suitable for ad-hoc execution of any kind of usage described in sqlexpression_toplevel 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: |
|
---|
Execute a SQL construct or string statement.
The underlying execution mechanics are used, that is if this is “offline mode” the SQL is written to the output buffer, otherwise the SQL is emitted on the current SQLAlchemy connection.
Return a tuple of the current ‘head versions’ that are represented in the target database.
For a migration stream without branches, this will be a single value, synonymous with that of MigrationContext.get_current_revision(). However when multiple unmerged branches exist within the target database, the returned tuple will contain a value for each head.
If this MigrationContext was configured in “offline” mode, that is with as_sql=True, the starting_rev parameter is returned in a one-length tuple.
If no version table is present, or if there are no revisions present, an empty tuple is returned.
New in version 0.7.0.
Return the current revision, usually that which is present in the alembic_version table in the database.
This method intends to be used only for a migration stream that does not contain unmerged branches in the target database; if there are multiple branches present, an exception is raised. The MigrationContext.get_current_heads() should be preferred over this method going forward in order to be compatible with branch migration support.
If this MigrationContext was configured in “offline” mode, that is with as_sql=True, the starting_rev parameter is returned instead, if any.
Run the migration scripts established for this MigrationContext, if any.
The commands in alembic.command will set up a function that is ultimately passed to the MigrationContext as the fn argument. This function represents the “work” that will be done when MigrationContext.run_migrations() is called, typically from within the env.py script of the migration environment. The “work function” then provides an iterable of version callables and other version information which in the case of the upgrade or downgrade commands are the list of version scripts to invoke. Other commands yield nothing, in the case that a command wants to run some other operation against the database such as the current or stamp commands.
Parameters: | **kw¶ – keyword arguments here will be passed to each migration callable, that is the upgrade() or downgrade() method within revision scripts. |
---|
Stamp the version table with a specific revision.
This method calculates those branches to which the given revision can apply, and updates those branches as though they were migrated towards that revision (either up or down). If no current branches include the revision, it is added as a new branch head.
New in version 0.7.0.