diff --git a/.changes/unreleased/Fixes-20240610-200522.yaml b/.changes/unreleased/Fixes-20240610-200522.yaml new file mode 100644 index 00000000000..456575644ac --- /dev/null +++ b/.changes/unreleased/Fixes-20240610-200522.yaml @@ -0,0 +1,6 @@ +kind: Fixes +body: Use model alias for the CTE identifier generated during ephemeral materialization +time: 2024-06-10T20:05:22.510814008Z +custom: + Author: jeancochrane + Issue: "5273" diff --git a/core/dbt/compilation.py b/core/dbt/compilation.py index d03407b2a4c..08de60490d3 100644 --- a/core/dbt/compilation.py +++ b/core/dbt/compilation.py @@ -371,7 +371,7 @@ def _recursively_prepend_ctes( _extend_prepended_ctes(prepended_ctes, new_prepended_ctes) - new_cte_name = self.add_ephemeral_prefix(cte_model.name) + new_cte_name = self.add_ephemeral_prefix(cte_model.identifier) rendered_sql = cte_model._pre_injected_sql or cte_model.compiled_code sql = f" {new_cte_name} as (\n{rendered_sql}\n)" diff --git a/tests/functional/compile/fixtures.py b/tests/functional/compile/fixtures.py index e0be7c895bf..97ccd6d16b6 100644 --- a/tests/functional/compile/fixtures.py +++ b/tests/functional/compile/fixtures.py @@ -42,6 +42,15 @@ select sum(n) from t; """ +first_ephemeral_model_with_alias_sql = """ +{{ config(materialized = 'ephemeral', alias = 'first_alias') }} +select 1 as fun +""" + +second_ephemeral_model_with_alias_sql = """ +select * from {{ ref('first_ephemeral_model_with_alias') }} +""" + schema_yml = """ version: 2 diff --git a/tests/functional/compile/test_compile.py b/tests/functional/compile/test_compile.py index e7732b09a8c..956169eddf1 100644 --- a/tests/functional/compile/test_compile.py +++ b/tests/functional/compile/test_compile.py @@ -10,10 +10,12 @@ from tests.functional.assertions.test_runner import dbtTestRunner from tests.functional.compile.fixtures import ( first_ephemeral_model_sql, + first_ephemeral_model_with_alias_sql, first_model_sql, model_multiline_jinja, schema_yml, second_ephemeral_model_sql, + second_ephemeral_model_with_alias_sql, second_model_sql, third_ephemeral_model_sql, with_recursive_model_sql, @@ -128,6 +130,24 @@ def test_with_recursive_cte(self, project): ] +class TestEphemeralModelWithAlias: + @pytest.fixture(scope="class") + def models(self): + return { + "first_ephemeral_model_with_alias.sql": first_ephemeral_model_with_alias_sql, + "second_ephemeral_model_with_alias.sql": second_ephemeral_model_with_alias_sql, + } + + def test_compile(self, project): + run_dbt(["compile"]) + + assert get_lines("second_ephemeral_model_with_alias") == [ + "with __dbt__cte__first_alias as (", + "select 1 as fun", + ") select * from __dbt__cte__first_alias", + ] + + class TestCompile: @pytest.fixture(scope="class") def models(self):