use std::any::{Any, TypeId};
use std::borrow::Cow;
use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::{Arc, OnceLock, PoisonError, RwLock};
use crate::model::Model;
use crate::query::Builder;
use crate::scope::{GlobalScope, SoftDeletes};
struct Registered {
name: Cow<'static, str>,
scope: Box<dyn Any + Send + Sync>,
}
type Registry = RwLock<HashMap<TypeId, Vec<Registered>>>;
fn registry() -> &'static Registry {
static REGISTRY: OnceLock<Registry> = OnceLock::new();
REGISTRY.get_or_init(Registry::default)
}
pub(crate) fn register<M: Model>(scope: Arc<dyn GlobalScope<M>>) {
let name = scope.name();
let mut registry = registry().write().unwrap_or_else(PoisonError::into_inner);
let scopes = registry.entry(TypeId::of::<M>()).or_default();
scopes.retain(|registered| registered.name != name);
scopes.push(Registered {
name,
scope: Box::new(scope),
});
}
fn registered<M: Model>() -> Vec<Arc<dyn GlobalScope<M>>> {
let registry = registry().read().unwrap_or_else(PoisonError::into_inner);
registry
.get(&TypeId::of::<M>())
.into_iter()
.flatten()
.filter_map(|registered| {
registered
.scope
.downcast_ref::<Arc<dyn GlobalScope<M>>>()
.cloned()
})
.collect()
}
pub(crate) fn scopes_of<M: Model>() -> Vec<Arc<dyn GlobalScope<M>>> {
let mut scopes = M::global_scopes();
scopes.extend(registered::<M>());
if M::meta().soft_deletes_enabled() {
scopes.push(Arc::new(SoftDeletes));
}
if M::meta().is_workspace_scoped() {
scopes.push(Arc::new(crate::workspace::WorkspaceScope));
}
scopes
}
pub struct ClosureScope<M, F> {
name: Cow<'static, str>,
scope: F,
_model: PhantomData<fn() -> M>,
}
impl<M, F> ClosureScope<M, F>
where
M: Model,
F: Fn(Builder<M>) -> Builder<M> + Send + Sync + 'static,
{
pub fn new(name: impl Into<Cow<'static, str>>, scope: F) -> Self {
ClosureScope {
name: name.into(),
scope,
_model: PhantomData,
}
}
}
impl<M, F> GlobalScope<M> for ClosureScope<M, F>
where
M: Model,
F: Fn(Builder<M>) -> Builder<M> + Send + Sync + 'static,
{
fn apply(&self, query: Builder<M>) -> Builder<M> {
(self.scope)(query)
}
fn name(&self) -> Cow<'static, str> {
self.name.clone()
}
}
impl<M: Model> Builder<M> {
pub fn without_global_scope_named(mut self, name: impl Into<Cow<'static, str>>) -> Self {
self.scopes.names.push(name.into());
self
}
pub fn without_global_scopes_except<N>(mut self, keep: impl IntoIterator<Item = N>) -> Self
where
N: Into<Cow<'static, str>>,
{
self.scopes.keep = Some(keep.into_iter().map(Into::into).collect());
self
}
pub fn removed_scopes(&self) -> Vec<Cow<'static, str>> {
scopes_of::<M>()
.iter()
.filter(|scope| self.scopes.removes(scope.as_ref()))
.map(|scope| scope.name())
.collect()
}
}
pub(crate) fn find<M: Model>(name: &str) -> Option<Arc<dyn GlobalScope<M>>> {
scopes_of::<M>()
.into_iter()
.find(|scope| scope.name() == name)
}