From f6ff024b80863031bf67477b62c14390a19d8110 Mon Sep 17 00:00:00 2001 From: Konsta Vesterinen Date: Fri, 24 Oct 2014 14:19:21 +0300 Subject: [PATCH] Fix alias handling in has_index --- CHANGES.rst | 1 + sqlalchemy_utils/functions/database.py | 10 ++++++++-- tests/functions/test_has_index.py | 6 ++++++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index e9aaf2e..8b5eebb 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -9,6 +9,7 @@ Here you can see the full list of changes between each SQLAlchemy-Utils release. - Made assert_* functions automatically rollback session - Fix alias handling in has_unique_index +- Fix alias handling in has_index 0.27.4 (2014-10-23) diff --git a/sqlalchemy_utils/functions/database.py b/sqlalchemy_utils/functions/database.py index aa4003e..6748f27 100644 --- a/sqlalchemy_utils/functions/database.py +++ b/sqlalchemy_utils/functions/database.py @@ -159,12 +159,18 @@ def has_index(column): has_index(table.c.locale) # False has_index(table.c.id) # True """ + table = column.table + if not isinstance(table, sa.Table): + raise TypeError( + 'Only columns belonging to Table objects are supported. Given ' + 'column belongs to %r.' % table + ) return ( - column is column.table.primary_key.columns.values()[0] + column is table.primary_key.columns.values()[0] or any( index.columns.values()[0] is column - for index in column.table.indexes + for index in table.indexes ) ) diff --git a/tests/functions/test_has_index.py b/tests/functions/test_has_index.py index 43f0474..3dfabf1 100644 --- a/tests/functions/test_has_index.py +++ b/tests/functions/test_has_index.py @@ -1,4 +1,5 @@ import sqlalchemy as sa +from pytest import raises from sqlalchemy.ext.declarative import declarative_base from sqlalchemy_utils import has_index @@ -23,6 +24,11 @@ class TestHasIndex(object): self.table = ArticleTranslation.__table__ + def test_column_that_belongs_to_an_alias(self): + alias = sa.orm.aliased(self.table) + with raises(TypeError): + assert has_index(alias.c.id) + def test_compound_primary_key(self): assert has_index(self.table.c.id) assert not has_index(self.table.c.locale)