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(email): include all labels for each thread in previews endpoints (#344)

Evan Hutnikadab38595573
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 657d8be7b7..e448da7056 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2835,6 +2835,7 @@ dependencies = [
"chrono",
"doppleganger",
"frecency",
+ "macro_db_migrator",
"macro_user_id",
"model-entity",
"model-error-response",
diff --git a/rust/cloud-storage/email/.sqlx/query-f33cae291a4c2d553de0f61e5c32bcc09c162de5ca96535567a6e307e86b5fb9.json b/rust/cloud-storage/email/.sqlx/query-f33cae291a4c2d553de0f61e5c32bcc09c162de5ca96535567a6e307e86b5fb9.json
new file mode 100644
index 0000000000..1ac755ddfb
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-f33cae291a4c2d553de0f61e5c32bcc09c162de5ca96535567a6e307e86b5fb9.json
@@ -0,0 +1,101 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT DISTINCT ON (l.id, m.thread_id)\n l.id,\n m.thread_id as \"thread_id!\",\n l.link_id,\n l.provider_label_id,\n l.name,\n l.created_at,\n l.message_list_visibility as \"message_list_visibility: _\",\n l.label_list_visibility as \"label_list_visibility: _\",\n l.type as \"type_: _\"\n FROM\n email_messages m\n JOIN email_message_labels ml ON m.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m.thread_id = ANY($1)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "thread_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "link_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "provider_label_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "name",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "message_list_visibility: _",
+ "type_info": {
+ "Custom": {
+ "name": "email_message_list_visibility_enum",
+ "kind": {
+ "Enum": [
+ "Show",
+ "Hide"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 7,
+ "name": "label_list_visibility: _",
+ "type_info": {
+ "Custom": {
+ "name": "email_label_list_visibility_enum",
+ "kind": {
+ "Enum": [
+ "LabelShow",
+ "LabelShowIfUnread",
+ "LabelHide"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 8,
+ "name": "type_: _",
+ "type_info": {
+ "Custom": {
+ "name": "email_label_type_enum",
+ "kind": {
+ "Enum": [
+ "System",
+ "User"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "f33cae291a4c2d553de0f61e5c32bcc09c162de5ca96535567a6e307e86b5fb9"
+}
diff --git a/rust/cloud-storage/email/Cargo.toml b/rust/cloud-storage/email/Cargo.toml
index 4fdd64e6ab..4a053952eb 100644
--- a/rust/cloud-storage/email/Cargo.toml
+++ b/rust/cloud-storage/email/Cargo.toml
@@ -41,4 +41,5 @@ utoipa = { workspace = true, optional = true }
uuid = { workspace = true }
[dev-dependencies]
+macro_db_migrator = { path = "../macro_db_migrator"}
serde_json = { workspace = true }
diff --git a/rust/cloud-storage/email/fixtures/email_labels.sql b/rust/cloud-storage/email/fixtures/email_labels.sql
new file mode 100644
index 0000000000..0a94d0e9f8
--- /dev/null
+++ b/rust/cloud-storage/email/fixtures/email_labels.sql
@@ -0,0 +1,73 @@
+-- Fixture for testing labels_by_thread_ids query
+-- Sets up threads, messages, labels, and their relationships
+
+-- Insert test link
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES
+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro1', 'user1', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+-- Insert test threads
+INSERT INTO email_threads (id, provider_id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES
+ ('11111111-1111-1111-1111-111111111111', 'thread1', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', true, false, NOW(), NOW()),
+ ('22222222-2222-2222-2222-222222222222', 'thread2', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', true, false, NOW(), NOW()),
+ ('33333333-3333-3333-3333-333333333333', 'thread3', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', true, false, NOW(), NOW()),
+ ('44444444-4444-4444-4444-444444444444', 'thread4', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', true, false, NOW(), NOW()),
+ ('55555555-5555-5555-5555-555555555555', 'thread5', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', true, false, NOW(), NOW());
+
+-- Insert test labels
+INSERT INTO email_labels (id, link_id, provider_label_id, name, message_list_visibility, label_list_visibility, type, created_at)
+VALUES
+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'INBOX', 'INBOX', 'Show', 'LabelShow', 'System', NOW()),
+ ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'IMPORTANT', 'IMPORTANT', 'Show', 'LabelShow', 'System', NOW()),
+ ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'SENT', 'SENT', 'Show', 'LabelShow', 'System', NOW()),
+ ('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Label_123', 'MyCustomLabel', 'Show', 'LabelShow', 'User', NOW());
+
+-- Insert test messages
+-- Thread 1: 1 message with INBOX and IMPORTANT labels
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, created_at, updated_at)
+VALUES
+ ('11111111-aaaa-aaaa-aaaa-111111111111', '11111111-1111-1111-1111-111111111111', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg1', NOW(), NOW());
+
+-- Thread 2: 1 message with INBOX and SENT labels
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, created_at, updated_at)
+VALUES
+ ('22222222-aaaa-aaaa-aaaa-222222222222', '22222222-2222-2222-2222-222222222222', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg2', NOW(), NOW());
+
+-- Thread 3: 2 messages both with INBOX label (test deduplication)
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, created_at, updated_at)
+VALUES
+ ('33333333-aaaa-aaaa-aaaa-333333333333', '33333333-3333-3333-3333-333333333333', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg3a', NOW(), NOW()),
+ ('33333333-bbbb-bbbb-bbbb-333333333333', '33333333-3333-3333-3333-333333333333', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg3b', NOW(), NOW());
+
+-- Thread 4: No messages (test empty case)
+
+-- Thread 5: 1 message with both system and user labels
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, created_at, updated_at)
+VALUES
+ ('55555555-aaaa-aaaa-aaaa-555555555555', '55555555-5555-5555-5555-555555555555', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg5', NOW(), NOW());
+
+-- Insert message-label relationships
+-- Thread 1 message: INBOX + IMPORTANT
+INSERT INTO email_message_labels (message_id, label_id)
+VALUES
+ ('11111111-aaaa-aaaa-aaaa-111111111111', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'),
+ ('11111111-aaaa-aaaa-aaaa-111111111111', 'cccccccc-cccc-cccc-cccc-cccccccccccc');
+
+-- Thread 2 message: INBOX + SENT
+INSERT INTO email_message_labels (message_id, label_id)
+VALUES
+ ('22222222-aaaa-aaaa-aaaa-222222222222', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'),
+ ('22222222-aaaa-aaaa-aaaa-222222222222', 'dddddddd-dddd-dddd-dddd-dddddddddddd');
+
+-- Thread 3 messages: Both have INBOX (test deduplication)
+INSERT INTO email_message_labels (message_id, label_id)
+VALUES
+ ('33333333-aaaa-aaaa-aaaa-333333333333', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'),
+ ('33333333-bbbb-bbbb-bbbb-333333333333', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb');
+
+-- Thread 5 message: INBOX (system) + MyCustomLabel (user)
+INSERT INTO email_message_labels (message_id, label_id)
+VALUES
+ ('55555555-aaaa-aaaa-aaaa-555555555555', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'),
+ ('55555555-aaaa-aaaa-aaaa-555555555555', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee');
\ No newline at end of file
diff --git a/rust/cloud-storage/email/justfile b/rust/cloud-storage/email/justfile
new file mode 100644
index 0000000000..298576ed00
--- /dev/null
+++ b/rust/cloud-storage/email/justfile
@@ -0,0 +1,6 @@
+DATABASE_URL := "postgres://user:password@localhost:5432/macrodb"
+
+mod sqlx '../sqlx.just'
+
+prepare_db:
+ just sqlx::prepare_db {{ DATABASE_URL }} --all-features
diff --git a/rust/cloud-storage/email/src/domain/models.rs b/rust/cloud-storage/email/src/domain/models.rs
index e1c2b1780c..993d0ebec3 100644
--- a/rust/cloud-storage/email/src/domain/models.rs
+++ b/rust/cloud-storage/email/src/domain/models.rs
@@ -87,6 +87,7 @@ pub struct EnrichedEmailThreadPreview {
pub thread: EmailThreadPreview,
pub attachments: Vec<Attachment>,
pub attachments_macro: Vec<AttachmentMacro>,
+ pub labels: Vec<Label>,
pub frecency_score: Option<AggregateFrecency>,
pub participants: Vec<Contact>,
}
@@ -193,3 +194,35 @@ pub struct GetEmailsRequest {
pub limit: Option<u32>,
pub query: Query<Uuid, SimpleSortMethod, ()>,
}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum MessageListVisibility {
+ Show,
+ Hide,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum LabelListVisibility {
+ LabelShow,
+ LabelShowIfUnread,
+ LabelHide,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum LabelType {
+ System,
+ User,
+}
+
+#[derive(Debug, Clone)]
+pub struct Label {
+ pub id: Uuid,
+ pub(crate) thread_id: Uuid,
+ pub link_id: Uuid,
+ pub provider_label_id: String,
+ pub name: String,
+ pub created_at: DateTime<Utc>,
+ pub message_list_visibility: MessageListVisibility,
+ pub label_list_visibility: LabelListVisibility,
+ pub type_: LabelType,
+}
diff --git a/rust/cloud-storage/email/src/domain/ports.rs b/rust/cloud-storage/email/src/domain/ports.rs
index 1e3e372f87..732f99662a 100644
--- a/rust/cloud-storage/email/src/domain/ports.rs
+++ b/rust/cloud-storage/email/src/domain/ports.rs
@@ -1,6 +1,6 @@
use crate::domain::models::{
Attachment, AttachmentMacro, Contact, EmailErr, EmailThreadPreview, EnrichedEmailThreadPreview,
- GetEmailsRequest, PreviewCursorQuery,
+ GetEmailsRequest, Label, PreviewCursorQuery,
};
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{PaginatedCursor, SimpleSortMethod};
@@ -28,6 +28,10 @@ pub trait EmailRepo: Send + Sync + 'static {
&self,
thread_ids: &[Uuid],
) -> impl Future<Output = Result<Vec<Contact>, Self::Err>> + Send;
+ fn labels_by_thread_ids(
+ &self,
+ thread_ids: &[Uuid],
+ ) -> impl Future<Output = Result<Vec<Label>, Self::Err>> + Send;
}
pub trait EmailService: Send + Sync + 'static {
diff --git a/rust/cloud-storage/email/src/domain/service.rs b/rust/cloud-storage/email/src/domain/service.rs
index d63ebd8d79..5a9baeb393 100644
--- a/rust/cloud-storage/email/src/domain/service.rs
+++ b/rust/cloud-storage/email/src/domain/service.rs
@@ -84,11 +84,13 @@ where
attachment_map_result,
macro_attachment_map_result,
participant_result,
+ labels_result,
frecency_scores,
) = tokio::join!(
self.email_repo.attachments_by_thread_ids(&thread_ids),
self.email_repo.macro_attachments_by_thread_ids(&thread_ids),
self.email_repo.contacts_by_thread_ids(&thread_ids),
+ self.email_repo.labels_by_thread_ids(&thread_ids),
self.frecency_service
.get_frecencies_by_ids(frecency_request)
);
@@ -105,6 +107,10 @@ where
.map_err(anyhow::Error::from)?
.into_iter()
.group_by(|v| v.thread_id);
+ let mut labels_map = labels_result
+ .map_err(anyhow::Error::from)?
+ .into_iter()
+ .group_by(|v| v.thread_id);
let mut frecency_scores_map: HashMap<AggregateId<'static>, FrecencyData> =
frecency_scores?.into_inner();
@@ -120,6 +126,7 @@ where
EnrichedEmailThreadPreview {
attachments: attachment_map.remove(&thread.id).unwrap_or_default(),
attachments_macro: macro_attachment_map.remove(&thread.id).unwrap_or_default(),
+ labels: labels_map.remove(&thread.id).unwrap_or_default(),
participants: participant_map.remove(&thread.id).unwrap_or_default(),
frecency_score: frecency_scores_map
.remove(&id)
diff --git a/rust/cloud-storage/email/src/inbound/axum/api_types.rs b/rust/cloud-storage/email/src/inbound/axum/api_types.rs
index c2a8d9d52b..994dffe232 100644
--- a/rust/cloud-storage/email/src/inbound/axum/api_types.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/api_types.rs
@@ -8,7 +8,8 @@ use utoipa::ToSchema;
use uuid::Uuid;
use crate::domain::models::{
- Attachment, AttachmentMacro, Contact, EmailThreadPreview, EnrichedEmailThreadPreview,
+ Attachment, AttachmentMacro, Contact, EmailThreadPreview, EnrichedEmailThreadPreview, Label,
+ LabelListVisibility, LabelType, MessageListVisibility,
};
/// common types of sorts based on timestamps
@@ -48,6 +49,7 @@ struct ApiThreadPreviewCursor {
macro_attachments: Vec<ApiAttachmentMacro>,
#[dg(rename = "participants")]
contacts: Vec<ApiContact>,
+ labels: Vec<ApiLabel>,
#[dg(map = map_frecency)]
frecency_score: Option<f64>,
}
@@ -138,6 +140,46 @@ pub struct ApiContact {
sfs_photo_url: Option<String>,
}
+#[derive(Debug, ToSchema, Serialize, Deserialize, Doppleganger)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+#[serde(rename_all = "camelCase")]
+#[dg(backward = Label)]
+pub struct ApiLabel {
+ id: Uuid,
+ link_id: Uuid,
+ provider_label_id: String,
+ name: String,
+ created_at: DateTime<Utc>,
+ message_list_visibility: ApiMessageListVisibility,
+ label_list_visibility: ApiLabelListVisibility,
+ type_: ApiLabelType,
+}
+
+#[derive(Debug, ToSchema, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Doppleganger)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+#[dg(backward = MessageListVisibility)]
+pub enum ApiMessageListVisibility {
+ Show,
+ Hide,
+}
+
+#[derive(Debug, ToSchema, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Doppleganger)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+#[dg(backward = LabelListVisibility)]
+pub enum ApiLabelListVisibility {
+ LabelShow,
+ LabelShowIfUnread,
+ LabelHide,
+}
+
+#[derive(Debug, ToSchema, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Doppleganger)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+#[dg(backward = LabelType)]
+pub enum ApiLabelType {
+ System,
+ User,
+}
+
#[derive(Debug, ToSchema, Serialize, Deserialize)]
#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
pub struct ApiPaginatedThreadCursor {
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo.rs
index 05d1547060..2a35ef36bf 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo.rs
@@ -1,3 +1,4 @@
+use crate::domain::models::Label;
use crate::domain::{
models::{
Attachment, AttachmentMacro, Contact, EmailThreadPreview, PreviewCursorQuery, PreviewView,
@@ -13,6 +14,8 @@ use uuid::Uuid;
mod db_types;
mod queries;
+#[cfg(test)]
+mod test;
#[derive(Clone)]
pub struct EmailPgRepo {
@@ -193,4 +196,35 @@ impl EmailRepo for EmailPgRepo {
.map(ThreadContactResult::mirror)
.collect())
}
+
+ async fn labels_by_thread_ids(&self, thread_ids: &[Uuid]) -> Result<Vec<Label>, Self::Err> {
+ // Query all labels for email_messages in the provided threads
+ // Include thread_id in the result set
+ Ok(sqlx::query_as!(
+ LabelDbRow,
+ r#"
+ SELECT DISTINCT ON (l.id, m.thread_id)
+ l.id,
+ m.thread_id as "thread_id!",
+ l.link_id,
+ l.provider_label_id,
+ l.name,
+ l.created_at,
+ l.message_list_visibility as "message_list_visibility: _",
+ l.label_list_visibility as "label_list_visibility: _",
+ l.type as "type_: _"
+ FROM
+ email_messages m
+ JOIN email_message_labels ml ON m.id = ml.message_id
+ JOIN email_labels l ON ml.label_id = l.id
+ WHERE m.thread_id = ANY($1)
+ "#,
+ thread_ids
+ )
+ .fetch_all(&self.pool)
+ .await?
+ .into_iter()
+ .map(LabelDbRow::mirror)
+ .collect())
+ }
}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs
index f1c4ddc0c7..86b38b78b2 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs
@@ -1,4 +1,7 @@
-use crate::domain::models::{Attachment, AttachmentMacro, EmailThreadPreview};
+use crate::domain::models::{
+ Attachment, AttachmentMacro, EmailThreadPreview, Label, LabelListVisibility, LabelType,
+ MessageListVisibility,
+};
use chrono::{DateTime, Utc};
use doppleganger::Doppleganger;
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
@@ -57,6 +60,53 @@ pub struct ThreadPreviewCursorDbRow {
pub updated_at: DateTime<Utc>,
}
+#[derive(Debug, sqlx::Type, Clone, Copy, PartialEq, Eq, Doppleganger)]
+#[dg(forward = MessageListVisibility)]
+#[sqlx(
+ type_name = "email_message_list_visibility_enum",
+ rename_all = "PascalCase"
+)]
+pub enum MessageListVisibilityDbRow {
+ Show,
+ Hide,
+}
+
+#[derive(Debug, sqlx::Type, Clone, Copy, PartialEq, Eq, Doppleganger)]
+#[dg(forward = LabelListVisibility)]
+#[sqlx(
+ type_name = "email_label_list_visibility_enum",
+ rename_all = "PascalCase"
+)]
+#[expect(clippy::enum_variant_names, reason = "Matches names from Gmail API")]
+pub enum LabelListVisibilityDbRow {
+ LabelShow,
+ LabelShowIfUnread,
+ LabelHide,
+}
+
+#[derive(Debug, sqlx::Type, Clone, Copy, PartialEq, Eq, Doppleganger)]
+#[dg(forward = LabelType)]
+#[sqlx(type_name = "email_label_type_enum", rename_all = "PascalCase")]
+pub enum LabelTypeDbRow {
+ System,
+ User,
+}
+
+#[derive(Doppleganger)]
+#[dg(forward = Label)]
+#[derive(Debug, Clone)]
+pub struct LabelDbRow {
+ pub id: Uuid,
+ pub thread_id: Uuid,
+ pub link_id: Uuid,
+ pub provider_label_id: String,
+ pub name: String,
+ pub created_at: DateTime<Utc>,
+ pub message_list_visibility: MessageListVisibilityDbRow,
+ pub label_list_visibility: LabelListVisibilityDbRow,
+ pub type_: LabelTypeDbRow,
+}
+
impl ThreadPreviewCursorDbRow {
pub fn with_user_id(self, owner_id: MacroUserIdStr<'_>) -> EmailThreadPreview {
let ThreadPreviewCursorDbRow {
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test.rs
new file mode 100644
index 0000000000..e90ab55264
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test.rs
@@ -0,0 +1,137 @@
+use super::*;
+use crate::domain::models::LabelType;
+use crate::domain::ports::EmailRepo;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::{Pool, Postgres};
+use uuid::Uuid;
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_labels"))
+)]
+async fn test_labels_by_thread_ids_single_thread(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS; // Dummy reference for IDE
+ let repo = EmailPgRepo::new(pool);
+
+ let thread_ids = vec![Uuid::parse_str("11111111-1111-1111-1111-111111111111")?];
+ let labels = repo.labels_by_thread_ids(&thread_ids).await?;
+
+ assert_eq!(labels.len(), 2, "Thread 1 should have 2 labels");
+
+ let inbox_label = labels.iter().find(|l| l.name == "INBOX");
+ assert!(inbox_label.is_some(), "Should have INBOX label");
+
+ let important_label = labels.iter().find(|l| l.name == "IMPORTANT");
+ assert!(important_label.is_some(), "Should have IMPORTANT label");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_labels"))
+)]
+async fn test_labels_by_thread_ids_multiple_threads(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let thread_ids = vec![
+ Uuid::parse_str("11111111-1111-1111-1111-111111111111")?,
+ Uuid::parse_str("22222222-2222-2222-2222-222222222222")?,
+ ];
+ let labels = repo.labels_by_thread_ids(&thread_ids).await?;
+
+ // Thread 1 has 2 labels (INBOX, IMPORTANT)
+ // Thread 2 has 2 labels (INBOX, SENT)
+ // Should get four unique labels as it's distinct across (thread_id, label_id)
+ assert_eq!(
+ labels.len(),
+ 4,
+ "Should have 4 unique labels across both threads"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_labels"))
+)]
+async fn test_labels_by_thread_ids_no_duplicate_labels_same_thread(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ // Thread 3 has multiple messages with the same label
+ let thread_ids = vec![Uuid::parse_str("33333333-3333-3333-3333-333333333333")?];
+ let labels = repo.labels_by_thread_ids(&thread_ids).await?;
+
+ assert_eq!(
+ labels.len(),
+ 1,
+ "Should have only 1 label despite multiple messages having it"
+ );
+ assert_eq!(labels[0].name, "INBOX");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_labels"))
+)]
+async fn test_labels_by_thread_ids_thread_with_no_labels(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let thread_ids = vec![Uuid::parse_str("44444444-4444-4444-4444-444444444444")?];
+ let labels = repo.labels_by_thread_ids(&thread_ids).await?;
+
+ assert_eq!(
+ labels.len(),
+ 0,
+ "Thread with no messages/labels should return empty"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_labels"))
+)]
+async fn test_labels_by_thread_ids_empty_input(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let thread_ids: Vec<Uuid> = vec![];
+ let labels = repo.labels_by_thread_ids(&thread_ids).await?;
+
+ assert_eq!(labels.len(), 0, "Empty input should return empty result");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_labels"))
+)]
+async fn test_labels_by_thread_ids_different_label_types(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let thread_ids = vec![Uuid::parse_str("55555555-5555-5555-5555-555555555555")?];
+ let labels = repo.labels_by_thread_ids(&thread_ids).await?;
+
+ assert_eq!(labels.len(), 2, "Should have both system and user labels");
+
+ let system_label = labels.iter().find(|l| l.name == "INBOX");
+ assert!(system_label.is_some());
+ assert_eq!(system_label.unwrap().type_, LabelType::System);
+
+ let user_label = labels.iter().find(|l| l.name == "MyCustomLabel");
+ assert!(user_label.is_some());
+ assert_eq!(user_label.unwrap().type_, LabelType::User);
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/sqlx.just b/rust/cloud-storage/sqlx.just
index f918dca661..2531634025 100644
--- a/rust/cloud-storage/sqlx.just
+++ b/rust/cloud-storage/sqlx.just
@@ -7,8 +7,8 @@ migrate_db $DATABASE_URL:
cargo sqlx migrate run
[no-cd]
-prepare_db $DATABASE_URL:
- cargo sqlx prepare
+prepare_db $DATABASE_URL *FLAGS:
+ cargo sqlx prepare -- {{ FLAGS }}
[no-cd]
drop_db $DATABASE_URL *FLAGS: