feat: edit/delete terms — audited, blocked when referenced (#30)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-06-05 18:43:02 +02:00
parent f6053068be
commit 09baf2949f
6 changed files with 542 additions and 3 deletions
+11
View File
@@ -10,6 +10,17 @@ pub mod vocab;
use sqlx::postgres::{PgPool, PgPoolOptions};
/// Result of a delete that catalogue-object references may block.
#[derive(Debug, PartialEq, Eq)]
pub enum DeleteOutcome {
/// The row was deleted.
Deleted,
/// Refused: `count` catalogue objects still reference it.
InUse { count: i64 },
/// The row did not exist.
NotFound,
}
/// A handle to the organization's PostgreSQL database.
#[derive(Clone)]
pub struct Db {
+116
View File
@@ -177,6 +177,122 @@ where
Ok(found.map(|_| TermRef::new(term_id, vocabulary_id)))
}
/// Update a term's `external_uri` and labels (full replace), recording an `updated`
/// audit entry. Returns `false` if no such term or the term does not belong to
/// `vocabulary_id`. Pass a transaction connection.
pub async fn update_term(
conn: &mut sqlx::PgConnection,
actor: AuditActor,
vocabulary_id: VocabularyId,
term_id: TermId,
external_uri: Option<&str>,
labels: &[LocalizedLabel],
) -> Result<bool, sqlx::Error> {
let updated =
sqlx::query("UPDATE term SET external_uri = $2 WHERE id = $1 AND vocabulary_id = $3")
.bind(term_id.to_uuid())
.bind(external_uri)
.bind(vocabulary_id.to_uuid())
.execute(&mut *conn)
.await?
.rows_affected();
if updated == 0 {
return Ok(false);
}
sqlx::query("DELETE FROM term_label WHERE term_id = $1")
.bind(term_id.to_uuid())
.execute(&mut *conn)
.await?;
for label in labels {
sqlx::query("INSERT INTO term_label (term_id, lang, label) VALUES ($1, $2, $3)")
.bind(term_id.to_uuid())
.bind(&label.lang)
.bind(&label.label)
.execute(&mut *conn)
.await?;
}
audit::record(
&mut *conn,
&NewAuditEvent {
actor,
action: AuditAction::Updated,
entity_type: TERM_ENTITY_TYPE.to_owned(),
entity_id: term_id.to_uuid(),
changes: Vec::new(),
},
)
.await?;
Ok(true)
}
/// Count catalogue objects that reference `term_id` through a `term`-typed field.
pub async fn count_objects_referencing_term<'e, E>(
executor: E,
term_id: TermId,
) -> Result<i64, sqlx::Error>
where
E: sqlx::PgExecutor<'e>,
{
sqlx::query_scalar(
"SELECT count(*) FROM object o WHERE EXISTS ( \
SELECT 1 FROM field_definition fd \
WHERE fd.data_type = 'term' AND o.fields ->> fd.key = $1 )",
)
.bind(term_id.to_string())
.fetch_one(executor)
.await
}
/// Delete a term (its labels cascade) unless catalogue objects reference it, recording a
/// `deleted` audit entry. Pass a transaction connection.
pub async fn delete_term(
conn: &mut sqlx::PgConnection,
actor: AuditActor,
vocabulary_id: VocabularyId,
term_id: TermId,
) -> Result<crate::DeleteOutcome, sqlx::Error> {
let exists =
sqlx::query_scalar::<_, i32>("SELECT 1 FROM term WHERE id = $1 AND vocabulary_id = $2")
.bind(term_id.to_uuid())
.bind(vocabulary_id.to_uuid())
.fetch_optional(&mut *conn)
.await?;
if exists.is_none() {
return Ok(crate::DeleteOutcome::NotFound);
}
let count = count_objects_referencing_term(&mut *conn, term_id).await?;
if count > 0 {
return Ok(crate::DeleteOutcome::InUse { count });
}
sqlx::query("DELETE FROM term WHERE id = $1")
.bind(term_id.to_uuid())
.execute(&mut *conn)
.await?;
audit::record(
&mut *conn,
&NewAuditEvent {
actor,
action: AuditAction::Deleted,
entity_type: TERM_ENTITY_TYPE.to_owned(),
entity_id: term_id.to_uuid(),
changes: Vec::new(),
},
)
.await?;
Ok(crate::DeleteOutcome::Deleted)
}
fn map_vocabulary(row: sqlx::postgres::PgRow) -> Result<Vocabulary, sqlx::Error> {
Ok(Vocabulary {
id: VocabularyId::from_uuid(row.try_get("id")?),
+146 -2
View File
@@ -1,5 +1,7 @@
use db::{Db, vocab};
use domain::{AuditActor, LocalizedLabel, NewTerm};
use db::{Db, catalog, fields, vocab};
use domain::{
AuditActor, FieldType, LocalizedLabel, NewFieldDefinition, NewTerm, ObjectInput, Visibility,
};
use sqlx::PgPool;
#[sqlx::test]
@@ -169,3 +171,145 @@ async fn resolve_term_checks_vocabulary_membership(pool: PgPool) {
.is_none()
);
}
fn sample_object_input() -> ObjectInput {
ObjectInput {
object_number: "X.1".into(),
object_name: "Test".into(),
number_of_objects: 1,
brief_description: None,
current_location: None,
current_owner: None,
recorder: None,
recording_date: None,
visibility: Visibility::Draft,
}
}
#[sqlx::test(migrations = "../db/migrations")]
async fn update_term_changes_labels_and_uri(pool: PgPool) {
let db = Db::from_pool(pool);
let mut tx = db.pool().begin().await.unwrap();
let vocab = vocab::create_vocabulary(&mut tx, AuditActor::System, "material")
.await
.unwrap();
let term_id = vocab::add_term(
&mut tx,
AuditActor::System,
&NewTerm {
vocabulary_id: vocab.id,
external_uri: None,
labels: vec![LocalizedLabel {
lang: "sv".into(),
label: "Trä".into(),
}],
},
)
.await
.unwrap();
let existed = vocab::update_term(
&mut tx,
AuditActor::System,
vocab.id,
term_id,
Some("https://example.org/wood"),
&[LocalizedLabel {
lang: "sv".into(),
label: "Träslag".into(),
}],
)
.await
.unwrap();
assert!(existed);
tx.commit().await.unwrap();
let term = vocab::term_by_id(db.pool(), term_id)
.await
.unwrap()
.unwrap();
assert_eq!(
term.external_uri.as_deref(),
Some("https://example.org/wood")
);
assert_eq!(term.labels.len(), 1);
assert_eq!(term.labels[0].label, "Träslag");
}
#[sqlx::test(migrations = "../db/migrations")]
async fn delete_term_blocks_when_referenced_then_succeeds(pool: PgPool) {
use db::DeleteOutcome;
let db = Db::from_pool(pool);
let mut tx = db.pool().begin().await.unwrap();
let vocab = vocab::create_vocabulary(&mut tx, AuditActor::System, "material")
.await
.unwrap();
let term_id = vocab::add_term(
&mut tx,
AuditActor::System,
&NewTerm {
vocabulary_id: vocab.id,
external_uri: None,
labels: vec![LocalizedLabel {
lang: "sv".into(),
label: "Trä".into(),
}],
},
)
.await
.unwrap();
fields::create_field_definition(
&mut tx,
&NewFieldDefinition {
key: "material".into(),
field_type: FieldType::Term {
vocabulary_id: vocab.id,
},
required: false,
group_key: None,
labels: vec![LocalizedLabel {
lang: "sv".into(),
label: "Material".into(),
}],
},
)
.await
.unwrap();
let obj = catalog::create_object(&mut tx, AuditActor::System, &sample_object_input())
.await
.unwrap();
let mut map = serde_json::Map::new();
map.insert(
"material".into(),
serde_json::Value::String(term_id.to_string()),
);
catalog::set_object_fields(&mut tx, AuditActor::System, obj, &map)
.await
.unwrap();
let blocked = vocab::delete_term(&mut tx, AuditActor::System, vocab.id, term_id)
.await
.unwrap();
assert_eq!(blocked, DeleteOutcome::InUse { count: 1 });
catalog::set_object_fields(&mut tx, AuditActor::System, obj, &serde_json::Map::new())
.await
.unwrap();
let ok = vocab::delete_term(&mut tx, AuditActor::System, vocab.id, term_id)
.await
.unwrap();
assert_eq!(ok, DeleteOutcome::Deleted);
assert!(
vocab::term_by_id(&mut *tx, term_id)
.await
.unwrap()
.is_none()
);
let gone = vocab::delete_term(&mut tx, AuditActor::System, vocab.id, term_id)
.await
.unwrap();
assert_eq!(gone, DeleteOutcome::NotFound);
}