use anyhow::Result;
use reblessive::tree::Stk;
use crate::catalog::providers::UserProvider;
use crate::ctx::FrozenContext;
use crate::dbs::Options;
use crate::doc::CursorDoc;
use crate::err::Error;
use crate::expr::parameterize::expr_to_ident;
use crate::expr::{Base, Expr, Literal, Value};
use crate::iam::{Action, ResourceKind};
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub(crate) struct RemoveUserStatement {
pub name: Expr,
pub base: Base,
pub if_exists: bool,
}
impl Default for RemoveUserStatement {
fn default() -> Self {
Self {
name: Expr::Literal(Literal::None),
base: Base::default(),
if_exists: false,
}
}
}
impl RemoveUserStatement {
pub(crate) async fn compute(
&self,
stk: &mut Stk,
ctx: &FrozenContext,
opt: &Options,
doc: Option<&CursorDoc>,
) -> Result<Value> {
ctx.is_allowed(opt, Action::Edit, ResourceKind::Actor, self.base)?;
let name = expr_to_ident(stk, ctx, opt, doc, &self.name, "user name").await?;
match self.base {
Base::Root => {
let txn = ctx.tx();
let us = match txn.get_root_user(&name, None).await? {
Some(x) => x,
None => {
if self.if_exists {
return Ok(Value::None);
}
return Err(Error::UserRootNotFound {
name,
}
.into());
}
};
let key = crate::key::root::us::new(&us.name);
txn.del(&key).await?;
txn.clear_cache();
Ok(Value::None)
}
Base::Ns => {
let txn = ctx.tx();
let ns = ctx.get_ns_id(opt).await?;
let us = match txn.get_ns_user(ns, &name, None).await? {
Some(x) => x,
None => {
if self.if_exists {
return Ok(Value::None);
}
return Err(Error::UserNsNotFound {
ns: opt.ns()?.to_string(),
name,
}
.into());
}
};
let key = crate::key::namespace::us::new(ns, &us.name);
txn.del(&key).await?;
txn.clear_cache();
Ok(Value::None)
}
Base::Db => {
let txn = ctx.tx();
let (ns, db) = ctx.expect_ns_db_ids(opt).await?;
let us = match txn.get_db_user(ns, db, &name, None).await? {
Some(x) => x,
None => {
if self.if_exists {
return Ok(Value::None);
}
return Err(Error::UserDbNotFound {
ns: opt.ns()?.to_string(),
db: opt.db()?.to_string(),
name,
}
.into());
}
};
let key = crate::key::database::us::new(ns, db, &us.name);
txn.del(&key).await?;
txn.clear_cache();
Ok(Value::None)
}
}
}
}