Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(tags): publish an entity event for every item a deleted tag leaves (#9120)

gbirmandf89a9dfe687
diff --git a/.sqlx/query-657e0c6418ff6bc4ada878194f855cd596d4b9a03aa07e03d924f815ad5ae95f.json b/.sqlx/query-657e0c6418ff6bc4ada878194f855cd596d4b9a03aa07e03d924f815ad5ae95f.json
deleted file mode 100644
index 8390945791..0000000000
--- a/.sqlx/query-657e0c6418ff6bc4ada878194f855cd596d4b9a03aa07e03d924f815ad5ae95f.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE entity_properties\n SET\n values = jsonb_set(\n values,\n '{value}',\n COALESCE(\n (\n SELECT jsonb_agg(elem)\n FROM jsonb_array_elements(values -> 'value') AS elem\n WHERE NOT (to_jsonb($2::text[]) @> elem)\n ),\n '[]'::jsonb\n )\n ),\n updated_at = NOW()\n WHERE property_definition_id = $1\n AND values -> 'value' ?| $2::text[]\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "TextArray"
- ]
- },
- "nullable": []
- },
- "hash": "657e0c6418ff6bc4ada878194f855cd596d4b9a03aa07e03d924f815ad5ae95f"
-}
diff --git a/.sqlx/query-7538979c27bfef441637be91ea6e375d3d9ca18d25fae8717924adf6ccb52416.json b/.sqlx/query-7538979c27bfef441637be91ea6e375d3d9ca18d25fae8717924adf6ccb52416.json
new file mode 100644
index 0000000000..baae04f830
--- /dev/null
+++ b/.sqlx/query-7538979c27bfef441637be91ea6e375d3d9ca18d25fae8717924adf6ccb52416.json
@@ -0,0 +1,86 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH previous AS (\n SELECT id, values\n FROM entity_properties\n WHERE property_definition_id = $1\n AND values -> 'value' ?| $2::text[]\n ORDER BY id\n FOR UPDATE\n )\n UPDATE entity_properties AS property\n SET\n values = jsonb_set(\n previous.values,\n '{value}',\n COALESCE(\n (\n SELECT jsonb_agg(elem)\n FROM jsonb_array_elements(previous.values -> 'value') AS elem\n WHERE NOT (to_jsonb($2::text[]) @> elem)\n ),\n '[]'::jsonb\n )\n ),\n updated_at = NOW()\n FROM previous\n WHERE property.id = previous.id\n RETURNING\n property.id,\n property.entity_id,\n property.entity_type as \"entity_type: EntityType\",\n property.property_definition_id,\n property.values as \"value: serde_json::Value\",\n previous.values as \"previous: serde_json::Value\",\n property.created_at,\n property.updated_at\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "entity_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "entity_type: EntityType",
+ "type_info": {
+ "Custom": {
+ "name": "property_entity_type",
+ "kind": {
+ "Enum": [
+ "CHANNEL",
+ "CHAT",
+ "DOCUMENT",
+ "PROJECT",
+ "THREAD",
+ "USER",
+ "COMPANY",
+ "TASK",
+ "CALL_RECORD",
+ "CALENDAR_EVENT",
+ "INITIATIVE",
+ "CONTACT",
+ "DATABASE_ROW"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 3,
+ "name": "property_definition_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "value: serde_json::Value",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 5,
+ "name": "previous: serde_json::Value",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ true,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "7538979c27bfef441637be91ea6e375d3d9ca18d25fae8717924adf6ccb52416"
+}
diff --git a/crates/properties/README.md b/crates/properties/README.md
index 8783114451..c05c8b01cb 100644
--- a/crates/properties/README.md
+++ b/crates/properties/README.md
@@ -34,7 +34,7 @@ nested model specifies otherwise.
| `property_option.created` | An option is added to a SELECT or TAG definition. | `option_id`, `property_definition_id`, `actor_user_id`, `value`, `color`, `display_order` |
| `property_option.updated` | An option is renamed, recolored, reordered, or moved to another definition by a tag promotion. The metadata is the full post-update state, not a delta, so `property_definition_id` is the definition that owns the option *after* the change. | `option_id`, `property_definition_id`, `actor_user_id`, `value`, `color`, `display_order` |
| `property_option.deleted` | An option is deleted. `value` is the pre-delete snapshot. | `option_id`, `property_definition_id`, `actor_user_id`, `value` |
-| `entity_property.updated` | An entity value is set, replaced, attached with a null value, or changed by an option add/remove. Bulk operations emit one event for each actual `(entity, property_definition)` mutation. | `entity_property_id`, `entity_id`, `entity_type`, `property_definition_id`, `actor_user_id`, `value`, `updated_at` |
+| `entity_property.updated` | An entity value is set, replaced, attached with a null value, changed by an option add/remove, or has a deleted option stripped from it. Bulk operations emit one event for each actual `(entity, property_definition)` mutation. | `entity_property_id`, `entity_id`, `entity_type`, `property_definition_id`, `actor_user_id`, `value`, `updated_at` |
| `entity_property.deleted` | One entity-property row is deleted. | `entity_property_id`, `entity_id`, `entity_type`, `property_definition_id`, `actor_user_id` |
| `entity_properties.cleared` | `delete_entity_properties` successfully wipes all property values for an entity, including the document-deletion path. One clear event replaces per-value deletion events. | `entity_id`, `entity_type`, `actor_user_id` |
@@ -109,9 +109,10 @@ Definition and option deletion have effects beyond the single event:
- `property.deleted` implies removal of every option and every entity-property
value under that definition. The database cascade does not emit
`property_option.deleted` or per-entity deletion events.
-- `property_option.deleted` implies that the option ID was stripped from every
- entity value that referenced it. This does not fan out
- `entity_property.updated` records.
+- `property_option.deleted` (single delete and option-set replace) is followed
+ by one `entity_property.updated` per entity value the option was stripped
+ from, including a value left empty. A database column's option delete
+ reports through the `databases` change events instead.
Consumers maintaining derived state must apply these implications. Definition
and entity records use different keys, so the lack of cross-key ordering also
@@ -126,9 +127,7 @@ in one transaction, and reports that as a label event plus one
`property_definition_id` is the *team* definition. An option changing its
owning definition is the only case where that field moves; consumers keyed on
the previous definition must re-read rather than assume it is stable.
-- A merge emits `property_option.deleted` for the retired personal option, with
- the same "stripped from every entity value" implication as any option
- deletion.
+- A merge emits `property_option.deleted` for the retired personal option.
- Both emit one `entity_property.updated` per affected entity, carrying the
entity's team-definition row. There is no event for the personal-definition
row the option was stripped from; the entity event is enough for consumers
diff --git a/crates/properties/src/domain/model.rs b/crates/properties/src/domain/model.rs
index 25b2b1491a..64fc322d1c 100644
--- a/crates/properties/src/domain/model.rs
+++ b/crates/properties/src/domain/model.rs
@@ -368,8 +368,14 @@ pub struct PropertyOptionReplacePlan {
/// Outcome of a whole-set option replace.
#[derive(Debug, Clone)]
pub enum PropertyOptionReplaceOutcome {
- /// Every change applied; carries the definition's options afterwards.
- Replaced(Vec<PropertyOption>),
+ /// Every change applied.
+ Replaced {
+ /// The definition's options afterwards.
+ options: Vec<PropertyOption>,
+ /// One post-commit snapshot per entity value a deleted option was
+ /// stripped from.
+ mutations: Vec<EntityPropertyMutationSnapshot>,
+ },
/// An option to delete or rewrite does not belong to the definition.
OptionNotFound,
/// Two options would share a value; nothing was applied.
diff --git a/crates/properties/src/domain/ports.rs b/crates/properties/src/domain/ports.rs
index 1730fd5d8f..b0af9e42b7 100644
--- a/crates/properties/src/domain/ports.rs
+++ b/crates/properties/src/domain/ports.rs
@@ -199,13 +199,13 @@ pub trait PropertiesRepo: Send + Sync + 'static {
) -> impl Future<Output = Result<PropertyOptionReplaceOutcome, Self::Err>> + Send;
/// Delete a property option and strip its id from every entity value that
- /// references it, atomically. Returns `true` if the option was deleted,
- /// `false` if it didn't exist.
+ /// references it, atomically. Returns `None` if the option didn't exist,
+ /// otherwise one post-commit snapshot per entity value it was stripped from.
fn delete_property_option(
&self,
property_definition_id: Uuid,
option_id: Uuid,
- ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+ ) -> impl Future<Output = Result<Option<Vec<EntityPropertyMutationSnapshot>>, Self::Err>> + Send;
/// Get the single tag definition owned by the given owner, if it exists.
// Explicit lifetime required by mockall's automock expansion.
diff --git a/crates/properties/src/domain/service_impl.rs b/crates/properties/src/domain/service_impl.rs
index 2838ca4fe4..c853f967a4 100644
--- a/crates/properties/src/domain/service_impl.rs
+++ b/crates/properties/src/domain/service_impl.rs
@@ -42,10 +42,10 @@ use super::events::{
};
use super::metadata;
use super::model::{
- EditReceipt, EntityOptionUpdateOutcome, EntityPropertyInfo, EntityPropertyOptionSelection,
- EntityPropertyOptionUpdate, PropertyAccessReceiptExt, PropertyDefinitionOwner,
- PropertyOptionReplaceOutcome, PropertyOptionReplacePlan, PropertyTargetKey,
- ResolvedPropertySubject, TagPromotionOutcome, TagRemapOutcome, TagScope, TagSet,
+ EditReceipt, EntityOptionUpdateOutcome, EntityPropertyInfo, EntityPropertyMutationSnapshot,
+ EntityPropertyOptionSelection, EntityPropertyOptionUpdate, PropertyAccessReceiptExt,
+ PropertyDefinitionOwner, PropertyOptionReplaceOutcome, PropertyOptionReplacePlan,
+ PropertyTargetKey, ResolvedPropertySubject, TagPromotionOutcome, TagScope, TagSet,
UpdatePropertyOptionOutcome, ViewReceipt,
};
use super::ports::{
@@ -447,10 +447,15 @@ where
Ok(result.definition)
}
- /// Publish one entity-property event per entity the remap rewrote, so the
- /// search index and Soup rebuild those entities from the committed rows.
- fn publish_tag_remap_events(&self, remap: &TagRemapOutcome, actor: &MacroUserIdStr<'_>) {
- for mutation in &remap.mutations {
+ /// Publish one entity-property event per entity an option delete or tag
+ /// remap rewrote, so search, activity and Soup rebuild those entities from
+ /// the committed rows.
+ fn publish_option_change_events(
+ &self,
+ mutations: &[EntityPropertyMutationSnapshot],
+ actor: &MacroUserIdStr<'_>,
+ ) {
+ for mutation in mutations {
self.publish_property_event(PropertyMacroEvent::entity_property_updated(
EntityPropertyUpdatedMetadata {
entity_property_id: mutation.property.id,
@@ -1540,13 +1545,13 @@ where
.await
.map_err(anyhow::Error::from)?;
- let after = match self
+ let (after, mutations) = match self
.repository
.replace_property_options(property_definition_id, &plan)
.await
.map_err(anyhow::Error::from)?
{
- PropertyOptionReplaceOutcome::Replaced(options) => options,
+ PropertyOptionReplaceOutcome::Replaced { options, mutations } => (options, mutations),
PropertyOptionReplaceOutcome::OptionNotFound => {
return Err(PropertiesErr::OptionNotFound);
}
@@ -1568,6 +1573,7 @@ where
};
self.publish_property_event(event);
}
+ self.publish_option_change_events(&mutations, user_id);
Ok(after)
}
@@ -1597,18 +1603,19 @@ where
return Err(PropertiesErr::OptionNotFound);
}
- let deleted = self
+ let mutations = self
.repository
.delete_property_option(property_definition_id, option_id)
.await
- .map_err(anyhow::Error::from)?;
-
- if !deleted {
- return Err(PropertiesErr::OptionNotFound);
- }
+ .map_err(anyhow::Error::from)?
+ .ok_or(PropertiesErr::OptionNotFound)?;
- tracing::info!("successfully deleted property option");
+ tracing::info!(
+ entities_updated = mutations.len(),
+ "successfully deleted property option"
+ );
self.publish_property_event(Self::property_option_deleted_event(&option, user_id));
+ self.publish_option_change_events(&mutations, user_id);
Ok(())
}
@@ -1702,7 +1709,7 @@ where
// The option keeps its id, so this reports the same label now hanging
// off the team definition rather than a newly created one.
self.publish_property_event(Self::property_option_updated_event(&remap.option, user_id));
- self.publish_tag_remap_events(&remap, user_id);
+ self.publish_option_change_events(&remap.mutations, user_id);
Ok(remap.option)
}
@@ -1743,7 +1750,7 @@ where
);
self.publish_property_event(Self::property_option_deleted_event(&source_option, user_id));
- self.publish_tag_remap_events(&remap, user_id);
+ self.publish_option_change_events(&remap.mutations, user_id);
Ok(remap.option)
}
diff --git a/crates/properties/src/domain/test.rs b/crates/properties/src/domain/test.rs
index 8d7933099e..68bffb4c0c 100644
--- a/crates/properties/src/domain/test.rs
+++ b/crates/properties/src/domain/test.rs
@@ -936,7 +936,7 @@ async fn property_option_event_delete_publishes_one_pre_delete_snapshot_with_exa
repo.expect_get_property_option()
.return_once(move |_| Box::pin(async move { Ok(Some(option)) }));
repo.expect_delete_property_option()
- .return_once(|_, _| Box::pin(async { Ok(true) }));
+ .return_once(|_, _| Box::pin(async { Ok(Some(Vec::new())) }));
let event_broker = RecordingEventBroker::default();
let service = service_with_event_broker(repo, event_broker.clone());
@@ -960,6 +960,90 @@ async fn property_option_event_delete_publishes_one_pre_delete_snapshot_with_exa
);
}
+#[tokio::test]
+async fn property_option_event_delete_publishes_every_stripped_entity() {
+ let property_definition_id = Uuid::from_u128(0xC9);
+ let option_id = Uuid::from_u128(0xCA);
+ let kept_option_id = Uuid::from_u128(0xCB);
+ let definition =
+ property_definition_for_event(property_definition_id, "Tags", DataType::Tag, true);
+ let option = property_option_for_event(
+ option_id,
+ property_definition_id,
+ 0,
+ PropertyOptionValue::String("Retired".to_string()),
+ Some("#ff0000"),
+ );
+
+ let mut repo = MockPropertiesRepo::new();
+ expect_owned_modifiable_definition(&mut repo, definition);
+ repo.expect_get_property_option()
+ .return_once(move |_| Box::pin(async move { Ok(Some(option)) }));
+ repo.expect_delete_property_option()
+ .return_once(move |_, _| {
+ Box::pin(async move {
+ Ok(Some(vec![
+ entity_property_mutation(
+ "doc1",
+ EntityType::Document,
+ property_definition_id,
+ Some(PropertyValue::SelectOption(vec![kept_option_id])),
+ ),
+ entity_property_mutation(
+ "thread1",
+ EntityType::Thread,
+ property_definition_id,
+ Some(PropertyValue::SelectOption(vec![])),
+ ),
+ ]))
+ })
+ });
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ service
+ .delete_property_option(&caller_user_id(), None, property_definition_id, option_id)
+ .await
+ .unwrap();
+
+ let events: Vec<_> = event_broker
+ .events()
+ .iter()
+ .map(|event| {
+ (
+ event.envelope["event_type"].as_str().unwrap().to_string(),
+ event.key.clone(),
+ event.envelope["metadata"]["value"].clone(),
+ event.envelope["metadata"]["actor_user_id"].clone(),
+ )
+ })
+ .collect();
+ let actor = serde_json::json!(caller_user_id().to_string());
+ assert_eq!(
+ events,
+ vec![
+ (
+ "property_option.deleted".to_string(),
+ property_definition_id.to_string(),
+ serde_json::json!({ "type": "string", "value": "Retired" }),
+ actor.clone(),
+ ),
+ (
+ "entity_property.updated".to_string(),
+ "doc1".to_string(),
+ serde_json::json!({ "type": "SelectOption", "value": [kept_option_id] }),
+ actor.clone(),
+ ),
+ (
+ "entity_property.updated".to_string(),
+ "thread1".to_string(),
+ serde_json::json!({ "type": "SelectOption", "value": [] }),
+ actor,
+ ),
+ ]
+ );
+}
+
#[tokio::test]
async fn property_option_event_delete_not_found_outcome_publishes_nothing() {
let property_definition_id = Uuid::from_u128(0xC5);
@@ -983,7 +1067,7 @@ async fn property_option_event_delete_not_found_outcome_publishes_nothing() {
repo.expect_get_property_option()
.return_once(move |_| Box::pin(async move { Ok(Some(option)) }));
repo.expect_delete_property_option()
- .return_once(|_, _| Box::pin(async { Ok(false) }));
+ .return_once(|_, _| Box::pin(async { Ok(None) }));
let event_broker = RecordingEventBroker::default();
let service = service_with_event_broker(repo, event_broker.clone());
diff --git a/crates/properties/src/outbound/database_option_writer.rs b/crates/properties/src/outbound/database_option_writer.rs
index bda8ff9d0a..cb74977b56 100644
--- a/crates/properties/src/outbound/database_option_writer.rs
+++ b/crates/properties/src/outbound/database_option_writer.rs
@@ -168,7 +168,7 @@ impl DatabaseOptionWriter for PropertiesPgRepo {
property_definition_id: Uuid,
option_id: Uuid,
) -> Result<bool, Self::Err> {
- let deleted = property_option_queries::delete_options_in_tx(
+ let (deleted, _) = property_option_queries::delete_options_in_tx(
transaction,
property_definition_id,
&[option_id],
diff --git a/crates/properties/src/outbound/options_test.rs b/crates/properties/src/outbound/options_test.rs
index b1a9c1066a..df18b26393 100644
--- a/crates/properties/src/outbound/options_test.rs
+++ b/crates/properties/src/outbound/options_test.rs
@@ -231,7 +231,7 @@ async fn delete_property_option_removes_option(pool: Pool<Postgres>) -> anyhow::
assert!(repo.get_property_option(option_id).await?.is_some());
let deleted = repo.delete_property_option(property_id, option_id).await?;
- assert!(deleted);
+ assert!(deleted.is_some());
assert!(repo.get_property_option(option_id).await?.is_none());
@@ -248,7 +248,7 @@ async fn delete_nonexistent_property_option(pool: Pool<Postgres>) -> anyhow::Res
let deleted = repo
.delete_property_option(PRIORITY_PROPERTY_ID.parse().unwrap(), Uuid::nil())
.await?;
- assert!(!deleted);
+ assert!(deleted.is_none());
Ok(())
}
@@ -312,8 +312,35 @@ async fn delete_property_option_strips_value_references(
.id;
// Delete option D.
- let deleted = repo.delete_property_option(property_id, opt_d).await?;
- assert!(deleted);
+ let deleted = repo
+ .delete_property_option(property_id, opt_d)
+ .await?
+ .expect("option D exists");
+
+ // One snapshot per entity that held D (the fixture's thread1 too), so the
+ // service can publish an entity event for each; doc1 never held D.
+ let mut stripped: Vec<_> = deleted
+ .into_iter()
+ .map(|m| (m.property.entity_id, m.value, m.previous_value))
+ .collect();
+ stripped.sort_by(|a, b| a.0.cmp(&b.0));
+ assert_eq!(
+ stripped,
+ vec![
+ (
+ "doc_cascade".to_string(),
+ Some(PropertyValue::SelectOption(vec![opt_a, opt_b, opt_c])),
+ Some(PropertyValue::SelectOption(vec![
+ opt_a, opt_b, opt_c, opt_d,
+ ])),
+ ),
+ (
+ "thread1".to_string(),
+ Some(PropertyValue::SelectOption(vec![])),
+ Some(PropertyValue::SelectOption(vec![opt_d])),
+ ),
+ ]
+ );
// Read the raw stored value (bypassing the read-path cleaner) to prove
// the dangling id is gone from storage, not just filtered on read.
@@ -488,7 +515,7 @@ async fn replace_property_options_applies_the_plan_in_one_pass(
)
.await?;
- let PropertyOptionReplaceOutcome::Replaced(options) = outcome else {
+ let PropertyOptionReplaceOutcome::Replaced { options, .. } = outcome else {
panic!("expected Replaced, got {outcome:?}");
};
let labels: Vec<(Uuid, String)> = options
@@ -554,12 +581,36 @@ async fn replace_property_options_strips_every_deleted_id(
)
.await?;
- let PropertyOptionReplaceOutcome::Replaced(options) = outcome else {
+ let PropertyOptionReplaceOutcome::Replaced { options, mutations } = outcome else {
panic!("expected Replaced, got {outcome:?}");
};
assert_eq!(options.len(), 2);
assert!(options.iter().all(|o| o.id != medium && o.id != urgent));
+ // The fixture's proj1 held Medium and thread1 held Urgent.
+ let mut stripped: Vec<_> = mutations
+ .into_iter()
+ .map(|m| (m.property.entity_id, m.value))
+ .collect();
+ stripped.sort_by(|a, b| a.0.cmp(&b.0));
+ assert_eq!(
+ stripped,
+ vec![
+ (
+ "doc_multi_delete".to_string(),
+ Some(PropertyValue::SelectOption(vec![low])),
+ ),
+ (
+ "proj1".to_string(),
+ Some(PropertyValue::SelectOption(vec![])),
+ ),
+ (
+ "thread1".to_string(),
+ Some(PropertyValue::SelectOption(vec![])),
+ ),
+ ]
+ );
+
let raw: serde_json::Value = sqlx::query_scalar!(
r#"
SELECT values as "values!: serde_json::Value"
diff --git a/crates/properties/src/outbound/properties_pg_repo.rs b/crates/properties/src/outbound/properties_pg_repo.rs
index 9da9ced6d0..d469a91169 100644
--- a/crates/properties/src/outbound/properties_pg_repo.rs
+++ b/crates/properties/src/outbound/properties_pg_repo.rs
@@ -323,7 +323,7 @@ impl PropertiesRepo for PropertiesPgRepo {
&self,
property_definition_id: Uuid,
option_id: Uuid,
- ) -> Result<bool, Self::Err> {
+ ) -> Result<Option<Vec<EntityPropertyMutationSnapshot>>, Self::Err> {
property_option_queries::delete_property_option(
&self.pool,
property_definition_id,
diff --git a/crates/properties/src/outbound/property_option_queries.rs b/crates/properties/src/outbound/property_option_queries.rs
index bae7e39e96..aad1b26ed8 100644
--- a/crates/properties/src/outbound/property_option_queries.rs
+++ b/crates/properties/src/outbound/property_option_queries.rs
@@ -2,17 +2,18 @@
use std::collections::HashMap;
-use models_properties::db;
use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};
+use models_properties::{EntityType, db};
use sqlx::{PgExecutor, Pool, Postgres};
use uuid::Uuid;
+use super::entity_property_queries::EntityPropertyMutationRow;
use super::query_error::PropertyQueryError;
use crate::domain::database_option_writer::ColorChange;
use crate::domain::model::{
- GetOrCreatePropertyOptionResult, PropertyOptionReplaceOutcome, PropertyOptionReplacePlan,
- UpdatePropertyOptionOutcome,
+ EntityPropertyMutationSnapshot, GetOrCreatePropertyOptionResult, PropertyOptionReplaceOutcome,
+ PropertyOptionReplacePlan, UpdatePropertyOptionOutcome,
};
/// Keep selected options alive until their assignment commits. Validation
@@ -425,27 +426,29 @@ pub async fn clear_emptied_database_row_values(
/// references it, atomically. Without the cleanup a stored value keeps the
/// dead id and a later set-value that echoes the full id list fails option
/// validation.
-/// Returns Ok(true) if the option was deleted, Ok(false) if it didn't exist.
-#[tracing::instrument(skip(pool))]
+/// Returns `None` if the option didn't exist, otherwise one snapshot per entity
+/// value the option was stripped from.
+#[tracing::instrument(skip(pool), err)]
pub async fn delete_property_option(
pool: &Pool<Postgres>,
property_definition_id: Uuid,
property_option_id: Uuid,
-) -> anyhow::Result<bool> {
+) -> anyhow::Result<Option<Vec<EntityPropertyMutationSnapshot>>> {
let mut tx = pool.begin().await?;
- let deleted =
+ let (deleted, mutations) =
delete_options_in_tx(&mut tx, property_definition_id, &[property_option_id]).await?;
tx.commit().await?;
- Ok(deleted == 1)
+ Ok((deleted == 1).then_some(mutations))
}
/// Deletes the given options in one statement each for the value cleanup and
-/// the delete. Returns how many options were deleted.
+/// the delete. Returns how many options were deleted and the post-write state
+/// of every entity value they were stripped from.
pub(crate) async fn delete_options_in_tx(
tx: &mut sqlx::Transaction<'_, Postgres>,
property_definition_id: Uuid,
option_ids: &[Uuid],
-) -> Result<u64, PropertyQueryError> {
+) -> Result<(u64, Vec<EntityPropertyMutationSnapshot>), PropertyQueryError> {
// Serialize removals before their cleanup snapshot. Otherwise an
// assignment can commit between cleanup and DELETE, leaving a stale id.
sqlx::query_scalar!(
@@ -462,31 +465,55 @@ pub(crate) async fn delete_options_in_tx(
.fetch_all(&mut **tx)
.await?;
let option_id_strings: Vec<String> = option_ids.iter().map(Uuid::to_string).collect();
- sqlx::query!(
+ // Lock the rows in a stable order, waiting out value writers so the
+ // returned previous value is the one this statement rewrote.
+ let rows = sqlx::query_as!(
+ EntityPropertyMutationRow,
r#"
- UPDATE entity_properties
+ WITH previous AS (
+ SELECT id, values
+ FROM entity_properties
+ WHERE property_definition_id = $1
+ AND values -> 'value' ?| $2::text[]
+ ORDER BY id
+ FOR UPDATE
+ )
+ UPDATE entity_properties AS property
SET
values = jsonb_set(
- values,
+ previous.values,
'{value}',
COALESCE(
(
SELECT jsonb_agg(elem)
- FROM jsonb_array_elements(values -> 'value') AS elem
+ FROM jsonb_array_elements(previous.values -> 'value') AS elem
WHERE NOT (to_jsonb($2::text[]) @> elem)
),
'[]'::jsonb
)
),
updated_at = NOW()
- WHERE property_definition_id = $1
- AND values -> 'value' ?| $2::text[]
+ FROM previous
+ WHERE property.id = previous.id
+ RETURNING
+ property.id,
+ property.entity_id,
+ property.entity_type as "entity_type: EntityType",
+ property.property_definition_id,
+ property.values as "value: serde_json::Value",
+ previous.values as "previous: serde_json::Value",
+ property.created_at,
+ property.updated_at
"#,
property_definition_id,
&option_id_strings,
)
- .execute(&mut **tx)
+ .fetch_all(&mut **tx)
.await?;
+ let mutations = rows
+ .into_iter()
+ .map(EntityPropertyMutationRow::into_snapshot)
+ .collect::<Result<_, _>>()?;
let result = sqlx::query!(
"DELETE FROM property_options WHERE property_definition_id = $1 AND id = ANY($2)",
@@ -496,7 +523,7 @@ pub(crate) async fn delete_options_in_tx(
.execute(&mut **tx)
.await?;
- Ok(result.rows_affected())
+ Ok((result.rows_affected(), mutations))
}
/// Applies a [`PropertyOptionReplacePlan`] in one transaction, one statement
@@ -510,12 +537,16 @@ pub async fn replace_property_options(
) -> anyhow::Result<PropertyOptionReplaceOutcome> {
let mut tx = pool.begin().await?;
- if !plan.delete.is_empty() {
- let deleted = delete_options_in_tx(&mut tx, property_definition_id, &plan.delete).await?;
+ let mutations = if plan.delete.is_empty() {
+ Vec::new()
+ } else {
+ let (deleted, mutations) =
+ delete_options_in_tx(&mut tx, property_definition_id, &plan.delete).await?;
if deleted != plan.delete.len() as u64 {
return Ok(PropertyOptionReplaceOutcome::OptionNotFound);
}
- }
+ mutations
+ };
if !plan.rewrite.is_empty() {
let rewrite_ids: Vec<Uuid> = plan.rewrite.iter().map(|r| r.option_id).collect();
@@ -623,8 +654,9 @@ pub async fn replace_property_options(
.await?;
tx.commit().await?;
- rows.into_iter()
+ let options = rows
+ .into_iter()
.map(|row| row.try_into().map_err(anyhow::Error::from))
- .collect::<anyhow::Result<Vec<_>>>()
- .map(PropertyOptionReplaceOutcome::Replaced)
+ .collect::<anyhow::Result<Vec<_>>>()?;
+ Ok(PropertyOptionReplaceOutcome::Replaced { options, mutations })
}