|
1 | 1 | {# This macro swaps two databases, for use in blue/green runs. #} |
2 | 2 | {# |
3 | | - To run: |
| 3 | + To run: |
4 | 4 | dbt run-operation swap_database --args "{db1: dev_commercial_dw2, db2: dev_commercial_dw}" |
| 5 | + |
| 6 | + To create missing db2 if it doesn't exist: |
| 7 | + dbt run-operation swap_database --args "{db1: dev_commercial_dw2, db2: dev_commercial_dw, create_missing_db: true}" |
5 | 8 | #} |
6 | 9 |
|
7 | | -{%- macro swap_database(db1, db2) -%} |
| 10 | +{%- macro swap_database(db1, db2, create_missing_db=false) -%} |
| 11 | + {# Check if db2 exists #} |
| 12 | + {% set check_db2_sql %} |
| 13 | + select count(*) as db_count |
| 14 | + from information_schema.databases |
| 15 | + where database_name = upper('{{ db2 }}') |
| 16 | + {% endset %} |
| 17 | +
|
| 18 | + {% set db2_exists_result = run_query(check_db2_sql) %} |
| 19 | + {% set db2_exists = db2_exists_result.columns[0].values()[0] > 0 %} |
| 20 | +
|
| 21 | + {# Create db2 if it doesn't exist and create_missing_db is true #} |
| 22 | + {% if not db2_exists %} |
| 23 | + {% if create_missing_db %} |
| 24 | + {% set create_db2_sql %} |
| 25 | + create database {{ db2 }}; |
| 26 | + {% endset %} |
| 27 | + |
| 28 | + {% do run_query(create_db2_sql) %} |
| 29 | + {{ print("Created database " ~ db2 ~ " as it did not exist") }} |
| 30 | + {% else %} |
| 31 | + {{ exceptions.raise_compiler_error("Database " ~ db2 ~ " does not exist. Set create_missing_db=true to create it automatically.") }} |
| 32 | + {% endif %} |
| 33 | + {% endif %} |
| 34 | + |
| 35 | + {# Perform the swap #} |
8 | 36 | {% set swap_db_sql %} |
9 | 37 | alter database {{ db1 }} swap with {{ db2 }}; |
10 | 38 | {% endset %} |
|
0 commit comments