Our largest fixings supplier sends advance shipping notices as a CSV file over SFTP: one line for each item on each pallet heading to our depots, so goods in knows what to expect. The file for a day is cumulative. When the supplier amends one line, they send the whole day again, and our loader relies on that being harmless. It copies the file into a staging table with COPY in CSV format, then inserts into the notices table with ON CONFLICT DO NOTHING on a unique index over supplier, notice reference, line number and batch code.
In October the supplier moved to a new ERP. The columns, the header and the order were identical, and their test file loaded cleanly. Three days later our Leeds depot was expecting a hundred and twenty boxes of decking screws against a pallet of forty, and goods in had raised shortage claims against the supplier for most of the week's deliveries.
The old export quoted every field, so an item with no batch code arrived as two double quotes. The new one quotes only when it must, so the same item arrived as nothing at all between two commas. In CSV format PostgreSQL's COPY reads those differently: an unquoted empty value is NULL, and a quoted empty value is an empty string. Most of what this supplier sends, screws and fixings, has no batch code, so most lines now loaded with a NULL batch code.
A unique index treats NULLs as distinct from each other, as the SQL standard says it should. An empty string equals another empty string, so a resent line used to collide with the stored one and be skipped. A NULL equals nothing, so every resent line went in as a new row, and an order amended twice in a day was expected three times.
COPY now lists the key columns in FORCE_NOT_NULL, which reads an empty value in those columns as an empty string whether it was quoted or not. Before inserting, the loader checks the staging table and stops if any key column holds a NULL. Our tests load the same notice written both ways, fully quoted and minimally quoted, and require identical rows. We removed the duplicates and withdrew the claims, with an apology.
A CSV file has no single meaning for an empty field. Two exports can both be valid and still disagree about whether a missing value is empty or absent, and a database that keeps the difference will keep it for you.
– Sergey Shinder
Top comments (1)
If you're on PG15 or newer,
NULLS NOT DISTINCTon that unique index guards every write path, not just the COPY one. I replayed your case on 17: three resends with an empty batch code gave 4 rows by default and 2 with it. The index build fails until the old duplicates are gone, so cleanup comes first.