-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #110 from DalgoT4D/106-unpivot-operation
unpivot op
- Loading branch information
Showing
8 changed files
with
317 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
{# | ||
Pivot values from columns to rows. Similar to pandas DataFrame melt() function. | ||
|
||
Example Usage: {{ unpivot(relation=ref('users'), cast_to='integer', exclude=['id','created_at']) }} | ||
|
||
Arguments: | ||
relation: Relation object, required. | ||
cast_to: The datatype to cast all unpivoted columns to. Default is varchar. | ||
exclude: A list of columns to keep but exclude from the unpivot operation. Default is none. | ||
remove: A list of columns to remove from the resulting table. Default is none. | ||
field_name: Destination table column name for the source table column names. | ||
value_name: Destination table column name for the pivoted values | ||
#} | ||
|
||
{% macro unpivot(relation=none, cast_to='varchar', exclude=none, remove=none, field_name='field_name', value_name='value', quote_identifiers=True) -%} | ||
{{ return(adapter.dispatch('unpivot', 'dbt_utils')(relation, cast_to, exclude, remove, field_name, value_name, quote_identifiers)) }} | ||
{% endmacro %} | ||
|
||
{% macro default__unpivot(relation=none, cast_to='varchar', exclude=none, remove=none, field_name='field_name', value_name='value', quote_identifiers=True) -%} | ||
|
||
{% if not relation %} | ||
{{ exceptions.raise_compiler_error("Error: argument `relation` is required for `unpivot` macro.") }} | ||
{% endif %} | ||
|
||
{%- set exclude = exclude if exclude is not none else [] %} | ||
{%- set remove = remove if remove is not none else [] %} | ||
|
||
{%- set include_cols = [] %} | ||
|
||
{%- set table_columns = {} %} | ||
|
||
{%- do table_columns.update({relation: []}) %} | ||
|
||
{%- do dbt_utils._is_relation(relation, 'unpivot') -%} | ||
{%- do dbt_utils._is_ephemeral(relation, 'unpivot') -%} | ||
{%- set cols = adapter.get_columns_in_relation(relation) %} | ||
|
||
{%- for col in cols -%} | ||
{%- if col.column.lower() not in remove|map('lower') and col.column.lower() not in exclude|map('lower') -%} | ||
{% do include_cols.append(col) %} | ||
{%- endif %} | ||
{%- endfor %} | ||
|
||
|
||
{%- for col in include_cols -%} | ||
{%- set current_col_name = adapter.quote(col.column) if quote_identifiers else col.column -%} | ||
select | ||
{%- for exclude_col in exclude %} | ||
{{ adapter.quote(exclude_col) if quote_identifiers else exclude_col }}, | ||
{%- endfor %} | ||
|
||
cast('{{ col.column }}' as {{ dbt.type_string() }}) as {{ adapter.quote(field_name) if quote_identifiers else field_name }}, | ||
cast( {% if col.data_type == 'boolean' %} | ||
{{ dbt.cast_bool_to_text(current_col_name) }} | ||
{% else %} | ||
{{ current_col_name }} | ||
{% endif %} | ||
as {{ cast_to }}) as {{ adapter.quote(value_name) if quote_identifiers else value_name }} | ||
|
||
from {{ relation }} | ||
|
||
{% if not loop.last -%} | ||
union all | ||
{% endif -%} | ||
{%- endfor -%} | ||
|
||
{%- endmacro %} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,89 @@ | ||
""" | ||
Generates a dbt model for unpivot | ||
This operation will only work in the chain of mergeoperations if its at the first step | ||
""" | ||
|
||
from logging import basicConfig, getLogger, INFO | ||
|
||
from dbt_automation.utils.dbtproject import dbtProject | ||
from dbt_automation.utils.columnutils import quote_columnname | ||
from dbt_automation.utils.interfaces.warehouse_interface import WarehouseInterface | ||
from dbt_automation.utils.columnutils import quote_columnname, quote_constvalue | ||
from dbt_automation.utils.tableutils import source_or_ref | ||
|
||
basicConfig(level=INFO) | ||
logger = getLogger() | ||
|
||
|
||
# pylint:disable=unused-argument,logging-fstring-interpolation | ||
def unpivot_dbt_sql( | ||
config: dict, | ||
warehouse: WarehouseInterface, | ||
): | ||
""" | ||
Generate SQL code for the coalesce_columns operation. | ||
""" | ||
source_columns = config.get("source_columns", []) # all columns | ||
exclude_columns = config.get( | ||
"exclude_columns", [] | ||
) # exclude from unpivot but keep in the resulting table | ||
unpivot_on_columns = config.get("unpivot_columns", []) # columns to unpivot | ||
input_table = config["input"] | ||
field_name = config.get("unpivot_field_name", "field_name") | ||
value_name = config.get("unpivot_value_name", "value") | ||
cast_datatype_to = config.get("cast_to", "varchar") | ||
if not cast_datatype_to and warehouse.name == "bigquery": | ||
cast_datatype_to = "STRING" | ||
|
||
if len(unpivot_on_columns) == 0: | ||
raise ValueError("No columns specified for unpivot") | ||
|
||
output_columns = list(set(exclude_columns) | set(unpivot_on_columns)) # union | ||
remove_columns = list(set(source_columns) - set(output_columns)) | ||
|
||
dbt_code = "{{ unpivot(" | ||
dbt_code += source_or_ref(**input_table) | ||
dbt_code += ", exclude=" | ||
dbt_code += ( | ||
"[" | ||
+ ",".join( | ||
[quote_constvalue(col_name, warehouse.name) for col_name in exclude_columns] | ||
) | ||
+ "] ," | ||
) | ||
dbt_code += f"cast_to={quote_constvalue(cast_datatype_to, warehouse.name)}, " | ||
dbt_code += "remove=" | ||
dbt_code += ( | ||
"[" | ||
+ ",".join( | ||
[quote_constvalue(col_name, warehouse.name) for col_name in remove_columns] | ||
) | ||
+ "] ," | ||
) | ||
dbt_code += f"field_name={quote_constvalue(field_name, warehouse.name)}, value_name={quote_constvalue(value_name, warehouse.name)}" | ||
dbt_code += ")}}\n" | ||
|
||
return dbt_code, output_columns | ||
|
||
|
||
def unpivot(config: dict, warehouse: WarehouseInterface, project_dir: str): | ||
""" | ||
Perform coalescing of columns and generate a DBT model. | ||
""" | ||
dbt_sql = "" | ||
if config["input"]["input_type"] != "cte": | ||
dbt_sql = ( | ||
"{{ config(materialized='table', schema='" + config["dest_schema"] + "') }}" | ||
) | ||
|
||
select_statement, output_cols = unpivot_dbt_sql(config, warehouse) | ||
dbt_sql += "\n" + select_statement | ||
|
||
dbt_project = dbtProject(project_dir) | ||
dbt_project.ensure_models_dir(config["dest_schema"]) | ||
|
||
output_name = config["output_name"] | ||
dest_schema = config["dest_schema"] | ||
model_sql_path = dbt_project.write_model(dest_schema, output_name, dbt_sql) | ||
|
||
return model_sql_path, output_cols |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.