|
1 | 1 | {% macro sqlserver__create_table_as(temporary, relation, sql) -%}
|
| 2 | + {#- TODO: add contracts here when in dbt 1.5 -#} |
| 3 | + {%- set sql_header = config.get('sql_header', none) -%} |
2 | 4 | {%- set as_columnstore = config.get('as_columnstore', default=true) -%}
|
3 |
| - {% set tmp_relation = relation.incorporate( |
4 |
| - path={"identifier": relation.identifier.replace("#", "") ~ '_temp_view'}, |
5 |
| - type='view')-%} |
6 | 5 | {%- set temp_view_sql = sql.replace("'", "''") -%}
|
| 6 | + {%- set tmp_relation = relation.incorporate( |
| 7 | + path={"identifier": relation.identifier.replace("#", "") ~ '_temp_view'}, |
| 8 | + type='view') -%} |
7 | 9 |
|
8 |
| - {{ sqlserver__drop_relation_script(tmp_relation) }} |
| 10 | + {{- sql_header if sql_header is not none -}} |
9 | 11 |
|
10 |
| - {{ sqlserver__drop_relation_script(relation) }} |
| 12 | + -- drop previous temp view |
| 13 | + {{- sqlserver__drop_relation_script(tmp_relation) }} |
11 | 14 |
|
| 15 | + -- create temp view |
12 | 16 | USE [{{ relation.database }}];
|
13 | 17 | EXEC('create view {{ tmp_relation.include(database=False) }} as
|
14 |
| - {{ temp_view_sql }} |
| 18 | + {{- temp_view_sql -}} |
15 | 19 | ');
|
16 | 20 |
|
17 |
| - SELECT * INTO {{ relation }} FROM |
18 |
| - {{ tmp_relation }} |
| 21 | + -- drop current version of the table |
| 22 | + {{- sqlserver__drop_relation_script(relation) -}} |
| 23 | + |
| 24 | + -- select into the table and create it that way |
| 25 | + {#- see https://learn.microsoft.com/en-us/sql/t-sql/queries/select-into-clause-transact-sql?view=sql-server-ver16#b-inserting-rows-using-minimal-logging #} |
| 26 | + ALTER DATABASE [{{ relation.database }}] SET RECOVERY BULK_LOGGED |
| 27 | + |
| 28 | + SELECT * |
| 29 | + INTO {% if temporary %}#{% endif %}{{ relation.include(database=(not temporary), schema=(not temporary)) }} |
| 30 | + FROM {{ tmp_relation }} |
| 31 | + |
| 32 | + {#- see https://learn.microsoft.com/en-us/sql/t-sql/queries/select-into-clause-transact-sql?view=sql-server-ver16#b-inserting-rows-using-minimal-logging #} |
| 33 | + ALTER DATABASE [{{ relation.database }}] SET RECOVERY FULL |
19 | 34 |
|
| 35 | + -- drop temp view |
20 | 36 | {{ sqlserver__drop_relation_script(tmp_relation) }}
|
21 | 37 |
|
22 |
| - {% if not temporary and as_columnstore -%} |
23 |
| - {{ sqlserver__create_clustered_columnstore_index(relation) }} |
24 |
| - {% endif %} |
| 38 | + {%- if not temporary and as_columnstore -%} |
| 39 | + -- add columnstore index |
| 40 | + {{ sqlserver__create_clustered_columnstore_index(relation) }} |
| 41 | + {%- endif -%} |
25 | 42 |
|
26 | 43 | {% endmacro %}
|
0 commit comments