I have a Python script that is executing the following command to copy the content of a CSV file to a database:
copy_query = "COPY table_name FROM STDIN DELIMITER '%s' CSV HEADER QUOTE '\"';" % (self.delimiter)
table_name represents an already created table with specific types. The data in the CSV file doesn't always match with the column type. For example, the CSV file could be like this:
"row1", 123, "2012-11-11"
"row2", 346, "2012-11-12"
"row3", \N, "2012-11-12"
As you can see, column 2 should be of type int, but since the data on row 3 doesn't match with type int, the entire operation fails. Is there a way to maybe reject this row altogether? I'd prefer it to fill in with some default value of the appropriate type, but rejecting the row outright is fine too. Thank you for your help!
COPYlike this. The usual solution is to import to a temporary/unlogged table with alltextcolumns, then do aninsert into ... select ...to transform it. See many existing related answers.