unit test and refactor database.py part 2

Add unit tests and refactor/fix/document issues related to the database.
(Part 2, because #619 grew too large.)

Related #484
Related #619

What issue is that? Would be useful to mention it here briefly.