forked from Montreal-Analytics/dbt-snowflake-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clone_database.sql
64 lines (46 loc) · 1.95 KB
/
clone_database.sql
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
56
57
58
59
60
61
62
63
64
{#
-- This macro clones the source database into the destination database and
-- optionally grants ownership over it, its schemata, and its schemata's tables
-- and views to a new owner.
#}
{% macro clone_database(
source_database,
destination_database,
new_owner_role=''
) %}
{% if source_database and destination_database %}
{{ (log("Cloning existing database " ~ source_database ~
" into database " ~ destination_database, info=True)) }}
{% call statement('clone_database', fetch_result=True, auto_begin=False) -%}
CREATE OR REPLACE DATABASE {{ destination_database }}
CLONE {{ source_database }};
{%- endcall %}
{%- set result = load_result('clone_database') -%}
{{ log(result['data'][0][0], info=True)}}
{% else %}
{{ exceptions.raise_compiler_error("Invalid arguments. Missing source database and/or destination database") }}
{% endif %}
{% if new_owner_role != '' %}
{% set list_schemas_query %}
-- get all schemata within the cloned database to then iterate through them and
-- change their ownership
SELECT schema_name
FROM {{ destination_database }}.information_schema.schemata
WHERE schema_name != 'INFORMATION_SCHEMA'
{% endset %}
{% set results = run_query(list_schemas_query) %}
{% if execute %}
{# Return the first column #}
{% set schemata_list = results.columns[0].values() %}
{% else %}
{% set schemata_list = [] %}
{% endif %}
{% for schema_name in schemata_list %}
{{ snowflake_utils.grant_ownership_on_schema_objects(new_owner_role, schema_name, destination_database) }}
{% endfor %}
{{ log("Grant ownership on " ~ destination_database ~ " to " ~ new_owner_role, info=True)}}
{% call statement('clone_database', fetch_result=True, auto_begin=False) -%}
GRANT ALL PRIVILEGES ON DATABASE {{ destination_database }} TO {{ new_owner_role }};
{%- endcall %}
{% endif %}
{% endmacro %}