diff --git a/sqlmesh/core/schema_diff.py b/sqlmesh/core/schema_diff.py index 7b8c7f16f7..e1f9d72a6c 100644 --- a/sqlmesh/core/schema_diff.py +++ b/sqlmesh/core/schema_diff.py @@ -498,8 +498,11 @@ def _drop_operation( columns = ensure_list(columns) operations: t.List[TableAlterColumnOperation] = [] column_pos, column_kwarg = self._get_matching_kwarg(columns[-1].name, struct, pos) - assert column_pos is not None - assert column_kwarg + if column_pos is None or not column_kwarg: + raise SQLMeshError( + f"Cannot drop column '{columns[-1].name}' from table '{table_name}' - column not found. " + f"This may indicate a mismatch between the expected and actual table schemas." + ) struct.expressions.pop(column_pos) operations.append( TableAlterDropColumnOperation( diff --git a/tests/core/test_schema_diff.py b/tests/core/test_schema_diff.py index e091dea539..52bd6bb606 100644 --- a/tests/core/test_schema_diff.py +++ b/tests/core/test_schema_diff.py @@ -15,6 +15,7 @@ TableAlterChangeColumnTypeOperation, NestedSupport, ) +from sqlmesh.utils.errors import SQLMeshError def test_schema_diff_calculate(): @@ -2341,3 +2342,27 @@ def test_ignore_additive_array_operations(): ignore_additive=True, ) assert len(operations_ignore_additive) == 0 + + +def test_drop_operation_missing_column_error(): + schema_differ = SchemaDiffer( + nested_support=NestedSupport.NONE, + support_positional_add=False, + ) + + # a struct that doesn't contain the column we're going to drop + current_struct = exp.DataType.build("STRUCT") + + with pytest.raises(SQLMeshError) as error_message: + schema_differ._drop_operation( + columns=[TableAlterColumn.primitive("missing_column")], + struct=current_struct, + pos=0, + root_struct=current_struct, + table_name="test_table", + ) + + assert ( + 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." + )