Changelog¶
1.8.0¶
Released: May 31, 2022changed¶
feature¶
usecase¶
The
op.drop_table()
operation directive will now trigger thebefore_drop()
andafter_drop()
DDL event hooks at the table level, which is similar to how thebefore_create()
andafter_create()
hooks are triggered by theop.create_table()
directive. Note that asop.drop_table()
accepts only a table name and optional schema name, theTable
object received by the event will not have any information within it other than the table name and schema name.References: #1037
Added new token
epoch
to thefile_template
option, which will populate the integer epoch as determined byint(create_date.timestamp())
. Pull request courtesy Caio Carvalho.References: #1027
bug¶
Fixed issue where a downgrade using a relative revision would fail in case of multiple branches with a single effectively head due to interdependencies between revisions.
References: #1026
Fixed issue in batch mode where CREATE INDEX would not use a new column name in the case of a column rename.
References: #1034
1.7.7¶
Released: March 14, 2022bug¶
Fixed issue where using
Operations.create_table()
in conjunction with aCheckConstraint
that referred to table-boundColumn
objects rather than string expressions would be added to the parent table potentially multiple times, resulting in an incorrect DDL sequence. Pull request courtesy Nicolas CANIART.References: #1004
The
logging.fileConfig()
line inenv.py
templates, which is used to setup Python logging for the migration run, is now conditional onConfig.config_file_name
not beingNone
. Otherwise, the line is skipped as there is no default logging configuration present.References: #986
Fixed bug where an
Operations.alter_column()
operation would change a “NOT NULL” column to “NULL” by emitting an ALTER COLUMN statement that did not specify “NOT NULL”. (In the absence of “NOT NULL” T-SQL was implicitly assuming “NULL”). AnOperations.alter_column()
operation that specifiesOperations.alter_column.type
should also specify include eitherOperations.alter_column.nullable
orOperations.alter_column.existing_nullable
to inform Alembic as to whether the emitted DDL should include “NULL” or “NOT NULL”; a warning is now emitted if this is missing under this scenario.References: #977
1.7.6¶
Released: February 1, 2022usecase¶
Add a new command
alembic ensure_version
, which will ensure that the Alembic version table is present in the target database, but does not alter its contents. Pull request courtesy Kai Mueller.References: #964
bug¶
Fixed regression where usage of a
with_variant()
datatype in conjunction with theexisting_type
option ofop.alter_column()
under batch mode would lead to an internal exception.References: #982
Implemented support for recognizing and rendering SQLAlchemy “variant” types going forward into SQLAlchemy 2.0, where the architecture of “variant” datatypes will be changing.
Added a rule to the MySQL impl so that the translation between JSON / LONGTEXT is accommodated by autogenerate, treating LONGTEXT from the server as equivalent to an existing JSON in the model.
References: #968
misc¶
Removed a warning raised by SQLAlchemy when dropping constraints on MSSQL regarding statement caching.
1.7.5¶
Released: November 11, 2021bug¶
Adjustments to the test suite to accommodate for error message changes occurring as of SQLAlchemy 1.4.27.
1.7.4¶
Released: October 6, 2021bug¶
Fixed a regression that prevented the use of post write hooks on python version lower than 3.9
References: #934
Fixed issue where the
MigrationContext.autocommit_block()
feature would fail to function when using a SQLAlchemy engine using 2.0 future mode.References: #944
1.7.3¶
Released: September 17, 2021bug¶
Fixed type annotations for the “constraint_name” argument of operations
create_primary_key()
,create_foreign_key()
. Pull request courtesy TilmanK.References: #914
1.7.2¶
Released: September 17, 2021bug¶
Added missing attributes from context stubs.
References: #900
Fixed an import in one of the .pyi files that was triggering an assertion error in some versions of mypy.
References: #897
Fixed issue where registration of custom ops was prone to failure due to the registration process running
exec()
on generated code that as of the 1.7 series includes pep-484 annotations, which in the case of end user code would result in name resolution errors when the exec occurs. The logic in question has been altered so that the annotations are rendered as forward references so that theexec()
can proceed.References: #920
1.7.1¶
Released: August 30, 2021bug¶
Corrected “universal wheel” directive in setup.cfg so that building a wheel does not target Python 2. The PyPi files index for 1.7.0 was corrected manually. Pull request courtesy layday.
References: #893
Fixed issue in generated .pyi files where default values for
Optional
arguments were missing, thereby causing mypy to consider them as required.References: #895
Fixed regression in batch mode due to #883 where the “auto” mode of batch would fail to accommodate any additional migration directives beyond encountering an
add_column()
directive, due to a mis-application of the conditional logic that was added as part of this change, leading to “recreate” mode not being used in cases where it is required for SQLite such as for unique constraints.References: #896
1.7.0¶
Released: August 30, 2021changed¶
Alembic 1.7 now supports Python 3.6 and above; support for prior versions including Python 2.7 has been dropped.
Make the
python-dateutil
library an optional dependency. This library is only required if thetimezone
option is used in the Alembic configuration. An extra require namedtz
is available withpip install alembic[tz]
to install it.References: #674
The dependency on
pkg_resources
which is part ofsetuptools
has been removed, so there is no longer any runtime dependency onsetuptools
. The functionality has been replaced withimportlib.metadata
andimportlib.resources
which are both part of Python std.lib, or via pypy dependencyimportlib-metadata
for Python version < 3.8 andimportlib-resources
for Python version < 3.9 (while importlib.resources was added to Python in 3.7, it did not include the “files” API until 3.9).References: #885
feature¶
Enhance
version_locations
parsing to handle paths containing spaces. The new configuration optionversion_path_separator
specifies the character to use when splitting theversion_locations
string. The default for new configurations isversion_path_separator = os
, which will useos.pathsep
(e.g.,;
on Windows).References: #842
Created a “test suite” similar to the one for SQLAlchemy, allowing developers of third-party dialects to test their code against a set of Alembic tests that have been specially selected to exercise back-end database operations. At the time of release, third-party dialects that have adopted the Alembic test suite to verify compatibility include CockroachDB and SAP ASE (Sybase).
References: #855
pep-484 type annotations have been added throughout the library. Additionally, stub .pyi files have been added for the “dynamically” generated Alembic modules
alembic.op
andalembic.config
, which include complete function signatures and docstrings, so that the functions in these namespaces will have both IDE support (vscode, pycharm, etc) as well as support for typing tools like Mypy. The files themselves are statically generated from their source functions within the source tree.
usecase¶
Named CHECK constraints are now supported by batch mode, and will automatically be part of the recreated table assuming they are named. They also can be explicitly dropped using
op.drop_constraint()
. For “unnamed” CHECK constraints, these are still skipped as they cannot be distinguished from the CHECK constraints that are generated by theBoolean
andEnum
datatypes.Note that this change may require adjustments to migrations that drop or rename columns which feature an associated named check constraint, such that an additional
op.drop_constraint()
directive should be added for that named constraint as there will no longer be an associated column for it; for theBoolean
andEnum
datatypes, anexisting_type
keyword may be passed toBatchOperations.drop_constraint
as well.References: #884
bug¶
Fixed regression due to #803 where the
.info
and.comment
attributes ofTable
would be lost inside of theDropTableOp
class, which when “reversed” into aCreateTableOp
would then have lost these elements. Pull request courtesy Nicolas CANIART.References: #879
Batch “auto” mode will now select for “recreate” if the
add_column()
operation is used on SQLite, and the column itself meets the criteria for SQLite where ADD COLUMN is not allowed, in this case a functional or parenthesized SQL expression or aComputed
(i.e. generated) column.References: #883
Re-implemented the
python-editor
dependency as a small internal function to avoid the need for external dependencies.References: #856
Fixed issue where usage of the PostgreSQL
postgresql_include
option within aOperations.create_index()
would raise a KeyError, as the additional column(s) need to be added to the table object used by the construct internally. The issue is equivalent to the SQL Server issue fixed in #513. Pull request courtesy Steven Bronson.References: #874
1.6.5¶
Released: May 27, 2021bug¶
Fixed issue where dialect-specific keyword arguments within the
DropIndex
operation directive would not render in the autogenerated Python code. As support was improved for adding dialect specific arguments to directives as part of #803, in particular arguments such as “postgresql_concurrently” which apply to the actual create/drop of the index, support was needed for these to render even in a drop index operation. Pull request courtesy Jet Zhou.References: #849
1.6.4¶
Released: May 24, 2021bug¶
1.6.3¶
Released: May 21, 2021bug¶
Fixed 1.6-series regression where
UniqueConstraint
and to a lesser extentIndex
objects would be doubled up in the generated model when theunique=True
/index=True
flags were used.References: #844
Fixed a bug where paths defined in post-write hook options would be wrongly escaped in non posix environment (Windows).
References: #839
Fixed regression where a revision file that contained its own down revision as a dependency would cause an endless loop in the traversal logic.
References: #843
1.6.2¶
Released: May 6, 2021bug¶
1.6.1¶
Released: May 6, 2021bug¶
Fixed regression in new revisioning traversal where “alembic downgrade base” would fail if the database itself were clean and unversioned; additionally repairs the case where downgrade would fail if attempting to downgrade to the current head that is already present.
References: #838
1.6.0¶
Released: May 3, 2021feature¶
Fix the documentation regarding the default command-line argument position of the revision script filename within the post-write hook arguments. Implement a
REVISION_SCRIPT_FILENAME
token, enabling the position to be changed. Switch fromstr.split()
toshlex.split()
for more robust command-line argument parsing.References: #819
Implement a
.cwd
(current working directory) suboption for post-write hooks (of typeconsole_scripts
). This is useful for tools like pre-commit, which rely on the working directory to locate the necessary config files. Add pre-commit as an example to the documentation. Minor change: rename some variables from ticket #819 to improve readability.References: #822
bug¶
Refactored the implementation of
MigrateOperation
constructs such asCreateIndexOp
,CreateTableOp
, etc. so that they no longer rely upon maintaining a persistent version of each schema object internally; instead, the state variables of each operation object will be used to produce the corresponding construct when the operation is invoked. The rationale is so that environments which make use of operation-manipulation schemes such as those those discussed in Fine-Grained Autogenerate Generation with Rewriters are better supported, allowing end-user code to manipulate the public attributes of these objects which will then be expressed in the final output, an example issome_create_index_op.kw["postgresql_concurrently"] = True
.Previously, these objects when generated from autogenerate would typically hold onto the original, reflected element internally without honoring the other state variables of each construct, preventing the public API from working.
References: #803
Fixed regression caused by the SQLAlchemy 1.4/2.0 compatibility switch where calling
.rollback()
or.commit()
explicitly within thecontext.begin_transaction()
context manager would cause it to fail when the block ended, as it did not expect that the transaction was manually closed.References: #829
Improved the rendering of
op.add_column()
operations when adding multiple columns to an existing table, so that the order of these statements matches the order in which the columns were declared in the application’s table metadata. Previously the added columns were being sorted alphabetically.References: #827
The algorithm used for calculating downgrades/upgrades/iterating revisions has been rewritten, to resolve ongoing issues of branches not being handled consistently particularly within downgrade operations, as well as for overall clarity and maintainability. This change includes that a deprecation warning is emitted if an ambiguous command such as “downgrade -1” when multiple heads are present is given.
In particular, the change implements a long-requested use case of allowing downgrades of a single branch to a branchpoint.
Huge thanks to Simon Bowly for their impressive efforts in successfully tackling this very difficult problem.
Added missing
batch_op.create_table_comment()
,batch_op.drop_table_comment()
directives to batch ops.References: #799
1.5.8¶
Released: March 23, 2021bug¶
Fixed regression caused by SQLAlchemy 1.4 where the “alembic current” command would fail due to changes in the
URL
object.References: #816
1.5.7¶
Released: March 11, 2021bug¶
Adjusted the recently added
EnvironmentContext.configure.include_name
hook to accommodate for additional object types such as “views” that don’t have a parent table, to support third party recipes and extensions. Pull request courtesy Oliver Rice.References: #813
1.5.6¶
Released: March 5, 2021bug¶
Fixed bug where the “existing_type” parameter, which the MSSQL dialect requires in order to change the nullability of a column in the absence of also changing the column type, would cause an ALTER COLUMN operation to incorrectly render a second ALTER statement without the nullability if a new type were also present, as the MSSQL-specific contract did not anticipate all three of “nullability”, “type_” and “existing_type” being sent at the same time.
References: #812
misc¶
Add async template to Alembic to bootstrap environments that use async DBAPI. Updated the cookbook to include a migration guide on how to adapt an existing environment for use with DBAPI drivers.
1.5.5¶
Released: February 20, 2021bug¶
Adjusted the use of SQLAlchemy’s “.copy()” internals to use “._copy()” for version 1.4.0, as this method is being renamed.
Added new config file option
prepend_sys_path
, which is a series of paths that will be prepended to sys.path; the default value in newly generated alembic.ini files is “.”. This fixes a long-standing issue where for some reason running the alembic command line would not place the local “.” path in sys.path, meaning an application locally present in “.” and importable through normal channels, e.g. python interpreter, pytest, etc. would not be located by Alembic, even though theenv.py
file is loaded relative to the current path whenalembic.ini
contains a relative path. To enable for existing installations, add the option to the alembic.ini file as follows:# sys.path path, will be prepended to sys.path if present. # defaults to the current working directory. prepend_sys_path = .
See also
Installation - updated documentation reflecting that local installation of the project is not necessary if running the Alembic cli from the local path.
References: #797
1.5.4¶
Released: February 3, 2021bug¶
Fixed bug in versioning model where a downgrade across a revision with a dependency on another branch, yet an ancestor is also dependent on that branch, would produce an erroneous state in the alembic_version table, making upgrades impossible without manually repairing the table.
References: #789
1.5.3¶
Released: January 29, 2021bug¶
Changed the default ordering of “CREATE” and “DROP” statements indexes and unique constraints within the autogenerate process, so that for example in an upgrade() operation, a particular index or constraint that is to be replaced such as for a casing convention change will not produce any naming conflicts. For foreign key constraint objects, this is already how constraints are ordered, and for table objects, users would normally want to use
Operations.rename_table()
in any case.References: #786
Fixed assorted autogenerate issues with SQL Server:
ignore default reflected identity on primary_key columns
improve server default comparison
References: #787
Fixed issue where autogenerate rendering of
op.alter_column()
would fail to include MySQLexisting_nullable=False
if the column were part of a primary key constraint within the table metadata.References: #788
1.5.2¶
Released: January 20, 2021bug¶
Fixed regression where new “loop detection” feature introduced in #757 produced false positives for revision names that have overlapping substrings between revision number and down revision and/or dependency, if the downrev/dependency were not in sequence form.
References: #784
Fixed regression where Alembic would fail to create a transaction properly if the
sqlalchemy.engine.Connection
were a so-called “branched” connection, that is, one where the.connect()
method had been called to create a “sub” connection.References: #782
1.5.1¶
Released: January 19, 2021bug¶
Fixed installation issue where the “templates” directory was not being installed, preventing commands like “list_templates” and “init” from working.
References: #780
1.5.0¶
Released: January 18, 2021changed¶
To accommodate SQLAlchemy 1.4 and 2.0, the migration model now no longer assumes that the SQLAlchemy Connection will autocommit an individual operation. This essentially means that for databases that use non-transactional DDL (pysqlite current driver behavior, MySQL), there is still a BEGIN/COMMIT block that will surround each individual migration. Databases that support transactional DDL should continue to have the same flow, either per migration or per-entire run, depending on the value of the
Environment.configure.transaction_per_migration
flag.A
CommandError
is raised if asqlalchemy.engine.Engine
is passed to theMigrationContext.configure()
method instead of asqlalchemy.engine.Connection
object. Previously, this would be a warning only.Alembic 1.5.0 now supports Python 2.7 and Python 3.6 and above, as well as SQLAlchemy 1.3.0 and above. Support is removed for Python 3 versions prior to 3.6 and SQLAlchemy versions prior to the 1.3 series.
References: #748
feature¶
Added new hook
EnvironmentContext.configure.include_name
, which complements theEnvironmentContext.configure.include_object
hook by providing a means of preventing objects of a certain name from being autogenerated before the SQLAlchemy reflection process takes place, and notably includes explicit support for passing each schema name whenEnvironmentContext.configure.include_schemas
is set to True. This is most important especially for environments that make use ofEnvironmentContext.configure.include_schemas
where schemas are actually databases (e.g. MySQL) in order to prevent reflection sweeps of the entire server.See also
Controlling What to be Autogenerated - new documentation section
References: #650
The revision tree is now checked for cycles and loops between revision files when the revision environment is loaded up. Scenarios such as a revision pointing to itself, or a revision that can reach itself via a loop, are handled and will raise the
CycleDetected
exception when the environment is loaded (expressed from the Alembic commandline as a failure message and nonzero return code). Previously, these situations were silently ignored up front, and the behavior of revision traversal would either be silently incorrect, or would produce errors such asRangeNotAncestorError
. Pull request courtesy Koichiro Den.References: #757
usecase¶
Added support for rendering of “identity” elements on
Column
objects, supported in SQLAlchemy via theIdentity
element introduced in version 1.4.Adding columns with identity is supported on PostgreSQL, MSSQL and Oracle. Changing the identity options or removing it is supported only on PostgreSQL and Oracle.
References: #730
Add
__main__.py
file to alembic package to support invocation withpython -m alembic
.
bug¶
Modified the
add_column()
operation such that theColumn
object in use is shallow copied to a new instance if thatColumn
is already attached to atable()
orTable
. This accommodates for the change made in SQLAlchemy issue #5618 which prohibits aColumn
from being associated with multipletable()
objects. This resumes support for using aColumn
inside of an Alembic operation that already refers to a parenttable()
orTable
as well as allows operation objects just autogenerated to work.References: #753
Added rendering for the
Table.prefixes
element to autogenerate so that the rendered Python code includes these directives. Pull request courtesy Rodrigo Ce Moretto.References: #721
Added missing “create comment” feature for columns that are altered in batch migrations.
References: #761
Made an adjustment to the PostgreSQL dialect to allow it to work more effectively in batch mode, where a datatype like Boolean or non-native Enum that may have embedded rules to generate CHECK constraints will be more correctly handled in that these constraints usually will not have been generated on the PostgreSQL backend; previously it would inadvertently assume they existed unconditionally in a special PG-only “drop constraint” step.
References: #773
removed¶
The long deprecated
EnvironmentContext.configure.include_symbol
hook is removed. TheEnvironmentContext.configure.include_object
andEnvironmentContext.configure.include_name
hooks both achieve the goals of this hook.Removed deprecated
--head_only
option to thealembic current
commandRemoved legacy parameter names from operations, these have been emitting warnings since version 0.8. In the case that legacy version files have not yet been updated, these can be modified directly in order to maintain compatibility:
Operations.drop_constraint()
- “type” (use “type_”) and “name” (use “constraint_name”)Operations.create_primary_key()
- “cols” (use “columns”) and “name” (use “constraint_name”)Operations.create_unique_constraint()
- “name” (use “constraint_name”), “source” (use “table_name”) and “local_cols” (use “columns”)Operations.batch_create_unique_constraint()
- “name” (use “constraint_name”)Operations.create_foreign_key()
- “name” (use “constraint_name”), “source” (use “source_table”), “referent” (use “referent_table”)Operations.batch_create_foreign_key()
- “name” (use “constraint_name”), “referent” (use “referent_table”)Operations.create_check_constraint()
- “name” (use “constraint_name”), “source” (use “table_name”)Operations.batch_create_check_constraint()
- “name” (use “constraint_name”)Operations.create_index()
- “name” (use “index_name”)Operations.drop_index()
- “name” (use “index_name”), “tablename” (use “table_name”)Operations.batch_drop_index()
- “name” (use “index_name”),Operations.create_table()
- “name” (use “table_name”)Operations.drop_table()
- “name” (use “table_name”)Operations.alter_column()
- “name” (use “new_column_name”)
1.4.3¶
Released: September 11, 2020bug¶
Added support to drop named CHECK constraints that are specified as part of a column, rather than table wide. Previously, only constraints associated with the table were considered.
References: #711
Fixed issue where the MySQL dialect would not correctly render the server default of a column in an alter operation, if the operation were programmatically generated from an autogenerate pass as it would not accommodate for the full structure of the DefaultClause construct.
References: #736
Fixed issue where the CAST applied to a JSON column when copying a SQLite table during batch mode would cause the data to be lost, as SQLite’s CAST with JSON appears to convert the data to the value “0”. The CAST is now skipped in a dialect-specific manner, including for JSON columns on SQLite. Pull request courtesy Sebastián Ramírez.
References: #697
The
alembic current
command no longer creates analembic_version
table in the database if one does not exist already, returning no version as the current version. This allows checking for migrations in parallel without introducing race conditions. Pull request courtesy Nikolay Edigaryev.References: #694
Fixed issue where columns in a foreign-key referenced table would be replaced with null-type columns during a batch operation; while this did not generally have any side effects, it could theoretically impact a batch operation that also targets that table directly and also would interfere with future changes to the
.append_column()
method to disallow implicit replacement of columns.Fixed issue where the
mssql_drop_foreign_key=True
flag onop.drop_column
would lead to incorrect syntax error due to a typo in the SQL emitted, same typo was present in the test as well so it was not detected. Pull request courtesy Oleg Shigorin.References: #716
1.4.2¶
Released: March 19, 2020usecase¶
Adjusted autogen comparison to accommodate for backends that support computed column reflection, dependent on SQLAlchemy version 1.3.16 or higher. This emits a warning if the SQL expression inside of a
Computed
value changes between the metadata and the database, as these expressions can’t be changed without dropping and recreating the column.References: #669
bug¶
Fixed an issue that prevented the test suite from running with the recently released py.test 5.4.0.
References: #668
Fixed more false-positive failures produced by the new “compare type” logic first added in #605, particularly impacting MySQL string types regarding flags such as “charset” and “collation”.
References: #671
Fixed issue in Oracle backend where a table RENAME with a schema-qualified name would include the schema in the “to” portion, which is rejected by Oracle.
References: #670
1.4.1¶
Released: March 1, 2020bug¶
Fixed regression caused by the new “type comparison” logic introduced in 1.4 as part of #605 where comparisons of MySQL “unsigned integer” datatypes would produce false positives, as the regular expression logic was not correctly parsing the “unsigned” token when MySQL’s default display width would be returned by the database. Pull request courtesy Paul Becotte.
References: #661
Error message for “path doesn’t exist” when loading up script environment now displays the absolute path. Pull request courtesy Rowan Hart.
References: #663
Fixed regression in 1.4.0 due to #647 where unique constraint comparison with mixed case constraint names while not using a naming convention would produce false positives during autogenerate.
References: #654
The check for matched rowcount when the alembic_version table is updated or deleted from is now conditional based on whether or not the dialect supports the concept of “rowcount” for UPDATE or DELETE rows matched. Some third party dialects do not support this concept. Pull request courtesy Ke Zhu.
Fixed long-standing bug where an inline column CHECK constraint would not be rendered within an “ADD COLUMN” operation. The DDL compiler is now consulted for inline constraints within the
Operations.add_column()
method as is done for regular CREATE TABLE operations.References: #655
1.4.0¶
Released: February 4, 2020feature¶
Added new parameters
BatchOperations.add_column.insert_before
,BatchOperations.add_column.insert_after
which provide for establishing the specific position in which a new column should be placed. Also addedOperations.batch_alter_table.partial_reordering
which allows the complete set of columns to be reordered when the new table is created. Both operations apply only to when batch mode is recreating the whole table usingrecreate="always"
. Thanks to Marcin Szymanski for assistance with the implementation.References: #640
usecase¶
Moved the use of the
__file__
attribute at the base of the Alembic package into the one place that it is specifically needed, which is when the config attempts to locate the template directory. This helps to allow Alembic to be fully importable in environments that are using Python memory-only import schemes. Pull request courtesy layday.References: #648
bug¶
Adjusted the unique constraint comparison logic in a similar manner as that of #421 did for indexes in order to take into account SQLAlchemy’s own truncation of long constraint names when a naming convention is in use. Without this step, a name that is truncated by SQLAlchemy based on a unique constraint naming convention or hardcoded name will not compare properly.
References: #647
A major rework of the “type comparison” logic is in place which changes the entire approach by which column datatypes are compared. Types are now compared based on the DDL string generated by the metadata type vs. the datatype reflected from the database. This means we compare types based on what would actually render and additionally if elements of the types change like string length, those changes are detected as well. False positives like those generated between SQLAlchemy Boolean and MySQL TINYINT should also be resolved. Thanks very much to Paul Becotte for lots of hard work and patience on this one.
See also
What does Autogenerate Detect (and what does it not detect?) - updated comments on type comparison
References: #605
misc¶
The internal inspection routines no longer use SQLAlchemy’s
Inspector.from_engine()
method, which is expected to be deprecated in 1.4. Theinspect()
function is now used.
1.3.3¶
Released: January 22, 2020usecase¶
Added support for rendering of “computed” elements on
Column
objects, supported in SQLAlchemy via the newComputed
element introduced in version 1.3.11. Pull request courtesy Federico Caselli.Note that there is currently no support for ALTER COLUMN to add, remove, or modify the “GENERATED ALWAYS AS” element from a column; at least for PostgreSQL, it does not seem to be supported by the database. Additionally, SQLAlchemy does not currently reliably reflect the “GENERATED ALWAYS AS” phrase from an existing column, so there is also no autogenerate support for addition or removal of the
Computed
element to or from an existing column, there is only support for adding new columns that include theComputed
element. In the case that theComputed
element is removed from theColumn
object in the table metadata, PostgreSQL and Oracle currently reflect the “GENERATED ALWAYS AS” expression as the “server default” which will produce an op that tries to drop the element as a default.References: #624
bug¶
Fixed issue where COMMENT directives for PostgreSQL failed to correctly include an explicit schema name, as well as correct quoting rules for schema, table, and column names. Pull request courtesy Matthew Sills.
References: #637
1.3.2¶
Released: December 16, 2019bug¶
Fixed regression introduced by #579 where server default rendering functions began to require a dialect implementation, however the
render_python_code()
convenience function did not include one, thus causing the function to fail when used in a server default context. The function now accepts a migration context argument and also creates one against the default dialect if one is not provided.References: #635
1.3.1¶
Released: November 13, 2019bug¶
Fixed bug in MSSQL dialect where the drop constraint execution steps used to remove server default or implicit foreign key constraint failed to take into account the schema name of the target table.
References: #621
1.3.0¶
Released: October 31, 2019feature¶
Added support for ALEMBIC_CONFIG environment variable, refers to the location of the alembic configuration script in lieu of using the -c command line option.
References: #608
bug¶
Fixed bug in new Variant autogenerate where the order of the arguments to Variant were mistakenly reversed.
References: #131
misc¶
Some internal modifications have been made to how the names of indexes and unique constraints work to make use of new functions added in SQLAlchemy 1.4, so that SQLAlchemy has more flexibility over how naming conventions may be applied to these objects.
1.2.1¶
Released: September 24, 2019bug¶
Reverted the name change of the “revisions” argument to
command.stamp()
to “revision” as apparently applications are calling upon this argument as a keyword name. Pull request courtesy Thomas Bechtold. Special translations are also added to the command line interface so that it is still known as “revisions” in the CLI.References: #601
Removed the “test requirements” from “setup.py test”, as this command now only emits a removal error in any case and these requirements are unused.
References: #592
1.2.0¶
Released: September 20, 2019feature¶
Added new
--purge
flag to thealembic stamp
command, which will unconditionally erase the version table before stamping anything. This is useful for development where non-existent version identifiers might be left within the table. Additionally,alembic.stamp
now supports a list of revision identifiers, which are intended to allow setting up muliple heads at once. Overall handling of version identifiers within thealembic.stamp
command has been improved with many new tests and use cases added.References: #473
Added new feature
MigrationContext.autocommit_block()
, a special directive which will provide for a non-transactional block inside of a migration script. The feature requires that: the database driver (e.g. DBAPI) supports the AUTOCOMMIT isolation mode. The directive also necessarily needs to COMMIT the existing transaction in progress in order to enter autocommit mode.See also
References: #123
Added “post write hooks” to revision generation. These allow custom logic to run after a revision Python script is generated, typically for the purpose of running code formatters such as “Black” or “autopep8”, but may be used for any arbitrary post-render hook as well, including custom Python functions or scripts. The hooks are enabled by providing a
[post_write_hooks]
section in the alembic.ini file. A single hook is provided which runs an arbitrary Python executable on the newly generated revision script, which can be configured to run code formatters such as Black; full examples are included in the documentation.References: #307
Added new flag
--package
toalembic init
. For environments where the Alembic migration files and such are within the package tree and importable as modules, this flag can be specified which will add the additional__init__.py
files in the version location and the environment location.References: #463
usecase¶
Added autogenerate support for
Column
objects that have dialect-specific**kwargs
, support first added in SQLAlchemy 1.3. This includes SQLite “on conflict” as well as options used by some third party dialects.References: #518
Added rendering for SQLAlchemy
Variant
datatypes, which render as the base type plus one or more.with_variant()
method calls.References: #131
Made the command interface revision lookup behavior more strict in that an Alembic revision number is only resolved based on a partial match rules if it has at least four characters, to prevent simple typographical issues from inadvertently running migrations.
References: #534
bug¶
Improved the Python rendering of a series of migration operations such that a single “pass” is rendered for a
UpgradeOps
orDowngradeOps
based on if no lines of Python code actually rendered under the operation, rather than whether or not sub-directives exist. Removed extra “pass” lines that would generate from theModifyTableOps
directive so that these aren’t duplicated under operation rewriting scenarios.References: #550
Fixed bug where rendering of comment text for table-level comments within
Operations.create_table_comment()
andOperations.drop_table_comment()
was not properly quote-escaped within rendered Python code for autogenerate.References: #549
Modified the logic of the
Rewriter
object such that it keeps a memoization of which directives it has processed, so that it can ensure it processes a particular directive only once, and additionally fixedRewriter
so that it functions correctly for multiple-pass autogenerate schemes, such as the one illustrated in the “multidb” template. By tracking which directives have been processed, a multiple-pass scheme which calls upon theRewriter
multiple times for the same structure as elements are added can work without running duplicate operations on the same elements more than once.References: #505
misc¶
Python 3.4 support is dropped, as the upstream tooling (pip, mysqlclient) etc are already dropping support for Python 3.4, which itself is no longer maintained.
1.1.0¶
Released: August 26, 2019usecase¶
The “alembic init” command will now proceed if the target directory exists as long as it’s still empty. Previously, it would not proceed if the directory existed. The new behavior is modeled from what git does, to accommodate for container or other deployments where an Alembic target directory may need to be already mounted instead of being created with alembic init. Pull request courtesy Aviskar KC.
References: #571
bug¶
Fixed bug where the double-percent logic applied to some dialects such as psycopg2 would be rendered in
--sql
mode, by allowing dialect options to be passed through to the dialect used to generate SQL and then providingparamstyle="named"
so that percent signs need not be doubled. For users having this issue, existing env.py scripts need to adddialect_opts={"paramstyle": "named"}
to their offline context.configure(). See thealembic/templates/generic/env.py
template for an example.References: #562
Fixed use of the deprecated “imp” module, which is used to detect pep3147 availability as well as to locate .pyc files, which started emitting deprecation warnings during the test suite. The warnings were not being emitted earlier during the test suite, the change is possibly due to changes in py.test itself but this is not clear. The check for pep3147 is set to True for any Python version 3.5 or greater now and importlib is used when available. Note that some dependencies such as distutils may still be emitting this warning. Tests are adjusted to accommodate for dependencies that emit the warning as well.
Fixed issue where emitting a change of column name for MySQL did not preserve the column comment, even if it were specified as existing_comment.
References: #594
Removed the “python setup.py test” feature in favor of a straight run of “tox”. Per Pypa / pytest developers, “setup.py” commands are in general headed towards deprecation in favor of tox. The tox.ini script has been updated such that running “tox” with no arguments will perform a single run of the test suite against the default installed Python interpreter.
References: #592
misc¶
Alembic 1.1 bumps the minimum version of SQLAlchemy to 1.1. As was the case before, Python requirements remain at Python 2.7, or in the 3.x series Python 3.4.
The test suite for Alembic now makes use of SQLAlchemy’s testing framework directly. Previously, Alembic had its own version of this framework that was mostly copied from that of SQLAlchemy to enable testing with older SQLAlchemy versions. The majority of this code is now removed so that both projects can leverage improvements from a common testing framework.
1.0.11¶
Released: June 25, 2019bug¶
SQLite server default reflection will ensure parenthesis are surrounding a column default expression that is detected as being a non-constant expression, such as a
datetime()
default, to accommodate for the requirement that SQL expressions have to be parenthesized when being sent as DDL. Parenthesis are not added to constant expressions to allow for maximum cross-compatibility with other dialects and existing test suites (such as Alembic’s), which necessarily entails scanning the expression to eliminate for constant numeric and string values. The logic is added to the two “reflection->DDL round trip” paths which are currently autogenerate and batch migration. Within autogenerate, the logic is on the rendering side, whereas in batch the logic is installed as a column reflection hook.References: #579
Improved SQLite server default comparison to accommodate for a
text()
construct that added parenthesis directly vs. a construct that relied upon the SQLAlchemy SQLite dialect to render the parenthesis, as well as improved support for various forms of constant expressions such as values that are quoted vs. non-quoted.References: #579
Fixed bug where the “literal_binds” flag was not being set when autogenerate would create a server default value, meaning server default comparisons would fail for functions that contained literal values.
Added support for MySQL “DROP CHECK”, which is added as of MySQL 8.0.16, separate from MariaDB’s “DROP CONSTRAINT” for CHECK constraints. The MySQL Alembic implementation now checks for “MariaDB” in server_version_info to decide which one to use.
References: #554
Fixed issue where MySQL databases need to use CHANGE COLUMN when altering a server default of CURRENT_TIMESTAMP, NOW() and probably other functions that are only usable with DATETIME/TIMESTAMP columns. While MariaDB supports both CHANGE and ALTER COLUMN in this case, MySQL databases only support CHANGE. So the new logic is that if the server default change is against a DateTime-oriented column, the CHANGE format is used unconditionally, as in the vast majority of cases the server default is to be CURRENT_TIMESTAMP which may also be potentially bundled with an “ON UPDATE CURRENT_TIMESTAMP” directive, which SQLAlchemy does not currently support as a distinct field. The fix addiionally improves the server default comparison logic when the “ON UPDATE” clause is present and there are parenthesis to be adjusted for as is the case on some MariaDB versions.
References: #564
Warnings emitted by Alembic now include a default stack level of 2, and in some cases it’s set to 3, in order to help warnings indicate more closely where they are originating from. Pull request courtesy Ash Berlin-Taylor.
Replaced the Python compatibility routines for
getargspec()
with a fully vendored version based ongetfullargspec()
from Python 3.3. Originally, Python was emitting deprecation warnings for this function in Python 3.8 alphas. While this change was reverted, it was observed that Python 3 implementations forgetfullargspec()
are an order of magnitude slower as of the 3.4 series where it was rewritten againstSignature
. While Python plans to improve upon this situation, SQLAlchemy projects for now are using a simple replacement to avoid any future issues.References: #563
1.0.10¶
Released: April 28, 2019bug¶
Fixed bug introduced in release 0.9.0 where the helptext for commands inadvertently got expanded to include function docstrings from the command.py module. The logic has been adjusted to only refer to the first line(s) preceding the first line break within each docstring, as was the original intent.
References: #552
Added an assertion in
RevisionMap.get_revisions()
and other methods which ensures revision numbers are passed as strings or collections of strings. Driver issues particularly on MySQL may inadvertently be passing bytes here which leads to failures later on.References: #551
Fixed bug when using the
EnvironmentContext.configure.compare_server_default
flag set toTrue
where a server default that is introduced in the table metadata on anInteger
column, where there is no existing server default in the database, would raise aTypeError
.References: #553
1.0.9¶
Released: April 15, 2019bug¶
Simplified the internal scheme used to generate the
alembic.op
namespace to no longer attempt to generate full method signatures (e.g. rather than generic*args, **kw
) as this was not working in most cases anyway, while in rare circumstances it would in fact sporadically have access to the real argument names and then fail when generating the function due to missing symbols in the argument signature.References: #548
1.0.8¶
Released: March 4, 2019bug¶
Removed use of deprecated
force
parameter for SQLAlchemy quoting functions as this parameter will be removed in a future release. Pull request courtesy Parth Shandilya(ParthS007).References: #528
Fixed issue where server default comparison on the PostgreSQL dialect would fail for a blank string on Python 3.7 only, due to a change in regular expression behavior in Python 3.7.
References: #541
1.0.7¶
Released: January 25, 2019bug¶
Fixed issue in new comment support where autogenerated Python code for comments wasn’t using
repr()
thus causing issues with quoting. Pull request courtesy Damien Garaud.References: #529
1.0.6¶
Released: January 13, 2019feature¶
Added Table and Column level comments for supported backends. New methods
Operations.create_table_comment()
andOperations.drop_table_comment()
are added. A new argumentsOperations.alter_column.comment
andOperations.alter_column.existing_comment
are added toOperations.alter_column()
. Autogenerate support is also added to ensure comment add/drops from tables and columns are generated as well as thatOperations.create_table()
,Operations.add_column()
both include the comment field from the sourceTable
orColumn
object.References: #422
1.0.5¶
Released: November 27, 2018bug¶
Resolved remaining Python 3 deprecation warnings, covering the use of inspect.formatargspec() with a vendored version copied from the Python standard library, importing collections.abc above Python 3.3 when testing against abstract base classes, fixed one occurrence of log.warn(), as well as a few invalid escape sequences.
References: #507
1.0.4¶
Released: November 27, 2018Code hosting has been moved to GitHub, at https://github.com/sqlalchemy/alembic. Additionally, the main Alembic website documentation URL is now https://alembic.sqlalchemy.org.
1.0.3¶
Released: November 14, 2018bug¶
1.0.2¶
Released: October 31, 2018bug¶
The
system=True
flag onColumn
, used primarily in conjunction with the Postgresql “xmin” column, now renders within the autogenerate render process, allowing the column to be excluded from DDL. Additionally, adding a system=True column to a model will produce no autogenerate diff as this column is implicitly present in the database.References: #515
Fixed issue where usage of the SQL Server
mssql_include
option within aOperations.create_index()
would raise a KeyError, as the additional column(s) need to be added to the table object used by the construct internally.References: #513
1.0.1¶
Released: October 17, 2018bug¶
Fixed an issue where revision descriptions were essentially being formatted twice. Any revision description that contained characters like %, writing output to stdout will fail because the call to config.print_stdout attempted to format any additional args passed to the function. This fix now only applies string formatting if any args are provided along with the output text.
References: #497
Fixed issue where removed method
union_update()
was used when a customizedMigrationScript
instance included entries in the.imports
data member, raising an AttributeError.References: #512
1.0.0¶
Released: July 13, 2018feature¶
For Alembic 1.0, Python 2.6 / 3.3 support is being dropped, allowing a fixed setup.py to be built as well as universal wheels. Pull request courtesy Hugo.
References: #491
With the 1.0 release, Alembic’s minimum SQLAlchemy support version moves to 0.9.0, previously 0.7.9.
bug¶
Fixed issue in batch where dropping a primary key column, then adding it back under the same name but without the primary_key flag, would not remove it from the existing PrimaryKeyConstraint. If a new PrimaryKeyConstraint is added, it is used as-is, as was the case before.
References: #502
0.9.10¶
Released: June 29, 2018bug¶
The “op.drop_constraint()” directive will now render using
repr()
for the schema name, in the same way that “schema” renders for all the other op directives. Pull request courtesy Denis Kataev.Added basic capabilities for external dialects to support rendering of “nested” types, like arrays, in a manner similar to that of the Postgresql dialect.
References: #494
Fixed issue where “autoincrement=True” would not render for a column that specified it, since as of SQLAlchemy 1.1 this is no longer the default value for “autoincrement”. Note the behavior only takes effect against the SQLAlchemy 1.1.0 and higher; for pre-1.1 SQLAlchemy, “autoincrement=True” does not render as was the case before. Pull request courtesy Elad Almos.
0.9.9¶
Released: March 22, 2018feature¶
Added new flag
--indicate-current
to thealembic history
command. When listing versions, it will include the token “(current)” to indicate the given version is a current head in the target database. Pull request courtesy Kazutaka Mise.References: #481
bug¶
The fix for #455 in version 0.9.6 involving MySQL server default comparison was entirely non functional, as the test itself was also broken and didn’t reveal that it wasn’t working. The regular expression to compare server default values like CURRENT_TIMESTAMP to current_timestamp() is repaired.
References: #455
Fixed bug where MySQL server default comparisons were basically not working at all due to incorrect regexp added in #455. Also accommodates for MariaDB 10.2 quoting differences in reporting integer based server defaults.
References: #483
Fixed bug in
op.drop_constraint()
for MySQL where quoting rules would not be applied to the constraint name.References: #487
0.9.8¶
Released: February 16, 2018bug¶
Fixed bug where the
Script.as_revision_number()
method did not accommodate for the ‘heads’ identifier, which in turn caused theEnvironmentContext.get_head_revisions()
andEnvironmentContext.get_revision_argument()
methods to be not usable when multiple heads were present. The :meth:.`EnvironmentContext.get_head_revisions` method returns a tuple in all cases as documented.References: #482
Fixed bug where autogenerate of
ExcludeConstraint
would render a raw quoted name for a Column that has case-sensitive characters, which when invoked as an inline member of the Table would produce a stack trace that the quoted name is not found. An incoming Column object is now rendered assa.column('name')
.References: #478
Fixed bug where the indexes would not be included in a migration that was dropping the owning table. The fix now will also emit DROP INDEX for the indexes ahead of time, but more importantly will include CREATE INDEX in the downgrade migration.
References: #468
Fixed the autogenerate of the module prefix when rendering the text_type parameter of postgresql.HSTORE, in much the same way that we do for ARRAY’s type and JSON’s text_type.
References: #480
Added support for DROP CONSTRAINT to the MySQL Alembic dialect to support MariaDB 10.2 which now has real CHECK constraints. Note this change does not add autogenerate support, only support for op.drop_constraint() to work.
References: #479
0.9.7¶
Released: January 16, 2018bug¶
Fixed regression caused by #421 which would cause case-sensitive quoting rules to interfere with the comparison logic for index names, thus causing indexes to show as added for indexes that have case-sensitive names. Works with SQLAlchemy 0.9 and later series.
References: #472
Fixed bug where autogenerate would produce a DROP statement for the index implicitly created by a Postgresql EXCLUDE constraint, rather than skipping it as is the case for indexes implicitly generated by unique constraints. Makes use of SQLAlchemy 1.0.x’s improved “duplicates index” metadata and requires at least SQLAlchemy version 1.0.x to function correctly.
References: #461
0.9.6¶
Released: October 13, 2017feature¶
The
alembic history
command will now make use of the revision environmentenv.py
unconditionally if therevision_environment
configuration flag is set to True. Previously, the environment would only be invoked if the history specification were against a database-stored revision token.References: #447
bug¶
Fixed a few Python3.6 deprecation warnings by replacing
StopIteration
withreturn
, as well as usinggetfullargspec()
instead ofgetargspec()
under Python 3.References: #458
An addition to #441 fixed in 0.9.5, we forgot to also filter for the
+
sign in migration names which also breaks due to the relative migrations feature.References: #441
Fixed bug expanding upon the fix for #85 which adds the correct module import to the “inner” type for an
ARRAY
type, the fix now accommodates for the genericsqlalchemy.types.ARRAY
type added in SQLAlchemy 1.1, rendering the inner type correctly regardless of whether or not the Postgresql dialect is present.References: #442
Fixed bug where server default comparison of CURRENT_TIMESTAMP would fail on MariaDB 10.2 due to a change in how the function is represented by the database during reflection.
References: #455
Fixed bug where comparison of
Numeric
types would produce a difference if the Python-sideNumeric
inadvertently specified a non-None “scale” with a “precision” of None, even though thisNumeric
type will pass over the “scale” argument when rendering. Pull request courtesy Ivan Mmelnychuk.The name of the temporary table in batch mode is now generated off of the original table name itself, to avoid conflicts for the unusual case of multiple batch operations running against the same database schema at the same time.
References: #457
A
ForeignKeyConstraint
can now render correctly if thelink_to_name
flag is set, as it will not attempt to resolve the name from a “key” in this case. Additionally, the constraint will render as-is even if the remote column name isn’t present on the referenced remote table.References: #456
Reworked “sourceless” system to be fully capable of handling any combination of: Python2/3x, pep3149 or not, PYTHONOPTIMIZE or not, for locating and loading both env.py files as well as versioning files. This includes: locating files inside of
__pycache__
as well as listing out version files that might be only inversions/__pycache__
, deduplicating version files that may be inversions/__pycache__
andversions/
at the same time, correctly looking for .pyc or .pyo files based on if pep488 is present or not. The latest Python3x deprecation warnings involving importlib are also corrected.References: #449
0.9.5¶
Released: August 9, 2017bug¶
A
CommandError
is raised if the “–rev-id” passed to therevision()
command contains dashes or at-signs, as this interferes with the command notation used to locate revisions.References: #441
Added support for the dialect-specific keyword arguments to
Operations.drop_index()
. This includes support forpostgresql_concurrently
and others.References: #424
Fixed bug in timezone feature introduced in #425 when the creation date in a revision file is calculated, to accommodate for timezone names that contain mixed-case characters in their name as opposed to all uppercase. Pull request courtesy Nils Philippsen.
0.9.4¶
Released: July 31, 2017bug¶
Added an additional attribute to the new
EnvironmentContext.configure.on_version_apply
API,MigrationInfo.up_revision_ids
, to accommodate for the uncommon case of thealembic stamp
command being used to move from multiple branches down to a common branchpoint; there will be multiple “up” revisions in this one case.
0.9.3¶
Released: July 6, 2017feature¶
Added a new callback hook
EnvironmentContext.configure.on_version_apply
, which allows user-defined code to be invoked each time an individual upgrade, downgrade, or stamp operation proceeds against a database. Pull request courtesy John Passaro.
bug¶
Fixed bug where autogen comparison of a
Variant
datatype would not compare to the dialect level type for the “default” implementation of theVariant
, returning the type as changed between database and table metadata.References: #433
Fixed unit tests to run correctly under the SQLAlchemy 1.0.x series prior to version 1.0.10 where a particular bug involving Postgresql exclude constraints was fixed.
References: #431
0.9.2¶
Released: May 18, 2017feature¶
Added a new configuration option
timezone
, a string timezone name that will be applied to the create date timestamp rendered inside the revision file as made available to thefile_template
used to generate the revision filename. Note this change adds thepython-dateutil
package as a dependency.References: #425
bug¶
Repaired
Operations.rename_table()
for SQL Server when the target table is in a remote schema, the schema name is omitted from the “new name” argument.References: #429
The autogenerate compare scheme now takes into account the name truncation rules applied by SQLAlchemy’s DDL compiler to the names of the
Index
object, when these names are dynamically truncated due to a too-long identifier name. As the identifier truncation is deterministic, applying the same rule to the metadata name allows correct comparison to the database-derived name.References: #421
misc¶
A warning is emitted when an object that’s not a
Connection
is passed toEnvironmentContext.configure()
. For the case of aEngine
passed, the check for “in transaction” introduced in version 0.9.0 has been relaxed to work in the case of an attribute error, as some users appear to be passing anEngine
and not aConnection
.References: #419
0.9.1¶
Released: March 1, 2017bug¶
0.9.0¶
Released: February 28, 2017feature¶
The
EnvironmentContext.configure.target_metadata
parameter may now be optionally specified as a sequence ofMetaData
objects instead of a singleMetaData
object. The autogenerate process will process the sequence ofMetaData
objects in order.References: #38
Added a keyword argument
process_revision_directives
to thecommand.revision()
API call. This function acts in the same role as the environment-levelEnvironmentContext.configure.process_revision_directives
, and allows API use of the command to drop in an ad-hoc directive process function. This function can be used among other things to place a completeMigrationScript
structure in place.Added support for Postgresql EXCLUDE constraints, including the operation directive
Operations.create_exclude_constraints()
as well as autogenerate render support for theExcludeConstraint
object as present in aTable
. Autogenerate detection for an EXCLUDE constraint added or removed to/from an existing table is not implemented as the SQLAlchemy Postgresql dialect does not yet support reflection of EXCLUDE constraints.Additionally, unknown constraint types now warn when encountered within an autogenerate action rather than raise.
References: #412
bug¶
A
CommandError
is now raised when a migration file opens a database transaction and does not close/commit/rollback, when the backend database or environment options also specify transactional_ddl is False. When transactional_ddl is not in use, Alembic doesn’t close any transaction so a transaction opened by a migration file will cause the following migrations to fail to apply.References: #369
The
autoincrement=True
flag is now rendered within theOperations.alter_column()
operation if the source column indicates that this flag should be set to True. The behavior is sensitive to the SQLAlchemy version in place, as the “auto” default option is new in SQLAlchemy 1.1. When the source column indicates autoincrement as True or “auto”, the flag will render as True if the original column contextually indicates that it should have “autoincrement” keywords, and when the source column explcitly sets it to False, this is also rendered. The behavior is intended to preserve the AUTO_INCREMENT flag on MySQL as the column is fully recreated on this backend. Note that this flag does not support alteration of a column’s “autoincrement” status, as this is not portable across backends.References: #413
Fixed bug where Postgresql JSON/JSONB types rendered on SQLAlchemy 1.1 would render the “astext_type” argument which defaults to the
Text()
type without the module prefix, similarly to the issue with ARRAY fixed in #85.References: #411
Fixed bug where Postgresql ARRAY type would not render the import prefix for the inner type; additionally, user-defined renderers take place for the inner type as well as the outer type. Pull request courtesy Paul Brackin.
References: #85
Fixed bug in
ops.create_foreign_key()
where the internal table representation would not be created properly if the foreign key referred to a table in a different schema of the same name. Pull request courtesy Konstantin Lebedev.
0.8.10¶
Released: January 17, 2017bug¶
The alembic_version table, when initially created, now establishes a primary key constraint on the “version_num” column, to suit database engines that don’t support tables without primary keys. This behavior can be controlled using the parameter
EnvironmentContext.configure.version_table_pk
. Note that this change only applies to the initial creation of the alembic_version table; it does not impact any existing alembic_version table already present.References: #406
Fixed bug where doing
batch_op.drop_constraint()
against the primary key constraint would fail to remove the “primary_key” flag from the column, resulting in the constraint being recreated.References: #402
Adjusted the logic originally added for #276 that detects MySQL unique constraints which are actually unique indexes to be generalized for any dialect that has this behavior, for SQLAlchemy version 1.0 and greater. This is to allow for upcoming SQLAlchemy support for unique constraint reflection for Oracle, which also has no dedicated concept of “unique constraint” and instead establishes a unique index.
Added a file ignore for Python files of the form
.#<name>.py
, which are generated by the Emacs editor. Pull request courtesy Markus Mattes.References: #356
0.8.9¶
Released: November 28, 2016bug¶
Adjustment to the “please adjust!” comment in the script.py.mako template so that the generated comment starts with a single pound sign, appeasing flake8.
References: #393
Batch mode will not use CAST() to copy data if type_ is given, however the basic type affinity matches that of the existing type. This to avoid SQLite’s CAST of TIMESTAMP which results in truncation of the data, in those cases where the user needs to add redundant type_ for other reasons.
References: #391
Continued pep8 improvements by adding appropriate whitespace in the base template for generated migrations. Pull request courtesy Markus Mattes.
References: #393
Added an additional check when reading in revision files to detect if the same file is being read twice; this can occur if the same directory or a symlink equivalent is present more than once in version_locations. A warning is now emitted and the file is skipped. Pull request courtesy Jiri Kuncar.
Fixed bug where usage of a custom TypeDecorator which returns a per-dialect type via
TypeDecorator.load_dialect_impl()
that differs significantly from the default “impl” for the type decorator would fail to compare correctly during autogenerate.References: #395
Fixed bug in Postgresql “functional index skip” behavior where a functional index that ended in ASC/DESC wouldn’t be detected as something we can’t compare in autogenerate, leading to duplicate definitions in autogenerated files.
References: #392
Fixed bug where the “base” specifier, as in “base:head”, could not be used explicitly when
--sql
mode was present.
0.8.8¶
Released: September 12, 2016feature¶
Added support for the USING clause to the ALTER COLUMN operation for Postgresql. Support is via the
op.alter_column.postgresql_using
parameter. Pull request courtesy Frazer McLean.References: #292
Autogenerate with type comparison enabled will pick up on the timezone setting changing between DateTime types. Pull request courtesy David Szotten.
misc¶
The imports in the default script.py.mako are now at the top so that flake8 editors don’t complain by default. PR courtesy Guilherme Mansur.
0.8.7¶
Released: July 26, 2016bug¶
Fixed bug where upgrading to the head of a branch which is already present would fail, only if that head were also the dependency of a different branch that is also upgraded, as the revision system would see this as trying to go in the wrong direction. The check here has been refined to distinguish between same-branch revisions out of order vs. movement along sibling branches.
References: #336
Adjusted the version traversal on downgrade such that we can downgrade to a version that is a dependency for a version in a different branch, without needing to remove that dependent version as well. Previously, the target version would be seen as a “merge point” for it’s normal up-revision as well as the dependency. This integrates with the changes for #377 and #378 to improve treatment of branches with dependencies overall.
References: #379
Fixed bug where a downgrade to a version that is also a dependency to a different branch would fail, as the system attempted to treat this as an “unmerge” of a merge point, when in fact it doesn’t have the other side of the merge point available for update.
References: #377
Fixed bug where the “alembic current” command wouldn’t show a revision as a current head if it were also a dependency of a version in a different branch that’s also applied. Extra logic is added to extract “implied” versions of different branches from the top-level versions listed in the alembic_version table.
References: #378
Fixed bug where a repr() or str() of a Script object would fail if the script had multiple dependencies.
Fixed bug in autogen where if the DB connection sends the default schema as “None”, this “None” would be removed from the list of schemas to check if include_schemas were set. This could possibly impact using include_schemas with SQLite.
Small adjustment made to the batch handling for reflected CHECK constraints to accommodate for SQLAlchemy 1.1 now reflecting these. Batch mode still does not support CHECK constraints from the reflected table as these can’t be easily differentiated from the ones created by types such as Boolean.
0.8.6¶
Released: April 14, 2016bug¶
Errors which occur within the Mako render step are now intercepted and raised as CommandErrors like other failure cases; the Mako exception itself is written using template-line formatting to a temporary file which is named in the exception message.
References: #367
Added a fix to Postgresql server default comparison which first checks if the text of the default is identical to the original, before attempting to actually run the default. This accommodates for default-generation functions that generate a new value each time such as a uuid function.
References: #365
Fixed bug introduced by the fix for #338 in version 0.8.4 where a server default could no longer be dropped in batch mode. Pull request courtesy Martin Domke.
References: #361
Fixed bug where SQL Server arguments for drop_column() would not be propagated when running under a batch block. Pull request courtesy Michal Petrucha.
0.8.5¶
Released: March 9, 2016bug¶
Fixed bug where the columns rendered in a
PrimaryKeyConstraint
in autogenerate would inappropriately render the “key” of the column, not the name. Pull request courtesy Jesse Dhillon.References: #335
Repaired batch migration support for “schema” types which generate constraints, in particular the
Boolean
datatype which generates a CHECK constraint. Previously, an alter column operation with this type would fail to correctly accommodate for the CHECK constraint on change both from and to this type. In the former case the operation would fail entirely, in the latter, the CHECK constraint would not get generated. Both of these issues are repaired.References: #354
Changing a schema type such as
Boolean
to a non-schema type would emit a drop constraint operation which emitsNotImplementedError
for the MySQL dialect. This drop constraint operation is now skipped when the constraint originates from a schema type.References: #355
0.8.4¶
Released: December 15, 2015feature¶
A major improvement to the hash id generation function, which for some reason used an awkward arithmetic formula against uuid4() that produced values that tended to start with the digits 1-4. Replaced with a simple substring approach which provides an even distribution. Pull request courtesy Antti Haapala.
Added an autogenerate renderer for the
ExecuteSQLOp
operation object; only renders if given a plain SQL string, otherwise raises NotImplementedError. Can be of help with custom autogenerate sequences that includes straight SQL execution. Pull request courtesy Jacob Magnusson.
bug¶
Batch mode generates a FOREIGN KEY constraint that is self-referential using the ultimate table name, rather than
_alembic_batch_temp
. When the table is renamed from_alembic_batch_temp
back to the original name, the FK now points to the right name. This will not work if referential integrity is being enforced (eg. SQLite “PRAGMA FOREIGN_KEYS=ON”) since the original table is dropped and the new table then renamed to that name, however this is now consistent with how foreign key constraints on other tables already operate with batch mode; these don’t support batch mode if referential integrity is enabled in any case.References: #345
Added a type-level comparator that distinguishes
Integer
,BigInteger
, andSmallInteger
types and dialect-specific types; these all have “Integer” affinity so previously all compared as the same.References: #341
Fixed bug where the
server_default
parameter ofalter_column()
would not function correctly in batch mode.References: #338
Adjusted the rendering for index expressions such that a
Column
object present in the sourceIndex
will not be rendered as table-qualified; e.g. the column name will be rendered alone. Table-qualified names here were failing on systems such as Postgresql.References: #337
0.8.3¶
Released: October 16, 2015bug¶
Fixed an 0.8 regression whereby the “imports” dictionary member of the autogen context was removed; this collection is documented in the “render custom type” documentation as a place to add new imports. The member is now known as
AutogenContext.imports
and the documentation is repaired.References: #332
Fixed bug in batch mode where a table that had pre-existing indexes would create the same index on the new table with the same name, which on SQLite produces a naming conflict as index names are in a global namespace on that backend. Batch mode now defers the production of both existing and new indexes until after the entire table transfer operation is complete, which also means those indexes no longer take effect during the INSERT from SELECT section as well; the indexes are applied in a single step afterwards.
References: #333
Added “pytest-xdist” as a tox dependency, so that the -n flag in the test command works if this is not already installed. Pull request courtesy Julien Danjou.
Fixed issue in PG server default comparison where model-side defaults configured with Python unicode literals would leak the “u” character from a
repr()
into the SQL used for comparison, creating an invalid SQL expression, as the server-side comparison feature in PG currently repurposes the autogenerate Python rendering feature to get a quoted version of a plain string default.References: #324
0.8.2¶
Released: August 25, 2015bug¶
Added workaround in new foreign key option detection feature for MySQL’s consideration of the “RESTRICT” option being the default, for which no value is reported from the database; the MySQL impl now corrects for when the model reports RESTRICT but the database reports nothing. A similar rule is in the default FK comparison to accommodate for the default “NO ACTION” setting being present in the model but not necessarily reported by the database, or vice versa.
References: #321
0.8.1¶
Released: August 22, 2015feature¶
A custom
EnvironmentContext.configure.process_revision_directives
hook can now generate op directives within theUpgradeOps
andDowngradeOps
containers that will be generated as Python code even when the--autogenerate
flag is False; provided thatrevision_environment=True
, the full render operation will be run even in “offline” mode.Implemented support for autogenerate detection of changes in the
ondelete
,onupdate
,initially
anddeferrable
attributes ofForeignKeyConstraint
objects on SQLAlchemy backends that support these on reflection (as of SQLAlchemy 1.0.8 currently Postgresql for all four, MySQL forondelete
andonupdate
only). A constraint object that modifies these values will be reported as a “diff” and come out as a drop/create of the constraint with the modified values. The fields are ignored for backends which don’t reflect these attributes (as of SQLA 1.0.8 this includes SQLite, Oracle, SQL Server, others).References: #317
bug¶
Repaired the render operation for the
ops.AlterColumnOp
object to succeed when the “existing_type” field was not present.Fixed a regression 0.8 whereby the “multidb” environment template failed to produce independent migration script segments for the output template. This was due to the reorganization of the script rendering system for 0.8. To accommodate this change, the
MigrationScript
structure will in the case of multiple calls toMigrationContext.run_migrations()
produce lists for theMigrationScript.upgrade_ops
andMigrationScript.downgrade_ops
attributes; eachUpgradeOps
andDowngradeOps
instance keeps track of its ownupgrade_token
anddowngrade_token
, and each are rendered individually.See also
Revision Generation with Multiple Engines / run_migrations() calls - additional detail on the workings of the
EnvironmentContext.configure.process_revision_directives
parameter when multiple calls toMigrationContext.run_migrations()
are made.References: #318
0.8.0¶
Released: August 12, 2015feature¶
Added new command
alembic edit
. This command takes the same arguments asalembic show
, however runs the target script file within $EDITOR. Makes use of thepython-editor
library in order to facilitate the handling of $EDITOR with reasonable default behaviors across platforms. Pull request courtesy Michel Albert.Added new multiple-capable argument
--depends-on
to thealembic revision
command, allowingdepends_on
to be established at the command line level rather than having to edit the file after the fact.depends_on
identifiers may also be specified as branch names at the command line or directly within the migration file. The values may be specified as partial revision numbers from the command line which will be resolved to full revision numbers in the output file.References: #311
The default test runner via “python setup.py test” is now py.test. nose still works via run_tests.py.
The internal system for Alembic operations has been reworked to now build upon an extensible system of operation objects. New operations can be added to the
op.
namespace, including that they are available in custom autogenerate schemes.See also
References: #302
The internal system for autogenerate been reworked to build upon the extensible system of operation objects present in #302. As part of this change, autogenerate now produces a full object graph representing a list of migration scripts to be written as well as operation objects that will render all the Python code within them; a new hook
EnvironmentContext.configure.process_revision_directives
allows end-user code to fully customize what autogenerate will do, including not just full manipulation of the Python steps to take but also what file or files will be written and where. Additionally, autogenerate is now extensible as far as database objects compared and rendered into scripts; any new operation directive can also be registered into a series of hooks that allow custom database/model comparison functions to run as well as to render new operation directives into autogenerate scripts.See also
bug¶
Fixed bug in batch mode where the
batch_op.create_foreign_key()
directive would be incorrectly rendered with the source table and schema names in the argument list.References: #315
Fixed bug where in the erroneous case that alembic_version contains duplicate revisions, some commands would fail to process the version history correctly and end up with a KeyError. The fix allows the versioning logic to proceed, however a clear error is emitted later when attempting to update the alembic_version table.
References: #314
misc¶
A range of positional argument names have been changed to be clearer and more consistent across methods within the
Operations
namespace. The most prevalent form of name change is that the descriptive namesconstraint_name
andtable_name
are now used where previously the namename
would be used. This is in support of the newly modularized and extensible system of operation objects inalembic.operations.ops
. An argument translation layer is in place across thealembic.op
namespace that will ensure that named argument calling styles that use the old names will continue to function by transparently translating to the new names, also emitting a warning. This, along with the fact that these arguments are positional in any case and aren’t normally passed with an explicit name, should ensure that the overwhelming majority of applications should be unaffected by this change. The only applications that are impacted are those that:use the
Operations
object directly in some way, rather than calling upon thealembic.op
namespace, andinvoke the methods on
Operations
using named keyword arguments for positional arguments liketable_name
,constraint_name
, etc., which commonly were namedname
as of 0.7.6.any application that is using named keyword arguments in place of positional argument for the recently added
BatchOperations
object may also be affected.
The naming changes are documented as “versionchanged” for 0.8.0:
0.7.7¶
Released: July 22, 2015feature¶
Implemented support for
BatchOperations.create_primary_key()
andBatchOperations.create_check_constraint()
. Additionally, table keyword arguments are copied from the original reflected table, such as the “mysql_engine” keyword argument.References: #305
bug¶
Fixed critical issue where a complex series of branches/merges would bog down the iteration algorithm working over redundant nodes for millions of cycles. An internal adjustment has been made so that duplicate nodes are skipped within this iteration.
References: #310
The
MigrationContext.stamp()
method, added as part of the versioning refactor in 0.7 as a more granular version ofcommand.stamp()
, now includes the “create the alembic_version table if not present” step in the same way as the command version, which was previously omitted.References: #300
Fixed bug where foreign key options including “onupdate”, “ondelete” would not render within the
op.create_foreign_key()
directive, even though they render within a fullForeignKeyConstraint
directive.References: #298
Repaired warnings that occur when running unit tests against SQLAlchemy 1.0.5 or greater involving the “legacy_schema_aliasing” flag.
0.7.6¶
Released: May 5, 2015feature¶
Fixed bug where the case of multiple mergepoints that all have the identical set of ancestor revisions would fail to be upgradable, producing an assertion failure. Merge points were previously assumed to always require at least an UPDATE in alembic_revision from one of the previous revs to the new one, however in this case, if one of the mergepoints has already been reached, the remaining mergepoints have no row to UPDATE therefore they must do an INSERT of their target version.
References: #297
Added support for type comparison functions to be not just per environment, but also present on the custom types themselves, by supplying a method
compare_against_backend
. Added a new documentation section Comparing Types describing type comparison fully.References: #296
Added a new option
EnvironmentContext.configure.literal_binds
, which will pass theliteral_binds
flag into the compilation of SQL constructs when using “offline” mode. This has the effect that SQL objects like inserts, updates, deletes as well as textual statements sent usingtext()
will be compiled such that the dialect will attempt to render literal values “inline” automatically. Only a subset of types is typically supported; theOperations.inline_literal()
construct remains as the construct used to force a specific literal representation of a value. TheEnvironmentContext.configure.literal_binds
flag is added to the “offline” section of theenv.py
files generated in new environments.References: #255
bug¶
Fully implemented the
copy_from
parameter for batch mode, which previously was not functioning. This allows “batch mode” to be usable in conjunction with--sql
.References: #289
Repaired support for the
BatchOperations.create_index()
directive, which was mis-named internally such that the operation within a batch context could not proceed. The create index operation will proceed as part of a larger “batch table recreate” operation only ifrecreate
is set to “always”, or if the batch operation includes other instructions that require a table recreate.References: #287
0.7.5¶
Released: March 19, 2015feature¶
Added a new feature
Config.attributes
, to help with the use case of sharing state such as engines and connections on the outside with a series of Alembic API calls; also added a new cookbook section to describe this simple but pretty important use case.The format of the default
env.py
script has been refined a bit; it now uses context managers not only for the scope of the transaction, but also for connectivity from the starting engine. The engine is also now called a “connectable” in support of the use case of an external connection being passed in.Added support for “alembic stamp” to work when given “heads” as an argument, when multiple heads are present.
References: #267
bug¶
The
--autogenerate
option is not valid when used in conjunction with “offline” mode, e.g.--sql
. This now raises aCommandError
, rather than failing more deeply later on. Pull request courtesy Johannes Erdfelt.References: #266
Fixed bug where the mssql DROP COLUMN directive failed to include modifiers such as “schema” when emitting the DDL.
References: #284
Postgresql “functional” indexes are necessarily skipped from the autogenerate process, as the SQLAlchemy backend currently does not support reflection of these structures. A warning is emitted both from the SQLAlchemy backend as well as from the Alembic backend for Postgresql when such an index is detected.
References: #282
Fixed bug where MySQL backend would report dropped unique indexes and/or constraints as both at the same time. This is because MySQL doesn’t actually have a “unique constraint” construct that reports differently than a “unique index”, so it is present in both lists. The net effect though is that the MySQL backend will report a dropped unique index/constraint as an index in cases where the object was first created as a unique constraint, if no other information is available to make the decision. This differs from other backends like Postgresql which can report on unique constraints and unique indexes separately.
References: #276
Fixed bug where using a partial revision identifier as the “starting revision” in
--sql
mode in a downgrade operation would fail to resolve properly.As a side effect of this change, the
EnvironmentContext.get_starting_revision_argument()
method will return the “starting” revision in its originally- given “partial” form in all cases, whereas previously when running within thecommand.stamp()
command, it would have been resolved to a full number before passing it to theEnvironmentContext
. The resolution of this value to a real revision number has basically been moved to a more fundamental level within the offline migration process.References: #269
0.7.4¶
Released: January 12, 2015bug¶
Repaired issue where a server default specified without
text()
that represented a numeric or floating point (e.g. with decimal places) value would fail in the Postgresql-specific check for “compare server default”; as PG accepts the value with quotes in the table specification, it’s still valid. Pull request courtesy Dimitris Theodorou.References: #241
The rendering of a
ForeignKeyConstraint
will now ensure that the names of the source and target columns are the database-side name of each column, and not the value of the.key
attribute as may be set only on the Python side. This is because Alembic generates the DDL for constraints as standalone objects without the need to actually refer to an in-PythonTable
object, so there’s no step that would resolve these Python-only key names to database column names.References: #259
Fixed bug in foreign key autogenerate where if the in-Python table used custom column keys (e.g. using the
key='foo'
kwarg toColumn
), the comparison of existing foreign keys to those specified in the metadata would fail, as the reflected table would not have these keys available which to match up. Foreign key comparison for autogenerate now ensures it’s looking at the database-side names of the columns in all cases; this matches the same functionality within unique constraints and indexes.References: #260
Fixed issue in autogenerate type rendering where types that belong to modules that have the name “sqlalchemy” in them would be mistaken as being part of the
sqlalchemy.
namespace. Pull req courtesy Bartosz Burclaf.References: #261
0.7.3¶
Released: December 30, 2014bug¶
Fixed regression in new versioning system where upgrade / history operation would fail on AttributeError if no version files were present at all.
References: #258
0.7.2¶
Released: December 18, 2014bug¶
Adjusted the SQLite backend regarding autogen of unique constraints to work fully with the current SQLAlchemy 1.0, which now will report on UNIQUE constraints that have no name.
Fixed bug in batch where if the target table contained multiple foreign keys to the same target table, the batch mechanics would fail with a “table already exists” error. Thanks for the help on this from Lucas Kahlert.
References: #254
Fixed an issue where the MySQL routine to skip foreign-key-implicit indexes would also catch unnamed unique indexes, as they would be named after the column and look like the FK indexes. Pull request courtesy Johannes Erdfelt.
References: #251
Repaired a regression in both the MSSQL and Oracle dialects whereby the overridden
_exec()
method failed to return a value, as is needed now in the 0.7 series.References: #253
0.7.1¶
Released: December 3, 2014feature¶
Support for autogenerate of FOREIGN KEY constraints has been added. These are delivered within the autogenerate process in the same manner as UNIQUE constraints, including
include_object
support. Big thanks to Ann Kamyshnikova for doing the heavy lifting here.References: #178
Added
naming_convention
argument toOperations.batch_alter_table()
, as this is necessary in order to drop foreign key constraints; these are often unnamed on the target database, and in the case that they are named, SQLAlchemy is as of the 0.9 series not including these names yet.Added two new arguments
Operations.batch_alter_table.reflect_args
andOperations.batch_alter_table.reflect_kwargs
, so that arguments may be passed directly to suit theTable
object that will be reflected.See also
bug¶
The
render_as_batch
flag was inadvertently hardcoded toTrue
, so all autogenerates were spitting out batch mode…this has been fixed so that batch mode again is only when selected in env.py.Fixed bug where the “source_schema” argument was not correctly passed when calling
BatchOperations.create_foreign_key()
. Pull request courtesy Malte Marquarding.Repaired the inspection, copying and rendering of CHECK constraints and so-called “schema” types such as Boolean, Enum within the batch copy system; the CHECK constraint will not be “doubled” when the table is copied, and additionally the inspection of the CHECK constraint for its member columns will no longer fail with an attribute error.
References: #249
0.7.0¶
Released: November 24, 2014changed¶
The
--head_only
option to thealembic current
command is deprecated; thecurrent
command now lists just the version numbers alone by default; use--verbose
to get at additional output.The default value of the
EnvironmentContext.configure.user_module_prefix
parameter is no longer the same as the SQLAlchemy prefix. When omitted, user-defined types will now use the__module__
attribute of the type class itself when rendering in an autogenerated module.References: #229
Minimum SQLAlchemy version is now 0.7.6, however at least 0.8.4 is strongly recommended. The overhaul of the test suite allows for fully passing tests on all SQLAlchemy versions from 0.7.6 on forward.
feature¶
The “multiple heads / branches” feature has now landed. This is by far the most significant change Alembic has seen since its inception; while the workflow of most commands hasn’t changed, and the format of version files and the
alembic_version
table are unchanged as well, a new suite of features opens up in the case where multiple version files refer to the same parent, or to the “base”. Merging of branches, operating across distinct named heads, and multiple independent bases are now all supported. The feature incurs radical changes to the internals of versioning and traversal, and should be treated as “beta mode” for the next several subsequent releases within 0.7.See also
References: #167
In conjunction with support for multiple independent bases, the specific version directories are now also configurable to include multiple, user-defined directories. When multiple directories exist, the creation of a revision file with no down revision requires that the starting directory is indicated; the creation of subsequent revisions along that lineage will then automatically use that directory for new files.
References: #124
Added “move and copy” workflow, where a table to be altered is copied to a new one with the new structure and the old one dropped, is now implemented for SQLite as well as all database backends in general using the new
Operations.batch_alter_table()
system. This directive provides a table-specific operations context which gathers column- and constraint-level mutations specific to that table, and at the end of the context creates a new table combining the structure of the old one with the given changes, copies data from old table to new, and finally drops the old table, renaming the new one to the existing name. This is required for fully featured SQLite migrations, as SQLite has very little support for the traditional ALTER directive. The batch directive is intended to produce code that is still compatible with other databases, in that the “move and copy” process only occurs for SQLite by default, while still providing some level of sanity to SQLite’s requirement by allowing multiple table mutation operations to proceed within one “move and copy” as well as providing explicit control over when this operation actually occurs. The “move and copy” feature may be optionally applied to other backends as well, however dealing with referential integrity constraints from other tables must still be handled explicitly.References: #21
Relative revision identifiers as used with
alembic upgrade
,alembic downgrade
andalembic history
can be combined with specific revisions as well, e.g.alembic upgrade ae10+3
, to produce a migration target relative to the given exact version.New commands added:
alembic show
,alembic heads
andalembic merge
. Also, a new option--verbose
has been added to several informational commands, such asalembic history
,alembic current
,alembic branches
, andalembic heads
.alembic revision
also contains several new options used within the new branch management system. The output of commands has been altered in many cases to support new fields and attributes; thehistory
command in particular now returns it’s “verbose” output only if--verbose
is sent; without this flag it reverts to it’s older behavior of short line items (which was never changed in the docs).Added new argument
Config.config_args
, allows a dictionary of replacement variables to be passed which will serve as substitution values when an API-producedConfig
consumes the.ini
file. Pull request courtesy Noufal Ibrahim.The
Table
object is now returned when theOperations.create_table()
method is used. ThisTable
is suitable for use in subsequent SQL operations, in particular theOperations.bulk_insert()
operation.References: #205
Indexes and unique constraints are now included in the
EnvironmentContext.configure.include_object
hook. Indexes are sent with type"index"
and unique constraints with type"unique_constraint"
.References: #203
SQLAlchemy’s testing infrastructure is now used to run tests. This system supports both nose and pytest and opens the way for Alembic testing to support any number of backends, parallel testing, and 3rd party dialect testing.
bug¶
The
alembic revision
command accepts the--sql
option to suit some very obscure use case where therevision_environment
flag is set up, so thatenv.py
is run whenalembic revision
is run even though autogenerate isn’t specified. As this flag is otherwise confusing, error messages are now raised ifalembic revision
is invoked with both--sql
and--autogenerate
or with--sql
withoutrevision_environment
being set.References: #248
Added a rule for Postgresql to not render a “drop unique” and “drop index” given the same name; for now it is assumed that the “index” is the implicit one Postgreql generates. Future integration with new SQLAlchemy 1.0 features will improve this to be more resilient.
References: #247
A change in the ordering when columns and constraints are dropped; autogenerate will now place the “drop constraint” calls before the “drop column” calls, so that columns involved in those constraints still exist when the constraint is dropped.
References: #247
The Oracle dialect sets “transactional DDL” to False by default, as Oracle does not support transactional DDL.
References: #245
Fixed a variety of issues surrounding rendering of Python code that contains unicode literals. The first is that the “quoted_name” construct that SQLAlchemy uses to represent table and column names as well as schema names does not
repr()
correctly on Py2K when the value contains unicode characters; therefore an explicit stringification is added to these. Additionally, SQL expressions such as server defaults were not being generated in a unicode-safe fashion leading to decode errors if server defaults contained non-ascii characters.References: #243
The
Operations.add_column()
directive will now additionally emit the appropriateCREATE INDEX
statement if theColumn
object specifiesindex=True
. Pull request courtesy David Szotten.References: #174
Bound parameters are now resolved as “literal” values within the SQL expression inside of a CheckConstraint(), when rendering the SQL as a text string; supported for SQLAlchemy 0.8.0 and forward.
References: #219
Added a workaround for SQLAlchemy issue #3023 (fixed in 0.9.5) where a column that’s part of an explicit PrimaryKeyConstraint would not have its “nullable” flag set to False, thus producing a false autogenerate. Also added a related correction to MySQL which will correct for MySQL’s implicit server default of ‘0’ when a NULL integer column is turned into a primary key column.
References: #199
Repaired issue related to the fix for #208 and others; a composite foreign key reported by MySQL would cause a KeyError as Alembic attempted to remove MySQL’s implicitly generated indexes from the autogenerate list.
References: #240
If the “alembic_version” table is present in the target metadata, autogenerate will skip this also. Pull request courtesy Dj Gilcrease.
References: #28
The
EnvironmentContext.configure.version_table
andEnvironmentContext.configure.version_table_schema
arguments are now honored during the autogenerate process, such that these names will be used as the “skip” names on both the database reflection and target metadata sides.References: #77
Revision files are now written out using the
'wb'
modifier toopen()
, since Mako reads the templates with'rb'
, thus preventing CRs from being doubled up as has been observed on windows. The encoding of the output now defaults to ‘utf-8’, which can be configured using a newly added config file parameteroutput_encoding
.References: #234
Added support for use of the
quoted_name
construct when using theschema
argument within operations. This allows a name containing a dot to be fully quoted, as well as to provide configurable quoting on a per-name basis.References: #230
Added a routine by which the Postgresql Alembic dialect inspects the server default of INTEGER/BIGINT columns as they are reflected during autogenerate for the pattern
nextval(<name>...)
containing a potential sequence name, then queriespg_catalog
to see if this sequence is “owned” by the column being reflected; if so, it assumes this is a SERIAL or BIGSERIAL column and the server default is omitted from the column reflection as well as any kind of server_default comparison or rendering, along with an INFO message in the logs indicating this has taken place. This allows SERIAL/BIGSERIAL columns to keep the SEQUENCE from being unnecessarily present within the autogenerate operation.References: #73
The system by which autogenerate renders expressions within a
Index
, theserver_default
ofColumn
, and theexisting_server_default
ofOperations.alter_column()
has been overhauled to anticipate arbitrary SQLAlchemy SQL constructs, such asfunc.somefunction()
,cast()
,desc()
, and others. The system does not, as might be preferred, render the full-blown Python expression as originally created within the application’s source code, as this would be exceedingly complex and difficult. Instead, it renders the SQL expression against the target backend that’s subject to the autogenerate, and then renders that SQL inside of atext()
construct as a literal SQL string. This approach still has the downside that the rendered SQL construct may not be backend-agnostic in all cases, so there is still a need for manual intervention in that small number of cases, but overall the majority of cases should work correctly now. Big thanks to Carlos Rivera for pull requests and support on this.The “match” keyword is not sent to
ForeignKeyConstraint
byOperations.create_foreign_key()
when SQLAlchemy 0.7 is in use; this keyword was added to SQLAlchemy as of 0.8.0.
0.6.7¶
Released: September 9, 2014feature¶
Added support for functional indexes when using the
Operations.create_index()
directive. Within the list of columns, the SQLAlchemytext()
construct can be sent, embedding a literal SQL expression; theOperations.create_index()
will perform some hackery behind the scenes to get theIndex
construct to cooperate. This works around some current limitations inIndex
which should be resolved on the SQLAlchemy side at some point.References: #222
bug¶
Fixed bug in MSSQL dialect where “rename table” wasn’t using
sp_rename()
as is required on SQL Server. Pull request courtesy Łukasz Bołdys.
0.6.6¶
Released: August 7, 2014feature¶
Added a new accessor
MigrationContext.config
, when used in conjunction with aEnvironmentContext
andConfig
, this config will be returned. Patch courtesy Marc Abramowitz.
bug¶
A file named
__init__.py
in theversions/
directory is now ignored by Alembic when the collection of version files is retrieved. Pull request courtesy Michael Floering.References: #95
Fixed Py3K bug where an attempt would be made to sort None against string values when autogenerate would detect tables across multiple schemas, including the default schema. Pull request courtesy paradoxxxzero.
Autogenerate render will render the arguments within a Table construct using
*[...]
when the number of columns/elements is greater than 255. Pull request courtesy Ryan P. Kelly.Fixed bug where foreign key constraints would fail to render in autogenerate when a schema name was present. Pull request courtesy Andreas Zeidler.
Some deep-in-the-weeds fixes to try to get “server default” comparison working better across platforms and expressions, in particular on the Postgresql backend, mostly dealing with quoting/not quoting of various expressions at the appropriate time and on a per-backend basis. Repaired and tested support for such defaults as Postgresql interval and array defaults.
References: #212
Liberalized even more the check for MySQL indexes that shouldn’t be counted in autogenerate as “drops”; this time it’s been reported that an implicitly created index might be named the same as a composite foreign key constraint, and not the actual columns, so we now skip those when detected as well.
References: #208
misc¶
When a run of Alembic command line fails due to
CommandError
, the output now prefixes the string with"FAILED:"
, and the error is also written to the log output usinglog.error()
.References: #209
0.6.5¶
Released: May 3, 2014feature¶
Added new feature
EnvironmentContext.configure.transaction_per_migration
, which when True causes the BEGIN/COMMIT pair to incur for each migration individually, rather than for the whole series of migrations. This is to assist with some database directives that need to be within individual transactions, without the need to disable transactional DDL entirely.References: #201
bug¶
This releases’ “autogenerate index detection” bug, when a MySQL table includes an Index with the same name as a column, autogenerate reported it as an “add” even though its not; this is because we ignore reflected indexes of this nature due to MySQL creating them implicitly. Indexes that are named the same as a column are now ignored on MySQL if we see that the backend is reporting that it already exists; this indicates that we can still detect additions of these indexes but not drops, as we cannot distinguish a backend index same-named as the column as one that is user generated or mysql-generated.
References: #202
Fixed bug where the
include_object()
filter would not receive the originalColumn
object when evaluating a database-only column to be dropped; the object would not include the parentTable
nor other aspects of the column that are important for generating the “downgrade” case where the column is recreated.References: #200
Fixed bug where
EnvironmentContext.get_x_argument()
would fail if theConfig
in use didn’t actually originate from a command line call.References: #195
Fixed another bug regarding naming conventions, continuing from #183, where add_index() drop_index() directives would not correctly render the
f()
construct when the index contained a convention-driven name.References: #194
0.6.4¶
Released: March 28, 2014feature¶
The
command.revision()
command now returns theScript
object corresponding to the newly generated revision. From this structure, one can get the revision id, the module documentation, and everything else, for use in scripts that call upon this command. Pull request courtesy Robbie Coomber.
bug¶
Added quoting to the table name when the special EXEC is run to drop any existing server defaults or constraints when the
drop_column.mssql_drop_check
ordrop_column.mssql_drop_default
arguments are used.References: #186
Added/fixed support for MySQL “SET DEFAULT” / “DROP DEFAULT” phrases, which will now be rendered if only the server default is changing or being dropped (e.g. specify None to alter_column() to indicate “DROP DEFAULT”). Also added support for rendering MODIFY rather than CHANGE when the column name isn’t changing.
References: #103
Added support for the
initially
,match
keyword arguments as well as dialect-specific keyword arguments toOperations.create_foreign_key()
.- tags:
feature
- tickets:
163
Altered the support for “sourceless” migration files (e.g. only .pyc or .pyo present) so that the flag “sourceless=true” needs to be in alembic.ini for this behavior to take effect.
References: #190
The feature that keeps on giving, index/unique constraint autogenerate detection, has even more fixes, this time to accommodate database dialects that both don’t yet report on unique constraints, but the backend does report unique constraints as indexes. The logic Alembic uses to distinguish between “this is an index!” vs. “this is a unique constraint that is also reported as an index!” has now been further enhanced to not produce unwanted migrations when the dialect is observed to not yet implement get_unique_constraints() (e.g. mssql). Note that such a backend will no longer report index drops for unique indexes, as these cannot be distinguished from an unreported unique index.
References: #185
Extensive changes have been made to more fully support SQLAlchemy’s new naming conventions feature. Note that while SQLAlchemy has added this feature as of 0.9.2, some additional fixes in 0.9.4 are needed to resolve some of the issues:
The
Operations
object now takes into account the naming conventions that are present on theMetaData
object that’s associated usingtarget_metadata
. WhenOperations
renders a constraint directive likeADD CONSTRAINT
, it now will make use of this naming convention when it produces its own temporaryMetaData
object.Note however that the autogenerate feature in most cases generates constraints like foreign keys and unique constraints with the final names intact; the only exception are the constraints implicit with a schema-type like Boolean or Enum. In most of these cases, the naming convention feature will not take effect for these constraints and will instead use the given name as is, with one exception….
Naming conventions which use the
"%(constraint_name)s"
token, that is, produce a new name that uses the original name as a component, will still be pulled into the naming convention converter and be converted. The problem arises when autogenerate renders a constraint with it’s already-generated name present in the migration file’s source code, the name will be doubled up at render time due to the combination of #1 and #2. So to work around this, autogenerate now renders these already-tokenized names using the newOperations.f()
component. This component is only generated if SQLAlchemy 0.9.4 or greater is in use.
Therefore it is highly recommended that an upgrade to Alembic 0.6.4 be accompanied by an upgrade of SQLAlchemy 0.9.4, if the new naming conventions feature is used.
References: #183
Suppressed IOErrors which can raise when program output pipe is closed under a program like
head
; however this only works on Python 2. On Python 3, there is not yet a known way to suppress the BrokenPipeError warnings without prematurely terminating the program via signals.References: #160
Fixed bug where
Operations.bulk_insert()
would not function properly whenOperations.inline_literal()
values were used, either in –sql or non-sql mode. The values will now render directly in –sql mode. For compatibility with “online” mode, a new flagmultiinsert
can be set to False which will cause each parameter set to be compiled and executed with individual INSERT statements.References: #179
Fixed a failure of the system that allows “legacy keyword arguments” to be understood, which arose as of a change in Python 3.4 regarding decorators. A workaround is applied that allows the code to work across Python 3 versions.
References: #175
0.6.3¶
Released: February 2, 2014feature¶
Added new argument
EnvironmentContext.configure.user_module_prefix
. This prefix is applied when autogenerate renders a user-defined type, which here is defined as any type that is from a module outside of thesqlalchemy.
hierarchy. This prefix defaults toNone
, in which case theEnvironmentContext.configure.sqlalchemy_module_prefix
is used, thus preserving the current behavior.References: #171
The
ScriptDirectory
system that loads migration files from aversions/
directory now supports so-called “sourceless” operation, where the.py
files are not present and instead.pyc
or.pyo
files are directly present where the.py
files should be. Note that while Python 3.3 has a new system of locating.pyc
/.pyo
files within a directory called__pycache__
(e.g. PEP-3147), PEP-3147 maintains support for the “source-less imports” use case, where the.pyc
/.pyo
are in present in the “old” location, e.g. next to the.py
file; this is the usage that’s supported even when running Python3.3.References: #163
bug¶
Added a workaround for when we call
fcntl.ioctl()
to get atTERMWIDTH
; if the function returns zero, as is reported to occur in some pseudo-ttys, the message wrapping system is disabled in the same way as ifioctl()
failed.References: #172
Added support for autogenerate covering the use case where
Table
objects specified in the metadata have an explicitschema
attribute whose name matches that of the connection’s default schema (e.g. “public” for Postgresql). Previously, it was assumed that “schema” wasNone
when it matched the “default” schema, now the comparison adjusts for this.References: #170
The
compare_metadata()
public API function now takes into account the settings forEnvironmentContext.configure.include_object
,EnvironmentContext.configure.include_symbol
, andEnvironmentContext.configure.include_schemas
, in the same way that the--autogenerate
command does. Pull request courtesy Roman Podoliaka.Calling
bulk_insert()
with an empty list will not emit any commands on the current connection. This was already the case with--sql
mode, so is now the case with “online” mode.References: #168
Enabled schema support for index and unique constraint autodetection; previously these were non-functional and could in some cases lead to attribute errors. Pull request courtesy Dimitris Theodorou.
More fixes to index autodetection; indexes created with expressions like DESC or functional indexes will no longer cause AttributeError exceptions when attempting to compare the columns.
References: #164
0.6.2¶
Released: Fri Dec 27 2013feature¶
Added new argument
mssql_drop_foreign_key
toOperations.drop_column()
. Likemssql_drop_default
andmssql_drop_check
, will do an inline lookup for a single foreign key which applies to this column, and drop it. For a column with more than one FK, you’d still need to explicitly useOperations.drop_constraint()
given the name, even though only MSSQL has this limitation in the first place.
bug¶
Autogenerate for
op.create_table()
will not include aPrimaryKeyConstraint()
that has no columns.Fixed bug in the not-internally-used
ScriptDirectory.get_base()
method which would fail if called on an empty versions directory.An almost-rewrite of the new unique constraint/index autogenerate detection, to accommodate a variety of issues. The emphasis is on not generating false positives for those cases where no net change is present, as these errors are the ones that impact all autogenerate runs:
Fixed an issue with unique constraint autogenerate detection where a named
UniqueConstraint
on both sides with column changes would render with the “add” operation before the “drop”, requiring the user to reverse the order manually.Corrected for MySQL’s apparent addition of an implicit index for a foreign key column, so that it doesn’t show up as “removed”. This required that the index/constraint autogen system query the dialect-specific implementation for special exceptions.
reworked the “dedupe” logic to accommodate MySQL’s bi-directional duplication of unique indexes as unique constraints, and unique constraints as unique indexes. Postgresql’s slightly different logic of duplicating unique constraints into unique indexes continues to be accommodated as well. Note that a unique index or unique constraint removal on a backend that duplicates these may show up as a distinct “remove_constraint()” / “remove_index()” pair, which may need to be corrected in the post-autogenerate if multiple backends are being supported.
added another dialect-specific exception to the SQLite backend when dealing with unnamed unique constraints, as the backend can’t currently report on constraints that were made with this technique, hence they’d come out as “added” on every run.
the
op.create_table()
directive will be auto-generated with theUniqueConstraint
objects inline, but will not double them up with a separatecreate_unique_constraint()
call, which may have been occurring. Indexes still get rendered as distinctop.create_index()
calls even when the corresponding table was created in the same script.the inline
UniqueConstraint
withinop.create_table()
includes all the options likedeferrable
,initially
, etc. Previously these weren’t rendering.
References: #157
The MSSQL backend will add the batch separator (e.g.
"GO"
) in--sql
mode after the finalCOMMIT
statement, to ensure that statement is also processed in batch mode. Courtesy Derek Harland.
0.6.1¶
Released: Wed Nov 27 2013feature¶
Expanded the size of the “slug” generated by “revision” to 40 characters, which is also configurable by new field
truncate_slug_length
; and also split on the word rather than the character; courtesy Frozenball.Support for autogeneration detection and rendering of indexes and unique constraints has been added. The logic goes through some effort in order to differentiate between true unique constraints and unique indexes, where there are some quirks on backends like Postgresql. The effort here in producing the feature and tests is courtesy of IJL.
References: #107
bug¶
Fixed bug where
op.alter_column()
in the MySQL dialect would fail to apply quotes to column names that had mixed casing or spaces.References: #152
Fixed the output wrapping for Alembic message output, so that we either get the terminal width for “pretty printing” with indentation, or if not we just output the text as is; in any case the text won’t be wrapped too short.
References: #135
Fixes to Py3k in-place compatibility regarding output encoding and related; the use of the new io.* package introduced some incompatibilities on Py2k. These should be resolved, due to the introduction of new adapter types for translating from io.* to Py2k file types, StringIO types. Thanks to Javier Santacruz for help with this.
Fixed py3k bug where the wrong form of
next()
was being called when using the list_templates command. Courtesy Chris Wilkes.References: #145
Fixed bug introduced by new
include_object
argument where the inspected column would be misinterpreted when using a user-defined type comparison function, causing a KeyError or similar expression-related error. Fix courtesy Maarten van Schaik.Added the “deferrable” keyword argument to
op.create_foreign_key()
so thatDEFERRABLE
constraint generation is supported; courtesy Pedro Romano.Ensured that strings going to stdout go through an encode/decode phase, so that any non-ASCII characters get to the output stream correctly in both Py2k and Py3k. Also added source encoding detection using Mako’s parse_encoding() routine in Py2k so that the __doc__ of a non-ascii revision file can be treated as unicode in Py2k.
References: #137
0.6.0¶
Released: Fri July 19 2013feature¶
Added new kw argument to
EnvironmentContext.configure()
include_object
. This is a more flexible version of theinclude_symbol
argument which allows filtering of columns as well as tables from the autogenerate process, and in the future will also work for types, constraints and other constructs. The fully constructed schema object is passed, including its name and type as well as a flag indicating if the object is from the local application metadata or is reflected.References: #101
The output of the
alembic history
command is now expanded to show information about each change on multiple lines, including the full top message, resembling the formatting of git log.Added
alembic.config.Config.cmd_opts
attribute, allows access to theargparse
options passed to thealembic
runner.Added new command line argument
-x
, allows extra arguments to be appended to the command line which can be consumed within anenv.py
script by looking atcontext.config.cmd_opts.x
, or more simply a new methodEnvironmentContext.get_x_argument()
.References: #120
Added
-r
argument toalembic history
command, allows specification of[start]:[end]
to view a slice of history. Accepts revision numbers, symbols “base”, “head”, a new symbol “current” representing the current migration, as well as relative ranges for one side at a time (i.e.-r-5:head
,-rcurrent:+3
). Courtesy Atsushi Odagiri for this feature.Source base is now in-place for Python 2.6 through 3.3, without the need for 2to3. Support for Python 2.5 and below has been dropped. Huge thanks to Hong Minhee for all the effort on this!
References: #55
bug¶
Added support for options like “name” etc. to be rendered within CHECK constraints in autogenerate. Courtesy Sok Ann Yap.
References: #125
Repaired autogenerate rendering of ForeignKeyConstraint to include use_alter argument, if present.
misc¶
Source repository has been moved from Mercurial to Git.
0.5.0¶
Released: Thu Apr 4 2013Note
Alembic 0.5.0 now requires at least version 0.7.3 of SQLAlchemy to run properly. Support for 0.6 has been dropped.
feature¶
Added
version_table_schema
argument toEnvironmentContext.configure()
, complements theversion_table
argument to set an optional remote schema for the version table. Courtesy Christian Blume.References: #76
Added
output_encoding
option toEnvironmentContext.configure()
, used with--sql
mode to apply an encoding to the output stream.References: #90
Added
Operations.create_primary_key()
operation, will genenerate an ADD CONSTRAINT for a primary key.References: #93
upgrade and downgrade commands will list the first line of the docstring out next to the version number. Courtesy Hong Minhee.
References: #115
Added –head-only option to “alembic current”, will print current version plus the symbol “(head)” if this version is the head or not. Courtesy Charles-Axel Dein.
The rendering of any construct during autogenerate can be customized, in particular to allow special rendering for user-defined column, constraint subclasses, using new
render_item
argument toEnvironmentContext.configure()
.References: #108
bug¶
Fixed format of RENAME for table that includes schema with Postgresql; the schema name shouldn’t be in the “TO” field.
References: #32
Fixed bug whereby double quoting would be applied to target column name during an
sp_rename
operation.References: #109
transactional_ddl flag for SQLite, MySQL dialects set to False. MySQL doesn’t support it, SQLite does but current pysqlite driver does not.
References: #112
Autogenerate will render additional table keyword arguments like “mysql_engine” and others within op.create_table().
References: #110
Fixed bug whereby create_index() would include in the constraint columns that are added to all Table objects using events, externally to the generation of the constraint. This is the same issue that was fixed for unique constraints in version 0.3.2.
Worked around a backwards-incompatible regression in Python3.3 regarding argparse; running “alembic” with no arguments now yields an informative error in py3.3 as with all previous versions. Courtesy Andrey Antukh.
A host of argument name changes within migration operations for consistency. Keyword arguments will continue to work on the old name for backwards compatibility, however required positional arguments will not:
Operations.alter_column()
-name
->new_column_name
- old name will work for backwards compatibility.Operations.create_index()
-tablename
->table_name
- argument is positional.Operations.drop_index()
-tablename
->table_name
- old name will work for backwards compatibility.Operations.drop_constraint()
-tablename
->table_name
- argument is positional.Operations.drop_constraint()
-type
->type_
- old name will work for backwards compatibilityReferences: #104
misc¶
SQLAlchemy 0.6 is no longer supported by Alembic - minimum version is 0.7.3, full support is as of 0.7.9.
0.4.2¶
Released: Fri Jan 11 2013feature¶
Added a README.unittests with instructions for running the test suite fully.
References: #96
bug¶
Fixed bug where autogenerate would fail if a Column to be added to a table made use of the “.key” parameter.
References: #99
The “implicit” constraint generated by a type such as Boolean or Enum will not generate an ALTER statement when run on SQlite, which does not support ALTER for the purpose of adding/removing constraints separate from the column def itself. While SQLite supports adding a CHECK constraint at the column level, SQLAlchemy would need modification to support this. A warning is emitted indicating this constraint cannot be added in this scenario.
References: #98
Added a workaround to setup.py to prevent “NoneType” error from occurring when “setup.py test” is run.
References: #96
Added an append_constraint() step to each condition within test_autogenerate:AutogenRenderTest.test_render_fk_constraint_kwarg if the SQLAlchemy version is less than 0.8, as ForeignKeyConstraint does not auto-append prior to 0.8.
References: #96
0.4.1¶
Released: Sun Dec 9 2012feature¶
Explicit error message describing the case when downgrade –sql is used without specifying specific start/end versions.
References: #66
bug¶
Added support for autogenerate render of ForeignKeyConstraint options onupdate, ondelete, initially, and deferred.
References: #92
Autogenerate will include “autoincrement=False” in the rendered table metadata if this flag was set to false on the source
Column
object.References: #94
Removed erroneous “emit_events” attribute from operations.create_table() documentation.
References: #81
Fixed the minute component in file_template which returned the month part of the create date.
0.4.0¶
Released: Mon Oct 01 2012feature¶
Support for tables in alternate schemas has been added fully to all operations, as well as to the autogenerate feature. When using autogenerate, specifying the flag include_schemas=True to Environment.configure() will also cause autogenerate to scan all schemas located by Inspector.get_schema_names(), which is supported by some (but not all) SQLAlchemy dialects including Postgresql. Enormous thanks to Bruno Binet for a huge effort in implementing as well as writing tests. .
References: #33
The command line runner has been organized into a reusable CommandLine object, so that other front-ends can re-use the argument parsing built in.
References: #70
Added “stdout” option to Config, provides control over where the “print” output of commands like “history”, “init”, “current” etc. are sent.
References: #43
Added support for alteration of MySQL columns that have AUTO_INCREMENT, as well as enabling this flag. Courtesy Moriyoshi Koizumi.
bug¶
Fixed the “multidb” template which was badly out of date. It now generates revision files using the configuration to determine the different upgrade_<xyz>() methods needed as well, instead of needing to hardcode these. Huge thanks to BryceLohr for doing the heavy lifting here.
References: #71
Fixed the regexp that was checking for .py files in the version directory to allow any .py file through. Previously it was doing some kind of defensive checking, probably from some early notions of how this directory works, that was prohibiting various filename patterns such as those which begin with numbers.
References: #72
Fixed MySQL rendering for server_default which didn’t work if the server_default was a generated SQL expression. Courtesy Moriyoshi Koizumi.
0.3.6¶
Released: Wed Aug 15 2012feature¶
Added include_symbol option to EnvironmentContext.configure(), specifies a callable which will include/exclude tables in their entirety from the autogeneration process based on name.
References: #27
Added year, month, day, hour, minute, second variables to file_template.
References: #59
Added ‘primary’ to the list of constraint types recognized for MySQL drop_constraint().
Added –sql argument to the “revision” command, for the use case where the “revision_environment” config option is being used but SQL access isn’t desired.
bug¶
Repaired create_foreign_key() for self-referential foreign keys, which weren’t working at all.
’alembic’ command reports an informative error message when the configuration is missing the ‘script_directory’ key.
References: #63
Fixes made to the constraints created/dropped alongside so-called “schema” types such as Boolean and Enum. The create/drop constraint logic does not kick in when using a dialect that doesn’t use constraints for these types, such as postgresql, even when existing_type is specified to alter_column(). Additionally, the constraints are not affected if existing_type is passed but type_ is not, i.e. there’s no net change in type.
References: #62
Improved error message when specifying non-ordered revision identifiers to cover the case when the “higher” rev is None, improved message overall.
References: #66
0.3.5¶
Released: Sun Jul 08 2012feature¶
Implemented SQL rendering for CheckConstraint() within autogenerate upgrade, including for literal SQL as well as SQL Expression Language expressions.
bug¶
Fixed issue whereby reflected server defaults wouldn’t be quoted correctly; uses repr() now.
References: #31
Fixed issue whereby when autogenerate would render create_table() on the upgrade side for a table that has a Boolean type, an unnecessary CheckConstraint() would be generated.
References: #58
0.3.4¶
Released: Sat Jun 02 2012bug¶
Fixed command-line bug introduced by the “revision_environment” feature.
0.3.3¶
Released: Sat Jun 02 2012feature¶
New config argument “revision_environment=true”, causes env.py to be run unconditionally when the “revision” command is run, to support script.py.mako templates with dependencies on custom “template_args”.
Added “template_args” option to configure() so that an env.py can add additional arguments to the template context when running the “revision” command. This requires either –autogenerate or the configuration directive “revision_environment=true”.
Added version_table argument to EnvironmentContext.configure(), allowing for the configuration of the version table name.
References: #34
Added support for “relative” migration identifiers, i.e. “alembic upgrade +2”, “alembic downgrade -1”. Courtesy Atsushi Odagiri for this feature.
bug¶
Added “type” argument to op.drop_constraint(), and implemented full constraint drop support for MySQL. CHECK and undefined raise an error. MySQL needs the constraint type in order to emit a DROP CONSTRAINT.
References: #44
Fixed bug whereby directories inside of the template directories, such as __pycache__ on Pypy, would mistakenly be interpreted as files which are part of the template.
References: #49
0.3.2¶
Released: Mon Apr 30 2012feature¶
Basic support for Oracle added, courtesy shgoh.
References: #40
Added support for UniqueConstraint in autogenerate, courtesy Atsushi Odagiri
bug¶
Fixed support of schema-qualified ForeignKey target in column alter operations, courtesy Alexander Kolov.
Fixed bug whereby create_unique_constraint() would include in the constraint columns that are added to all Table objects using events, externally to the generation of the constraint.
0.3.1¶
Released: Sat Apr 07 2012bug¶
bulk_insert() fixes:
bulk_insert() operation was not working most likely since the 0.2 series when used with an engine.
Repaired bulk_insert() to complete when used against a lower-case-t table and executing with only one set of parameters, working around SQLAlchemy bug #2461 in this regard.
bulk_insert() uses “inline=True” so that phrases like RETURNING and such don’t get invoked for single-row bulk inserts.
bulk_insert() will check that you’re passing a list of dictionaries in, raises TypeError if not detected.
References: #41
0.3.0¶
Released: Thu Apr 05 2012feature¶
Added a bit of autogenerate to the public API in the form of the function alembic.autogenerate.compare_metadata.
misc¶
The focus of 0.3 is to clean up and more fully document the public API of Alembic, including better accessors on the MigrationContext and ScriptDirectory objects. Methods that are not considered to be public on these objects have been underscored, and methods which should be public have been cleaned up and documented, including:
MigrationContext.get_current_revision() ScriptDirectory.iterate_revisions() ScriptDirectory.get_current_head() ScriptDirectory.get_heads() ScriptDirectory.get_base() ScriptDirectory.generate_revision()
0.2.2¶
Released: Mon Mar 12 2012feature¶
Informative error message when op.XYZ directives are invoked at module import time.
Added execution_options parameter to op.execute(), will call execution_options() on the Connection before executing.
The immediate use case here is to allow access to the new no_parameters option in SQLAlchemy 0.7.6, which allows some DBAPIs (psycopg2, MySQLdb) to allow percent signs straight through without escaping, thus providing cross-compatible operation with DBAPI execution and static script generation.
script_location can be interpreted by pkg_resources.resource_filename(), if it is a non-absolute URI that contains colons. This scheme is the same one used by Pyramid.
References: #29
added missing support for onupdate/ondelete flags for ForeignKeyConstraint, courtesy Giacomo Bagnoli
bug¶
Fixed inappropriate direct call to util.err() and therefore sys.exit() when Config failed to locate the config file within library usage.
References: #35
Autogenerate will emit CREATE TABLE and DROP TABLE directives according to foreign key dependency order.
implement ‘tablename’ parameter on drop_index() as this is needed by some backends.
setup.py won’t install argparse if on Python 2.7/3.2
fixed a regression regarding an autogenerate error message, as well as various glitches in the Pylons sample template. The Pylons sample template requires that you tell it where to get the Engine from now. courtesy Marcin Kuzminski
References: #30
drop_index() ensures a dummy column is added when it calls “Index”, as SQLAlchemy 0.7.6 will warn on index with no column names.
0.2.1¶
Released: Tue Jan 31 2012bug¶
Fixed the generation of CHECK constraint, regression from 0.2.0
References: #26
0.2.0¶
Released: Mon Jan 30 2012feature¶
API rearrangement allows everything Alembic does to be represented by contextual objects, including EnvironmentContext, MigrationContext, and Operations. Other libraries and applications can now use things like “alembic.op” without relying upon global configuration variables. The rearrangement was done such that existing migrations should be OK, as long as they use the pattern of “from alembic import context” and “from alembic import op”, as these are now contextual objects, not modules.
References: #19
The naming of revision files can now be customized to be some combination of “rev id” and “slug”, the latter of which is based on the revision message. By default, the pattern “<rev>_<slug>” is used for new files. New script files should include the “revision” variable for this to work, which is part of the newer script.py.mako scripts.
References: #24
Can create alembic.config.Config with no filename, use set_main_option() to add values. Also added set_section_option() which will add sections.
References: #23
bug¶
env.py templates call connection.close() to better support programmatic usage of commands; use NullPool in conjunction with create_engine() as well so that no connection resources remain afterwards.
References: #25
fix the config.main() function to honor the arguments passed, remove no longer used “scripts/alembic” as setuptools creates this for us.
References: #22
Fixed alteration of column type on MSSQL to not include the keyword “TYPE”.
0.1.1¶
Released: Wed Jan 04 2012feature¶
PyPy is supported.
Python 2.5 is supported, needs __future__.with_statement
Add alembic_module_prefix argument to configure() to complement sqlalchemy_module_prefix.
References: #18
bug¶
Clean up file write operations so that file handles are closed.
Fix autogenerate so that “pass” is generated between the two comments if no net migrations were present.
Fix autogenerate bug that prevented correct reflection of a foreign-key referenced table in the list of “to remove”.
References: #16
Fix bug where create_table() didn’t handle self-referential foreign key correctly
References: #17
Default prefix for autogenerate directives is “op.”, matching the mako templates.
References: #18
fix quotes not being rendered in ForeignKeConstraint during autogenerate
References: #14
0.1.0¶
Released: Wed Nov 30 2011Initial release. Status of features:
Alembic is used in at least one production environment, but should still be considered ALPHA LEVEL SOFTWARE as of this release, particularly in that many features are expected to be missing / unimplemented. Major API changes are not anticipated but for the moment nothing should be assumed.
The author asks that you please report all issues, missing features, workarounds etc. to the bugtracker.
Python 3 is supported and has been tested.
The “Pylons” and “MultiDB” environment templates have not been directly tested - these should be considered to be samples to be modified as needed. Multiple database support itself is well tested, however.
Postgresql and MS SQL Server environments have been tested for several weeks in a production environment. In particular, some involved workarounds were implemented to allow fully-automated dropping of default- or constraint-holding columns with SQL Server.
MySQL support has also been implemented to a basic degree, including MySQL’s awkward style of modifying columns being accommodated.
Other database environments not included among those three have not been tested, at all. This includes Firebird, Oracle, Sybase. Adding support for these backends should be straightforward. Please report all missing/ incorrect behaviors to the bugtracker! Patches are welcome here but are optional - please just indicate the exact format expected by the target database.
SQLite, as a backend, has almost no support for schema alterations to existing databases. The author would strongly recommend that SQLite not be used in a migration context - just dump your SQLite database into an intermediary format, then dump it back into a new schema. For dev environments, the dev installer should be building the whole DB from scratch. Or just use Postgresql, which is a much better database for non-trivial schemas. Requests for full ALTER support on SQLite should be reported to SQLite’s bug tracker at http://www.sqlite.org/src/wiki?name=Bug+Reports, as Alembic will not be implementing the “rename the table to a temptable then copy the data into a new table” workaround. Note that Alembic will at some point offer an extensible API so that you can implement commands like this yourself.
Well-tested directives include add/drop table, add/drop column, including support for SQLAlchemy “schema” types which generate additional CHECK constraints, i.e. Boolean, Enum. Other directives not included here have not been strongly tested in production, i.e. rename table, etc.
Both “online” and “offline” migrations, the latter being generated SQL scripts to hand off to a DBA, have been strongly production tested against Postgresql and SQL Server.
Modify column type, default status, nullable, is functional and tested across PG, MSSQL, MySQL, but not yet widely tested in production usage.
Many migrations are still outright missing, i.e. create/add sequences, etc. As a workaround, execute() can be used for those which are missing, though posting of tickets for new features/missing behaviors is strongly encouraged.
Autogenerate feature is implemented and has been tested, though only a little bit in a production setting. In particular, detection of type and server default changes are optional and are off by default; they can also be customized by a callable. Both features work but can have surprises particularly the disparity between BIT/TINYINT and boolean, which hasn’t yet been worked around, as well as format changes performed by the database on defaults when it reports back. When enabled, the PG dialect will execute the two defaults to be compared to see if they are equivalent. Other backends may need to do the same thing.
The autogenerate feature only generates “candidate” commands which must be hand-tailored in any case, so is still a useful feature and is safe to use. Please report missing/broken features of autogenerate! This will be a great feature and will also improve SQLAlchemy’s reflection services.
Support for non-ASCII table, column and constraint names is mostly nonexistent. This is also a straightforward feature add as SQLAlchemy itself supports unicode identifiers; Alembic itself will likely need fixes to logging, column identification by key, etc. for full support here.