Refactoring unit tests and db relations

Partial changes, still not complete.