Merged from downstream cedf34b0bdce1ac4d512f815f8c4a7d062715fb6

 * Switched to an UPSERT that's compatible with Postgres < 9.3