feat: edit/delete authorities, blocked when referenced (#30)
This commit is contained in:
@@ -124,6 +124,115 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Update an authority's `external_uri` and labels (full replace), recording an
|
||||
/// `updated` audit entry. Returns `false` if no such authority. `kind` is immutable.
|
||||
pub async fn update_authority(
|
||||
conn: &mut sqlx::PgConnection,
|
||||
actor: AuditActor,
|
||||
id: AuthorityId,
|
||||
external_uri: Option<&str>,
|
||||
labels: &[LocalizedLabel],
|
||||
) -> Result<bool, sqlx::Error> {
|
||||
let updated = sqlx::query("UPDATE authority SET external_uri = $2 WHERE id = $1")
|
||||
.bind(id.to_uuid())
|
||||
.bind(external_uri)
|
||||
.execute(&mut *conn)
|
||||
.await?
|
||||
.rows_affected();
|
||||
|
||||
if updated == 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
sqlx::query("DELETE FROM authority_label WHERE authority_id = $1")
|
||||
.bind(id.to_uuid())
|
||||
.execute(&mut *conn)
|
||||
.await?;
|
||||
|
||||
for label in labels {
|
||||
sqlx::query("INSERT INTO authority_label (authority_id, lang, label) VALUES ($1, $2, $3)")
|
||||
.bind(id.to_uuid())
|
||||
.bind(&label.lang)
|
||||
.bind(&label.label)
|
||||
.execute(&mut *conn)
|
||||
.await?;
|
||||
}
|
||||
|
||||
audit::record(
|
||||
&mut *conn,
|
||||
&NewAuditEvent {
|
||||
actor,
|
||||
action: AuditAction::Updated,
|
||||
entity_type: AUTHORITY_ENTITY_TYPE.to_owned(),
|
||||
entity_id: id.to_uuid(),
|
||||
changes: Vec::new(),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Count catalogue objects referencing `id` through an `authority`-typed field.
|
||||
pub async fn count_objects_referencing_authority<'e, E>(
|
||||
executor: E,
|
||||
id: AuthorityId,
|
||||
) -> 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 = 'authority' AND o.fields ->> fd.key = $1 )",
|
||||
)
|
||||
.bind(id.to_string())
|
||||
.fetch_one(executor)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Delete an authority (labels cascade) unless catalogue objects reference it,
|
||||
/// recording a `deleted` audit entry.
|
||||
pub async fn delete_authority(
|
||||
conn: &mut sqlx::PgConnection,
|
||||
actor: AuditActor,
|
||||
id: AuthorityId,
|
||||
) -> Result<crate::DeleteOutcome, sqlx::Error> {
|
||||
let exists = sqlx::query_scalar::<_, i32>("SELECT 1 FROM authority WHERE id = $1")
|
||||
.bind(id.to_uuid())
|
||||
.fetch_optional(&mut *conn)
|
||||
.await?;
|
||||
|
||||
if exists.is_none() {
|
||||
return Ok(crate::DeleteOutcome::NotFound);
|
||||
}
|
||||
|
||||
let count = count_objects_referencing_authority(&mut *conn, id).await?;
|
||||
|
||||
if count > 0 {
|
||||
return Ok(crate::DeleteOutcome::InUse { count });
|
||||
}
|
||||
|
||||
sqlx::query("DELETE FROM authority WHERE id = $1")
|
||||
.bind(id.to_uuid())
|
||||
.execute(&mut *conn)
|
||||
.await?;
|
||||
|
||||
audit::record(
|
||||
&mut *conn,
|
||||
&NewAuditEvent {
|
||||
actor,
|
||||
action: AuditAction::Deleted,
|
||||
entity_type: AUTHORITY_ENTITY_TYPE.to_owned(),
|
||||
entity_id: id.to_uuid(),
|
||||
changes: Vec::new(),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(crate::DeleteOutcome::Deleted)
|
||||
}
|
||||
|
||||
fn map_authority(row: sqlx::postgres::PgRow) -> Result<Authority, sqlx::Error> {
|
||||
let kind_str: String = row.try_get("kind")?;
|
||||
let kind = AuthorityKind::from_db(&kind_str)
|
||||
|
||||
@@ -1,7 +1,23 @@
|
||||
use db::{Db, authority};
|
||||
use domain::{AuditActor, AuthorityKind, LocalizedLabel, NewAuthority};
|
||||
use db::{Db, authority, catalog, fields};
|
||||
use domain::{
|
||||
AuditActor, AuthorityKind, LocalizedLabel, NewAuthority, NewFieldDefinition, Visibility,
|
||||
};
|
||||
use sqlx::PgPool;
|
||||
|
||||
fn sample_object_input() -> domain::ObjectInput {
|
||||
domain::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 new_person(name_sv: &str, name_en: &str) -> NewAuthority {
|
||||
NewAuthority {
|
||||
kind: AuthorityKind::Person,
|
||||
@@ -131,3 +147,117 @@ async fn authority_with_no_labels_round_trips_empty(pool: PgPool) {
|
||||
assert_eq!(got.kind, AuthorityKind::Organisation);
|
||||
assert!(got.labels.is_empty());
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../db/migrations")]
|
||||
async fn update_authority_changes_labels(pool: PgPool) {
|
||||
let db = Db::from_pool(pool);
|
||||
let mut tx = db.pool().begin().await.unwrap();
|
||||
let id = authority::create_authority(
|
||||
&mut tx,
|
||||
AuditActor::System,
|
||||
&NewAuthority {
|
||||
kind: AuthorityKind::Person,
|
||||
external_uri: None,
|
||||
labels: vec![LocalizedLabel {
|
||||
lang: "sv".into(),
|
||||
label: "Anon".into(),
|
||||
}],
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let existed = authority::update_authority(
|
||||
&mut tx,
|
||||
AuditActor::System,
|
||||
id,
|
||||
Some("https://viaf.org/1"),
|
||||
&[LocalizedLabel {
|
||||
lang: "sv".into(),
|
||||
label: "Astrid".into(),
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(existed);
|
||||
tx.commit().await.unwrap();
|
||||
|
||||
let a = authority::authority_by_id(db.pool(), id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(a.external_uri.as_deref(), Some("https://viaf.org/1"));
|
||||
assert_eq!(a.labels[0].label, "Astrid");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../db/migrations")]
|
||||
async fn delete_authority_blocks_when_referenced(pool: PgPool) {
|
||||
use db::DeleteOutcome;
|
||||
|
||||
let db = Db::from_pool(pool);
|
||||
let mut tx = db.pool().begin().await.unwrap();
|
||||
let id = authority::create_authority(
|
||||
&mut tx,
|
||||
AuditActor::System,
|
||||
&NewAuthority {
|
||||
kind: AuthorityKind::Person,
|
||||
external_uri: None,
|
||||
labels: vec![LocalizedLabel {
|
||||
lang: "sv".into(),
|
||||
label: "Astrid".into(),
|
||||
}],
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
fields::create_field_definition(
|
||||
&mut tx,
|
||||
&NewFieldDefinition {
|
||||
key: "maker".into(),
|
||||
field_type: domain::FieldType::Authority {
|
||||
kind: Some(AuthorityKind::Person),
|
||||
},
|
||||
required: false,
|
||||
group_key: None,
|
||||
labels: vec![LocalizedLabel {
|
||||
lang: "sv".into(),
|
||||
label: "Tillverkare".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("maker".into(), serde_json::Value::String(id.to_string()));
|
||||
catalog::set_object_fields(&mut tx, AuditActor::System, obj, &map)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
authority::delete_authority(&mut tx, AuditActor::System, id)
|
||||
.await
|
||||
.unwrap(),
|
||||
DeleteOutcome::InUse { count: 1 }
|
||||
);
|
||||
|
||||
catalog::set_object_fields(&mut tx, AuditActor::System, obj, &serde_json::Map::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
authority::delete_authority(&mut tx, AuditActor::System, id)
|
||||
.await
|
||||
.unwrap(),
|
||||
DeleteOutcome::Deleted
|
||||
);
|
||||
assert_eq!(
|
||||
authority::delete_authority(&mut tx, AuditActor::System, id)
|
||||
.await
|
||||
.unwrap(),
|
||||
DeleteOutcome::NotFound
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user