diff --git a/sqlmesh/core/engine_adapter/snowflake.py b/sqlmesh/core/engine_adapter/snowflake.py index 7b67976f66..f0708bb1fd 100644 --- a/sqlmesh/core/engine_adapter/snowflake.py +++ b/sqlmesh/core/engine_adapter/snowflake.py @@ -83,6 +83,15 @@ class SnowflakeEngineAdapter( exp.DataType.build("TIMESTAMP_NTZ", dialect=DIALECT).this: [(9,)], exp.DataType.build("TIMESTAMP_TZ", dialect=DIALECT).this: [(9,)], }, + "type_aliases": { + # In Snowflake, INT, INTEGER, BIGINT, SMALLINT, TINYINT and BYTEINT are synonyms for NUMBER(38, 0). + exp.DataType.build(alias, dialect="snowflake").this: exp.DataType.build( + "NUMBER(38, 0)", dialect="snowflake" + ) + for alias in ("INT", "INTEGER", "BIGINT", "SMALLINT", "TINYINT", "BYTEINT") + }, + # Snowflake rejects in-place ALTER COLUMN SET DATA TYPE when NUMBER scale changes (error 040052). + "fixed_scale_types": {exp.DataType.build("DECIMAL", dialect=DIALECT).this}, } MANAGED_TABLE_KIND = "DYNAMIC TABLE" SNOWPARK = "snowpark" diff --git a/sqlmesh/core/schema_diff.py b/sqlmesh/core/schema_diff.py index ecf38b18a8..606700a129 100644 --- a/sqlmesh/core/schema_diff.py +++ b/sqlmesh/core/schema_diff.py @@ -350,6 +350,12 @@ class SchemaDiffer(PydanticModel): max_parameter_length: Numeric parameter values corresponding to "max". Example: `VARCHAR(max)` -> `VARCHAR(65535)`. types_with_unlimited_length: Data types that accept values of any length up to system limits. Any explicitly parameterized type can ALTER to its unlimited length version, along with different types in some engines. + type_aliases: Mapping from unparameterized dialect alias types (as ``exp.DType``) to their canonical + ``exp.DataType`` (e.g. Snowflake's ``INT``/``BIGINT``/``SMALLINT``/``TINYINT`` -> ``NUMBER(38, 0)``). + Two column types whose resolved aliases are equal are treated as identical (no alter emitted). + fixed_scale_types: Parameterized numeric types (as ``exp.DType``) whose scale (second parameter) cannot + be changed in place via ``ALTER COLUMN`` (e.g. Snowflake ``NUMBER``/``DECIMAL``, where precision can + widen only when scale remains identical). treat_alter_data_type_as_destructive: The SchemaDiffer will only output change data type operations if it concludes the change is compatible and won't result in data loss. If this flag is set to True, it will flag these data type changes as destructive. This was added for dbt adapter support and likely shouldn't @@ -369,6 +375,8 @@ class SchemaDiffer(PydanticModel): parameterized_type_defaults: t.Dict[exp.DType, t.List[t.Tuple[t.Union[int, float], ...]]] = {} max_parameter_length: t.Dict[exp.DType, t.Union[int, float]] = {} types_with_unlimited_length: t.Dict[exp.DType, t.Set[exp.DType]] = {} + type_aliases: t.Dict[exp.DType, exp.DataType] = {} + fixed_scale_types: t.Set[exp.DType] = set() treat_alter_data_type_as_destructive: bool = False _coerceable_types: t.Dict[exp.DataType, t.Set[exp.DataType]] = {} @@ -386,20 +394,56 @@ def coerceable_types(self) -> t.Dict[exp.DataType, t.Set[exp.DataType]]: self._coerceable_types = coerceable_types return self._coerceable_types + def _resolve_type_alias(self, data_type: exp.DataType) -> exp.DataType: + if not data_type.expressions and data_type.this in self.type_aliases: + return self.type_aliases[data_type.this] + return data_type + + def _are_equivalent_types(self, current_type: exp.DataType, new_type: exp.DataType) -> bool: + if current_type == new_type: + return True + resolved_current = self._resolve_type_alias(current_type) + resolved_new = self._resolve_type_alias(new_type) + if resolved_current == resolved_new: + return True + if ( + resolved_current.this == resolved_new.this + and not resolved_current.is_type(*exp.DataType.NESTED_TYPES) + and (resolved_current != current_type or resolved_new != new_type) + and resolved_current.this in self.parameterized_type_defaults + ): + try: + return self.get_type_parameters(resolved_current) == self.get_type_parameters( + resolved_new + ) + except ValueError: + return False + return False + def _is_compatible_type(self, current_type: exp.DataType, new_type: exp.DataType) -> bool: + resolved_current = self._resolve_type_alias(current_type) + resolved_new = self._resolve_type_alias(new_type) # types are identical or both types are parameterized and new has higher precision # - default parameter values are automatically provided if not present - if current_type == new_type or ( - self._is_precision_increase_allowed(current_type) - and self._is_precision_increase(current_type, new_type) + if resolved_current == resolved_new or ( + self._is_precision_increase_allowed(resolved_current) + and self._is_precision_increase(resolved_current, resolved_new) ): return True # types are un-parameterized and compatible - if current_type in self.compatible_types: - return new_type in self.compatible_types[current_type] + if ( + current_type in self.compatible_types + and new_type in self.compatible_types[current_type] + ): + return True + if resolved_current in self.compatible_types and ( + new_type in self.compatible_types[resolved_current] + or resolved_new in self.compatible_types[resolved_current] + ): + return True # new type is un-parameterized and has unlimited length, current type is compatible - if not new_type.expressions and new_type.this in self.types_with_unlimited_length: - return current_type.this in self.types_with_unlimited_length[new_type.this] + if not resolved_new.expressions and resolved_new.this in self.types_with_unlimited_length: + return resolved_current.this in self.types_with_unlimited_length[resolved_new.this] return False def _is_coerceable_type(self, current_type: exp.DataType, new_type: exp.DataType) -> bool: @@ -431,6 +475,13 @@ def _is_precision_increase(self, current_type: exp.DataType, new_type: exp.DataT if len(current_params) != len(new_params): return False + if ( + current_type.this in self.fixed_scale_types + and len(current_params) >= 2 + and current_params[1] != new_params[1] + ): + return False + return all(new >= current for current, new in zip(current_params, new_params)) return False @@ -702,7 +753,7 @@ def _resolve_alter_operations( _, new_type = _get_name_and_type(new_kwarg) _, current_type = _get_name_and_type(current_kwarg) columns = parent_columns + [TableAlterColumn.from_struct_kwarg(current_kwarg)] - if new_type == current_type: + if self._are_equivalent_types(current_type, new_type): continue operations.extend( self._alter_operation( diff --git a/tests/core/test_schema_diff.py b/tests/core/test_schema_diff.py index 52bd6bb606..169419506a 100644 --- a/tests/core/test_schema_diff.py +++ b/tests/core/test_schema_diff.py @@ -10,6 +10,7 @@ TableAlterColumnPosition, TableAlterOperation, get_schema_differ, + has_drop_alteration, TableAlterAddColumnOperation, TableAlterDropColumnOperation, TableAlterChangeColumnTypeOperation, @@ -2366,3 +2367,100 @@ def test_drop_operation_missing_column_error(): str(error_message.value) == "Cannot drop column 'missing_column' from table 'test_table' - column not found. This may indicate a mismatch between the expected and actual table schemas." ) + + +@pytest.mark.parametrize( + "current_type,new_type", + [ + ("INT", "BIGINT"), + ("BIGINT", "INT"), + ("INTEGER", "BIGINT"), + ("SMALLINT", "BIGINT"), + ("TINYINT", "INTEGER"), + ("BYTEINT", "BIGINT"), + ("NUMBER(38, 0)", "INT"), + ("INT", "NUMBER(38, 0)"), + ("DECIMAL(38, 0)", "BIGINT"), + ("NUMBER", "BIGINT"), + ("NUMBER(38)", "BIGINT"), + ("BIGINT", "NUMBER(38)"), + ], +) +def test_snowflake_integer_synonyms_produce_no_alter(current_type: str, new_type: str): + differ = get_schema_differ("snowflake") + ops = differ.compare_columns( + "t", + {"c": exp.DataType.build(current_type, dialect="snowflake")}, + {"c": exp.DataType.build(new_type, dialect="snowflake")}, + ) + assert ops == [] + + +def test_snowflake_unparameterized_decimal_equals_bigint(): + differ = get_schema_differ("snowflake") + ops = differ.compare_columns( + "t", + {"c": exp.DataType(this=exp.DType.DECIMAL)}, + {"c": exp.DataType.build("BIGINT", dialect="snowflake")}, + ) + assert ops == [] + + +def test_snowflake_integer_synonym_precision_widening_and_narrowing(): + differ = get_schema_differ("snowflake") + + # Widening NUMBER(10, 0) -> BIGINT (NUMBER(38, 0)) is a non-destructive type alter + widen_ops = differ.compare_columns( + "t", + {"c": exp.DataType.build("NUMBER(10, 0)", dialect="snowflake")}, + {"c": exp.DataType.build("BIGINT", dialect="snowflake")}, + ) + assert len(widen_ops) == 1 + assert isinstance(widen_ops[0], TableAlterChangeColumnTypeOperation) + assert not widen_ops[0].is_destructive + + # Widening precision with unchanged scale NUMBER(10, 2) -> NUMBER(20, 2) stays non-destructive + same_scale_widen_ops = differ.compare_columns( + "t", + {"c": exp.DataType.build("NUMBER(10, 2)", dialect="snowflake")}, + {"c": exp.DataType.build("NUMBER(20, 2)", dialect="snowflake")}, + ) + assert len(same_scale_widen_ops) == 1 + assert isinstance(same_scale_widen_ops[0], TableAlterChangeColumnTypeOperation) + assert not same_scale_widen_ops[0].is_destructive + + # Scale changes (INT -> NUMBER(38, 2), NUMBER(38, 0) -> NUMBER(38, 2), NUMBER(10, 0) -> NUMBER(20, 2)) + # must stay destructive (DROP + ADD) because Snowflake rejects in-place scale alterations (error 040052) + for cur_t, new_t in [ + ("INT", "NUMBER(38, 2)"), + ("NUMBER(38, 0)", "NUMBER(38, 2)"), + ("NUMBER(10, 0)", "NUMBER(20, 2)"), + ]: + scale_ops = differ.compare_columns( + "t", + {"c": exp.DataType.build(cur_t, dialect="snowflake")}, + {"c": exp.DataType.build(new_t, dialect="snowflake")}, + ) + assert len(scale_ops) == 2 + assert isinstance(scale_ops[0], TableAlterDropColumnOperation) + assert isinstance(scale_ops[1], TableAlterAddColumnOperation) + assert has_drop_alteration(scale_ops) + + # Narrowing BIGINT (NUMBER(38, 0)) -> NUMBER(10, 0) remains destructive (DROP + ADD) + narrow_ops = differ.compare_columns( + "t", + {"c": exp.DataType.build("BIGINT", dialect="snowflake")}, + {"c": exp.DataType.build("NUMBER(10, 0)", dialect="snowflake")}, + ) + assert len(narrow_ops) == 2 + assert isinstance(narrow_ops[0], TableAlterDropColumnOperation) + assert isinstance(narrow_ops[1], TableAlterAddColumnOperation) + assert has_drop_alteration(narrow_ops) + + # Incompatible change INT -> VARCHAR remains destructive + incompat_ops = differ.compare_columns( + "t", + {"c": exp.DataType.build("INT", dialect="snowflake")}, + {"c": exp.DataType.build("VARCHAR", dialect="snowflake")}, + ) + assert has_drop_alteration(incompat_ops)