Skip to content

Add support for cascading deletes #1186

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
alazier opened this issue Dec 6, 2014 · 77 comments
Open

Add support for cascading deletes #1186

alazier opened this issue Dec 6, 2014 · 77 comments
Labels
Blocked This issue is blocked by another issue gathering-interest T-Feature

Comments

@alazier
Copy link
Contributor

alazier commented Dec 6, 2014

Blocked on support in core.

@alazier alazier added Blocked This issue is blocked by another issue backlog and removed Blocked This issue is blocked by another issue labels Dec 6, 2014
@vittoriom
Copy link

Is this still in the works?

@jpsim
Copy link
Contributor

jpsim commented Jan 14, 2015

Is this still in the works?

Yes, we'll post here as soon as we have something to share.

@obrhoff
Copy link

obrhoff commented May 2, 2015

Anything new about this Issue / Feature. It's really hard to keep the database consistency with this feature missing.

@jpsim
Copy link
Contributor

jpsim commented Jun 14, 2015

Looks like this is working well in core now (as of realm/realm-core#867), so it should just be a matter of exposing it through the Objective-C & Swift APIs.

@effzehn
Copy link

effzehn commented Jul 6, 2015

Any estimation on how long until this feature is implemented and exposed?

@mrackwitz mrackwitz self-assigned this Jul 6, 2015
@AliSoftware
Copy link

Interested in this as well :)

@mrackwitz
Copy link
Contributor

We're currently actively working on a last conceptual question around this issue in core, which we want to see resolved so that we're able to keep the related APIs as intuitive as possible. We can't give yet an exact ETA, but we'll keep you posted with our further progress and are looking forward to be able to expose it as much as you.

@siuying
Copy link

siuying commented Sep 9, 2015

That would definitely helpful.

@com314159
Copy link

I have write a Helper , you can just delete all the object with one line code. I just read all the Realm property value and delete it. maybe it will help you. check out at :https://github.com/com314159/RealmDeleteCascad

[RLMHelper deleteModelCascad:model inRealm:realm];

@vittoriom
Copy link

Looks interesting, but not exactly "safe to use" in a production environment with thousands of users :D

@bawn
Copy link

bawn commented Dec 5, 2015

+1

@o15a3d4l11s2
Copy link

+1

1 similar comment
@santihbc
Copy link

+1

@pusolito
Copy link

pusolito commented Jan 1, 2016

Any update on this issue? This feature is one of the big factors holding me back from adopting Realm.

@ghost
Copy link

ghost commented Jan 6, 2016

If that helps anyone, I'm using an alternative approach in the mean time: a kind of garbage collection. The idea is that there's a realm entity called RootClassIdentifier each entry of which contains the name of a class that definitely needs to stay in the DB. Starting from the objects of those classes the tree is gradually copied into a temporary realm. When that's done, the old realm is deleted and the new one is used. I'm aware there should be performance issues if the number of objects to be kept increases drastically, but so far in my use case it takes less than one second. If this ever becomes a problem I'll just start to perform it less often, like on each 10 app runs. Here's a sample code:

- (void)performGarbageCollection {
    NSDate *startOfGCDate = [NSDate date];
    NSError *error;
    NSString *temporaryRealmName = @"tmp";
    // Rename all realm files to tmp
    [self.realm writeCopyToPath:... error:&error]; //generate path to temporaryRealmName
    [self.realm beginWriteTransaction];
    [self.realm deleteAllObjects];
    [self.realm commitWriteTransaction];

    // move the data
    RLMRealm *sourceRealm = [OFMObjectCache realmForDomain:temporaryRealmName];

    [self.realm beginWriteTransaction];
    RLMResults *rootClasses = [RootClassIdentifier allObjectsInRealm:sourceRealm];
    for (RootClassIdentifier *rootClassIdentifier in rootClasses) {
        Class aClass = NSClassFromString(rootClassIdentifier.className);
        for (id object in [aClass allObjectsInRealm:sourceRealm]) {
            [aClass createOrUpdateInRealm:self.realm withObject:object];
        }
    }
    [self.realm commitWriteTransaction];
    sourceRealm = nil;

    NSFileManager *fm = [[NSFileManager alloc] init];
    NSString *pathForTmp = ...;//get the path to the tmp realm

    NSDirectoryEnumerator *enumerator = [fm enumeratorAtPath:pathForTmp];
    // Remove tmp files
    for (NSString *fileName in enumerator) {
        NSString *absoluteString = [pathForTmp stringByAppendingPathComponent:fileName];

        BOOL isDirectory = NO;
        [fm fileExistsAtPath:absoluteString isDirectory:&isDirectory];
        if (!isDirectory) {
            NSRange range = [fileName rangeOfString:temporaryRealmName];
            if (range.location != NSNotFound) {
                BOOL result = [fm removeItemAtPath:absoluteString error:&error];
                if (!result) {
                    // handle error
                }
            }
        } else {
            [enumerator skipDescendants];
        }
    }
    NSDate *endOfGCDate = [NSDate date];
    NSLog(@"Garbage collection took %.3lf", [endOfGCDate timeIntervalSinceDate:startOfGCDate]);
}

Adding root classes goes like this:

[self.realm beginWriteTransaction];
[self.realm addOrUpdateObject:[[OFMRootClassIdentifier alloc] initWithClassName:NSStringFromClass(self.class)]];
[self.realm commitWriteTransaction];

And happens in the init method of classes that have as data models any of those root entities.
I hope this makes sense. So far it seems to work well for me, although I'd drop this approach in a blink if cascading deletions would be available.

@bmunkholm
Copy link
Contributor

Outside of Core6 upgrade the biggest blocker for cascading deletes is to make support for that with sync. That's a bit tricky, and we currently don't have a committed timeframe for that, unfortunately. But this issue will surely be updated ones we have more info.

@chkkassd
Copy link

Any update on this issue?

@Zhuinden
Copy link

Zhuinden commented Oct 26, 2018

Or it could be supported for non-sync Realms only until Sync supports it 😄

@bsrz
Copy link

bsrz commented Nov 8, 2018

Almost 4 years since the opening of this issue. For a feature that comes built-in with CoreData. It's kind of disappointing that Realm isn't making this a priority. Slowly moving away from Realm because of this.

@VladimirMitin
Copy link

Almost 4 years since the opening of this issue. For a feature that comes built-in with CoreData. It's kind of disappointing that Realm isn't making this a priority. Slowly moving away from Realm because of this.

Me too.

@rayflection
Copy link

Sybase has cascading delete triggers 30 years ago. Just sayin'.

@jaltin
Copy link

jaltin commented Feb 15, 2019

Is there any news on the implementation of this feature?

@ivnsch
Copy link

ivnsch commented Feb 25, 2019

Also very disappointed that this hasn't been implemented so far. I released my app and have had several complaints already about db being inaccessible (corrupted) so the app has to be removed and reinstalled. I try to ensure consistency by doing everything manually (cascade deletes, foreign keys, semantic uniques, migration from local to synced realm) but this is (evidently) far from ideal. This is basic functionality that the database should provide out of the box. Realm is very fragile and gets in an inconsistent state easily, resulting in unusable apps. Please improve this.

@ariantomichael
Copy link

bump

@keshavkishore09
Copy link

Implemented Realm in my whole app, didn't know we would be encountering this issue at earliest. Creating hell lot of problem to manage the objects. How soon we will have this feature?

@o15a3d4l11s2
Copy link

o15a3d4l11s2 commented Jul 23, 2019

@keshavkishore09, we are also waiting for the feature, but in the meantime there are enough solutions that can solve your problem until they release the cascade deletion. Check the answers above. To sum it up: what we did was extend the realm models with a new method that returns the properties/objects that should be cascade-deleted. Then for each such property/object we do the same until all is deleted.

@effzehn
Copy link

effzehn commented Jul 23, 2019

The PR for this feature is open since June 2018. This issue is being discussed since 2014. Make of that what you will, but at this point you should think about your in-house solution like many other people in this thread did.

@bmunkholm
Copy link
Contributor

I'm not assuming this will help anyone, but I can at least spread a bit of light over our thinking. I can confirm that we are going to do this. It is "just" a matter of time and resources. So far we have not prioritized it high as there are workarounds, and we have focused on other bugs and features without workarounds. That's of course not useful for anyone wanting this feature.
But this is one of the top features we want to add once we have rolled out Core6, which we are now actively working on again. As for timing, my best guess (as plans looks right now) is that it won't make it this year, but early next year.
We appreciate all your patience with this and understand the impatience...

@ZsoltMolnarrr
Copy link

Hello!
Can we have some update please?
While we wait for official support, can any of the contributors points towards a suggested workaround?
For example is this solution correct https://gist.github.com/verebes1/02950e46fff91456f2ad359b3f3ec3d9 ?

@bmunkholm
Copy link
Contributor

I can give a quick update. As you may have seen we have released a beta with Core6 and Frozen Objects (do try it out!) and expect the GA version in April. We are currently implementing " Embedded Objects" that will give you a similar functionality if it fits your data models. But it won't help you much for highly linked data models where you can't just embed one model in another. That is still something we will look into prioritizing this year.

@sergstav
Copy link

sergstav commented Feb 9, 2021

@bmunkholm Hello, can we give some updates on this?

@bmunkholm
Copy link
Contributor

Embedded Objects was released a while back and would enable the cascading delete semantics in most cases. Have you looked at that?

@sergstav
Copy link

sergstav commented Feb 9, 2021

@bmunkholm oh, no, sorry. Thank you for quick response! Can you suggest on which version Embedded Objects was released?

@sergstav
Copy link

sergstav commented Feb 9, 2021

@bmunkholm ok, I found it.

@bdkjones
Copy link

bdkjones commented Mar 31, 2021

Is embeddedObject the end of the story here? This blog post makes it sound like Realm thinks Cascading Deletes are now a solved problem: https://developer.mongodb.com/article/realm-database-cascading-deletes/

But...they aren't. The limitation that EmbeddedObject can't be queried directly makes them far less useful. And other object-graph frameworks such as Core Data (which is what I'm coming from) don't have this limitation. So I'm trying to understand if this issue is still open and being worked on, or if EmbeddedObject is the end of it.

It's also possible I don't understand Realm's performance. Suppose I have:

final class Parent: Object
{
    let kids: List<Child> = List()
}


final class Child: EmbeddedObject
{
    let linkedParents: LinkingObjects<Parent> = LinkingObjects(fromType: Parent.self, property: "kids")
    @objc dynamic var foo: String = "some string"
}

Suppose I have 2,600,000 Parent objects, each with a few Child objects. Is it really going to be performant to run realm.objects(Parent.self)..., and then filter to find the ONE Child object with a particular value of foo?

That can't be as fast as directly querying for the Child where foo == someValue, can it?

@tgoyne
Copy link
Member

tgoyne commented Mar 31, 2021

More and better cascading delete functionality is still on the roadmap, although not in the immediate future. We think embedded objects cover many of the cases where people want cascading deletes, but they definitely don't cover anything.

WRT to the second half of your question, the best you can do currently is probably:

for parent in realm.objects(Parent.self).filter("ANY kids.foo = %@", someValue) {
    for child in parent.kids.filter("foo = %@", someValue) {
        // ...
    }
}

This is typically going to be significantly slower than Querying Child directly would be

@bdkjones
Copy link

bdkjones commented Mar 31, 2021

In my case, Child is just a wrapper with one string property, foo. (I did this because Realm didn’t appear to allow queries against List<String>, although that seems to be outdated information now?)

If I abandoned the Child objects and instead used:

class Parent: Object
{
    let foo: List<String> = List()
}

Would this query be reasonably the same performance as querying a Child wrapper object? —>

realm.objects(Parent.self).filter(NSPredicate(format: “%@ IN[c] foo“, someStringValue)

(Thanks for the guidance. It’s just very expensive in terms of dev time to try different approaches and profile them; I’m hoping your experience can point me down the best path.)

@tgoyne
Copy link
Member

tgoyne commented Mar 31, 2021

We don't support using IN in that way, but I'm guessing that ANY foo ==[c] %@ is what you want (it is the same operation as IN with a constant value on the lhs and a property on the rhs would be if we supported that). How it compares performance-wise to querying Child and then getting the parent objects via LinkingObjects depends on what the ratio of Parent to Child objects is. If you have a small set of Child objects which are each linked to by a very large number of Parents, then querying Child will be much faster. This is because accessing a LinkingObjects object just reads a persisted data structure and doesn't have to do a table scan on Parent.

If each Child object has exactly one parent, or if there's more Child objects than Parent objects, then querying via a List on the parent should be a bit faster than either a query on the value over the link or a query on Child and looking up the parent from that.

@bdkjones
Copy link

@tgoyne Thanks! In my case, the vast majority of Parent objects will have exactly one String in foo: List<String> and only a few will have multiple Strings in the list.

(The list items are filepaths. Most Parent objects have one filepath on disk, but a few have multiple paths to duplicate files.)

It sounds like

realm.objects(Parent.self).filter(NSPredicate(format: “ANY foo ==[c] %@“, someStringValue)

should be performant, without needing the wrapper Child objects that I can’t query if they’re embedded. The List of Strings solves the problem with cascading deletes for me.

@tgoyne
Copy link
Member

tgoyne commented Mar 31, 2021

Yep, for that it sounds like a List<String> is exactly what you want now that we finally support querying those.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Blocked This issue is blocked by another issue gathering-interest T-Feature
Projects
None yet
Development

No branches or pull requests