Refactor build databases script