diff options
author | Frederick Muriuki Muriithi | 2023-07-19 09:41:07 +0300 |
---|---|---|
committer | Frederick Muriuki Muriithi | 2023-07-19 09:41:07 +0300 |
commit | 82722fefd007edbddf08175686570e2ed307097e (patch) | |
tree | 36fdbe31e7962dea2b1df8dcac032e5e61a353ee /gn3 | |
parent | 9b2f5b8bf533a8ed360752cf9199f83bdd4454a3 (diff) | |
download | genenetwork3-82722fefd007edbddf08175686570e2ed307097e.tar.gz |
Extract reusable code to separate module
Extract the reusable function into a separate `query_tools` module for use in
other modules.
Diffstat (limited to 'gn3')
-rw-r--r-- | gn3/db/phenotypes.py | 12 | ||||
-rw-r--r-- | gn3/db/query_tools.py | 7 |
2 files changed, 11 insertions, 8 deletions
diff --git a/gn3/db/phenotypes.py b/gn3/db/phenotypes.py index 228459f..605ca73 100644 --- a/gn3/db/phenotypes.py +++ b/gn3/db/phenotypes.py @@ -8,6 +8,8 @@ from MySQLdb.cursors import DictCursor from gn3.db_utils import Connection as DBConnection +from .query_tools import mapping_to_query_columns + @dataclass(frozen=True) class Phenotype: @@ -179,16 +181,10 @@ def fetch_trait(conn: DBConnection, dataset_id: int, trait_name: str) -> dict: query, {"dataset_id": dataset_id, "trait_name": trait_name}) return cursor.fetchone() -def _mapping_to_query_columns_(mapping_dict: dict[str, str]) -> tuple[str, ...]: - """ - Internal function to convert mapping dicts into column clauses for queries. - """ - return tuple(f"{tcol} as {dcol}" for dcol, tcol in mapping_dict.items()) - def fetch_metadata(conn: DBConnection, phenotype_id: int) -> dict: """Get the phenotype metadata by ID.""" with conn.cursor(cursorclass=DictCursor) as cursor: - cols = ', '.join(_mapping_to_query_columns_(phenotype_mapping)) + cols = ', '.join(mapping_to_query_columns(phenotype_mapping)) cursor.execute( (f"SELECT Id as id, {cols} FROM Phenotype " "WHERE Id=%(phenotype_id)s"), @@ -198,7 +194,7 @@ def fetch_metadata(conn: DBConnection, phenotype_id: int) -> dict: def fetch_publication(conn: DBConnection, publication_id: int) -> dict: """Fetch the publication by its ID.""" with conn.cursor(cursorclass=DictCursor) as cursor: - cols = ', '.join(_mapping_to_query_columns_(publication_mapping)) + cols = ', '.join(mapping_to_query_columns(publication_mapping)) cursor.execute( (f"SELECT Id as id, {cols} FROM Publication " "WHERE Id=%(publication_id)s"), diff --git a/gn3/db/query_tools.py b/gn3/db/query_tools.py new file mode 100644 index 0000000..2e3dd84 --- /dev/null +++ b/gn3/db/query_tools.py @@ -0,0 +1,7 @@ +"""Functions and utilities to use when generating queries""" + +def mapping_to_query_columns(mapping_dict: dict[str, str]) -> tuple[str, ...]: + """ + Internal function to convert mapping dicts into column clauses for queries. + """ + return tuple(f"{tcol} as {dcol}" for dcol, tcol in mapping_dict.items()) |