TODO:optimize sql query and refactor