From cf908fb357ecd2e7b4933e3266d46011365637a3 Mon Sep 17 00:00:00 2001 From: Kishore Nallan Date: Fri, 7 Oct 2022 12:51:29 +0530 Subject: [PATCH] Validate `query_by` id. --- src/collection.cpp | 14 ++++++++++---- test/collection_specific_more_test.cpp | 20 ++++++++++++++++++++ 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/collection.cpp b/src/collection.cpp index cf99523b..6e8fd9d3 100644 --- a/src/collection.cpp +++ b/src/collection.cpp @@ -935,6 +935,12 @@ Option Collection::search(const std::string & raw_query, std::vector processed_search_fields; for(const std::string& field_name: raw_search_fields) { + if(field_name == "id") { + // `id` field needs to be handled separately, we will not handle for now + std::string error = "Cannot use `id` as a query by field."; + return Option(400, error); + } + auto field_op = extract_field_name(field_name, search_schema, processed_search_fields, true, enable_nested_fields); if(!field_op.ok()) { return Option(field_op.code(), field_op.error()); @@ -965,10 +971,10 @@ Option Collection::search(const std::string & raw_query, } } - for(const std::string & field_name: group_by_fields) { - if(search_schema.count(field_name) == 0) { - std::string error = "Could not find a field named `" + field_name + "` in the schema."; - return Option(404, error); + for(const std::string& field_name: group_by_fields) { + if(field_name == "id") { + std::string error = "Cannot use `id` as a group by field."; + return Option(400, error); } field search_field = search_schema.at(field_name); diff --git a/test/collection_specific_more_test.cpp b/test/collection_specific_more_test.cpp index 8bf2d95a..90dd6679 100644 --- a/test/collection_specific_more_test.cpp +++ b/test/collection_specific_more_test.cpp @@ -1457,4 +1457,24 @@ TEST_F(CollectionSpecificMoreTest, MustExcludeOutOf) { auto res = res_op.get(); ASSERT_EQ(1, res["hits"].size()); ASSERT_EQ(0, res.count("out_of")); +} + +TEST_F(CollectionSpecificMoreTest, ValidateQueryById) { + nlohmann::json schema = R"({ + "name": "coll1", + "fields": [ + {"name": "title", "type": "string"} + ] + })"_json; + + Collection* coll1 = collectionManager.create_collection(schema).get(); + + nlohmann::json doc; + doc["id"] = "doc-1"; + doc["title"] = "Sample Title 1"; + ASSERT_TRUE(coll1->add(doc.dump()).ok()); + + auto res_op = coll1->search("doc-1", {"id"}, "", {}, {}, {2}, 10, 1, FREQUENCY, {true}, 0); + ASSERT_FALSE(res_op.ok()); + ASSERT_EQ("Cannot use `id` as a query by field.", res_op.error()); } \ No newline at end of file