Manually managed clone of code from psycopg2