aboutsummaryrefslogtreecommitdiff
path: root/gn_auth/auth/authorisation/resources/groups/models.py
diff options
context:
space:
mode:
Diffstat (limited to 'gn_auth/auth/authorisation/resources/groups/models.py')
-rw-r--r--gn_auth/auth/authorisation/resources/groups/models.py48
1 files changed, 43 insertions, 5 deletions
diff --git a/gn_auth/auth/authorisation/resources/groups/models.py b/gn_auth/auth/authorisation/resources/groups/models.py
index 2df5f04..b8a5235 100644
--- a/gn_auth/auth/authorisation/resources/groups/models.py
+++ b/gn_auth/auth/authorisation/resources/groups/models.py
@@ -237,15 +237,53 @@ def is_group_leader(conn: db.DbConnection, user: User, group: Group) -> bool:
return "group-leader" in role_names
-def all_groups(conn: db.DbConnection) -> Maybe[Sequence[Group]]:
+def __build_groups_list_query__(base: str, search: Optional[str] = None) -> tuple[str, tuple[Optional[str], ...]]:
+ """Build up the query from given search terms."""
+ if bool(search):
+ _search = search.strip()
+ return ((f"{base} WHERE groups.group_name LIKE ? "
+ "OR groups.group_metadata LIKE ?"),
+ (f"%{search}%", f"%{search}%"))
+ return base, tuple()
+
+
+def __limit_results_length__(base: str, start: int = 0, length: int = 0) -> str:
+ """Add the `LIMIT … OFFSET …` clause to query `base`."""
+ if length > 0:
+ return f"{base} LIMIT {length} OFFSET {start}"
+ return base
+
+
+def all_groups(
+ conn: db.DbConnection,
+ search: Optional[str] = None,
+ start: int = 0,
+ length: int = 0
+) -> Maybe[tuple[tuple[Group, ...], int, int]]:
"""Retrieve all existing groups"""
with db.cursor(conn) as cursor:
- cursor.execute("SELECT * FROM groups")
+ cursor.execute("SELECT COUNT(*) FROM groups")
+ _groups_total_count = int(cursor.fetchone()["COUNT(*)"])
+
+ _qdets = __build_groups_list_query__(
+ "SELECT COUNT(*) FROM groups", search)
+ cursor.execute(*__build_groups_list_query__(
+ "SELECT COUNT(*) FROM groups", search))
+ _filtered_total_count = int(cursor.fetchone()["COUNT(*)"])
+
+ _query, _params = __build_groups_list_query__(
+ "SELECT * FROM groups", search)
+
+ cursor.execute(__limit_results_length__(_query, start, length),
+ _params)
res = cursor.fetchall()
if res:
- return Just(tuple(
- Group(row["group_id"], row["group_name"],
- json.loads(row["group_metadata"])) for row in res))
+ return Just((
+ tuple(
+ Group(row["group_id"], row["group_name"],
+ json.loads(row["group_metadata"])) for row in res),
+ _groups_total_count,
+ _filtered_total_count))
return Nothing