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.
`BuildCommand` was not included in this lock because it gets a lock of its own, since most of `BuildCommand` does not need synchronization. If the entire block must remain synchronized, then would should remove the lock from BuildCommand.