psycopg2 code optimized