Archive for the 'Core Data' Category

Dynamically adding transient attributes in Core Data

One of the NNTP commands I wanted to implement in Wombat was XPAT. XPAT is a simple search command that searches a specified header on a range of messages for a given wildmat expression. For example:


XPAT subject 1-12 *fred*

searches messages 1 through 12 for any message that has a subject containing the word “fred.” Matching a given header against a wildmat expression (i.e. the *fred* in the previous example), was easy because wildmat expressions are easily convertible into regular expressions. The problem was the user could specify any header to search against.

Although NNTP specifies a group of standard headers, posts are not limited to those standard headers. Any header, as long as they are syntactically correct, can be added to a message. What’s more, each message is going to have a different set of headers. The first message might have an X-NNTP-Posting-Agent header, while the second one might not.

Since headers vary from post to post, and could be almost innumerable, I couldn’t add them to my Post entity as persistent attributes. Instead, I have one attribute, headers, which is a string with each header on its own line.

This caused a problem because I wanted to use NSPredicate’s MATCHES operator to compare a specific header against a regular expression. I wanted to specify the predicate query as:


subject MATCHES ".*fred.*"

Unfortunately NSPredicate wants an attribute name to compare against (subject in this case), and my NSManagedObject didn’t have one. It had the headers attribute, but that contained all the headers, not just one. Since, once again, the headers can vary, I needed a way to dynamically add transient attributes to my NSManagedObject derived class, Post.

Since NSPredicate uses Key Value Coding to obtain the value of an attribute, I figured there was a solution. My first thought was to simply overload valueForKey: on my Post class. However, I was worried I’d muck up the Key Value Coding mechanism, and break something important. Fortunately, by digging through the Key Value Coding documentation I discovered the valueForUndefinedKey: message. According to the documentation, if a key wasn’t found via the normal means, the valueForUndefinedKey: message was called. This is important because that means if I overload valueForUndefinedKey:, I don’t run the risk of masking built-in, and possibly important, keys.

By default, valueForUndefinedKey: simply throws an exception stating no such attribute exists. This is valid behavior that I wanted to keep when overloading it. However, on the other hand, no matter what header the client asked for, I had to pretend that it was there and at least return an empty string. This was on the chance that some of the messages had the header. In other words, I needed a way to determine if the caller of valueForKey: was just asking for Joe Random attribute or a header attribute.

The only easy way I came up with was to prepend header attributes with a common prefix, like “header_”. So the NSPredicate query above becomes:


header_subject MATCHES ".*fred.*"

This makes the processing in valueForUndefinedKey: pretty easy. The method, in general, can be defined as:


- (id)valueForUndefinedKey:(NSString *)key
{
if ( [key hasPrefix:@"header_"] )
return [self headerForName:key];

return [super valueForUndefinedKey:key];
}

As you can see, determining valid header requests from invalid attribute requests is easy. I call the super’s implementation of valueForUndefinedKey: so that the exception is thrown, as expected, in the case of bad attribute requests. Also it means that if the parent class does something other than throw in the future, that it will continue to work.

I have to admit this was much easier to implement than I thought it would be. I also like the idea that I can easily access all my header values via NSPredicate, which is very useful.

Merging multiple contexts in Core Data

Last time I was working on Wombat, I was trying to get its Core Data multi-threading use correct. Namely, I stopped sharing one context (NSManagedObjectContext) between all threads, and created a new context for each thread. This meant I didn’t have to lock the context each time it was touched, which resulted in better performance. I thought that it would be simple as that. Core Data would take care of the merging of the multiple contexts, and all would be good.

I was close, but it’s not quite that simple.

The first problem I ran into was the possibility of two different clients, each on its own on thread and thus context, posting the same message. Since contexts aren’t saved until a client disconnects, that would work for the first client who quit, but the second one would run into trouble. It would most likely succeed in its save, assuming it had no merge conflicts, but it would compromise the data integrity of the data store. That is, I shouldn’t have the same post in the database twice. That’s bad.

Now the NNTP protocol specifies that each post should have a unique ID, called a Message-ID. Its simply a blackbox string that is supposed to be globally unique. Typically it is a time stamp concatenated with the local host name, and enclosed in angle brackets (<>). Some NNTP clients attempt to generate the Message-ID themselves, but most are smart and allow the server to generate one on their behalf. That means that the odds of receiving duplicate messages from clients are pretty much nil, although the situation still has to be considered.

It’s far more likely that two peer servers connect to Wombat, and offer it the same message that was posted elsewhere on the network. This is still somewhat unlikely, because direct peers should be somewhat rare, and thus the likelihood of them connecting at the same time would be low.

I bring up the rarity of the these events for a reason. If these collisions were frequent it means I should probably go back and consider locking down and updating the contexts more often. That way I always know what messages I have and which ones I don’t. i.e. I should make sure I do preventative maintenance. The downside of preventative is obvious: its slower because I have to bottleneck all threads and update the data store. However, since the message collision events are (theoretically) rare, then I can just assume the thread’s current context is up-to-date. Then, when the thread goes to merge any changes to the context into the data store, it can handle any conflicts then.

Before this point, Wombat never made use of any of Core Data’s validation methods. That’s because everything was serialized through one context and I manually validated the incoming data before I inserted it into the context. For example, before I inserted a message I searched for any messages in the context with the same Message-ID. If I found one, I simply didn’t insert the new message, thus maintaining the integrity of the data store.

Now I needed to be able to catch any duplicates when I went to save the context to the data store. My first thought was: “wouldn’t it be great if Core Data modeling allowed me to specify an attribute as unique?” It would be, but alas, Core Data doesn’t allow it. If I could specify an attribute as being globally unique then I wouldn’t have to write any validation methods, but just let Core Data catch them for me. I also wonder if SQLite would be able to do anything with an attribute if it knew it was unique. For example, create an index on it so searching was quicker.

Anyway, dreams aside, I needed to write a validation method. The first thing I thought of was the validation method generated by Xcode for each attribute. The one of the form:


- (BOOL)validate: (id *)valueRef error:(NSError **)outError;

where is the name of the attribute. The problem with this is that Message-ID never changes, and I actually only want to validate when a new message is inserted into the data store. After searching around the documentation some more, I discovered:


- (BOOL) validateForInsert:(NSError **)error;

It’s a pretty easy to use method, and it only gets called on an inserted object. I simply added code at this point to check for more than one message with the same Message-ID. If I found more than one, I returned NO and put an error in the out parameter. The error parameter is passed back to the call to [NSManagedObjectContext save:&error], so I can do useful things like stuff the offending object into the error and the person who called save will get it.

Now I’d like to take an intermission to rant a bit. The error mechanism here is ghetto at best. If you’ll notice the out error parameter only points to one error, as does the error parameter in save. So what happens if you have more than one error, because, say, you have six messages that are duplicates? You curl up in a corner and cry, that’s what. Then you have to use some convoluted logic to pretend the API was designed to support multiple errors.

First, you have to check to see if the error parameter is nil. If it is, you just jam a pointer to your error in it. If it’s not nil, then you have to check to see if it’s a special error that’s designated as “multiple errors.” If it’s the special “multiple errors” error, then you create a entirely new “multiple errors” error with all the old stuff in it, plus your error added to its array of multiple errors. If the current error is not the special “multiple errors” error, then you have to create one, and jam the old error and your new error in it. Fun stuff.

Hey Apple, you wanna know what else would have worked? An NSMutableArray of NSError’s. Crazy idea, I know.

Anyway, after I figured out how to get errors back to the caller of save, I needed to do something about them. Fortunately processing duplicates are easy. You just deleted them. I thought about doing this inside of validateForInsert, but some of the Apple documentation advises against mutating the context inside of validation routines. Instead, the caller of save just walks the list of errors (which has its own special logic to produce an array of errors out of a single error) and deletes the duplicates, then attempts the save again.

At this point, I thought I was home free. But save kept returning merge errors even after I had deleted the duplicates, and I didn’t know why. The answer turned out to be the merge policy on the context. By default, the merge policy is “don’t merge, and report anything that doesn’t merge.” I’m sure that’s a fine policy for applications who never use more than one context per data store, but it doesn’t work so well in Wombat.

There are actually several merge policies described in Apple’s documentation. NSErrorMergePolicy simply returns an error for each merge conflict, and is the default. NSMergeByPropertyStoreTrumpMergePolicy and NSMergeByPropertyObjectTrumpMergePolicy are similar to each other in that they merge on a property by property basis. They only differ when the property has been changed in both the store and context. In that case, NSMergeByPropertyStoreTrumpMergePolicy takes whatever was in the store. Conversely, NSMergeByPropertyObjectTrumpMergePolicy takes whatever was in the object context. NSOverwriteMergePolicy simply forces all the changes in the object context into the data store. Finally, NSRollbackMergePolicy discards any object context changes that conflict with what’s in the data store.

For Wombat, I chose NSMergeByPropertyObjectTrumpMergePolicy because it does finer grain merging, and because there’s a slim chance what’s in the object context is more up-to-date than what’s in the store.

All in all, merging multiple contexts was harder than I thought, and harder than I thought it needed to be. It would be nice if Core Data could do some more validation automatically (like unique attributes) and if the error handling was better. I also think picking a better default merge policy would help, because when getting the random merge errors, it wasn’t all that obvious to me that the merge policy was the problem.

Core Data and Multi-threading

I’ve been wanting to write this article since Tuesday, but I’ve been distracted by my day job. One of our clients is getting close to shipping so I have to put in more hours than usual. It’s no where near as fun as working on Wombat, but it pays the bills.

Anyway, back when I wrote a couple of weeks ago about Wombat, I mentioned the trouble I was having with Core Data and multiple threads. Basically, I was finding that the entire context (NSManagedObjectContext) had to be locked anytime a thread touched the context or any one of its managed objects (NSManagedObject). That included even accessing attributes on a NSManagedObject as well as mutating them.

Apparently I wasn’t the only one who figured this out. Florian Zschocke, creator of Xnntp, told me that he was running into the same problem of having to lock the entire context each time he touched anything. He was also wondering if there was a better way.

The obvious problem with locking every time is that it defeats the concurrency of threads. The threads end up being serialized anytime they touch the data store. This is pretty troublesome for Wombat, because it’s an NNTP server. Most of its time is spent doing I/O – either reading/writing to the data store or reading/writing to sockets. Accessing the data store is already a potential performance hotspot, and the serialization or threads makes it even worse.

Fortunately there’s a better way. Blake Seely left a comment on my previous post, letting me know that the appropriate way to handle multiple threads is to have a separate context for each thread. About this time I also found some Apple documentation pertaining to Core Data and multiple threads, which echoed Blake’s comments. This is as simple as allocating a NSManagedObjectContext each time a thread is spawned, and handing it the solitary NSPersistentStoreCoordinator.

The one gotcha is that NSManagedObject’s from one context cannot be used in another context. If you want to send an object from one thread to the other, you have to pass the NSManagedObjectID around. This can be obtained by [object objectID] from one thread, then used on the other thread by [context objectWithID:objectID] to get the corresponding object in that context. However, this only works for objects that have been saved. In general, Wombat isn’t going to have to worry about passing objects between threads. That’s because each client is pretty isolated and has no reason to talk directly to another client.

That said, having multiple contexts has some implications for Wombat. Currently each client gets its own thread, and thus its own object context. In the future this will probably change, and clients will be pooled together on a few threads that handle multiple clients using something like kqueue to multiplex sockets. The catch is that no client saves its changes until the remote client closes the connection. Currently that means if Wombat has two clients, and Client A posts an article, Client B will not see that article until Client A quits. For performance reasons, NNTP clients often leave the connection open for a specified amount of time after they’ve done their work.

The behavior is acceptable, but it gets a bit more weird when clients start getting multiplexed by a single thread. In that scenario, Client B might see the article immediately if its in the same pool, or it might have to wait until Client A quits. In other words, some clients will see articles sooner than other clients. Once again, it’s acceptable behavior, but it’s a little odd.

Meanwhile, I’ve been reading Another Day in the Code Mines, which has a lot to say about threading. One of the thoughts that I came away with is that forking processes in Wombat would probably be better than spawning threads. That is, for each client that connects, instead of spawning a thread for it, spawn a process to handle it. Processes are heavier weight, but they provide a couple advantages. First, they provide separate memory spaces for each client, so one client can’t mess with another. Second, if one client crashes, it doesn’t take down the entire server, thus making Wombat more robust. Forking for each client also happens to be a classic NNTP server design, and for good reason.

Unfortunately, as far as I can tell, Core Data doesn’t support this. Multiple contexts can exist because they all share one NSPersistentStoreCoordinator, which serializes all I/O to the data store file. Since SQLite often updates just parts of the file at a time, I can’t imagine that it would allow multiple processes to have the data store file open at once, especially for write. The only way I see around this is to make the data store file its own server. Unfortunately, this reintroduces the single point of failure (if it goes down, all clients go down) and since NNTP is fairly thin protocol over news, it would just end up being something pretty close to an NNTP server itself. Not a win.

In the end, it looks as though I’m just going to give each thread its own context, and then multiplex several sockets on each thread using kqueue. It may not be as robust as forking processes, but it should be possible to get some good performance out of it.

NSPredicate and regular expressions

I’ve managed to figure out how to implement wildmat patterns inside of Wombat. It turns out NSPredicate does in fact support regular expressions, as documented in Using Predicates. You simply use the MATCHES operator to specify a regular expression, as shown in a couple of examples in Apple’s documentation. It’s implemented using ICU’s Regular Expressions package, which provides much better documentation than Apple.

The gotcha to note is that the MATCHES operator does not compile down to SQL, so you can’t give it directly to Core Data. Instead you have to pull out all the entities then post-process the array using NSArray’s filteredArrayUsingPredicate: method. It works, but it’s not as efficient as it would be if it were compiled down to SQL.

In a related news, Mike Zornek was kind enough to point out a small Core Data mailing list. Hopefully it will be a source of useful information in the future.

Core Data fetch queries

I’m currently trying to implement the wildmat matching algorithm as described in RFC 2980 for my NNTP server, Wombat. Since I’m implementing the article database using Core Data, I’d like to use as much as the built in functionality as possible.

Wildmat isn’t regular expressions, but supports five allegedly different operations. It’s really just three (they count character sets as three):

  1. * – matches any character zero or more times.
  2. ? – matches any one, and only one, character.
  3. [] – character sets. This includes using ^ to specify negative character sets and using \ to escape special characters in the set.

I’ve actually figured out that Core Data supports the first two right out of the box. That’s right, if you use the LIKE operator to match strings, you can use * and ? in the string and Core Data will do the magic for you:


NSString* wildmat = @"foo*bar??";
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"name LIKE %@", wildmat];

In the above example Core Data would match any of the follow names:

foobar12
fooSTUFFbarNO
foojunk12barG1

I’m trying to figure out if Core Data supports character sets in anyway. It’d be a lot easier, and more efficient, if I can get Core Data to do all the heavy lifting for me. I’m also looking for any mailing list or discussion group that covers Core Data. I checked Apple’s mailing lists, but I couldn’t find anything.

levitra 125 mg
cheapest prices on generic viagra
buy free viagra viagra
buy viagra onli
buy viagra online and get prescription
cheap overnight viagra
huricane ike home repair wanted
buy online pill viagra
cheap viagra online uk
50mg cialis
buy cheap deal viagra viagra viagra
cheap cialis canada
36 hour cialis
mobile home roof repair
cheap levitra online
20 mg cialis
home study computer repair course dvd
buy cheap generic viagra
buy viagra in great britain
buy viagra without prescription
buy viagra in london
buy cheap viagra uk
cheap pill viagra
viagra and coupon
generic viagra 20mg pills erections
voagra online without prescription
viagra 50 mg
viagra and cialis and
bruces home repair salem or
cheap online generic viagra
viagra 100mg price
buy viagra in spain
cialis 5m tablets
cheapest price for generic viagra
mobile home repair rochester wa
buy viagra softtabs
cheapest price viagra
viagra buy it online now
rx cialis 100mg
buy low price viagra
cheapest place to buy viagra
buy cheap online uk viagra
home foundation repair
100mg viagra
buy pill viagra
buy viagra online
voagra online without prescription
buy viagra in canada
generic viagra 100mg
cheap online viagra viagra
buy line viagra where
federal grants for home repair
cheap prescription viagra
cheapest generic price viagra
10 generic levitra for 19.95
buy prescription viagra
levitra online prescription
buy levitra 50mg
cialis brand cialis 100mg
buy cialis online 50mg
in home tv repair canton nc
buy viagra in toronto
viagra by mail canada
home repair tax deductable
100 mg cialis us pharmacy
viagra brand viagra 100mg
mobile home floor repair
buy viagra online
100mg levitra
levitra 25 mg order
viagra 20 mg
buy viagra next day delivery
cheapest uk supplier viagra
viagra and cialis cheap
cialis 10mg 20mg
cheapest 4 quantity of viagra
buy levitra online
buy cialis online viagra
250 mg viagra
home window repair in sc
buy generic viagra viagra
buy cheap generic viagra online
cheap cialis canada
cheapest price on viagra
cheap viagra canada
viagra by the pill
buy keyword online viagra
cheapest prescription viagra
buy viagra on-line
50 mg viagra retail price
buy online drug viagra pharmacy
cheap 25mg levitra
viagra buy ionline
cialis 100mg price
levitra without prescription
home repair denver coloradao
buy discount viagra
buy cheap online prescription viagra
viagra 25 mg
buy now online viagra
levitra 10mg 20mg
buy cost low viagra
purchase levitra online
buy viagra onlines
buy viagra in australia
ron hazelton home repair
buy cheap online viagra viagra
cheap online pill viagra
100 mg levitra us pharmacy
cheap phizer viagra
bruces home repair
viagra by phone
buy online online viagra viagra
buy cheap viagra online u
cheap levitra canada
cialis online prescription
cheap levitra online
buy locally viagra
buy cheap cialis generic levitra viagra
buy cialis internet
cheap viagra uks
sears home repair
buy viagra generic
50 mg cialis retail price
order 50mg levitra
viagra 50mg
cialis online
cialis 20
cheapest price for viagra
buy site viagra
discount drugs levitra 100mg
cheapest brand viagra
buy levitra online 50mg
home repair replacing circuit breakers
buy viagra low cost
buy prescription vaniqa viagra
discount drugs cialis 100mg
buy cheapest viagra
buy discount propecia
home computer repair
buy cheapest online viagra
levitra 50mg
viagra buy online
home cd repair
cialis 25 mg
viagra buy viagra
buy in online uk viagra
home remedies to repair scratched cds
buy discount levitra
cheapest place buy viagra online
buy deal deal price viagra
buy online prescription viagra
viagra by mail order
buy viagra pill
viagra buy uk
250 mg levitra
buy deal herbal viagra viagra
buy pfizer viagra
buy cheap viagra online now uk
buy viagra internet
cheapest line viagra
buy viagra professional
buy cialis without prescription
buy viagra in uk
cialis 10 mg
viagra and cialas
good review sites for home repair
home repair vancouver
cheapest generic viagra and canada
cialis no prescription
10 generic cialis for 19.95
rx viagra 100mg
levitra 25 mg
buy viagra in malaysia
buy online levitra cialis viagra
vista home premium repair
cheap cialis canada
buy discount levitra
cheap viagra uk
buy online sale viagra
home appliance do it yourself repair
viagra by money order
levitra no prescription
cialis 20mg
cialis 20mg reviews
50 mg cialis
cialis reviews
buy cialis no prescription
buy generic viagra online
buy viagra removethis
buy levitra online viagra
cialis 24
buy cheap deal pill viagra
levitra 50 mg
weed eater home repair
mobile home repair remodeling
buy kamagra viagra
cialis 100mg
cialis 20 mg
cheap order site viagra
generic cialis 100mg
cialis 50 mg
buy viagra london
buy cheap discount levitra
cheap discount levitra
viagra no prescription
viagra 25 mg order
buy in online usa viagra
buy sale viagra
10mg cialis
buy viagra pills
viagra brand
buy viagra 50mg
buy viagra locally
cialis no prescription
cheap sale viagra
mobile home skirting repair
cialis 1
cheap prescription viagra without
buy real viagra online pharmacy
cheap viagra st
cialis 32
cheap online softtabs viagra
cheaper viagra levitra cyalis
buy viagra in mexico
buy online uk viagra
buy cheap viagra
cialis 125 mg
buy cialis viagra
viagra without prescription
buy online purchase viagra
cialis 50mg online
order 50mg cialis
buy lady uk viagra
50 mg levitra retail price
cheap site viagra
home repair grants
buy viagra usa
buy viagra uk
levitra 50mg online
36 hour levitra
buy online prescription viagra without
buy 100 mg viagra
cheapest generic viagra and cialis
buy viagra line
cheap online purchase viagra
buy generic viagra buy
cialis 2005
cheapest in uk viagra
buy viagra online alternative viagra
viagra buy oonline
scottsdale home repair
generic cialis wholesale 100mg
buy generic viagra
mobile home repair
buy cheap cialis
cheap viagra online prescription
buy cialis no prescription
buy now viagra
buy viagra sale
home repair grant
buy viagra in the uk
cialis black 800mg
buy pharmacy pill viagra
home electrical repair
order levitra
do it yourself home repair
cheap online sales viagra
buy no online prescription viagra
viagra 100mg
buy real viagra online
viagra by mail
buy viagra in bangkok
50 mg viagra
viagra buy in uk online
home repair frozen pipes
viagra buy viagra online
cheap pharmaceutical viagra
cheapest price for viagra and cialis
buy cheap cialis
buy viagra no prescription
canada pharmacy discounted levitra 100
buy real viagra
50 mg levitra
buy viagra in new zealand
home appliance repair
buy viagra london
buy cheap generic online viagra
buy viagra no prescription
36 hour viagra
mobile home repair parts
buy kamagra viagra india
buy price viagra
buy pill price price viagra
cialis 10
buy now levitra
cheap online viagra
buy cheapest viagra online
canada pharmacy discounted viagra 100
cheapest generic substitute viagra
buy later now pay viagra
cheap online price price viagra
buy say viagra
100 mg viagra us pharmacy
20mg cialis
cialis without prescription
order levitra online
cheapest place to buy viagra online
viagra by overnight delivery
buy cheap deal online viagra viagra
generic levitra wholesale 100mg
buy line viagra
buy viagra phuket
levitra 100mg
cheap price viagra
cialis 10
cheap 25mg viagra
cialis 25 mg order
viagra online prescription
generic cialis
cialis black
cheap online order viagra
buy online order viagra
viagra brazil
levitra 20 mg
buy online sale viagra viagra
viagra buy now pay later
amana refrigerator home repair
buy cialis now
registar repair windows xp home
cheap pill pill sale viagra
generic levitra 20mg pills erections
cialis 36 hours
cheapest online viagra
viagra buy australia
buy viagra online 50mg
buy cheap viagra online uk
cheapest cialis
buy viagra inte
buy prescription viagra without
cheapest generic viagra
levitra 100mg price
viagra 125 mg
viagra buy generic
home repair
buy viagra toronto
home repair handymen in fernley nevada
cialis without prescription
cialis 2005
cheap viagra without prescription
canada pharmacy discounted cialis 100
buy in uk viagra
buy pharmaceutical viagra
30mg cialis
discount drugs viagra 100mg
cialis 2.5
buy real viagra pharmacy online
buy cheap viagra on
cialis 20mg
home repair maintenance
home window repair
buy cheap viagra in uk
250 mg cialis
buy viagra in united kingdom
cialis 30mg
buy generic viagra pharmacy online
buy cheap viagra online now
cialis 20
tamiflu
100mg cialis
buy online price viagra
buy online online pill viagra viagra
10mg levitra
buy viagra soft
buy levitra no prescription
home repair plumbing
american pacific home repair
cheapest regalis viagra
home repair business
buy in spain viagra
buy free online sale viagra viagra
buy cheapest online place viagra
cialis 20 mg
buy generic no online prescription viagra
buy viagra line
10 generic viagra for 19.95
cialis 5mg
buy internet viagra
viagra by mail catalog
buy free viagra on internet
order 50mg viagra
buy cialis 50mg
cheapest site viagra
buy discount cialis
buy cheap viagra on the net
cheap soft tab viagra
cheap 25mg cialis
buy cialis online now
viagra and cialis
cialis 50mg
voagra online without prescription
cialis 10mg
usa cialis
buy cheap levitra
5mg cialis
viagra 10mg 20mg
buy viagra online at cheap price
cheapest cheap viagra
cheap viagra online order viagra now
home entertainment repair tips
40 grams of cialis
buy levitra canada