Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

utils: generalize utility to find find_constraint_name #557

Merged
merged 1 commit into from
Jun 3, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,27 +12,16 @@

from alembic import op
import sqlalchemy as sa
from caravel.utils import generic_find_constraint_name

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 find_constraint_name(upgrade=True):
cols = {'column_name'} if upgrade else {'datasource_name'}
return generic_find_constraint_name(table='columns', columns=cols, referenced='datasources')

def upgrade():
constraint = find_constraint_name() or 'fk_columns_column_name_datasources'
Expand All @@ -47,4 +36,3 @@ def downgrade():
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'])

17 changes: 17 additions & 0 deletions caravel/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
from datetime import datetime

import parsedatetime
import sqlalchemy as sa
from dateutil.parser import parse
from alembic import op
from flask import flash, Markup
from flask_appbuilder.security.sqla import models as ab_models
from markdown import markdown as md
Expand Down Expand Up @@ -255,3 +257,18 @@ def readfile(filepath):
with open(filepath) as f:
content = f.read()
return content


def generic_find_constraint_name(table, columns, referenced):
"""
Utility to find a constraint name in alembic migrations
"""
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) == columns:
return fk.name
return None