use vantage_core::{Result, error};
use vantage_dataset::prelude::{ActiveEntity, ActiveRecord};
use vantage_types::{Entity, InvariantValue, TryIntoRecord};
use crate::{
table::Table,
traits::{column_like::ColumnLike, table_source::TableSource},
};
pub trait GetRefExt<T: TableSource, E> {
fn get_ref<E2: Entity<T::Value> + 'static>(&self, relation: &str) -> Result<Table<T, E2>>;
}
impl<'a, T, E> GetRefExt<T, E> for ActiveEntity<'a, Table<T, E>, E>
where
T: TableSource,
T::Id: Into<T::Value>,
T::Value: InvariantValue,
E: Entity<T::Value> + 'static,
<E as TryIntoRecord<T::Value>>::Error: std::fmt::Debug,
{
fn get_ref<E2: Entity<T::Value> + 'static>(&self, relation: &str) -> Result<Table<T, E2>> {
let mut record = self
.data()
.clone()
.try_into_record()
.map_err(|e| error!("Failed to serialize entity to record", error = e))?;
let id_field = self
.dataset()
.id_field()
.map(|c| c.name().to_string())
.unwrap_or_else(|| "id".to_string());
record.insert(id_field, self.id().clone().into());
self.dataset().get_ref_from_row::<E2>(relation, &record)
}
}
impl<'a, T, E> GetRefExt<T, E> for ActiveRecord<'a, Table<T, E>>
where
T: TableSource,
T::Value: InvariantValue,
E: Entity<T::Value> + 'static,
{
fn get_ref<E2: Entity<T::Value> + 'static>(&self, relation: &str) -> Result<Table<T, E2>> {
let row: &vantage_types::Record<T::Value> = self;
self.dataset().get_ref_from_row::<E2>(relation, row)
}
}