From 33c3465d159ef917e1cf9a1159b3866479a9913a Mon Sep 17 00:00:00 2001 From: Jeremy McCormick Date: Mon, 26 Aug 2024 13:16:38 -0500 Subject: [PATCH] Add validator that checks if index names are unique within the schema --- python/felis/datamodel.py | 32 +++++++++++++++++++++++++++++++- tests/test_datamodel.py | 11 +++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/python/felis/datamodel.py b/python/felis/datamodel.py index b97dd10f..fc99fe3c 100644 --- a/python/felis/datamodel.py +++ b/python/felis/datamodel.py @@ -848,7 +848,37 @@ def check_unique_constraint_names(self: Schema) -> Schema: constraint_names.add(constraint_name) if duplicate_names: - raise ValueError(f"Duplicate constraint names found in schema: {duplicate_names}") + raise ValueError(f"Duplicate index names found in schema: {duplicate_names}") + + return self + + @model_validator(mode="after") + def check_unique_index_names(self: Schema) -> Schema: + """Check for duplicate index names in the schema. + + Returns + ------- + `Schema` + The schema being validated. + + Raises + ------ + ValueError + Raised if duplicate index names are found in the schema. + """ + index_names = set() + duplicate_names = [] + + for table in self.tables: + for index in table.indexes: + index_name = index.name + if index_name in index_names: + duplicate_names.append(index_name) + else: + index_names.add(index_name) + + if duplicate_names: + raise ValueError(f"Duplicate index names found in schema: {duplicate_names}") return self diff --git a/tests/test_datamodel.py b/tests/test_datamodel.py index 4ab2a6cf..67681099 100644 --- a/tests/test_datamodel.py +++ b/tests/test_datamodel.py @@ -478,6 +478,17 @@ def test_check_unique_constraint_names(self) -> None: with self.assertRaises(ValidationError): Schema(name="testSchema", id="#test_id", tables=[test_tbl]) + def test_check_unique_index_names(self) -> None: + """Test that index names are unique.""" + test_col = Column(name="test_column1", id="#test_table#test_column1", datatype="int") + test_col2 = Column(name="test_column2", id="##test_table#test_column2", datatype="string", length=256) + test_tbl = Table(name="test_table", id="#test_table", columns=[test_col, test_col2]) + test_idx = Index(name="idx_test", id="#idx_test", columns=[test_col.id]) + test_idx2 = Index(name="idx_test", id="#idx_test2", columns=[test_col2.id]) + test_tbl.indexes = [test_idx, test_idx2] + with self.assertRaises(ValidationError): + Schema(name="test_schema", id="#test-schema", tables=[test_tbl]) + def test_model_validate(self) -> None: """Load a YAML test file and validate the schema data model.""" with open(TEST_YAML) as test_yaml: