use anyhow::{Result, bail};
use reblessive::tree::Stk;
use surrealdb_strand::TableName;
use uuid::Uuid;
use crate::catalog::providers::TableProvider;
use crate::catalog::{Error as CatalogError, TableDefinition};
use crate::ctx::FrozenContext;
use crate::dbs::Options;
use crate::doc::CursorDoc;
use crate::exec::Error as ExecError;
use crate::expr::Base;
use crate::expr::statements::remove::table::RemoveTableStatement;
use crate::iam::{Action, ResourceKind};
use crate::key::schema::{ForeignTableKey, TblRoot};
use crate::legacy::expr::statements::remove::retire_table_indexes;
use crate::legacy::{expr_to_ident, kill_table_subscriptions};
use crate::val::Value;
pub(crate) async fn remove_table_statement_compute(
this: &RemoveTableStatement,
stk: &mut Stk,
ctx: &FrozenContext,
opt: &Options,
doc: Option<&CursorDoc>,
) -> Result<Value> {
ctx.is_allowed(opt, Action::Edit, ResourceKind::Table, Base::Db)?;
let name = TableName::new(expr_to_ident(stk, ctx, opt, doc, &this.name, "table name").await?);
let (ns_name, db_name) = opt.ns_db()?;
let (ns, db) = ctx.expect_ns_db_ids(opt).await?;
let txn = ctx.tx();
let Some(tb) = txn.get_tb(ns, db, &name, None).await? else {
if this.if_exists {
return Ok(Value::None);
}
return Err(CatalogError::TbNotFound {
name,
}
.into());
};
let fts = txn.all_tb_views(ns, db, &name, None).await?;
if !fts.is_empty() {
let mut message =
format!("Cannot delete table `{name}` on which a view is defined, table(s) `");
for (idx, f) in fts.iter().enumerate() {
if idx != 0 {
message.push_str("`, `")
}
message.push_str(f.name.as_str());
}
message.push_str("` are defined as a view on this table.");
bail!(ExecError::Query {
message
});
}
for other in txn.all_tb(ns, db, None).await?.iter() {
let Some(rel) = crate::kvs::lightweight::lightweight_relation(&other.table_type) else {
continue;
};
if other.name == name || (!rel.from.contains(&name) && !rel.to.contains(&name)) {
continue;
}
anyhow::ensure!(
crate::kvs::lightweight::lightweight_relation_is_empty(&txn, ns, db, &other.name, rel)
.await?,
ExecError::Thrown(format!(
"cannot remove `{name}`: the LIGHTWEIGHT relation `{}` uses it as an endpoint \
and still holds edges — delete them first (e.g. `DELETE {}`)",
other.name, other.name
))
);
}
if let Some(rel) = crate::kvs::lightweight::lightweight_relation(&tb.table_type) {
anyhow::ensure!(
crate::kvs::lightweight::lightweight_relation_is_empty(&txn, ns, db, &name, rel)
.await?,
ExecError::Thrown(format!(
"cannot remove the LIGHTWEIGHT relation `{name}` while it holds edges: delete \
them first (e.g. `DELETE {name}`)"
))
);
}
retire_table_indexes(ctx, &txn, ns, db, &tb, this.expunge).await?;
kill_table_subscriptions(ctx, &txn, ns, db, &name).await?;
if this.expunge {
txn.clr_tb(ns_name, db_name, &name).await?
} else {
txn.del_tb(ns_name, db_name, &name).await?
};
let key = TblRoot {
ns,
db,
tb: std::borrow::Cow::Borrowed(&name),
};
if this.expunge {
txn.clr_prefix_key(&key).await?
} else {
txn.del_prefix_key(&key).await?
};
if let Some(tables) = tb.view.as_ref().map(|v| v.source_tables()) {
for ft in tables.iter() {
let key = ForeignTableKey {
ns,
db,
tb: std::borrow::Cow::Borrowed(ft),
ft: std::borrow::Cow::Borrowed(&name),
};
txn.del_key(&key).await?;
let foreign_tb = txn.expect_tb(ns, db, ft).await?;
txn.replace_tb(
ns_name,
db_name,
&TableDefinition {
cache_tables_ts: Uuid::now_v7(),
..(*foreign_tb).clone()
},
)
.await?;
}
}
txn.clear_cache();
Ok(Value::None)
}