postgresql scripts refactoring