Refined the logic of generating database