forked from dbt-msft/dbt-sqlserver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrelation.sql
More file actions
55 lines (51 loc) · 2.28 KB
/
relation.sql
File metadata and controls
55 lines (51 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
{% macro sqlserver__make_temp_relation(base_relation, suffix='__dbt_temp') %}
{%- set temp_identifier = base_relation.identifier ~ suffix -%}
{%- set temp_relation = base_relation.incorporate(
path={"identifier": temp_identifier}) -%}
{{ return(temp_relation) }}
{% endmacro %}
{% macro sqlserver__get_drop_sql(relation) -%}
{% if relation.type == 'view' -%}
{% call statement('find_references', fetch_result=true) %}
{{ get_use_database_sql(relation.database) }}
select
sch.name as schema_name,
obj.name as view_name
from sys.sql_expression_dependencies refs
inner join sys.objects obj
on refs.referencing_id = obj.object_id
inner join sys.schemas sch
on obj.schema_id = sch.schema_id
where refs.referenced_database_name = '{{ relation.database }}'
and refs.referenced_schema_name = '{{ relation.schema }}'
and refs.referenced_entity_name = '{{ relation.identifier }}'
and obj.type = 'V'
{{ get_query_options() }}
{% endcall %}
{% set references = load_result('find_references')['data'] %}
{% for reference in references -%}
-- dropping referenced view {{ reference[0] }}.{{ reference[1] }}
{% do adapter.drop_relation
(api.Relation.create(
identifier = reference[1], schema = reference[0], database = relation.database, type='view'
))%}
{% endfor %}
{% elif relation.type == 'table'%}
{% set object_id_type = 'U' %}
{%- else -%}
{{ exceptions.raise_not_implemented('Invalid relation being dropped: ' ~ relation) }}
{% endif %}
{{ get_use_database_sql(relation.database) }}
EXEC('DROP {{ relation.type }} IF EXISTS {{ relation.include(database=False) }};');
{% endmacro %}
{% macro sqlserver__rename_relation(from_relation, to_relation) -%}
{% call statement('rename_relation') -%}
{{ get_use_database_sql(from_relation.database) }}
EXEC sp_rename '{{ from_relation.schema }}.{{ from_relation.identifier }}', '{{ to_relation.identifier }}'
{%- endcall %}
{% endmacro %}
{% macro sqlserver__truncate_relation(relation) -%}
{% call statement('truncate_relation') -%}
truncate table {{ relation }}
{%- endcall %}
{% endmacro %}