feat(jinja): add option to format time filters using strftime (#30323)

This commit is contained in:
Ville Brofeldt
2024-09-18 10:47:38 -07:00
committed by GitHub
parent 930078b6f5
commit a3952051e1
3 changed files with 33 additions and 0 deletions

View File

@@ -360,6 +360,9 @@ The macro takes the following parameters:
- `target_type`: The target temporal type as recognized by the target database (e.g. `TIMESTAMP`, `DATE` or
`DATETIME`). If `column` is defined, the format will default to the type of the column. This is used to produce
the format of the `from_expr` and `to_expr` properties of the returned `TimeFilter` object.
- `strftime`: format using the `strftime` method of `datetime` for custom time formatting.
([see docs for valid format codes](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes)).
When defined `target_type` will be ignored.
- `remove_filter`: When set to true, mark the filter as processed, removing it from the outer query. Useful when a
filter should only apply to the inner query.

View File

@@ -375,11 +375,13 @@ class ExtraCache:
return filters
# pylint: disable=too-many-arguments
def get_time_filter(
self,
column: str | None = None,
default: str | None = None,
target_type: str | None = None,
strftime: str | None = None,
remove_filter: bool = False,
) -> TimeFilter:
"""Get the time filter with appropriate formatting,
@@ -395,6 +397,8 @@ class ExtraCache:
the format will default to the type of the column. This is used to produce
the format of the `from_expr` and `to_expr` properties of the returned
`TimeFilter` object.
:param strftime: format using the `strftime` method of `datetime`. When defined
`target_type` will be ignored.
:param remove_filter: When set to true, mark the filter as processed,
removing it from the outer query. Useful when a filter should
only apply to the inner query.
@@ -434,6 +438,8 @@ class ExtraCache:
from_expr, to_expr = get_since_until_from_time_range(time_range)
def _format_dttm(dttm: datetime | None) -> str | None:
if strftime and dttm:
return dttm.strftime(strftime)
return (
self.database.db_engine_spec.convert_dttm(target_type or "", dttm)
if self.database and dttm

View File

@@ -958,6 +958,30 @@ def test_metric_macro_no_dataset_id_with_context_chart_no_datasource_id(
["dttm"],
["dttm"],
),
(
"Filter is formatted with the custom format, ignoring target_type",
["dttm"],
{"target_type": "DATE", "strftime": "%Y%m%d", "remove_filter": True},
"trino://mydb",
[
{
"filters": [
{
"col": "dttm",
"op": "TEMPORAL_RANGE",
"val": "Last month",
},
],
}
],
TimeFilter(
from_expr="20240803",
to_expr="20240903",
time_range="Last month",
),
["dttm"],
["dttm"],
),
],
)
def test_get_time_filter(