database: Remove global variable and remove duplicated code