use std::borrow::Cow;
use std::future::Future;
use navree_db::Uow;
use navree_kernel::BoxFuture;
use uuid::Uuid;
use crate::column::Filter;
use crate::error::{OrmError, Result};
use crate::exec::{ExecContext, Target};
use crate::hooks::{Flow, ModelEvent, ModelHook};
use crate::ir::{ColumnRef, Expr, Operator};
use crate::model::{Model, PrimaryKey};
use crate::query::Builder;
use crate::record::Record;
use crate::scope::GlobalScope;
use crate::value::{Field, Value};
tokio::task_local! {
static EXPLICIT: Uuid;
static TARGET: Option<Uuid>;
}
pub async fn scope<F: Future>(workspace: Uuid, future: F) -> F::Output {
EXPLICIT.scope(workspace, future).await
}
pub fn current() -> Option<Uuid> {
EXPLICIT
.try_with(|workspace| *workspace)
.ok()
.or_else(|| TARGET.try_with(|workspace| *workspace).ok().flatten())
.or_else(|| Uow::current().and_then(|uow| uow.workspace()))
}
pub fn current_in(ctx: &ExecContext) -> Option<Uuid> {
EXPLICIT
.try_with(|workspace| *workspace)
.ok()
.or_else(|| ctx.uow().and_then(Uow::workspace))
.or_else(current)
}
pub(crate) fn with_target<R>(target: &Target<'_>, build: impl FnOnce() -> R) -> R {
let workspace = target.uow().and_then(Uow::workspace);
TARGET.sync_scope(workspace, build)
}
#[derive(Clone, Copy, Debug, Default)]
pub struct WorkspaceScope;
impl<M: Model> GlobalScope<M> for WorkspaceScope {
fn apply(&self, query: Builder<M>) -> Builder<M> {
let Some(column) = M::meta().workspace_column() else {
return query;
};
match current() {
Some(workspace) => query.where_(workspace_filter::<M>(column, workspace)),
None => query.with_error(no_workspace::<M>("query")),
}
}
}
fn workspace_filter<M: Model>(column: &'static str, workspace: Uuid) -> Filter {
Filter::compare(
Expr::Column(ColumnRef::new(Some(M::meta().table()), column)),
Operator::Eq,
Expr::Value(Value::from(workspace)),
)
}
fn no_workspace<M: Model>(operation: &str) -> String {
let name = M::meta().name();
format!(
"{name} is scoped to workspaces, but there is no current workspace to {operation} it in: \
run it in a workspace request (CurrentWorkspace or the InWorkspace guard), on a unit of work \
that entered a workspace, or inside navree_orm::workspace::scope(id, ..); or name the \
workspace with for_workspace(id) / opt out with without_workspace_scope()"
)
}
impl<M: Model> Builder<M> {
pub fn without_workspace_scope(self) -> Self {
self.without_global_scope::<WorkspaceScope>()
}
pub fn for_workspace(self, workspace: Uuid) -> Self {
match M::meta().workspace_column() {
Some(column) => self
.without_workspace_scope()
.where_(workspace_filter::<M>(column, workspace)),
None => self.with_error(format!(
"{} is not scoped to workspaces: for_workspace() needs #[model(workspace)]",
M::meta().name()
)),
}
}
}
fn workspace_of<M: Model>(model: &M, column: &str) -> Result<Option<Uuid>> {
let value = model
.value(column)?
.ok_or_else(|| crate::model::derive_support::unknown_column::<M>(column))?;
let workspace = <Option<Uuid>>::from_value(value).map_err(|error| OrmError::Decode {
model: Cow::Borrowed(M::meta().name()),
column: column.to_owned(),
expected: Cow::Borrowed("a workspace id (Uuid)"),
message: error.to_string(),
})?;
Ok(workspace.filter(|id| !id.is_nil()))
}
pub(crate) fn fill_new<M: Model>(model: &mut M, current: Option<Uuid>) -> Result<()> {
let Some(column) = M::meta().workspace_column() else {
return Ok(());
};
match (workspace_of(model, column)?, current) {
(None, Some(workspace)) => model.set_value(column, Value::from(workspace)),
(None, None) => Err(OrmError::Workspace {
model: Cow::Borrowed(M::meta().name()),
message: no_workspace::<M>("create"),
}),
(Some(own), Some(workspace)) if own != workspace => Err(OrmError::Workspace {
model: Cow::Borrowed(M::meta().name()),
message: format!(
"cannot create a {} in workspace {own} while working in workspace {workspace}",
M::meta().name()
),
}),
(Some(_), _) => Ok(()),
}
}
pub(crate) fn fill_for_insert<M: Model>(ctx: &ExecContext, model: &mut M) -> Result<()> {
fill_new(model, current_in(ctx))
}
pub(crate) fn check_assignments<M: Model>(assignments: &[(Cow<'static, str>, Expr)]) -> Result<()> {
let Some(column) = M::meta().workspace_column() else {
return Ok(());
};
if assignments.iter().any(|(name, _)| name == column) {
return Err(OrmError::Workspace {
model: Cow::Borrowed(M::meta().name()),
message: format!(
"the `{column}` of {} records cannot be changed by a mass update",
M::meta().name()
),
});
}
Ok(())
}
pub(crate) struct WorkspaceHook;
impl<M: Model> ModelHook<M> for WorkspaceHook {
fn before<'a>(
&'a self,
event: ModelEvent,
ctx: &'a ExecContext,
record: &'a mut Record<M>,
) -> BoxFuture<'a, Result<Flow>> {
Box::pin(async move {
let Some(column) = M::meta().workspace_column() else {
return Ok(Flow::Continue);
};
let current = current_in(ctx);
match event {
ModelEvent::Creating => fill_new(&mut record.model, current)?,
ModelEvent::Updating => {
let stored = match &record.original {
Some(original) => workspace_of(original, column)?,
None => workspace_of(&record.model, column)?,
};
if workspace_of(&record.model, column)? != stored {
return Err(OrmError::Workspace {
model: Cow::Borrowed(M::meta().name()),
message: format!(
"the workspace of a {} cannot change (`{column}` was changed)",
M::meta().name()
),
});
}
check_belongs(record, stored, current)?;
}
ModelEvent::Deleting | ModelEvent::ForceDeleting | ModelEvent::Restoring => {
let stored = match &record.original {
Some(original) => workspace_of(original, column)?,
None => workspace_of(&record.model, column)?,
};
check_belongs(record, stored, current)?;
}
_ => {}
}
Ok(Flow::Continue)
})
}
}
fn check_belongs<M: Model>(
record: &Record<M>,
stored: Option<Uuid>,
current: Option<Uuid>,
) -> Result<()> {
match (stored, current) {
(Some(own), Some(workspace)) if own != workspace => Err(OrmError::not_found(
M::meta().name(),
vec![record.key().to_key_string()],
)),
_ => Ok(()),
}
}