简体   繁体   中英

disable postgresql constraints by jdbc

I am trying to insert data into db using JDBC, when doing so I have to disable constraints - check, not-null, foreign-keys.

alter table user_table disable trigger all;

I have tried with the above query it doesn't work.

I need a way to disable all the constraints at start of the program, and when transaction are completed I need to enable the constraints back.

I am using JDBC4 and Postgresql 9.0.

The documentation of PostgreSQL says for the ALL part:

Disable or enable all triggers belonging to the table. ( This requires superuser privilege if any of the triggers are internally generated constraint triggers such as those that are used to implement foreign key constraints or deferrable uniqueness and exclusion constraints.)

So I guess that the user you are using to insert the data is not a superuser since you list foreign key checks in your question.

However: Unless your requirements are very special I think you are on the wrong route:

Disabling the checks / triggers all together is a very big gun which wrecks your data consistency quite easily. And since you want to re-enable the checks at the end of the transaction it seems you don't want to do this.

It would be better if you can get away with deferrable constraints at the beginning. Then you can use the SET CONSTRAINTS command which is automatically bound to the transaction scope. You can be sure that your consistency is not at risk. Lookup also the CREATE TABLE documentation regarding deferrable triggers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM