From cc5f677ff1941c68b16dbb9db1ba27f29b494d45 Mon Sep 17 00:00:00 2001 From: Matthew Treinish Date: Thu, 25 Jun 2015 15:28:16 -0400 Subject: [PATCH] Don't try to create indexes twice In certain environments the index attempted to be created in migration 13d819bbb0ff can sometimes already exist in the db which causes an error when they already exist. This is likely do to an error on my part when I originally wrote the migration and not testing things properly. This commit remedies this situation by checking if the indexes exist prior to attempting to create them. If an index exists we just skip the creation step and move on. This is safe since the end state of the migration doesn't change, it just makes it safe to execute in more strict DBs. Change-Id: I901175c2b07efc3e1747e58ca7ea4a46c5149ffa --- .../13d819bbb0ff_create_missing_indexes.py | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/subunit2sql/migrations/versions/13d819bbb0ff_create_missing_indexes.py b/subunit2sql/migrations/versions/13d819bbb0ff_create_missing_indexes.py index 8dc2300..5c2b6fc 100644 --- a/subunit2sql/migrations/versions/13d819bbb0ff_create_missing_indexes.py +++ b/subunit2sql/migrations/versions/13d819bbb0ff_create_missing_indexes.py @@ -24,13 +24,32 @@ Create Date: 2014-06-20 21:27:01.629724 revision = '13d819bbb0ff' down_revision = '4ca26dac400e' +from alembic import context from alembic import op +from sqlalchemy.engine import reflection def upgrade(): - op.create_index('ix_test_id', 'tests', ['test_id']) - op.create_index('ix_test_run_test_id', 'test_runs', ['test_id']) - op.create_index('ix_test_run_run_id', 'test_runs', ['run_id']) + migration_context = context.get_context() + insp = reflection.Inspector(migration_context.bind) + test_indx = insp.get_indexes('tests') + test_indx_names = [x['name'] for x in test_indx] + test_indx_columns = [x['column_names'][0] for x in test_indx + if len(x) == 1] + test_run_indx = insp.get_indexes('test_runs') + test_run_indx_names = [x['name'] for x in test_run_indx] + test_run_indx_columns = [x['column_names'][0] for x in test_run_indx + if len(x) == 1] + if ('ix_test_id' not in test_indx_names and + 'test_id' not in test_indx_columns): + op.create_index('ix_test_id', 'tests', ['test_id']) + if ('ix_test_run_test_id' not in test_run_indx_names and + 'test_id' not in test_run_indx_columns): + op.create_index('ix_test_run_test_id', 'test_runs', ['test_id']) + if ('ix_test_run_run_id' not in test_run_indx_names and + 'run_id' not in test_run_indx_columns): + op.create_index('ix_test_run_run_id', 'test_runs', ['run_id']) + op.create_unique_constraint('uq_test_runs', 'test_runs', ['test_id', 'run_id'])