use anyhow::{Result, bail};
use reblessive::tree::Stk;
use surrealdb_strand::Strand;
use super::DefineKind;
use crate::catalog::NamespaceDefinition;
use crate::catalog::providers::NamespaceProvider;
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, FlowResultExt, Literal};
use crate::iam::{Action, ResourceKind};
use crate::val::Value;
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub(crate) struct DefineNamespaceStatement {
pub kind: DefineKind,
pub id: Option<u32>,
pub name: Expr,
pub comment: Expr,
}
impl Default for DefineNamespaceStatement {
fn default() -> Self {
Self {
kind: DefineKind::Default,
id: None,
name: Expr::Literal(Literal::String(Strand::default())),
comment: Expr::Literal(Literal::None),
}
}
}
impl DefineNamespaceStatement {
#[instrument(level = "trace", name = "DefineNamespaceStatement::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::Namespace, Base::Root)?;
let txn = ctx.tx();
let name: Strand =
expr_to_ident(stk, ctx, opt, doc, &self.name, "namespace name").await?.into();
let namespace_id = if let Some(ns) = txn.get_ns_by_name(name.as_str(), None).await? {
match self.kind {
DefineKind::Default => {
if !opt.import {
bail!(Error::NsAlreadyExists {
name: name.to_string(),
});
}
}
DefineKind::Overwrite => {}
DefineKind::IfNotExists => return Ok(Value::None),
}
ns.namespace_id
} else {
ctx.try_get_sequences()?.next_namespace_id(Some(ctx)).await?
};
let comment = stk
.run(|stk| self.comment.compute(stk, ctx, opt, doc))
.await
.catch_return()?
.cast_to()?;
let ns_def = NamespaceDefinition {
namespace_id,
name,
comment,
};
txn.put_ns(ns_def).await?;
txn.clear_cache();
Ok(Value::None)
}
}