use std::any::TypeId;
use std::borrow::Cow;
use std::future::Future;
use std::sync::{Arc, OnceLock, RwLock};
use crate::error::{OrmError, Result};
use crate::model::Model;
use crate::relations::morph::{MorphTarget, MorphTargetOf};
#[derive(Clone)]
pub(crate) struct MorphEntry {
pub(crate) name: Cow<'static, str>,
pub(crate) type_id: TypeId,
pub(crate) model: &'static str,
pub(crate) target: Arc<dyn MorphTarget>,
}
#[derive(Clone, Default)]
pub struct MorphMap {
entries: Vec<MorphEntry>,
required: bool,
}
fn global() -> &'static RwLock<MorphMap> {
static GLOBAL: OnceLock<RwLock<MorphMap>> = OnceLock::new();
GLOBAL.get_or_init(|| RwLock::new(MorphMap::default()))
}
tokio::task_local! {
static SCOPED: MorphMap;
}
impl MorphMap {
pub fn new() -> Self {
MorphMap::default()
}
pub fn with<M: Model>(mut self) -> Self {
self.add::<M>();
self
}
pub fn required(mut self) -> Self {
self.required = true;
self
}
fn add<M: Model>(&mut self) {
let name = M::morph_name();
self.entries
.retain(|entry| entry.name != name && entry.type_id != TypeId::of::<M>());
self.entries.push(MorphEntry {
name,
type_id: TypeId::of::<M>(),
model: M::meta().name(),
target: Arc::new(MorphTargetOf::<M>::new()),
});
}
pub fn register<M: Model>() {
global()
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.add::<M>();
}
pub fn require(required: bool) {
global()
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.required = required;
}
pub(crate) fn current() -> MorphMap {
SCOPED.try_with(MorphMap::clone).unwrap_or_else(|_| {
global()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
})
}
pub async fn scope<F: Future>(self, future: F) -> F::Output {
SCOPED.scope(self, future).await
}
pub fn model_for(name: &str) -> Option<&'static str> {
MorphMap::current().entry(name).map(|entry| entry.model)
}
pub fn name_for<M: Model>() -> Option<Cow<'static, str>> {
MorphMap::current()
.entries
.iter()
.find(|entry| entry.type_id == TypeId::of::<M>())
.map(|entry| entry.name.clone())
}
pub fn is_required() -> bool {
MorphMap::current().required
}
pub fn names() -> Vec<Cow<'static, str>> {
MorphMap::current()
.entries
.iter()
.map(|entry| entry.name.clone())
.collect()
}
pub(crate) fn entry(&self, name: &str) -> Option<&MorphEntry> {
self.entries.iter().find(|entry| entry.name == name)
}
pub(crate) fn entries(&self) -> &[MorphEntry] {
&self.entries
}
}
pub(crate) fn type_name_of<M: Model>() -> Result<Cow<'static, str>> {
let map = MorphMap::current();
if map.required
&& !map
.entries
.iter()
.any(|entry| entry.type_id == TypeId::of::<M>())
{
return Err(OrmError::MorphNotMapped {
model: Cow::Borrowed(M::meta().name()),
});
}
Ok(M::morph_name())
}