Fix premature db access

Seems to solve premature database access described in #405 without too much hackery.

Someone should review to see if I'm missing something this is going to kill.