horizon-sdk 9.0.0

Canonical Rust data access layer for the Horizon platform
Documentation
use chrono::Utc;
use uuid::Uuid;

use crate::types::error::{HorizonError, PostgresError, Result};
use crate::types::model::Normalizer;

use super::PostgresRepository;

impl PostgresRepository {
    /// Archive a normalizer by ID (soft delete).
    ///
    /// The normalizer table uses soft deletes via `is_archived` instead of
    /// hard deletes; archiving frees the name for reuse because the unique
    /// constraint is partial (`WHERE NOT is_archived`). Returns
    /// `HorizonError::Postgres(PostgresError::NotFound)` if no row with the
    /// given ID exists.
    pub async fn archive_normalizer(&self, id: Uuid) -> Result<Normalizer> {
        let now = Utc::now();
        let result = sqlx::query_as!(
            Normalizer,
            r#"
            UPDATE horizon_public.normalizer
            SET is_archived = true, modified_datetime = $2
            WHERE id = $1
            RETURNING id, created_datetime, modified_datetime,
                      name AS "name?", description, is_archived AS "is_archived?",
                      organization_id AS "organization_id?"
            "#,
            id,
            now,
        )
        .fetch_optional(&self.pool)
        .await?;

        result.ok_or_else(|| {
            HorizonError::Postgres(PostgresError::NotFound {
                entity: "normalizer".to_owned(),
                id: id.into(),
            })
        })
    }

    /// Create a normalizer.
    pub async fn insert_normalizer(&self, normalizer: &Normalizer) -> Result<Normalizer> {
        let now = Utc::now();
        let org = self.organization_id.or(normalizer.organization_id);
        Ok(sqlx::query_as!(
            Normalizer,
            r#"
            INSERT INTO horizon_public.normalizer
                (id, name, description, is_archived, organization_id, modified_datetime)
            VALUES (COALESCE($1, gen_random_uuid()), $2, $3, COALESCE($4, false), $5, $6)
            RETURNING id, created_datetime, modified_datetime,
                      name AS "name?", description, is_archived AS "is_archived?",
                      organization_id AS "organization_id?"
            "#,
            normalizer.id,
            normalizer.name,
            normalizer.description,
            normalizer.is_archived,
            org,
            now,
        )
        .fetch_one(&self.pool)
        .await?)
    }

    /// List all normalizer records.
    pub async fn list_normalizers(&self) -> Result<Vec<Normalizer>> {
        Ok(sqlx::query_as!(
            Normalizer,
            r#"
            SELECT id, created_datetime, modified_datetime,
                   name AS "name?", description, is_archived AS "is_archived?",
                   organization_id AS "organization_id?"
            FROM horizon_public.normalizer
            "#,
        )
        .fetch_all(&self.pool)
        .await?)
    }

    /// Read a normalizer by ID.
    pub async fn read_normalizer(&self, id: Uuid) -> Result<Option<Normalizer>> {
        Ok(sqlx::query_as!(
            Normalizer,
            r#"
            SELECT id, created_datetime, modified_datetime,
                   name AS "name?", description, is_archived AS "is_archived?",
                   organization_id AS "organization_id?"
            FROM horizon_public.normalizer WHERE id = $1
            "#,
            id,
        )
        .fetch_optional(&self.pool)
        .await?)
    }

    /// Update an existing normalizer by ID.
    ///
    /// Returns `HorizonError::Postgres(PostgresError::NotFound)` if no row
    /// with the given ID exists. Matches Python `BaseRepository.update()`
    /// semantics.
    pub async fn update_normalizer(&self, normalizer: &Normalizer) -> Result<Normalizer> {
        let now = Utc::now();
        let org = self.organization_id.or(normalizer.organization_id);
        let result = sqlx::query_as!(
            Normalizer,
            r#"
            UPDATE horizon_public.normalizer
            SET
                name = $2,
                description = $3,
                is_archived = COALESCE($4, false),
                organization_id = $5,
                modified_datetime = $6
            WHERE id = $1
            RETURNING id, created_datetime, modified_datetime,
                      name AS "name?", description, is_archived AS "is_archived?",
                      organization_id AS "organization_id?"
            "#,
            normalizer.id,
            normalizer.name,
            normalizer.description,
            normalizer.is_archived,
            org,
            now,
        )
        .fetch_optional(&self.pool)
        .await?;

        result.ok_or_else(|| {
            HorizonError::Postgres(PostgresError::NotFound {
                entity: "normalizer".to_owned(),
                id: normalizer.id.into(),
            })
        })
    }

    /// Insert a normalizer or update it if a row with the same ID already
    /// exists. Sets `modified_datetime` to now and falls back to the
    /// repository's `organization_id` when the model does not provide one.
    pub async fn upsert_normalizer(&self, normalizer: &Normalizer) -> Result<Normalizer> {
        let now = Utc::now();
        let org = self.organization_id.or(normalizer.organization_id);
        Ok(sqlx::query_as!(
            Normalizer,
            r#"
            INSERT INTO horizon_public.normalizer
                (id, name, description, is_archived, organization_id, modified_datetime)
            VALUES (COALESCE($1, gen_random_uuid()), $2, $3, COALESCE($4, false), $5, $6)
            ON CONFLICT (id) DO UPDATE SET
                name = EXCLUDED.name, description = EXCLUDED.description,
                is_archived = EXCLUDED.is_archived,
                organization_id = EXCLUDED.organization_id,
                modified_datetime = EXCLUDED.modified_datetime
            RETURNING id, created_datetime, modified_datetime,
                      name AS "name?", description, is_archived AS "is_archived?",
                      organization_id AS "organization_id?"
            "#,
            normalizer.id,
            normalizer.name,
            normalizer.description,
            normalizer.is_archived,
            org,
            now,
        )
        .fetch_one(&self.pool)
        .await?)
    }
}