Migrator for DocBase

| February 7th, 2010

I made a few updates for DocBase: a configuration file for a document database and a migrator to handle configuration changes. Read on for a few details. ### Configuration

As I was developing my app, I noticed that I was quickly outgrowing the measly 17 buckets I had originally hard coded for a database. It’s not too bad for a hundred or so documents, but probably not sufficient for several thousand documents. I knew it really need to be configurable. So in comes the docbase configuration file.

The configuration is just saved as another JSON dictionary in the document database folder and right now it only contains the setting for the number of buckets. There’s a few important changes that go along with this.

I moved anything that might give cause an error (within reason) outside of the initializer for BRDocBase. Now, if something is wrong, like it can’t create the database or the configuration is wrong it’ll give an error on the first call to one of the main methods (anything that has an error parameter). Basically, all the file-based initialization is done lazily. I’ve never seen an init method take an error parameter, and it just feels wrong to me.

If a configuration isn’t passed to the init method, one of two things will happen. If it’s a new database, a default configuration will be used. Otherwise, the configuration that already exists will be used. In either this case, the configuration property will return nil until it has actually completed its lazy initialization. If a configuration is passed on initialization and it doesn’t match the existing configuration, the lazy initialization will fail with a configuration mismatch error (this can be useful in updating a configuration).

Migrator

Without someway to migrate a database, there’s no way to change the configuration, so I added BRDocBaseMigrator. It’s pretty simple class right now that can update a database to use a new configuration. It just uses brute force to read and re-write all the documents in the database in the new configuration.

The migrator is smart enough to not do anything if the configuration matches. In that case, the original document database will be returned. So if fairly simple to create/open a database that always has a particular configuration:

NSString* path = ...;
NSDictionary* config = ...;
NSError* error;
BRDocBase* docBase = [[BRDocBaseMigrator docBaseMigrator]
    update:[BRDocBase docBaseWithPath:path]
    toConfiguration:config 
    error:&error];

Now if the configuration isn’t what is wanted, it’ll be updated. Otherwise it will just return.

Leave a Reply