use anyhow::Result;
use reblessive::tree::Stk;
use super::retire_database_indexes;
use crate::catalog::providers::DatabaseProvider;
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 RemoveDatabaseStatement {
pub name: Expr,
pub if_exists: bool,
pub expunge: bool,
}
impl Default for RemoveDatabaseStatement {
fn default() -> Self {
Self {
name: Expr::Literal(Literal::None),
if_exists: false,
expunge: false,
}
}
}
impl RemoveDatabaseStatement {
#[instrument(level = "trace", name = "RemoveDatabaseStatement::compute", skip_all)]
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::Database, Base::Ns)?;
let txn = ctx.tx();
let name = expr_to_ident(stk, ctx, opt, doc, &self.name, "database name").await?;
let ns = opt.ns()?;
let db = match txn.get_db_by_name(ns, &name, None).await? {
Some(x) => x,
None => {
if self.if_exists {
return Ok(Value::None);
} else {
return Err(Error::DbNotFound {
name,
}
.into());
}
}
};
retire_database_indexes(ctx, &txn, db.namespace_id, db.database_id).await?;
if let Some(seq) = ctx.get_sequences() {
seq.database_removed(&txn, db.namespace_id, db.database_id).await?;
}
txn.del_db_deferred(ns, &db.name, self.expunge).await?;
if let Some(cache) = ctx.get_cache() {
cache.clear();
}
txn.clear_cache();
Ok(Value::None)
}
}