about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public01@thebird.nl>2026-10-03 14:57:25 +0000
committerPjotr <wrk@bosa.lan>2026-10-04 06:23:13 +0000
commit18f20d6df2310ef822e541791770dfe9d7b26fc2 (patch)
treeac0f12720d8c2800325129f5f55d4154d0fbba52 /src
parent924bcf3d25c01ccfd1cdf04bcc0308c5c1fd4ddb (diff)
downloadgenenetwork4-18f20d6df2310ef822e541791770dfe9d7b26fc2.tar.gz
Add GET /groups/{group}/traits/{trait_id}/values, publish trait data.
* src/db.rs (TraitValue): New struct.
(get_group_trait_values): New function. Joins PublishData, Strain and
PublishXRef by group Id and PublishXRef.Id, matching gn-guile's
gn.data.dataset:get-bxd-publish-name-value-dict generalized beyond
BXD: PublishXRef.Id alone isn't unique across groups, only the pair
(InbredSetId, Id) is, the same way GeneNetwork2's
wqflask.api.router.trait_sample_data combines trait_name with a group
or dataset to resolve a Publish trait.
* src/lib.rs (GroupTraitLookup): New enum, distinguishes a missing
group from a missing trait in an existing group.
(get_group_trait_values_result): New function, looks up a group then
its trait, returning a GroupTraitLookup.
(group_trait_values): New handler for GET
/groups/{group}/traits/{trait_id}/values. 404s as group_not_found or
trait_not_found depending on what get_group_trait_values_result
found.
(app): Register it.
* tests/group_trait_values.rs, test/python/test_group_trait_values.py:
New files.
* tests/openapi.rs, test/python/test_openapi.py: Check the new path
is in the generated spec.
* README.md (GET /groups/{group}/traits/{trait_id}/values): Document
it, including that only Publish (phenotype) traits are supported so
far, not ProbeSet or Geno traits.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XDDpXvZBQat9uSgDeEMJ8d
Diffstat (limited to 'src')
-rw-r--r--src/db.rs31
-rw-r--r--src/lib.rs1
-rw-r--r--src/routes/groups.rs83
3 files changed, 115 insertions, 0 deletions
diff --git a/src/db.rs b/src/db.rs
index 7ada339..9ea0ab0 100644
--- a/src/db.rs
+++ b/src/db.rs
@@ -238,3 +238,34 @@ pub fn get_group_strains(
         },
     )
 }
+
+/// One strain's value for a published (phenotype) trait, matching
+/// GeneNetwork2's wqflask.api.router.trait_sample_data (the Publish
+/// branch, trimmed to just name and value).
+#[derive(Serialize, utoipa::ToSchema)]
+pub struct TraitValue {
+    pub name: String,
+    pub value: Option<f64>,
+}
+
+/// Fetch the per-strain values of one published trait (a PublishXRef
+/// row) within a group. Mirrors gn-guile's
+/// gn.data.dataset:get-bxd-publish-name-value-dict, generalized to any
+/// group rather than hardcoding InbredSetId=1 (BXD); PublishXRef.Id
+/// alone isn't unique across groups (only the pair (InbredSetId, Id)
+/// is), so group_id is required to pick the right trait, the same way
+/// GeneNetwork2's trait_sample_data combines trait_name with a group
+/// or dataset to resolve a Publish trait.
+pub fn get_group_trait_values(group_id: u16, trait_id: u32) -> Result<Vec<TraitValue>, mysql::Error> {
+    let pool = Pool::new(Opts::from_url(&sql_uri())?)?;
+    let mut conn = pool.get_conn()?;
+    conn.exec_map(
+        "SELECT Strain.Name, PublishData.value \
+         FROM PublishData, Strain, PublishXRef \
+         WHERE PublishXRef.InbredSetId = :group_id AND PublishXRef.Id = :trait_id \
+                AND PublishXRef.DataId = PublishData.Id AND PublishData.StrainId = Strain.Id \
+         ORDER BY Strain.Name",
+        mysql::params! { "group_id" => group_id, "trait_id" => trait_id },
+        |(name, value)| TraitValue { name, value },
+    )
+}
diff --git a/src/lib.rs b/src/lib.rs
index ccdafd8..c46b981 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -34,6 +34,7 @@ pub fn app() -> Router {
         .routes(routes!(routes::groups::groups))
         .routes(routes!(routes::groups::group_by_name))
         .routes(routes!(routes::groups::group_strains))
+        .routes(routes!(routes::groups::group_trait_values))
         .routes(routes!(routes::correlation::correlation))
         .split_for_parts();
     router
diff --git a/src/routes/groups.rs b/src/routes/groups.rs
index 7c32ae9..8a82c48 100644
--- a/src/routes/groups.rs
+++ b/src/routes/groups.rs
@@ -153,3 +153,86 @@ pub async fn group_strains(
         .with_next("/groups")
     })
 }
+
+/// What get_group_trait_values_result found, so the handler can tell a
+/// missing group from a missing trait and return the right 404.
+enum GroupTraitLookup {
+    GroupNotFound,
+    TraitNotFound,
+    Values(Vec<db::TraitValue>),
+}
+
+fn get_group_trait_values_result(
+    group: &str,
+    trait_id: u32,
+) -> Result<GroupTraitLookup, mysql::Error> {
+    match db::get_group_by_name(group)? {
+        None => Ok(GroupTraitLookup::GroupNotFound),
+        Some(group) => {
+            let values = db::get_group_trait_values(group.id, trait_id)?;
+            if values.is_empty() {
+                Ok(GroupTraitLookup::TraitNotFound)
+            } else {
+                Ok(GroupTraitLookup::Values(values))
+            }
+        }
+    }
+}
+
+#[utoipa::path(get, path = "/groups/{group}/traits/{trait_id}/values", summary = "Get one published trait's value in each of a group's strains", params(
+    ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id"),
+    ("trait_id" = u32, Path, description = "PublishXRef.Id of a published (phenotype) trait")
+), responses(
+    (status = 200, description = "The group's per-strain values for the trait", body = Vec<db::TraitValue>),
+    (status = 404, description = "No matching group, or no matching trait in that group", body = ApiError),
+    (status = 500, description = "Database error", body = ApiError)
+))]
+pub async fn group_trait_values(
+    Extension(request_id): Extension<RequestId>,
+    Path((group, trait_id)): Path<(String, u32)>,
+) -> Result<Json<Vec<db::TraitValue>>, ApiError> {
+    let rid = request_id_string(&request_id);
+    let not_found_group = group.clone();
+    tokio::task::spawn_blocking(move || get_group_trait_values_result(&group, trait_id))
+        .await
+        .map_err(|e| {
+            ApiError::new(
+                StatusCode::INTERNAL_SERVER_ERROR,
+                "internal_error",
+                "Internal error",
+                e.to_string(),
+                "group_trait_values",
+            )
+            .with_request_id(rid.clone())
+        })?
+        .map_err(|e| {
+            ApiError::new(
+                StatusCode::INTERNAL_SERVER_ERROR,
+                "database_error",
+                "Database error",
+                e.to_string(),
+                "group_trait_values",
+            )
+            .with_request_id(rid.clone())
+        })
+        .and_then(|lookup| match lookup {
+            GroupTraitLookup::Values(values) => Ok(Json(values)),
+            GroupTraitLookup::GroupNotFound => Err(ApiError::new(
+                StatusCode::NOT_FOUND,
+                "group_not_found",
+                "Group not found",
+                format!("No group matching '{not_found_group}'."),
+                "group_trait_values",
+            )
+            .with_request_id(rid.clone())
+            .with_next("/groups")),
+            GroupTraitLookup::TraitNotFound => Err(ApiError::new(
+                StatusCode::NOT_FOUND,
+                "trait_not_found",
+                "Trait not found",
+                format!("No trait {trait_id} in group '{not_found_group}'."),
+                "group_trait_values",
+            )
+            .with_request_id(rid)),
+        })
+}