use anyhow::Result;
use reblessive::tree::Stk;
use surrealdb_strand::TableName;
use uuid::Uuid;
use crate::catalog::providers::TableProvider;
use crate::catalog::{Error, TableDefinition};
use crate::ctx::FrozenContext;
use crate::dbs::Options;
use crate::doc::CursorDoc;
use crate::expr::Base;
use crate::expr::statements::remove::field::RemoveFieldStatement;
use crate::iam::{Action, ResourceKind};
use crate::key::schema::FieldKey;
use crate::legacy::{expr_to_ident, expr_to_idiom};
use crate::val::Value;
pub(crate) async fn remove_field_statement_compute(
this: &RemoveFieldStatement,
stk: &mut Stk,
ctx: &FrozenContext,
opt: &Options,
doc: Option<&CursorDoc>,
) -> Result<Value> {
ctx.is_allowed(opt, Action::Edit, ResourceKind::Field, Base::Db)?;
let table_name =
TableName::new(expr_to_ident(stk, ctx, opt, doc, &this.table_name, "table name").await?);
let name = expr_to_idiom(stk, ctx, opt, doc, &this.name, "field name").await?;
let (ns_name, db_name) = opt.ns_db()?;
let (ns, db) = ctx.expect_ns_db_ids(opt).await?;
let txn = ctx.tx();
if let Some(tb) = txn.get_tb(ns, db, &table_name, None).await? {
anyhow::ensure!(
crate::kvs::lightweight::lightweight_relation(&tb.table_type).is_none(),
crate::exec::Error::Thrown(
"a LIGHTWEIGHT relation's fields cannot be removed: its in/out contract is \
managed by the table definition"
.to_owned(),
)
);
}
let name = name.to_raw_string();
let fd = match txn.get_tb_field(ns, db, &table_name, &name, None).await? {
Some(x) => x,
None => {
if this.if_exists {
return Ok(Value::None);
} else {
return Err(Error::FdNotFound {
name,
}
.into());
}
}
};
let key = FieldKey {
ns,
db,
tb: std::borrow::Cow::Borrowed(&table_name),
fd: std::borrow::Cow::Borrowed(&name),
};
txn.del_key(&key).await?;
crate::legacy::expr::statements::define::field::purge_dropped_reference_keys(
&txn,
ns,
db,
&table_name,
&fd,
None,
)
.await?;
let Some(tb) = txn.get_tb(ns, db, &table_name, None).await? else {
return Err(Error::TbNotFound {
name: table_name,
}
.into());
};
txn.replace_tb(
ns_name,
db_name,
&TableDefinition {
cache_fields_ts: Uuid::now_v7(),
graph_inline_gen: if fd.inline {
tb.graph_inline_gen.wrapping_add(1)
} else {
tb.graph_inline_gen
},
..(*tb).clone()
},
)
.await?;
txn.clear_cache();
Ok(Value::None)
}