surrealdb_sql/statements/define/
index.rsuse crate::ctx::Context;
use crate::dbs::{Options, Transaction};
use crate::doc::CursorDoc;
use crate::err::Error;
use crate::iam::{Action, ResourceKind};
use crate::{statements::UpdateStatement, Base, Ident, Idioms, Index, Strand, Value, Values};
use derive::Store;
use revision::revisioned;
use serde::{Deserialize, Serialize};
use std::fmt::{self, Display};
#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
#[revisioned(revision = 1)]
pub struct DefineIndexStatement {
pub name: Ident,
pub what: Ident,
pub cols: Idioms,
pub index: Index,
pub comment: Option<Strand>,
}
impl DefineIndexStatement {
pub(crate) async fn compute(
&self,
ctx: &Context<'_>,
opt: &Options,
txn: &Transaction,
doc: Option<&CursorDoc<'_>>,
) -> Result<Value, Error> {
opt.is_allowed(Action::Edit, ResourceKind::Index, &Base::Db)?;
let mut run = txn.lock().await;
run.clear_cache();
let key = crate::key::table::ix::new(opt.ns(), opt.db(), &self.what, &self.name);
run.add_ns(opt.ns(), opt.strict).await?;
run.add_db(opt.ns(), opt.db(), opt.strict).await?;
run.add_tb(opt.ns(), opt.db(), &self.what, opt.strict).await?;
run.set(key, self).await?;
let key = crate::key::index::all::new(opt.ns(), opt.db(), &self.what, &self.name);
run.delp(key, u32::MAX).await?;
let key = crate::key::table::ix::prefix(opt.ns(), opt.db(), &self.what);
run.clr(key).await?;
drop(run);
let opt = &opt.new_with_force(true);
let opt = &opt.new_with_fields(false);
let opt = &opt.new_with_events(false);
let opt = &opt.new_with_tables(false);
let stm = UpdateStatement {
what: Values(vec![Value::Table(self.what.clone().into())]),
..UpdateStatement::default()
};
stm.compute(ctx, opt, txn, doc).await?;
Ok(Value::None)
}
}
impl Display for DefineIndexStatement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "DEFINE INDEX {} ON {} FIELDS {}", self.name, self.what, self.cols)?;
if Index::Idx != self.index {
write!(f, " {}", self.index)?;
}
if let Some(ref v) = self.comment {
write!(f, " COMMENT {v}")?
}
Ok(())
}
}