CoreStore icon indicating copy to clipboard operation
CoreStore copied to clipboard

How to destroy a SQLiteStore?

Open dginsburg opened this issue 5 years ago • 2 comments

Hi John,

I'm working on a new project and want to thank you for CoreStore. I was dreading using Core Data after my past experiences but CoreStore really improves the situation.

I'm struggling with how to safely delete a SQLiteStore that has already been added to the stack. This is what I've implemented but I'm not confident in it at all. This seems like a capability that would be better as a part of CoreStore so it can clean up first.

        guard let oldStack = dataStack, let coordinator = oldStack.unsafeContext().persistentStoreCoordinator, coordinator.persistentStores.count > 0 else { return }
        dataStack = nil

        let filesToDelete = databaseFileUrls
        oldStack.unsafeContext().reset()
        coordinator.perform {
            coordinator.persistentStores.forEach { try? coordinator.remove($0) }
            try? coordinator.destroyPersistentStore(at: self.store.fileURL, ofType: SQLiteStore.storeType, options: self.store.storeOptions)
            
            print("[Database] Deleting database files: \(filesToDelete)")
            filesToDelete.forEach { try? FileManager.default.removeItem(at: $0) }
        }

I'm holding onto a reference for the DataStack so I can do what it does asynchronously in deinit. For reasons I don't understand, destroyPersistentStore doesn't delete the files so I delete them manually.

With some basic testing I've already seen CoreStore throw exceptions due to underlying file access issues for in flight transactions. CoreStore handles the exceptions gracefully, but that doesn't seem like a proper solution. It also smells that I have to use something called unsafeContext to accomplish this.

I think what I'm doing is not an uncommon use case. Our customers can be in multiple accounts and I'd like to isolate the accounts and just delete the entire store if they lose access to one of them.

Ideas? Thanks.

dginsburg avatar May 22 '19 16:05 dginsburg

Hello,

Did you find a solution ? I'm exactly in the same case as you.

Thank you !

Lapinou42 avatar Sep 10 '19 13:09 Lapinou42

I would suggest to let the DataStack deallocate itself first, then delete the related files. Admittedly this is very difficult the way CoreStore is currently designed (which is why I haven't written public utilities for it). I do have projects that regularly recreates stores, you just have to manage the DataStack lifecyle on your own.

How I do it:

  • Create a designated folder where you will put your database files.
  • When switching stores, simply create a new designated folder, create a DataStack/SQLiteStore for that folder
  • Delete old designated folder

JohnEstropia avatar Sep 21 '19 23:09 JohnEstropia