Deep refactor db package, for better testability and portability to different DB.

Title says all.