Add db error handling, move stage definitions to separate module.