feat: edit/delete field definitions — audited, blocked when in use (#36)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
+118
-2
@@ -1,11 +1,15 @@
|
||||
//! Registry of flexible field definitions.
|
||||
|
||||
use domain::{
|
||||
AuthorityKind, FieldDefinition, FieldDefinitionId, FieldType, LocalizedLabel,
|
||||
NewFieldDefinition, VocabularyId,
|
||||
AuditAction, AuditActor, AuthorityKind, FieldDefinition, FieldDefinitionId, FieldType,
|
||||
LocalizedLabel, NewAuditEvent, NewFieldDefinition, VocabularyId,
|
||||
};
|
||||
use sqlx::Row;
|
||||
|
||||
use crate::audit;
|
||||
|
||||
const FIELD_DEFINITION_ENTITY_TYPE: &str = "field_definition";
|
||||
|
||||
/// Labels aggregated per row as JSON, to read a definition and its labels in one query.
|
||||
const LABELS_JSON: &str = "COALESCE(json_agg(json_build_object('lang', fdl.lang, 'label', fdl.label) \
|
||||
ORDER BY fdl.lang) FILTER (WHERE fdl.field_definition_id IS NOT NULL), '[]'::json)";
|
||||
@@ -121,3 +125,115 @@ fn map_field_definition(row: sqlx::postgres::PgRow) -> Result<FieldDefinition, s
|
||||
labels: labels.0,
|
||||
})
|
||||
}
|
||||
|
||||
/// Update a field definition's mutable attributes (`required`, `group_key`, labels);
|
||||
/// `key`, `data_type`, and binding are immutable and untouched. Records an `updated`
|
||||
/// audit entry. Returns `false` if no such key. Pass a transaction connection.
|
||||
pub async fn update_field_definition(
|
||||
conn: &mut sqlx::PgConnection,
|
||||
actor: AuditActor,
|
||||
key: &str,
|
||||
required: bool,
|
||||
group_key: Option<&str>,
|
||||
labels: &[LocalizedLabel],
|
||||
) -> Result<bool, sqlx::Error> {
|
||||
let id: Option<uuid::Uuid> =
|
||||
sqlx::query_scalar("SELECT id FROM field_definition WHERE key = $1")
|
||||
.bind(key)
|
||||
.fetch_optional(&mut *conn)
|
||||
.await?;
|
||||
|
||||
let Some(id) = id else { return Ok(false) };
|
||||
|
||||
sqlx::query("UPDATE field_definition SET required = $2, group_key = $3 WHERE id = $1")
|
||||
.bind(id)
|
||||
.bind(required)
|
||||
.bind(group_key)
|
||||
.execute(&mut *conn)
|
||||
.await?;
|
||||
|
||||
sqlx::query("DELETE FROM field_definition_label WHERE field_definition_id = $1")
|
||||
.bind(id)
|
||||
.execute(&mut *conn)
|
||||
.await?;
|
||||
|
||||
for label in labels {
|
||||
sqlx::query(
|
||||
"INSERT INTO field_definition_label (field_definition_id, lang, label) \
|
||||
VALUES ($1, $2, $3)",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(&label.lang)
|
||||
.bind(&label.label)
|
||||
.execute(&mut *conn)
|
||||
.await?;
|
||||
}
|
||||
|
||||
audit::record(
|
||||
&mut *conn,
|
||||
&NewAuditEvent {
|
||||
actor,
|
||||
action: AuditAction::Updated,
|
||||
entity_type: FIELD_DEFINITION_ENTITY_TYPE.to_owned(),
|
||||
entity_id: id,
|
||||
changes: Vec::new(),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Count catalogue objects that store a value under field `key`.
|
||||
pub async fn count_objects_using_field<'e, E>(executor: E, key: &str) -> Result<i64, sqlx::Error>
|
||||
where
|
||||
E: sqlx::PgExecutor<'e>,
|
||||
{
|
||||
sqlx::query_scalar("SELECT count(*) FROM object WHERE jsonb_exists(fields, $1)")
|
||||
.bind(key)
|
||||
.fetch_one(executor)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Delete a field definition (labels cascade) unless catalogue objects use its key,
|
||||
/// recording a `deleted` audit entry. Pass a transaction connection.
|
||||
pub async fn delete_field_definition(
|
||||
conn: &mut sqlx::PgConnection,
|
||||
actor: AuditActor,
|
||||
key: &str,
|
||||
) -> Result<crate::DeleteOutcome, sqlx::Error> {
|
||||
let id: Option<uuid::Uuid> =
|
||||
sqlx::query_scalar("SELECT id FROM field_definition WHERE key = $1")
|
||||
.bind(key)
|
||||
.fetch_optional(&mut *conn)
|
||||
.await?;
|
||||
|
||||
let Some(id) = id else {
|
||||
return Ok(crate::DeleteOutcome::NotFound);
|
||||
};
|
||||
|
||||
let count = count_objects_using_field(&mut *conn, key).await?;
|
||||
|
||||
if count > 0 {
|
||||
return Ok(crate::DeleteOutcome::InUse { count });
|
||||
}
|
||||
|
||||
sqlx::query("DELETE FROM field_definition WHERE id = $1")
|
||||
.bind(id)
|
||||
.execute(&mut *conn)
|
||||
.await?;
|
||||
|
||||
audit::record(
|
||||
&mut *conn,
|
||||
&NewAuditEvent {
|
||||
actor,
|
||||
action: AuditAction::Deleted,
|
||||
entity_type: FIELD_DEFINITION_ENTITY_TYPE.to_owned(),
|
||||
entity_id: id,
|
||||
changes: Vec::new(),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(crate::DeleteOutcome::Deleted)
|
||||
}
|
||||
|
||||
+123
-2
@@ -1,7 +1,24 @@
|
||||
use db::{Db, fields, vocab};
|
||||
use domain::{AuditActor, AuthorityKind, FieldType, LocalizedLabel, NewFieldDefinition};
|
||||
use db::{Db, DeleteOutcome, catalog, fields, vocab};
|
||||
use domain::{
|
||||
AuditActor, AuthorityKind, FieldType, LocalizedLabel, NewFieldDefinition, ObjectInput,
|
||||
Visibility,
|
||||
};
|
||||
use sqlx::PgPool;
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
fn labels() -> Vec<LocalizedLabel> {
|
||||
vec![
|
||||
LocalizedLabel {
|
||||
@@ -171,3 +188,107 @@ async fn any_authority_scalar_and_zero_labels_round_trip(pool: PgPool) {
|
||||
let keys: Vec<&str> = all.iter().map(|d| d.key.as_str()).collect();
|
||||
assert_eq!(keys, vec!["donor", "on_display"]);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../db/migrations")]
|
||||
async fn update_field_definition_edits_labels_group_required(pool: PgPool) {
|
||||
let db = Db::from_pool(pool);
|
||||
let mut tx = db.pool().begin().await.unwrap();
|
||||
|
||||
fields::create_field_definition(
|
||||
&mut tx,
|
||||
&NewFieldDefinition {
|
||||
key: "weight".into(),
|
||||
field_type: FieldType::Integer,
|
||||
required: false,
|
||||
group_key: None,
|
||||
labels: vec![LocalizedLabel {
|
||||
lang: "sv".into(),
|
||||
label: "Vikt".into(),
|
||||
}],
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let existed = fields::update_field_definition(
|
||||
&mut tx,
|
||||
AuditActor::System,
|
||||
"weight",
|
||||
true,
|
||||
Some("Mått"),
|
||||
&[LocalizedLabel {
|
||||
lang: "sv".into(),
|
||||
label: "Vikt (g)".into(),
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(existed);
|
||||
|
||||
tx.commit().await.unwrap();
|
||||
|
||||
let def = fields::field_definition_by_key(db.pool(), "weight")
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(def.required);
|
||||
assert_eq!(def.group_key.as_deref(), Some("Mått"));
|
||||
assert_eq!(def.labels[0].label, "Vikt (g)");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../db/migrations")]
|
||||
async fn delete_field_definition_blocks_when_objects_use_it(pool: PgPool) {
|
||||
let db = Db::from_pool(pool);
|
||||
let mut tx = db.pool().begin().await.unwrap();
|
||||
|
||||
fields::create_field_definition(
|
||||
&mut tx,
|
||||
&NewFieldDefinition {
|
||||
key: "weight".into(),
|
||||
field_type: FieldType::Integer,
|
||||
required: false,
|
||||
group_key: None,
|
||||
labels: vec![LocalizedLabel {
|
||||
lang: "sv".into(),
|
||||
label: "Vikt".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("weight".into(), serde_json::Value::from(42));
|
||||
catalog::set_object_fields(&mut tx, AuditActor::System, obj, &map)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
fields::delete_field_definition(&mut tx, AuditActor::System, "weight")
|
||||
.await
|
||||
.unwrap(),
|
||||
DeleteOutcome::InUse { count: 1 }
|
||||
);
|
||||
|
||||
catalog::set_object_fields(&mut tx, AuditActor::System, obj, &serde_json::Map::new())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
fields::delete_field_definition(&mut tx, AuditActor::System, "weight")
|
||||
.await
|
||||
.unwrap(),
|
||||
DeleteOutcome::Deleted
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
fields::delete_field_definition(&mut tx, AuditActor::System, "weight")
|
||||
.await
|
||||
.unwrap(),
|
||||
DeleteOutcome::NotFound
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user