horizon-sdk 9.0.0

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

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

use super::PostgresRepository;

impl PostgresRepository {
    /// Delete an ontology by ID. Returns the number of rows removed.
    pub async fn delete_ontology(&self, id: Uuid) -> Result<u64> {
        let result = sqlx::query!("DELETE FROM horizon_public.ontology WHERE id = $1", id)
            .execute(&self.pool)
            .await?;
        Ok(result.rows_affected())
    }

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

    /// Create a batch of ontologies in a single multi-row INSERT.
    ///
    /// Per-column slices are passed to `PostgreSQL` `UNNEST(...)` so the
    /// entire batch becomes one SQL statement and one network round-trip.
    /// Missing IDs are filled by `gen_random_uuid()` server-side, and
    /// `modified_datetime` is set to the same `now()` value for every
    /// row.
    ///
    /// Returns the inserted rows in input order. Wraps the statement in
    /// a transaction so a per-row failure rolls back the entire batch.
    #[allow(
        clippy::as_conversions,
        reason = "sqlx::query_as! requires `&Vec<T> as &[T]` ascription to bind a nullable Postgres array; conversion direction is unambiguous (same element type)"
    )]
    pub async fn insert_ontology_batch(&self, ontologies: &[Ontology]) -> Result<Vec<Ontology>> {
        if ontologies.is_empty() {
            return Ok(Vec::new());
        }
        let now = Utc::now();
        let ids: Vec<Option<Uuid>> = ontologies.iter().map(|ontology| ontology.id).collect();
        let names: Vec<Option<String>> = ontologies
            .iter()
            .map(|ontology| ontology.name.clone())
            .collect();
        let descriptions: Vec<Option<String>> = ontologies
            .iter()
            .map(|ontology| ontology.description.clone())
            .collect();
        let orgs: Vec<Option<Uuid>> = ontologies
            .iter()
            .map(|ontology| self.organization_id.or(ontology.organization_id))
            .collect();
        let mut tx = self.pool.begin().await?;
        let rows = sqlx::query_as!(
            Ontology,
            r#"
            WITH source AS (
                SELECT
                    COALESCE(id, gen_random_uuid()) AS id,
                    name, description, organization_id, ord
                FROM UNNEST($1::uuid[], $2::text[], $3::text[], $4::uuid[]) WITH ORDINALITY
                    AS batch(id, name, description, organization_id, ord)
            ),
            inserted AS (
                INSERT INTO horizon_public.ontology
                    (id, name, description, organization_id, modified_datetime)
                SELECT id, name, description, organization_id, $5 FROM source
                RETURNING id, created_datetime, modified_datetime,
                          name, description, organization_id
            )
            SELECT inserted.id, inserted.created_datetime, inserted.modified_datetime,
                   inserted.name, inserted.description, inserted.organization_id
            FROM inserted
            JOIN source ON source.id = inserted.id
            ORDER BY source.ord
            "#,
            &ids as &[Option<Uuid>],
            &names as &[Option<String>],
            &descriptions as &[Option<String>],
            &orgs as &[Option<Uuid>],
            now,
        )
        .fetch_all(&mut *tx)
        .await?;
        tx.commit().await?;
        debug!(batch_size = rows.len(), "insert_ontology_batch");
        Ok(rows)
    }

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

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

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

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

    /// Insert an ontology 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_ontology(&self, ontology: &Ontology) -> Result<Ontology> {
        let now = Utc::now();
        let org = self.organization_id.or(ontology.organization_id);
        Ok(sqlx::query_as!(
            Ontology,
            r#"
            INSERT INTO horizon_public.ontology
                (id, name, description, organization_id, modified_datetime)
            VALUES (COALESCE($1, gen_random_uuid()), $2, $3, $4, $5)
            ON CONFLICT (id) DO UPDATE SET
                name = EXCLUDED.name, description = EXCLUDED.description,
                organization_id = EXCLUDED.organization_id,
                modified_datetime = EXCLUDED.modified_datetime
            RETURNING id, created_datetime, modified_datetime,
                      name, description, organization_id
            "#,
            ontology.id,
            ontology.name,
            ontology.description,
            org,
            now,
        )
        .fetch_one(&self.pool)
        .await?)
    }
}