From e56e268f306e2bbd39277a58098b3f8786a33899 Mon Sep 17 00:00:00 2001 From: Vitor Avila Date: Wed, 20 Mar 2024 11:39:12 -0300 Subject: [PATCH] fix(sqlglot): Convert metric syntax back to dialect-specific after parsing it --- src/preset_cli/cli/superset/sync/dbt/metrics.py | 4 ++-- tests/cli/superset/sync/dbt/metrics_test.py | 16 ++++++++++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/preset_cli/cli/superset/sync/dbt/metrics.py b/src/preset_cli/cli/superset/sync/dbt/metrics.py index 25a2e8c8..0d3fb1d4 100644 --- a/src/preset_cli/cli/superset/sync/dbt/metrics.py +++ b/src/preset_cli/cli/superset/sync/dbt/metrics.py @@ -89,7 +89,7 @@ def get_metric_expression(metric_name: str, metrics: Dict[str, MetricSchema]) -> ) token.replace(parent_expression) - return expression.sql() + return expression.sql(dialect=metric["dialect"]) sorted_metric = dict(sorted(metric.items())) raise Exception(f"Unable to generate metric expression from: {sorted_metric}") @@ -285,7 +285,7 @@ def convert_query_to_projection(sql: str, dialect: MFSQLEngine) -> str: ) metric_expression.set("this", case_expression) - return metric_expression.sql() + return metric_expression.sql(dialect=DIALECT_MAP.get(dialect)) def convert_metric_flow_to_superset( diff --git a/tests/cli/superset/sync/dbt/metrics_test.py b/tests/cli/superset/sync/dbt/metrics_test.py index 0268abbc..09c92265 100644 --- a/tests/cli/superset/sync/dbt/metrics_test.py +++ b/tests/cli/superset/sync/dbt/metrics_test.py @@ -238,7 +238,7 @@ def test_get_metric_expression_derived_legacy() -> None: result = get_metric_expression(unique_id, metrics) assert ( result - == "SAFE_DIVIDE(SUM(CASE WHEN \"product_line\" = 'Classic Cars' THEN price_each * 0.80 ELSE price_each * 0.70 END), SUM(price_each))" + == "SAFE_DIVIDE(SUM(IF(`product_line` = 'Classic Cars', price_each * 0.80, price_each * 0.70)), SUM(price_each))" ) @@ -683,7 +683,19 @@ def test_convert_query_to_projection() -> None: """, MFSQLEngine.BIGQUERY, ) - == "CAST(SUM(CASE WHEN is_food_item = 1 THEN product_price ELSE 0 END) AS DOUBLE) / CAST(NULLIF(SUM(product_price), 0) AS DOUBLE)" + == "CAST(SUM(CASE WHEN is_food_item = 1 THEN product_price ELSE 0 END) AS FLOAT64) / CAST(NULLIF(SUM(product_price), 0) AS FLOAT64)" + ) + + assert ( + convert_query_to_projection( + """ + SELECT + AVG(DATE_DIFF(start_date, end_date, DAY)) AS avg_time_diff + FROM `dbt-tutorial-347100`.`dbt_beto`.`order_items` order_item_src_98 + """, + MFSQLEngine.BIGQUERY, + ) + == "AVG(DATE_DIFF(start_date, end_date, DAY))" ) with pytest.raises(ValueError) as excinfo: