Skip to content

Open Source alternative to Algolia + Pinecone and an Easier-to-Use alternative to ElasticSearch ⚡ 🔍 ✨ Fast, typo tolerant, in-memory fuzzy Search Engine for building delightful search experiences

Ensure that `id` field cannot be altered.

Kishore Nallan19ac76b681f4
diff --git a/src/collection.cpp b/src/collection.cpp
index acd4e901..e661cdaa 100644
--- a/src/collection.cpp
+++ b/src/collection.cpp
@@ -2810,6 +2810,10 @@ Option<bool> Collection::validate_alter_payload(nlohmann::json& schema_changes,
const std::string& field_name = kv.value()["name"].get<std::string>();
+ if(field_name == "id") {
+ return Option<bool>(400, "Field `" + field_name + "` cannot be altered.");
+ }
+
if(kv.value().contains("drop")) {
delete_field_names.insert(field_name);
}
diff --git a/test/collection_schema_change_test.cpp b/test/collection_schema_change_test.cpp
index 8ffd09cc..7409ca27 100644
--- a/test/collection_schema_change_test.cpp
+++ b/test/collection_schema_change_test.cpp
@@ -219,6 +219,17 @@ TEST_F(CollectionSchemaChangeTest, AddNewFieldsToCollection) {
alter_op = coll1->alter(schema_changes);
ASSERT_TRUE(alter_op.ok());
+ // try to add `id` field
+ schema_changes = R"({
+ "fields": [
+ {"name": "id", "type": "int32"}
+ ]
+ })"_json;
+
+ alter_op = coll1->alter(schema_changes);
+ ASSERT_FALSE(alter_op.ok());
+ ASSERT_EQ("Field `id` cannot be altered.", alter_op.error());
+
ASSERT_EQ(9, coll1->get_schema().size());
ASSERT_EQ(12, coll1->get_fields().size());
ASSERT_EQ(5, coll1->_get_index()->_get_numerical_index().size());
@@ -310,6 +321,17 @@ TEST_F(CollectionSchemaChangeTest, DropFieldsFromCollection) {
ASSERT_EQ("", coll1->get_fallback_field_type());
ASSERT_EQ("", coll1->get_default_sorting_field());
+ // try to drop `id` field
+ schema_changes = R"({
+ "fields": [
+ {"name": "id", "drop": true}
+ ]
+ })"_json;
+
+ alter_op = coll1->alter(schema_changes);
+ ASSERT_FALSE(alter_op.ok());
+ ASSERT_EQ("Field `id` cannot be altered.", alter_op.error());
+
// try restoring collection from disk: all fields should be deleted
collectionManager.dispose();
delete store;
@@ -476,6 +498,18 @@ TEST_F(CollectionSchemaChangeTest, AlterValidations) {
ASSERT_FALSE(alter_op.ok());
ASSERT_EQ("Field `title` has an invalid data type `foobar`, see docs for supported data types.",alter_op.error());
+ // add + drop `id` field
+ schema_changes = R"({
+ "fields": [
+ {"name": "id", "drop": true},
+ {"name": "id", "type": "string"}
+ ]
+ })"_json;
+
+ alter_op = coll1->alter(schema_changes);
+ ASSERT_FALSE(alter_op.ok());
+ ASSERT_EQ("Field `id` cannot be altered.", alter_op.error());
+
collectionManager.drop_collection("coll1");
}