use anyhow::{Result, bail};
use reblessive::tree::Stk;
use super::DefineKind;
use crate::catalog::DatabaseDefinition;
use crate::catalog::providers::{DatabaseProvider, NamespaceProvider};
use crate::ctx::FrozenContext;
use crate::dbs::Options;
use crate::doc::CursorDoc;
use crate::err::Error;
use crate::expr::changefeed::ChangeFeed;
use crate::expr::parameterize::expr_to_ident;
use crate::expr::statements::info::InfoStructure;
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 DefineDatabaseStatement {
pub kind: DefineKind,
pub id: Option<u32>,
pub name: Expr,
pub strict: bool,
pub comment: Expr,
pub changefeed: Option<ChangeFeed>,
}
impl Default for DefineDatabaseStatement {
fn default() -> Self {
Self {
kind: DefineKind::Default,
id: None,
name: Expr::Literal(Literal::None),
comment: Expr::Literal(Literal::None),
changefeed: None,
strict: false,
}
}
}
impl DefineDatabaseStatement {
#[instrument(level = "trace", name = "DefineDatabaseStatement::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 ns = opt.ns()?;
let txn = ctx.tx();
let nsv = txn.get_or_add_ns(Some(ctx), ns).await?;
let name = expr_to_ident(stk, ctx, opt, doc, &self.name, "database name").await?;
let database_id = if let Some(db) = txn.get_db_by_name(ns, &name, None).await? {
match self.kind {
DefineKind::Default => {
if !opt.import {
bail!(Error::DbAlreadyExists {
name: name.clone(),
});
}
}
DefineKind::Overwrite => {}
DefineKind::IfNotExists => {
return Ok(Value::None);
}
}
db.database_id
} else {
ctx.try_get_sequences()?.next_database_id(Some(ctx), nsv.namespace_id).await?
};
let comment = stk
.run(|stk| self.comment.compute(stk, ctx, opt, doc))
.await
.catch_return()?
.cast_to()?;
let db_def = DatabaseDefinition {
namespace_id: nsv.namespace_id,
database_id,
name: name.clone().into(),
comment,
changefeed: self.changefeed,
strict: self.strict,
};
txn.put_db(nsv.name.as_str(), db_def).await?;
if let Some(cache) = ctx.get_cache() {
cache.clear();
}
txn.clear_cache();
Ok(Value::None)
}
}
impl InfoStructure for DefineDatabaseStatement {
fn structure(self) -> Value {
Value::from(map! {
"name" => self.name.structure(),
"comment" => self.comment.structure(),
})
}
}