use thread locking to serialize all db access

also reenable check_same_thread so we get exceptions instead of crashes,
although that shouldn't be possible anymore with this locking in place

I'm still researching exactly what we can and can't do with sqlite from multiple threads, but in the mean time, I'll be really surprised if we have any more database issues with this commit in.

We were actually doing worse than sharing db connections between threads. We were overwriting and closing them between threads, leading to some really random stuff.

Maybe it's appropriate to do a bit of refactoring in light of this, but I didn't take the time to do that now. As is, I expect this to fix #933, #931, #929, #761, #743, #729, #677