realm / realm-core

Core database component for the Realm Mobile Database SDKs
https://realm.io
Apache License 2.0
1.01k stars 155 forks source link

Allow passing a managed collection when setting a Mixed or Collection property #7422

Open elle-j opened 6 months ago

elle-j commented 6 months ago

Describe your problem or use case

For the collection in Mixed feature (as well as for regular collections) it would be really convenient if Core could accept a managed collection in the set/insert APIs. This could save the SDKs from heavy lifting when assigning an already managed collection to a Mixed or Collection field.

The issue is that SDKs currently need to clear the existing collection before assigning a new one. So in the case of a self-assignment, all the data in the collection would be lost, e.g.:

// Update a list on a Mixed property.
obj.mixed[0] = [1, 2, 3];
obj.mixed[0] = obj.mixed[0]; // Result is an empty list 😢

The current implementations would (a) clear the LHS, (b) create a new collection, (c) and assign the content from the RHS element by element. However, for a self-assignment, this would clear the target list in Core and the RHS collection will be empty since it is operating on the same underlying list.

A current workaround for SDKs would be to first (a) detect a self-assignment, (b) replicate the full RHS as an unmanaged collection in memory, then perform the same prior steps but use the replicated structure instead. (We likely cannot just treat it as a no-op for self assignment as we need to ensure that we generate the appropriate merge instructions.)

We would like to avoid potentially having to load deeply nested collections into memory.

Describe the solution you'd like

Perhaps this could be generalized to a more efficient Core API where Core would clone the content of the RHS-collection into the new collection.

At least being able to pass a managed collection and have Core handle the insertions from there.

sync-by-unito[bot] commented 6 months ago

➤ PM Bot commented:

Jira ticket: RCORE-2002

dianaafanador3 commented 4 months ago

RealmSwift is using the insert API for both appending and inserting, the only difference is we use the size as the index when adding, because of this, both adding and or inserting at a index is failing when reassigning a collection