reorganised database code so it's a bit more DRY

Signed-off-by: Mikolaj Szabo <savingprivateblue@gmail.com>