|
9 | 9 | from sqlglot.optimizer.normalize_identifiers import normalize_identifiers |
10 | 10 | from sqlglot.optimizer.qualify_columns import quote_identifiers |
11 | 11 |
|
| 12 | +import sqlmesh.core.constants as c |
12 | 13 | from sqlmesh.core.dialect import to_schema |
13 | 14 | from sqlmesh.core.engine_adapter.mixins import ( |
14 | 15 | GetCurrentCatalogFromFunctionMixin, |
|
43 | 44 | "_get_data_objects": CatalogSupport.REQUIRES_SET_CATALOG, |
44 | 45 | "create_schema": CatalogSupport.REQUIRES_SET_CATALOG, |
45 | 46 | "drop_schema": CatalogSupport.REQUIRES_SET_CATALOG, |
| 47 | + "drop_catalog": CatalogSupport.REQUIRES_SET_CATALOG, # needs a catalog to issue a query to information_schema.databases even though the result is global |
46 | 48 | } |
47 | 49 | ) |
48 | 50 | class SnowflakeEngineAdapter(GetCurrentCatalogFromFunctionMixin, ClusteredByMixin, RowDiffMixin): |
@@ -125,10 +127,34 @@ def catalog_support(self) -> CatalogSupport: |
125 | 127 | return CatalogSupport.FULL_SUPPORT |
126 | 128 |
|
127 | 129 | def _create_catalog(self, catalog_name: exp.Identifier) -> None: |
128 | | - self.execute(exp.Create(this=exp.Table(this=catalog_name), kind="DATABASE", exists=True)) |
| 130 | + props = exp.Properties( |
| 131 | + expressions=[exp.SchemaCommentProperty(this=exp.Literal.string(c.SQLMESH_MANAGED))] |
| 132 | + ) |
| 133 | + self.execute( |
| 134 | + exp.Create( |
| 135 | + this=exp.Table(this=catalog_name), kind="DATABASE", exists=True, properties=props |
| 136 | + ) |
| 137 | + ) |
129 | 138 |
|
130 | 139 | def _drop_catalog(self, catalog_name: exp.Identifier) -> None: |
131 | | - self.execute(exp.Drop(this=exp.Table(this=catalog_name), kind="DATABASE", exists=True)) |
| 140 | + # only drop the catalog if it was created by SQLMesh, which is indicated by its comment matching {c.SQLMESH_MANAGED} |
| 141 | + exists_check = ( |
| 142 | + exp.select(exp.Literal.number(1)) |
| 143 | + .from_(exp.to_table("information_schema.databases")) |
| 144 | + .where( |
| 145 | + exp.and_( |
| 146 | + exp.column("database_name").eq(exp.Literal.string(catalog_name)), |
| 147 | + exp.column("comment").eq(exp.Literal.string(c.SQLMESH_MANAGED)), |
| 148 | + ) |
| 149 | + ) |
| 150 | + ) |
| 151 | + normalize_identifiers(exists_check, dialect=self.dialect) |
| 152 | + if self.fetchone(exists_check, quote_identifiers=True) is not None: |
| 153 | + self.execute(exp.Drop(this=exp.Table(this=catalog_name), kind="DATABASE", exists=True)) |
| 154 | + else: |
| 155 | + logger.warning( |
| 156 | + f"Not dropping database {catalog_name.sql(dialect=self.dialect)} because there is no indication it is '{c.SQLMESH_MANAGED}'" |
| 157 | + ) |
132 | 158 |
|
133 | 159 | def _create_table( |
134 | 160 | self, |
|
0 commit comments