Skip to content

Commit

Permalink
Conververting datetime based on database dialects (#446)
Browse files Browse the repository at this point in the history
  • Loading branch information
mistercrunch committed May 10, 2016
1 parent 77e9e6a commit c4e3020
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 6 deletions.
1 change: 0 additions & 1 deletion TODO.md
Expand Up @@ -33,7 +33,6 @@ List of TODO items for Caravel
* CREATE VIEW button from SQL editor
* Test button for when editing SQL expression
* Slider form element
* datasource in explore mode could be a dropdown
* [druid] Allow for post aggregations (ratios!)
* in/notin filters autocomplete (druid)

Expand Down
28 changes: 24 additions & 4 deletions caravel/models.py
Expand Up @@ -410,6 +410,24 @@ def grains(self):
if self.sqlalchemy_uri.startswith(db_type):
return grains

def dttm_converter(self, dttm):
"""Returns a string that the database flavor understands as a date"""
default = "'{}'".format(dttm.strftime('%Y-%m-%d %H:%M:%S.%f'))
iso = dttm.isoformat()
d = {
'mssql': "CONVERT(DATETIME, '{}', 126)".format(iso), #untested
'mysql': default,
'oracle':
"""TO_TIMESTAMP('{}', 'YYYY-MM-DD"T"HH24:MI:SS.ff6')""".format(
dttm.isoformat()),
'presto': default,
'sqlite': default,
}
for k, v in d.items():
if self.sqlalchemy_uri.startswith(k):
return v
return default

def grains_dict(self):
return {grain.name: grain for grain in self.grains()}

Expand Down Expand Up @@ -630,14 +648,16 @@ def query( # sqla

tf = '%Y-%m-%d %H:%M:%S.%f'
time_filter = [
timestamp >= from_dttm.strftime(tf),
timestamp <= to_dttm.strftime(tf),
timestamp >= text(self.database.dttm_converter(from_dttm)),
timestamp <= text(self.database.dttm_converter(to_dttm)),
]
inner_time_filter = copy(time_filter)
if inner_from_dttm:
inner_time_filter[0] = timestamp >= inner_from_dttm.strftime(tf)
inner_time_filter[0] = timestamp >= text(
self.database.dttm_converter(inner_from_dttm))
if inner_to_dttm:
inner_time_filter[1] = timestamp <= inner_to_dttm.strftime(tf)
inner_time_filter[1] = timestamp <= text(
self.database.dttm_converter(inner_to_dttm))
else:
inner_time_filter = []

Expand Down
3 changes: 2 additions & 1 deletion caravel/views.py
Expand Up @@ -112,7 +112,8 @@ class TableColumnInlineView(CompactCRUDMixin, CaravelModelView): # noqa
can_delete = False
edit_columns = [
'column_name', 'verbose_name', 'description', 'groupby', 'filterable',
'table', 'count_distinct', 'sum', 'min', 'max', 'expression', 'is_dttm']
'table', 'count_distinct', 'sum', 'min', 'max', 'expression',
'is_dttm', ]
add_columns = edit_columns
list_columns = [
'column_name', 'type', 'groupby', 'filterable', 'count_distinct',
Expand Down

0 comments on commit c4e3020

Please sign in to comment.