Safely switch database files (replacing the old with the new) #58

Closed
wants to merge 2 commits into
from

Conversation

Projects
None yet
3 participants

I have a case where I'm using a database and in a separate thread I'm downloading data and creating a updated database. Once the updated (new) database is ready, I need to safely switch from the old database to the new one, replacing the old database. The use of a queue in FMDB 2 gave me a concise way to do this.

Here are my changes and a test for changing a queue's database on the fly.

Owner

ccgus commented Apr 10, 2012

Neat, thanks for doing this!

Give me a couple of days to check it over and merge this in- I'm trying to release some products right now and my bandwidth is a little constrained.

Owner

ccgus commented Apr 11, 2012

Quick question while I'm looking over this code- why wouldn't just closing the old db's queue and swapping whatever ivar held it with a new db queue not work? I'm just wondering what the restrictions are that it has to be done inside the queue.

Is it a thread coordination issue maybe?

Indeed.

I have the new database being generated via GCD dispatch_async while database queries are being triggered via the main thread (iOS). My case may not be common so I'll not take offense if you don't accept the pull request, but it was very useful for me to copy and switch database files (as triggered by a background GCD thread) in a thread safe manner.

The synchronous queue gave me the serial protection necessary. If everything was in one thread then closing the db queue and creating a new db would definitely suffice.

At a minimum, consider this pull request as thanks for implementing the db queue!

Owner

ccgus commented Apr 11, 2012

I'm trying to think of a way to expose use the internal queue for stuff like this, and then your code could be placed inside a category (it is pretty specific to your need), but still not have to worry about coordinating across threads.

I'm not sure it's possible in your case though, but I'm still thinking on it :) (the db ivar is private, and you'd need to close that guy and such).

Owner

ccgus commented Apr 14, 2012

OK, so I've looked and thought about this for a little bit, and I can't think of any way to make this of general use for everyone. As it stands, I think you're the only person who would ever use this call :)

I thought about adding a method along the lines of executeBlockOnQueue:(^etc), which you could then use to coordinate the closing + deleting + opening of a new database. But that only gets things part of the way to what you'd need- (it would also require exposing the ivars publicly, which I don't think is a good idea).

So… I think you're just going to have to coordinate the closing + opening on your own side.

ccgus closed this Apr 14, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment