Use the UPSERT functionality from PostgreSQL 9.5.