Skip to content

Commit

Permalink
feat: implement dateadd macro
Browse files Browse the repository at this point in the history
  • Loading branch information
silviustanimir committed Nov 14, 2023
1 parent 8a89554 commit d8fea96
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ This dbt package contains macros for SQL functions to run the dbt project on mul
- [Multiple databases](#Multiple-databases)
- [as_varchar](#as_varchar-source)
- [create_index](#create_index-source)
- [date_add](#date_add-source)
- [date_from_timestamp](#date_from_timestamp-source)
- [datediff](#datediff-source)
- [string_agg](#string_agg-source)
Expand Down Expand Up @@ -79,6 +80,12 @@ In case you want to create the index on a source table, refer to the table using
) }}
```

#### dateadd ([source](macros/multiple_databases/dateadd.sql))
This macro adds a specified number value (as a signed integer) to a specified datepart of an input date value, and then returns that modified value. The datepart can be any of the following values for SQL Server and Snowflake: year, quarter, month, week, day, hour, minute, second, millisecond. For Databricks, the datepart can be any of the following values: year, day, hour, minute, second, millisecond. The difference in weeks is calculated for weeks starting on Monday.

Usage:
`{{ pm_utils.dateadd('[datepart]', [number], '[expression]') }}`

#### date_from_timestamp ([source](macros/multiple_databases/date_from_timestamp.sql))
This macro extracts the date part from a datetime field.

Expand Down
19 changes: 19 additions & 0 deletions macros/multiple_databases/dateadd.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{%- macro dateadd(datepart, number, datetime_field) -%}
{%- if target.type == 'snowflake' -%}
dateadd({{ datepart }}, {{ number }}, try_to_timestamp(to_varchar({{ datetime_field }})))
{%- elif target.type == 'sqlserver' -%}
dateadd({{ datepart }}, {{ number }}, try_convert(datetime2, {{ datetime_field }}))
{%- elif target.type == 'databricks' -%}
{%- if datepart == 'second' -%}
timestamp_millis(bigint(unix_millis({{ datetime_field }}) + {{ number }}*1000))
{%- elif datepart == 'minute' -%}
timestamp_millis(bigint(unix_millis({{ datetime_field }}) + {{ number }}*6000))
{%- elif datepart == 'hour' -%}
timestamp_millis(bigint(unix_millis({{ datetime_field }}) + {{ number }}*3600000))
{%- elif datepart == 'day' -%}
timestamp_millis(bigint(unix_millis({{ datetime_field }}) + {{ number }}*86400000))
{%- elif datepart == 'year' -%}
timestamp_millis(bigint(add_months({{ datetime_field }}, {{ number }}*12) + bigint(unix_millis({{ datetime_field }})) - bigint(unix_millis(date_trunc('DD', {{ datetime_field }})))))
{%- endif -%}
{%- endif -%}
{%- endmacro -%}

0 comments on commit d8fea96

Please sign in to comment.