Fix use-after-free issue

Signed-off-by: Sebastian Ramacher <sebastian+dev@ramacher.at>
Fix various issues if database == NULL

Signed-off-by: Sebastian Ramacher <sebastian+dev@ramacher.at>