You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Rework one-to-one relationships to remove existing instead of panicking (#20232)
# Objective
- Issue: #18847
- Resolves panic when establishing a one-to-one relationship to an
entity that already has an existing relationship from another entity.
## Solution
- Modified the `on_insert` hook in the `Relationship` trait to detect
one-to-one relationships (where the target collection type is `Entity`)
and automatically remove any existing relationship before establishing
the new one.
- Uses runtime type checking with `TypeId` to identify one-to-one vs
one-to-many relationships.
- Safely removes the existing source relationship using `try_remove()`
to handle edge cases gracefully.
## Testing
- Removed panic assertions from `Entity::add()` and
`Entity::extend_from_iter()` methods that would previously crash when
attempting to establish overlapping one-to-one relationships
- Modified existing test `one_to_one_relationship_shared_target` by
removing `#[should_panic]` and adding assertions to verify:
- Original relationship is properly removed
- New relationship is correctly established
- Target entity points to the new source
---------
Co-authored-by: Chris Russell <[email protected]>
/// May be faster than repeatedly calling [`Self::add`].
@@ -345,14 +351,7 @@ impl RelationshipSourceCollection for Entity {
345
351
}
346
352
347
353
fnadd(&mutself,entity:Entity) -> bool{
348
-
assert_eq!(
349
-
*self,
350
-
Entity::PLACEHOLDER,
351
-
"Entity {entity} attempted to target an entity with a one-to-one relationship, but it is already targeted by {}. You must remove the original relationship first.",
352
-
*self
353
-
);
354
354
*self = entity;
355
-
356
355
true
357
356
}
358
357
@@ -389,15 +388,17 @@ impl RelationshipSourceCollection for Entity {
"Entity {entity} attempted to target an entity with a one-to-one relationship, but it is already targeted by {}. You must remove the original relationship first.",
0 commit comments