From 938f6cdb033fb885e1780cef2d472c9bccec2c70 Mon Sep 17 00:00:00 2001 From: Luca Albertalli Date: Tue, 31 May 2016 23:16:19 -0700 Subject: [PATCH] Modified the migration function to to automatically detect the the foreign keys based on the signature. It supports also sqlite using batch migrations --- ...3_fix_wrong_constraint_on_table_columns.py | 36 ++++++++++++++++--- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/caravel/migrations/versions/1226819ee0e3_fix_wrong_constraint_on_table_columns.py b/caravel/migrations/versions/1226819ee0e3_fix_wrong_constraint_on_table_columns.py index b63a762a1b58..af96538849aa 100644 --- a/caravel/migrations/versions/1226819ee0e3_fix_wrong_constraint_on_table_columns.py +++ b/caravel/migrations/versions/1226819ee0e3_fix_wrong_constraint_on_table_columns.py @@ -13,12 +13,38 @@ from alembic import op import sqlalchemy as sa +naming_convention = { + "fk": + "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", +} + +def find_constraint_name(upgrade = True): + __table = 'columns' + __cols = {'column_name'} if upgrade else {'datasource_name'} + __referenced = 'datasources' + __ref_cols = {'datasource_name'} if upgrade else {'column_name'} + + engine = op.get_bind().engine + m = sa.MetaData({}) + t=sa.Table(__table,m, autoload=True, autoload_with=engine) + + for fk in t.foreign_key_constraints: + if fk.referred_table.name == __referenced and \ + set(fk.column_keys) == __cols: + return fk.name + return None def upgrade(): - op.drop_constraint('columns_ibfk_1', 'columns', type_="foreignkey") - op.create_foreign_key('columns_ibfk_1', 'columns', 'datasources', ['datasource_name'], ['datasource_name']) - + constraint = find_constraint_name() or 'fk_columns_column_name_datasources' + with op.batch_alter_table("columns", + naming_convention=naming_convention) as batch_op: + batch_op.drop_constraint(constraint, type_="foreignkey") + batch_op.create_foreign_key('fk_columns_datasource_name_datasources', 'datasources', ['datasource_name'], ['datasource_name']) def downgrade(): - op.drop_constraint('columns_ibfk_1', 'columns', type_="foreignkey") - op.create_foreign_key('columns_ibfk_1', 'columns', 'datasources', ['columns'], ['datasource_name']) + constraint = find_constraint_name(False) or 'fk_columns_datasource_name_datasources' + with op.batch_alter_table("columns", + naming_convention=naming_convention) as batch_op: + batch_op.drop_constraint(constraint, type_="foreignkey") + batch_op.create_foreign_key('fk_columns_column_name_datasources', 'datasources', ['column_name'], ['datasource_name']) + \ No newline at end of file