Files
Oxicloud/src/infrastructure/repositories/pg/contact_pg_repository.rs
T

379 lines
14 KiB
Rust
Raw Normal View History

2025-04-13 01:04:04 +02:00
use async_trait::async_trait;
use chrono::Utc;
2026-02-14 01:29:34 +01:00
use serde_json::Value as JsonValue;
use sqlx::{PgPool, Row, types::Uuid};
2025-04-13 01:04:04 +02:00
use std::sync::Arc;
use super::contact_persistence_dto::{
2026-02-14 01:29:34 +01:00
AddressPersistenceDto, EmailPersistenceDto, PhonePersistenceDto, addresses_from_persistence,
addresses_to_persistence, emails_from_persistence, emails_to_persistence,
phones_from_persistence, phones_to_persistence,
};
2026-02-14 01:29:34 +01:00
use crate::common::errors::DomainError;
use crate::domain::entities::contact::Contact;
use crate::domain::repositories::contact_repository::{ContactRepository, ContactRepositoryResult};
2025-04-13 01:04:04 +02:00
pub struct ContactPgRepository {
pool: Arc<PgPool>,
}
impl ContactPgRepository {
pub fn new(pool: Arc<PgPool>) -> Self {
Self { pool }
}
/// Maps a database row to a Contact domain entity
fn row_to_contact(row: &sqlx::postgres::PgRow) -> Result<Contact, DomainError> {
let email_json: JsonValue = row.get("email");
let phone_json: JsonValue = row.get("phone");
let address_json: JsonValue = row.get("address");
let emails = serde_json::from_value::<Vec<EmailPersistenceDto>>(email_json)
.map(emails_from_persistence)
.unwrap_or_default();
let phones = serde_json::from_value::<Vec<PhonePersistenceDto>>(phone_json)
.map(phones_from_persistence)
.unwrap_or_default();
let addresses = serde_json::from_value::<Vec<AddressPersistenceDto>>(address_json)
.map(addresses_from_persistence)
.unwrap_or_default();
Ok(Contact::from_raw(
row.get("id"),
row.get("address_book_id"),
row.get("uid"),
row.get::<Option<String>, _>("full_name"),
row.get::<Option<String>, _>("first_name"),
row.get::<Option<String>, _>("last_name"),
row.get::<Option<String>, _>("nickname"),
emails,
phones,
addresses,
row.get::<Option<String>, _>("organization"),
row.get::<Option<String>, _>("title"),
row.get::<Option<String>, _>("notes"),
row.get::<Option<String>, _>("photo_url"),
row.get("birthday"),
row.get("anniversary"),
row.get("vcard"),
row.get("etag"),
row.get("created_at"),
row.get("updated_at"),
))
}
2025-04-13 01:04:04 +02:00
}
#[async_trait]
impl ContactRepository for ContactPgRepository {
async fn create_contact(&self, contact: Contact) -> ContactRepositoryResult<Contact> {
// Convert domain entities to persistence DTOs for JSONB serialization
let email_dtos = emails_to_persistence(contact.email());
let phone_dtos = phones_to_persistence(contact.phone());
let address_dtos = addresses_to_persistence(contact.address());
2026-02-14 01:29:34 +01:00
let email_json = serde_json::to_value(&email_dtos).unwrap_or(JsonValue::Null);
let phone_json = serde_json::to_value(&phone_dtos).unwrap_or(JsonValue::Null);
let address_json = serde_json::to_value(&address_dtos).unwrap_or(JsonValue::Null);
2026-02-14 01:29:34 +01:00
let row = sqlx::query(
2025-04-13 01:04:04 +02:00
r#"
INSERT INTO carddav.contacts (
id, address_book_id, uid, full_name, first_name, last_name, nickname,
email, phone, address, organization, title, notes, photo_url,
birthday, anniversary, vcard, etag, created_at, updated_at
)
VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14,
$15, $16, $17, $18, $19, $20
)
RETURNING
id, address_book_id, uid, full_name, first_name, last_name, nickname,
email, phone, address, organization, title, notes, photo_url,
birthday, anniversary, vcard, etag, created_at, updated_at
2026-02-14 01:29:34 +01:00
"#,
2025-04-13 01:04:04 +02:00
)
.bind(contact.id())
.bind(contact.address_book_id())
.bind(contact.uid())
.bind(contact.full_name_owned())
.bind(contact.first_name_owned())
.bind(contact.last_name_owned())
.bind(contact.nickname_owned())
2025-04-13 01:04:04 +02:00
.bind(email_json)
.bind(phone_json)
.bind(address_json)
.bind(contact.organization_owned())
.bind(contact.title_owned())
.bind(contact.notes_owned())
.bind(contact.photo_url_owned())
.bind(contact.birthday().copied())
.bind(contact.anniversary().copied())
.bind(contact.vcard())
.bind(contact.etag())
.bind(*contact.created_at())
.bind(*contact.updated_at())
2025-04-13 01:04:04 +02:00
.fetch_one(&*self.pool)
.await
.map_err(|e| DomainError::database_error(format!("Failed to create contact: {}", e)))?;
Self::row_to_contact(&row)
2025-04-13 01:04:04 +02:00
}
async fn update_contact(&self, contact: Contact) -> ContactRepositoryResult<Contact> {
let now = Utc::now();
// Convert domain entities to persistence DTOs for JSONB serialization
let email_dtos = emails_to_persistence(contact.email());
let phone_dtos = phones_to_persistence(contact.phone());
let address_dtos = addresses_to_persistence(contact.address());
2026-02-14 01:29:34 +01:00
let email_json = serde_json::to_value(&email_dtos).unwrap_or(JsonValue::Null);
let phone_json = serde_json::to_value(&phone_dtos).unwrap_or(JsonValue::Null);
let address_json = serde_json::to_value(&address_dtos).unwrap_or(JsonValue::Null);
2026-02-14 01:29:34 +01:00
2025-04-13 01:04:04 +02:00
// Create a clone of the contact with the updated timestamp
let mut updated_contact = contact.clone();
updated_contact.set_updated_at(now);
2026-02-14 01:29:34 +01:00
let row = sqlx::query(
2025-04-13 01:04:04 +02:00
r#"
UPDATE carddav.contacts
SET
full_name = $1,
first_name = $2,
last_name = $3,
nickname = $4,
email = $5,
phone = $6,
address = $7,
organization = $8,
title = $9,
notes = $10,
photo_url = $11,
birthday = $12,
anniversary = $13,
vcard = $14,
etag = $15,
updated_at = $16
WHERE id = $17
RETURNING
id, address_book_id, uid, full_name, first_name, last_name, nickname,
email, phone, address, organization, title, notes, photo_url,
birthday, anniversary, vcard, etag, created_at, updated_at
2026-02-14 01:29:34 +01:00
"#,
2025-04-13 01:04:04 +02:00
)
.bind(updated_contact.full_name_owned())
.bind(updated_contact.first_name_owned())
.bind(updated_contact.last_name_owned())
.bind(updated_contact.nickname_owned())
2025-04-13 01:04:04 +02:00
.bind(email_json)
.bind(phone_json)
.bind(address_json)
.bind(updated_contact.organization_owned())
.bind(updated_contact.title_owned())
.bind(updated_contact.notes_owned())
.bind(updated_contact.photo_url_owned())
.bind(updated_contact.birthday().copied())
.bind(updated_contact.anniversary().copied())
.bind(updated_contact.vcard())
.bind(updated_contact.etag())
2025-04-13 01:04:04 +02:00
.bind(now)
.bind(updated_contact.id())
2025-04-13 01:04:04 +02:00
.fetch_one(&*self.pool)
.await
.map_err(|e| DomainError::database_error(format!("Failed to update contact: {}", e)))?;
Self::row_to_contact(&row)
2025-04-13 01:04:04 +02:00
}
async fn delete_contact(&self, id: &Uuid) -> ContactRepositoryResult<()> {
sqlx::query(
r#"
DELETE FROM carddav.contacts
WHERE id = $1
2026-02-14 01:29:34 +01:00
"#,
2025-04-13 01:04:04 +02:00
)
.bind(id)
.execute(&*self.pool)
.await
.map_err(|e| DomainError::database_error(format!("Failed to delete contact: {}", e)))?;
Ok(())
}
async fn get_contact_by_id(&self, id: &Uuid) -> ContactRepositoryResult<Option<Contact>> {
let row_opt = sqlx::query(
r#"
SELECT
id, address_book_id, uid, full_name, first_name, last_name, nickname,
email, phone, address, organization, title, notes, photo_url,
birthday, anniversary, vcard, etag, created_at, updated_at
FROM carddav.contacts
WHERE id = $1
2026-02-14 01:29:34 +01:00
"#,
2025-04-13 01:04:04 +02:00
)
.bind(id)
.fetch_optional(&*self.pool)
.await
.map_err(|e| DomainError::database_error(format!("Failed to get contact by id: {}", e)))?;
match row_opt {
Some(row) => Ok(Some(Self::row_to_contact(&row)?)),
None => Ok(None),
2025-04-13 01:04:04 +02:00
}
}
2026-02-14 01:29:34 +01:00
async fn get_contact_by_uid(
&self,
address_book_id: &Uuid,
uid: &str,
) -> ContactRepositoryResult<Option<Contact>> {
2025-04-13 01:04:04 +02:00
let row_opt = sqlx::query(
r#"
SELECT
id, address_book_id, uid, full_name, first_name, last_name, nickname,
email, phone, address, organization, title, notes, photo_url,
birthday, anniversary, vcard, etag, created_at, updated_at
FROM carddav.contacts
WHERE address_book_id = $1 AND uid = $2
2026-02-14 01:29:34 +01:00
"#,
2025-04-13 01:04:04 +02:00
)
.bind(address_book_id)
.bind(uid)
.fetch_optional(&*self.pool)
.await
.map_err(|e| DomainError::database_error(format!("Failed to get contact by uid: {}", e)))?;
match row_opt {
Some(row) => Ok(Some(Self::row_to_contact(&row)?)),
None => Ok(None),
2025-04-13 01:04:04 +02:00
}
}
2026-02-14 01:29:34 +01:00
async fn get_contacts_by_address_book(
&self,
address_book_id: &Uuid,
) -> ContactRepositoryResult<Vec<Contact>> {
let rows = sqlx::query(
2025-04-13 01:04:04 +02:00
r#"
SELECT
id, address_book_id, uid, full_name, first_name, last_name, nickname,
email, phone, address, organization, title, notes, photo_url,
birthday, anniversary, vcard, etag, created_at, updated_at
FROM carddav.contacts
WHERE address_book_id = $1
ORDER BY full_name, first_name, last_name
2026-02-14 01:29:34 +01:00
"#,
2025-04-13 01:04:04 +02:00
)
.bind(address_book_id)
.fetch_all(&*self.pool)
.await
2026-02-14 01:29:34 +01:00
.map_err(|e| {
DomainError::database_error(format!("Failed to get contacts by address book: {}", e))
})?;
2025-04-13 01:04:04 +02:00
let mut contacts = Vec::new();
for row in &rows {
contacts.push(Self::row_to_contact(row)?);
}
2025-04-13 01:04:04 +02:00
Ok(contacts)
}
async fn get_contacts_by_email(&self, email: &str) -> ContactRepositoryResult<Vec<Contact>> {
let search_pattern = format!("%{}%", email);
2026-02-14 01:29:34 +01:00
let rows = sqlx::query(
2025-04-13 01:04:04 +02:00
r#"
SELECT
id, address_book_id, uid, full_name, first_name, last_name, nickname,
email, phone, address, organization, title, notes, photo_url,
birthday, anniversary, vcard, etag, created_at, updated_at
FROM carddav.contacts
WHERE email::text ILIKE $1
ORDER BY full_name, first_name, last_name
2026-02-14 01:29:34 +01:00
"#,
2025-04-13 01:04:04 +02:00
)
.bind(&search_pattern)
.fetch_all(&*self.pool)
.await
2026-02-14 01:29:34 +01:00
.map_err(|e| {
DomainError::database_error(format!("Failed to get contacts by email: {}", e))
})?;
2025-04-13 01:04:04 +02:00
let mut contacts = Vec::new();
for row in &rows {
contacts.push(Self::row_to_contact(row)?);
}
2025-04-13 01:04:04 +02:00
Ok(contacts)
}
2026-02-14 01:29:34 +01:00
async fn get_contacts_by_group(
&self,
group_id: &Uuid,
) -> ContactRepositoryResult<Vec<Contact>> {
let rows = sqlx::query(
2025-04-13 01:04:04 +02:00
r#"
SELECT
c.id, c.address_book_id, c.uid, c.full_name, c.first_name, c.last_name, c.nickname,
c.email, c.phone, c.address, c.organization, c.title, c.notes, c.photo_url,
c.birthday, c.anniversary, c.vcard, c.etag, c.created_at, c.updated_at
FROM carddav.contacts c
INNER JOIN carddav.group_memberships m ON c.id = m.contact_id
WHERE m.group_id = $1
ORDER BY c.full_name, c.first_name, c.last_name
2026-02-14 01:29:34 +01:00
"#,
2025-04-13 01:04:04 +02:00
)
.bind(group_id)
.fetch_all(&*self.pool)
.await
2026-02-14 01:29:34 +01:00
.map_err(|e| {
DomainError::database_error(format!("Failed to get contacts by group: {}", e))
})?;
2025-04-13 01:04:04 +02:00
let mut contacts = Vec::new();
for row in &rows {
contacts.push(Self::row_to_contact(row)?);
}
2025-04-13 01:04:04 +02:00
Ok(contacts)
}
2026-02-14 01:29:34 +01:00
async fn search_contacts(
&self,
address_book_id: &Uuid,
query: &str,
) -> ContactRepositoryResult<Vec<Contact>> {
2025-04-13 01:04:04 +02:00
let search_pattern = format!("%{}%", query);
2026-02-14 01:29:34 +01:00
let rows = sqlx::query(
2025-04-13 01:04:04 +02:00
r#"
SELECT
id, address_book_id, uid, full_name, first_name, last_name, nickname,
email, phone, address, organization, title, notes, photo_url,
birthday, anniversary, vcard, etag, created_at, updated_at
FROM carddav.contacts
WHERE address_book_id = $1
AND (
full_name ILIKE $2
OR first_name ILIKE $2
OR last_name ILIKE $2
OR nickname ILIKE $2
OR email::text ILIKE $2
OR phone::text ILIKE $2
OR organization ILIKE $2
)
ORDER BY full_name, first_name, last_name
2026-02-14 01:29:34 +01:00
"#,
2025-04-13 01:04:04 +02:00
)
.bind(address_book_id)
.bind(&search_pattern)
.fetch_all(&*self.pool)
.await
.map_err(|e| DomainError::database_error(format!("Failed to search contacts: {}", e)))?;
let mut contacts = Vec::new();
for row in &rows {
contacts.push(Self::row_to_contact(row)?);
}
2025-04-13 01:04:04 +02:00
Ok(contacts)
}
2026-02-14 01:29:34 +01:00
}