Fix issues with using the database

* Fix issue with 'database locked' in tests
* Fix issue with database thread safety

Change-Id: Ieffbc42a7767d0790e57461d564fccf68c0274db