refactored posgresql script