Hei,
i have a question about the best practice here. I have a Golang Project which uses as Postgres Database and specific Migrations. The Database has many tables and some depend on each other (Table A has FK to Table B, Table B has FK to Table A). My "problem" is now that i have to import data from CSV files, which i do with the COPY … FROM … WITH Command. Each CSV file contains the Data for a specific table.
If i try to use the copy command i get the error: "insert or update on table "b" violates foreign key constraint". Thats right, because in table a is no data right now. And cause of the FKs the problem happens on both sides.
So what is the best way to import the data?
Thanks 🙂
2
Answers
Possible solution approach:
1.) create the table without the FK constraints
2.) load the data into tables
3.) add the FK constraints to tables with ALTER TABLE:
Example:
You can defer
deferrable
constraints until the end of a transaction:Problem is, you have to make sure your foreign key constraints are
deferrable
in the first place – by default they are not, soset constraints all deferred;
won’t affect them.You can do this dynamically for the time of your import (online demo):
Carry out your import in a transaction with deferred constraints, then undo your alterations by replacing
deferrable
withnot deferrable
:As already stated, an alternative would be to set up your schema without these constraints and add them after importing the data. That might require you to find and separate them from their table definitions, which again calls for a similar dynamic sql.