Fix #314 Deadlock due to locking in sqlite3_prepare_v2

* Lock database as a whole operation instead of locking per command execution.

* Add sleep workaround at the end of ReplicationTest.TestPushManyNewDocuments to ensure that all pending replication tasks are all drained.