Threadsafe database

A bit of a big hammer, there...

I've made distinct commits, for ease of review, but I figure they all kind of go together. If you review the commits, remember that notifications for comments made on commits can "go in the wrong place", so please make the comments on the pull request, thanks!