|
1 | | -{% macro check_for_nested_cte(sql) %} |
2 | | - {% if execute %} {# Ensure this runs only at execution time #} |
3 | | - {% set cleaned_sql = sql | lower | replace("\n", " ") %} {# Convert to lowercase and remove newlines #} |
4 | | - {% set cte_count = cleaned_sql.count("with ") %} {# Count occurrences of "WITH " #} |
5 | | - {% if cte_count > 1 %} |
6 | | - {{ return(True) }} |
7 | | - {% else %} |
8 | | - {{ return(False) }} {# No nested CTEs found #} |
9 | | - {% endif %} |
10 | | - {% else %} |
11 | | - {{ return(False) }} {# Return False during parsing #} |
12 | | - {% endif %} |
13 | | -{% endmacro %} |
14 | | - |
15 | | - |
16 | 1 | {% macro fabric__create_table_as(temporary, relation, sql) -%} |
17 | | - |
18 | 2 | {% set query_label = apply_label() %} |
19 | | - {% set contract_config = config.get('contract') %} |
20 | | - {% set is_nested_cte = check_for_nested_cte(sql) %} |
21 | | - |
22 | | - {% if is_nested_cte and contract_config.enforced %} |
| 3 | + {% set tmp_vw_relation = relation.incorporate(path={"identifier": relation.identifier ~ '__dbt_tmp_vw'}, type='view')-%} |
| 4 | + {% do adapter.drop_relation(tmp_vw_relation) %} |
| 5 | + {{ get_create_view_as_sql(tmp_vw_relation, sql) }} |
23 | 6 |
|
24 | | - {{ exceptions.raise_compiler_error( |
25 | | - "Since the contract is enforced and the model contains a nested CTE, Fabric DW uses CREATE TABLE + INSERT to load data. |
26 | | - INSERT INTO is not supported with nested CTEs. To resolve this, either disable contract enforcement or modify the model." |
27 | | - ) }} |
28 | | - |
29 | | - {%- elif not is_nested_cte and contract_config.enforced %} |
| 7 | + {% set contract_config = config.get('contract') %} |
| 8 | + {% if contract_config.enforced %} |
30 | 9 |
|
31 | 10 | CREATE TABLE {{relation}} |
32 | 11 | {{ build_columns_constraints(relation) }} |
33 | 12 | {{ get_assert_columns_equivalent(sql) }} |
34 | | - |
35 | 13 | {% set listColumns %} |
36 | 14 | {% for column in model['columns'] %} |
37 | 15 | {{ "["~column~"]" }}{{ ", " if not loop.last }} |
38 | 16 | {% endfor %} |
39 | 17 | {%endset%} |
40 | 18 |
|
41 | | - {% set tmp_vw_relation = relation.incorporate(path={"identifier": relation.identifier ~ '__dbt_tmp_vw'}, type='view')-%} |
42 | | - {% do adapter.drop_relation(tmp_vw_relation) %} |
43 | | - {{ get_create_view_as_sql(tmp_vw_relation, sql) }} |
44 | | - |
45 | 19 | INSERT INTO {{relation}} ({{listColumns}}) |
46 | 20 | SELECT {{listColumns}} FROM {{tmp_vw_relation}} {{ query_label }} |
47 | 21 |
|
48 | 22 | {%- else %} |
49 | | - |
50 | 23 | {%- set query_label_option = query_label.replace("'", "''") -%} |
51 | | - {%- set sql_with_quotes = sql.replace("'", "''") -%} |
52 | | - EXEC('CREATE TABLE {{relation}} AS {{sql_with_quotes}} {{ query_label_option }}'); |
53 | | - |
| 24 | + EXEC('CREATE TABLE {{relation}} AS SELECT * FROM {{tmp_vw_relation}} {{ query_label_option }}'); |
54 | 25 | {% endif %} |
55 | 26 | {% endmacro %} |
0 commit comments