diff --git a/caravel/models.py b/caravel/models.py index cff39548d1f8..e4734b697d67 100644 --- a/caravel/models.py +++ b/caravel/models.py @@ -55,7 +55,9 @@ from caravel import app, db, db_engine_specs, get_session, utils, sm from caravel.source_registry import SourceRegistry from caravel.viz import viz_types -from caravel.utils import flasher, MetricPermException, DimSelector +from caravel.utils import ( + flasher, MetricPermException, DimSelector, wrap_clause_in_parens +) config = app.config @@ -1005,9 +1007,9 @@ def visit_column(element, compiler, **kw): cond = ~cond where_clause_and.append(cond) if extras and 'where' in extras: - where_clause_and += [text(extras['where'])] + where_clause_and += [wrap_clause_in_parens(extras['where'])] if extras and 'having' in extras: - having_clause_and += [text(extras['having'])] + having_clause_and += [wrap_clause_in_parens(extras['having'])] if granularity: qry = qry.where(and_(*(time_filter + where_clause_and))) else: diff --git a/caravel/utils.py b/caravel/utils.py index 968b9e9cf1f0..7f8d33b026c9 100644 --- a/caravel/utils.py +++ b/caravel/utils.py @@ -491,3 +491,10 @@ def __exit__(self, type, value, traceback): except ValueError as e: logging.warning("timeout can't be used in the current context") logging.exception(e) + + +def wrap_clause_in_parens(sql): + """Wrap where/having clause with parenthesis if necessary""" + if sql.strip(): + sql = '({})'.format(sql) + return sa.text(sql)