Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(comms): add in pg outbound port for user repo (#1139)

Will Hutchinsone57c0e3fbaf9
diff --git a/rust/cloud-storage/comms/.sqlx/query-137986b2287f8a7e8d9023d6f9bfee888a6e18170f84df631df81e3e84158348.json b/rust/cloud-storage/comms/.sqlx/query-137986b2287f8a7e8d9023d6f9bfee888a6e18170f84df631df81e3e84158348.json
new file mode 100644
index 0000000000..cbf66c3866
--- /dev/null
+++ b/rust/cloud-storage/comms/.sqlx/query-137986b2287f8a7e8d9023d6f9bfee888a6e18170f84df631df81e3e84158348.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n u.id as user_profile_id,\n mui.first_name,\n mui.last_name\n FROM macro_user_info mui\n JOIN \"User\" u ON mui.macro_user_id = u.macro_user_id\n WHERE u.id = ANY($1)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_profile_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "first_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "last_name",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ true
+ ]
+ },
+ "hash": "137986b2287f8a7e8d9023d6f9bfee888a6e18170f84df631df81e3e84158348"
+}
diff --git a/rust/cloud-storage/comms/src/outbound/fixtures/users.sql b/rust/cloud-storage/comms/src/outbound/fixtures/users.sql
new file mode 100644
index 0000000000..2b1499f73e
--- /dev/null
+++ b/rust/cloud-storage/comms/src/outbound/fixtures/users.sql
@@ -0,0 +1,20 @@
+-- Test fixture for PgUserRepo tests
+-- Inserts test users with associated user info
+
+-- First insert into macro_user (parent table for both User and macro_user_info)
+INSERT INTO "macro_user" (id, username, email, stripe_customer_id) VALUES
+ ('11111111-1111-1111-1111-111111111111', 'user1', '[email protected]', 'stripe_1'),
+ ('22222222-2222-2222-2222-222222222222', 'user2', '[email protected]', 'stripe_2'),
+ ('33333333-3333-3333-3333-333333333333', 'user3', '[email protected]', 'stripe_3');
+
+-- Insert user info (first_name, last_name)
+INSERT INTO "macro_user_info" (macro_user_id, first_name, last_name) VALUES
+ ('11111111-1111-1111-1111-111111111111', 'John', 'Doe'),
+ ('22222222-2222-2222-2222-222222222222', NULL, NULL),
+ ('33333333-3333-3333-3333-333333333333', 'Jane', 'Smith');
+
+-- Insert User records (id format: macro|{EMAIL})
+INSERT INTO "User" (id, email, macro_user_id) VALUES
+ ('macro|[email protected]', '[email protected]', '11111111-1111-1111-1111-111111111111'),
+ ('macro|[email protected]', '[email protected]', '22222222-2222-2222-2222-222222222222'),
+ ('macro|[email protected]', '[email protected]', '33333333-3333-3333-3333-333333333333');
diff --git a/rust/cloud-storage/comms/src/outbound/postgres.rs b/rust/cloud-storage/comms/src/outbound/postgres.rs
index 99bb43dbec..9c44293db9 100644
--- a/rust/cloud-storage/comms/src/outbound/postgres.rs
+++ b/rust/cloud-storage/comms/src/outbound/postgres.rs
@@ -1 +1,2 @@
pub mod comms_repo;
+pub mod user_repo;
diff --git a/rust/cloud-storage/comms/src/outbound/postgres/user_repo/mod.rs b/rust/cloud-storage/comms/src/outbound/postgres/user_repo/mod.rs
new file mode 100644
index 0000000000..7cfde71a89
--- /dev/null
+++ b/rust/cloud-storage/comms/src/outbound/postgres/user_repo/mod.rs
@@ -0,0 +1,72 @@
+//! Database-backed implementation of UserRepo that queries MacroDB directly.
+
+use std::collections::HashSet;
+
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use rootcause::Report;
+use sqlx::PgPool;
+
+use crate::domain::models::UserName;
+use crate::domain::ports::UserRepo;
+
+#[cfg(test)]
+mod test;
+
+/// Fetches user names from the database for the given user profile IDs.
+///
+/// This queries the `macro_user_info` table joined with the `User` table
+/// to retrieve first and last names for users.
+#[tracing::instrument(skip(db), err)]
+async fn get_names_for_ids(
+ db: &PgPool,
+ ids: &[MacroUserIdStr<'_>],
+) -> Result<Vec<UserName>, Report> {
+ let rows = sqlx::query!(
+ r#"
+ SELECT
+ u.id as user_profile_id,
+ mui.first_name,
+ mui.last_name
+ FROM macro_user_info mui
+ JOIN "User" u ON mui.macro_user_id = u.macro_user_id
+ WHERE u.id = ANY($1)
+ "#,
+ &ids.iter().map(|s| s.to_string()).collect::<Vec<String>>()
+ )
+ .fetch_all(db)
+ .await?;
+
+ let names = rows
+ .into_iter()
+ .map(|row| UserName {
+ id: MacroUserIdStr::parse_from_str(&row.user_profile_id)
+ .expect("valid macro user id from db")
+ .into_owned(),
+ first_name: row.first_name,
+ last_name: row.last_name,
+ })
+ .collect();
+
+ Ok(names)
+}
+
+/// Database-backed implementation of UserRepo.
+pub struct PgUserRepo {
+ pool: PgPool,
+}
+
+impl PgUserRepo {
+ /// Creates a new PgUserRepo with the given database connection pool.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+impl UserRepo for PgUserRepo {
+ async fn get_names_for_ids(
+ &self,
+ ids: HashSet<MacroUserIdStr<'_>>,
+ ) -> Result<Vec<UserName>, Report> {
+ get_names_for_ids(&self.pool, &ids.into_iter().collect::<Vec<_>>()).await
+ }
+}
diff --git a/rust/cloud-storage/comms/src/outbound/postgres/user_repo/test.rs b/rust/cloud-storage/comms/src/outbound/postgres/user_repo/test.rs
new file mode 100644
index 0000000000..fa90093a3b
--- /dev/null
+++ b/rust/cloud-storage/comms/src/outbound/postgres/user_repo/test.rs
@@ -0,0 +1,102 @@
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::Pool;
+
+use super::get_names_for_ids;
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("users"))
+)]
+async fn test_get_single_user_name(pool: Pool<sqlx::Postgres>) {
+ let ids = vec![MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()];
+
+ let names = get_names_for_ids(&pool, &ids).await.unwrap();
+
+ assert_eq!(names.len(), 1);
+ assert_eq!(names[0].id.as_ref(), "macro|[email protected]");
+ assert_eq!(names[0].first_name.as_deref(), Some("John"));
+ assert_eq!(names[0].last_name.as_deref(), Some("Doe"));
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("users"))
+)]
+async fn test_get_multiple_user_names(pool: Pool<sqlx::Postgres>) {
+ let ids = vec![
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ ];
+
+ let names = get_names_for_ids(&pool, &ids).await.unwrap();
+
+ assert_eq!(names.len(), 3);
+
+ // Find each user in the results (order not guaranteed)
+ let user1 = names
+ .iter()
+ .find(|n| n.id.as_ref() == "macro|[email protected]")
+ .expect("user1 should be present");
+ assert_eq!(user1.first_name.as_deref(), Some("John"));
+ assert_eq!(user1.last_name.as_deref(), Some("Doe"));
+
+ let user2 = names
+ .iter()
+ .find(|n| n.id.as_ref() == "macro|[email protected]")
+ .expect("user2 should be present");
+ assert_eq!(user2.first_name, None);
+ assert_eq!(user2.last_name, None);
+
+ let user3 = names
+ .iter()
+ .find(|n| n.id.as_ref() == "macro|[email protected]")
+ .expect("user3 should be present");
+ assert_eq!(user3.first_name.as_deref(), Some("Jane"));
+ assert_eq!(user3.last_name.as_deref(), Some("Smith"));
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("users"))
+)]
+async fn test_get_user_names_with_nonexistent_ids(pool: Pool<sqlx::Postgres>) {
+ let ids = vec![
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ ];
+
+ let names = get_names_for_ids(&pool, &ids).await.unwrap();
+
+ // Should only return the one that exists
+ assert_eq!(names.len(), 1);
+ assert_eq!(names[0].id.as_ref(), "macro|[email protected]");
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("users"))
+)]
+async fn test_get_user_names_empty_input(pool: Pool<sqlx::Postgres>) {
+ let ids: Vec<MacroUserIdStr<'_>> = vec![];
+
+ let names = get_names_for_ids(&pool, &ids).await.unwrap();
+
+ assert!(names.is_empty());
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("users"))
+)]
+async fn test_get_user_names_all_nonexistent(pool: Pool<sqlx::Postgres>) {
+ let ids = vec![
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ ];
+
+ let names = get_names_for_ids(&pool, &ids).await.unwrap();
+
+ assert!(names.is_empty());
+}