Skip to content

Commit

Permalink
Update dateaddog.sql
Browse files Browse the repository at this point in the history
  • Loading branch information
techvaquero authored Feb 28, 2024
1 parent 0eec821 commit 5a03fb9
Showing 1 changed file with 9 additions and 61 deletions.
70 changes: 9 additions & 61 deletions integration_tests/macros/dateaddog.sql
Original file line number Diff line number Diff line change
@@ -1,62 +1,10 @@
{% macro databricks__dateadd(datepart, interval, from_date_or_timestamp) %}

{%- set clock_component -%}
{# make sure the dates + timestamps are real, otherwise raise an error asap #}
to_unix_timestamp({{ spark_utils.assert_not_null('to_timestamp', from_date_or_timestamp) }})
- to_unix_timestamp({{ spark_utils.assert_not_null('date', from_date_or_timestamp) }})
{%- endset -%}

{%- if datepart in ['day', 'week'] -%}

{%- set multiplier = 7 if datepart == 'week' else 1 -%}

to_timestamp(
to_unix_timestamp(
date_add(
{{ spark_utils.assert_not_null('date', from_date_or_timestamp) }},
cast({{interval}} * {{multiplier}} as int)
)
) + {{clock_component}}
)

{%- elif datepart in ['month', 'quarter', 'year'] -%}

{%- set multiplier -%}
{%- if datepart == 'month' -%} 1
{%- elif datepart == 'quarter' -%} 3
{%- elif datepart == 'year' -%} 12
{%- endif -%}
{%- endset -%}

to_timestamp(
to_unix_timestamp(
add_months(
{{ spark_utils.assert_not_null('date', from_date_or_timestamp) }},
cast({{interval}} * {{multiplier}} as int)
)
) + {{clock_component}}
)

{%- elif datepart in ('hour', 'minute', 'second', 'millisecond', 'microsecond') -%}

{%- set multiplier -%}
{%- if datepart == 'hour' -%} 3600
{%- elif datepart == 'minute' -%} 60
{%- elif datepart == 'second' -%} 1
{%- elif datepart == 'millisecond' -%} (1/1000000)
{%- elif datepart == 'microsecond' -%} (1/1000000)
{%- endif -%}
{%- endset -%}

to_timestamp(
{{ spark_utils.assert_not_null('to_unix_timestamp', from_date_or_timestamp) }}
+ cast({{interval}} * {{multiplier}} as int)
)

{%- else -%}

{{ exceptions.raise_compiler_error("macro dateadd not implemented for datepart ~ '" ~ datepart ~ "' ~ on Spark") }}

{%- endif -%}

{% macro dateadd(unit, measure, base) %}
CASE
WHEN lower({{unit}}) = 'year' THEN {{base}} + make_interval({{measure}})
WHEN lower({{unit}}) = 'month' THEN {{base}} + make_interval(0, {{measure}})
WHEN lower({{unit}}) = 'day' THEN {{base}} + make_interval(0, 0, 0, {{measure}})
WHEN lower({{unit}}) = 'hour' THEN {{base}} + make_interval(0, 0, 0, 0, {{measure}})
WHEN lower({{unit}}) = 'minute' THEN {{base}} + make_interval(0, 0, 0, 0, 0, {{measure}})
WHEN lower({{unit}}) = 'second' THEN {{base}} + make_interval(0, 0, 0, 0, 0, 0, {{measure}})
END
{% endmacro %}

0 comments on commit 5a03fb9

Please sign in to comment.