Remove hardcoded foreign keys from db.catalog.api

Change-Id: Icc5af337c7aa9621bd8b557be8b87413c053be88
This commit is contained in:
Timur Sufiev 2014-04-08 20:05:46 +04:00
parent 3349aca848
commit f960c88209

View File

@ -12,6 +12,7 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from sqlalchemy import inspection
from sqlalchemy import or_ from sqlalchemy import or_
from sqlalchemy.orm import attributes from sqlalchemy.orm import attributes
from sqlalchemy import sql from sqlalchemy import sql
@ -279,27 +280,29 @@ def package_search(filters, context):
query = query.filter(pkg.fully_qualified_name == filters['fqn']) query = query.filter(pkg.fully_qualified_name == filters['fqn'])
if 'search' in filters.keys(): if 'search' in filters.keys():
fk_fields = {'categories': 'Category',
'tags': 'Tag',
'class_definitions': 'Class'}
conditions = [] conditions = []
search_str = filters['search']
for delimiter in ',;':
search_str = search_str.replace(delimiter, ' ')
key_words = ['%{0}%'.format(word) for word in search_str.split()]
relationships = inspection.inspect(pkg).relationships
for attr in dir(pkg): searchable_attrs = set([
if attr.startswith('_'): 'fully_qualified_name', 'author', 'name', 'description', 'tags',
continue 'categories', 'class_definitions'])
if isinstance(getattr(pkg, attr), searchable_pkg_attrs = set(dir(pkg)) & searchable_attrs
attributes.InstrumentedAttribute):
search_str = filters['search'] for attr_name in searchable_pkg_attrs:
for delim in ',;': attr = getattr(pkg, attr_name)
search_str = search_str.replace(delim, ' ') if isinstance(attr, attributes.InstrumentedAttribute):
for key_word in search_str.split(): if attr_name in relationships:
_word = '%{value}%'.format(value=key_word) model = relationships[attr_name].mapper.class_
if attr in fk_fields.keys(): for key_word in key_words:
condition = getattr(pkg, attr).any( condition = attr.any(model.name.like(key_word))
getattr(models, fk_fields[attr]).name.like(_word))
conditions.append(condition) conditions.append(condition)
else: else:
conditions.append(getattr(pkg, attr).like(_word)) for key_word in key_words:
conditions.append(attr.like(key_word))
query = query.filter(or_(*conditions)) query = query.filter(or_(*conditions))
sort_keys = filters.get('order_by', []) or ['created'] sort_keys = filters.get('order_by', []) or ['created']