From 55f17ab28b1f76da35728415ae39fc1a99b80740 Mon Sep 17 00:00:00 2001 From: Jeny Sadadia Date: Fri, 17 Nov 2023 17:46:00 +0530 Subject: [PATCH 1/2] api.db: enable boolean query fields for GET requests Enable support for querying boolean fields while getting objects from API such as nodes or models. e.g. find all the active admin users using `http://API_SERVER/users?is_active=true&is_superuser=true` Signed-off-by: Jeny Sadadia --- api/db.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/api/db.py b/api/db.py index 87933e68..b03cd198 100644 --- a/api/db.py +++ b/api/db.py @@ -37,6 +37,11 @@ class Database: 'ne': '$ne', } + BOOL_VALUE_MAP = { + 'true': True, + 'false': False + } + def __init__(self, service='mongodb://db:27017', db_name='kernelci'): self._motor = motor_asyncio.AsyncIOMotorClient(service) self._db = self._motor[db_name] @@ -103,10 +108,19 @@ def _convert_int_values(cls, attributes): if isinstance(val, tuple) and len(val) == 2 and val[0] == 'int' } + def _convert_bool_values(self, attributes): + for key, val in attributes.items(): + if isinstance(val, str): + bool_value = self.BOOL_VALUE_MAP.get(val.lower()) + if bool_value is not None: + attributes[key] = bool_value + return attributes + def _prepare_query(self, attributes): query = attributes.copy() query.update(self._translate_operators(query)) query.update(self._convert_int_values(query)) + query.update(self._convert_bool_values(query)) return query async def find_by_attributes(self, model, attributes): From 54008c5d18dfd6e19fc50c7f8db36a2e627da265 Mon Sep 17 00:00:00 2001 From: Jeny Sadadia Date: Mon, 27 Nov 2023 12:13:17 +0530 Subject: [PATCH 2/2] migrations: fix user document migration for `bool` fields Instead of using integer values 1 and 0 for `User` model boolean fields, use `True` and `False` to enable querying boolean fields in MongoDB as per the syntax. Fixes: 310f3d6 ("migration: add migration for user documents") Signed-off-by: Jeny Sadadia --- migrations/20231102101356_user.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/migrations/20231102101356_user.py b/migrations/20231102101356_user.py index 3a24b852..7257f550 100644 --- a/migrations/20231102101356_user.py +++ b/migrations/20231102101356_user.py @@ -23,9 +23,9 @@ def upgrade(db: "pymongo.database.Database"): "_id": user['_id'], "email": user['profile']['email'], "hashed_password": user['profile']['hashed_password'], - "is_active": 1, - "is_superuser": 0, - "is_verified": 0, + "is_active": True, + "is_superuser": False, + "is_verified": False, "username": user['profile']['username'], "groups": user['profile']['groups'] },