tree with a modern linkage

This commit is contained in:
filipriec
2025-03-08 19:42:02 +01:00
parent ba672098c2
commit b0daa4ff18

View File

@@ -1,4 +1,4 @@
// server/src/table_definition/handlers/get_profile_tree.rs // src/table_definition/handlers/get_profile_tree.rs
use tonic::{Request, Response, Status}; use tonic::{Request, Response, Status};
use sqlx::PgPool; use sqlx::PgPool;
use common::proto::multieko2::{ use common::proto::multieko2::{
@@ -22,15 +22,25 @@ pub async fn get_profile_tree(
.map_err(|e| Status::internal(format!("Failed to fetch profiles: {}", e)))?; .map_err(|e| Status::internal(format!("Failed to fetch profiles: {}", e)))?;
for profile in profile_records { for profile in profile_records {
// Get all tables with their dependencies // Get all tables with their dependencies from the links table
let tables = sqlx::query!( let tables = sqlx::query!(
r#" r#"
SELECT SELECT
td.table_name, td.table_name,
ltd.table_name as "linked_table_name?" COALESCE(
json_agg(
json_build_object(
'linked_name', ltd.table_name,
'required', tdl.is_required
)
) FILTER (WHERE ltd.id IS NOT NULL),
'[]'
) as dependencies
FROM table_definitions td FROM table_definitions td
LEFT JOIN table_definitions ltd ON td.linked_table_id = ltd.id LEFT JOIN table_definition_links tdl ON td.id = tdl.source_table_id
LEFT JOIN table_definitions ltd ON tdl.linked_table_id = ltd.id
WHERE td.profile_id = $1 WHERE td.profile_id = $1
GROUP BY td.table_name
"#, "#,
profile.id profile.id
) )
@@ -38,22 +48,23 @@ pub async fn get_profile_tree(
.await .await
.map_err(|e| Status::internal(format!("Failed to fetch tables: {}", e)))?; .map_err(|e| Status::internal(format!("Failed to fetch tables: {}", e)))?;
// Group dependencies per table
let mut table_map = std::collections::HashMap::new();
for table in tables {
let entry = table_map.entry(table.table_name)
.or_insert(Vec::new());
if let Some(linked) = table.linked_table_name {
entry.push(linked);
}
}
// Convert to protobuf format // Convert to protobuf format
let proto_tables = table_map.into_iter() let proto_tables = tables.into_iter()
.map(|(name, depends_on)| Table { .map(|record| {
name, // Handle the Option<Value> properly
depends_on let dependencies = record.dependencies
.map(|val| serde_json::from_value::<Vec<serde_json::Value>>(val))
.transpose()
.unwrap_or_else(|_| Some(Vec::new()))
.unwrap_or_default();
Table {
name: record.table_name,
depends_on: dependencies
.into_iter()
.filter_map(|d| d["linked_name"].as_str().map(|s| s.to_string()))
.collect()
}
}) })
.collect(); .collect();