Skip to content

Commit

Permalink
Add parens for custom where and having (#1337)
Browse files Browse the repository at this point in the history
  • Loading branch information
yejianye authored and mistercrunch committed Oct 20, 2016
1 parent b2f7081 commit 458651f
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
8 changes: 5 additions & 3 deletions caravel/models.py
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down
7 changes: 7 additions & 0 deletions caravel/utils.py
Expand Up @@ -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)

0 comments on commit 458651f

Please sign in to comment.