How to disable foreign key constraints in postgresql - postgresql

I'm using AWS Aurora Postgres and using DMS to migrate from RDS postgres to Aurora PG. In order to perform the FULL LOAD I want to disable foreign key constraints and triggers on all the objects. I'm able to disable triggers but couldn't find a way to disable constraints.
Below doesn't work:
ALTER TABLE so_items DISABLE CONSTRAINT so_items_so_id_fkey;
It throws:
ERROR: syntax error at or near "CONSTRAINT"
LINE 1: ALTER TABLE so_items DISABLE CONSTRAINT so_items_so_id_fkey;
^
SQL state: 42601
Character: 30
Setting "session_replication_role" = "replica" in the parameter group didn't work. While the DMS task tries to truncate the table part of preparation it still fails with foreign key violation errors.
Please advise any workarounds.
Note: I couldn't do below since in RDS I do not have permissions to do so even with master account:
alter table so_items disable trigger ALL;
ERROR: permission denied: "RI_ConstraintTrigger_c_16520" is a system trigger
SQL state: 42501

You shouldn't modify the triggers a Postgres constraint relies on. This is an implementation detail for which you shouldn't care about.
You cannot disable constraints, really.
To turn constraints temporarily off, you can defer the constraint check to the end of transactions:
ALTER TABLE so_items ALTER CONSTRAINT so_items_so_id_fkey DEFERRABLE INITIALLY DEFERRED;
With that modification the constraint is evaluated after a modification at the end of the current transaction. This will allow you to break the constraint inside of a transaction.
You may DROP CONSTRAINTs
ALTER TABLE so_items DROP CONSTRAINT so_items_so_id_fkey;
which will delete it permanently.
Edit: It is also possible to disable the triggers which also affects the foreign key constraints of the table
ALTER TABLE so_items DISABLE TRIGGER ALL;
But when you are re-enabling the triggers afterwards, the foreign keys are not checked. This might lead to invalid / inconsistent foreign keys in the database.

For Postgres :-
It is easier to disable all triggers with:
SET session_replication_role = 'replica';
And after migration reenable all with
SET session_replication_role = 'origin';

Related

Vendor-independent SQL syntax for dropping unique and primary key constraints

Precondition:
I am using Liquibase with SQL scripts in my app. I started testing with Oracle DB, but now I need to switch to PostgreSQL DB.
Problem:
When I added constraints, I didn't add the names of the constraints.
Liquibase changelog contains a script for dropping unique and primary key constraints:
alter table SCENARIO drop primary key/
alter table SCENARIO drop unique (OWNER_ID)/
This syntax doesn't sync with PostgreSQL
Could you give some advice, on how to resolve this problem?
Screenshots:

Why are foreign keys active after disabling triggers on a table?

I'm trying to refresh some data that's referred to by other data - I want to truncate and reload the ms_automobile table, but the rm_automobile table has a foreign key to it.
It looks like the 'DISABLE TRIGGER' statements are working (run as postgres, a superuser):
mobilesurvey=# ALTER TABLE ms_automobile DISABLE TRIGGER ALL;
ALTER TABLE
mobilesurvey=# ALTER TABLE rm_automobile DISABLE TRIGGER ALL;
ALTER TABLE
But I can't then truncate the ms_automobile table:
mobilesurvey=# TRUNCATE TABLE ms_automobile;
ERROR: cannot truncate a table referenced in a foreign key constraint
DETAIL: Table "rm_automobile" references "ms_automobile".
HINT: Truncate table "rm_automobile" at the same time, or use TRUNCATE ... CASCADE.
Again, I do not want to lose the rm_automobile data; after the TRUNCATE I'm planning on doing a pg_restore that includes the missing ms_automobile data.
If possible, I'd like to disable instead of dropping the constraints - there are more of them, and maintaining disable/enable seems a lot less error-prone than maintaining drop/add.
So, how can I actually disable the foreign keys here?
Disabling triggers works as you expect on DELETE (and not on TRUNCATE).
DELETE FROM ms_automobile;
TRUNCATE is implemented in the specific way different from INSERT/UPDATE/DELETE. It doesn't use triggers but checks referential integrity once before its execution.

Deletion with on restrict constraint postgres

Is it possible to delete the row "on cascade" in postgres if there is a restrict constraint?
And is it possible to change all restrict constraints to cascade constraints automatically?
Neither is possible. Your options would be to:
DROP CONSTRAINT, DELETE and ADD CONSTRAINT
or
DROP CONSTRAINT, ADD CONSTRAINT ... ON DELETE CASCADE and DELETE
From PostgreSQL Documentation you can see what alterations can be done on table constraints:
I. SQL Commands - ALTER TABLE

ALTER TABLE Database NOCHECK CONSTRAINT FK_XXXXXX_DB

I need to make an update on a table (sql 2008 server).
I use sqlcmd and my update is on a file named update.sql and i use sqlcmd for run it.
In this update, i need to replace a value for an other.
Example:
use db
go
update db SET fab=9 where fab=10
Go
update db set fab=7 where fab=8
GO
update db set fab=6 where fab=17
GO
update db set fab=11 where fab=12
GO
And I have this message :
Message 2627, Level 14, State 1 sqlserveur Server, Line 1 Violation of PRIMARY KEY constraint PK_database can not insert duplicate key in object dbo.database. duplicate key value is <2.9 the statement has been terminated
Could you please tell me how I can use THE NOCHEK CONTRAINT, because I've try it but it's does work.
thank you very Much!!!!!
ALTER TABLE Test_Table
NOCHECK CONSTRAINT your_Constraint_Name
GO
This is one way of disabling your constraints but it only works for Foreign keys and check constraints.
Your Error Message says Violation of PRIMARY KEY constraint this cant be disabled you will need to drop the Primary Key.

PostgreSQL - disabling constraints

I have a table with approx 5 million rows which has a fk constraint referencing the primary key of another table (also approx 5 million rows).
I need to delete about 75000 rows from both tables. I know that if I try doing this with the fk constraint enabled it's going to take an unacceptable amount of time.
Coming from an Oracle background my first thought was to disable the constraint, do the delete & then reenable the constraint. PostGres appears to let me disable constraint triggers if I am a super user (I'm not, but I am logging in as the user that owns/created the objects) but that doesn't seem to be quite what I want.
The other option is to drop the constraint and then reinstate it. I'm worried that rebuilding the constraint is going to take ages given the size of my tables.
Any thoughts?
edit: after Billy's encouragement I've tried doing the delete without changing any constraints and it takes in excess of 10 minutes. However, I have discovered that the table from which I'm trying to delete has a self referential foreign key ... duplicated (& non indexed).
Final update - I dropped the self referential foreign key, did my delete and added it back in. Billy's right all round but unfortunately I can't accept his comment as the answer!
Per previous comments, it should be a problem. That said, there is a command that may be what you're looking to - it'll set the constraints to deferred so they're checked on COMMIT, not on every delete. If you're doing just one big DELETE of all the rows, it won't make a difference, but if you're doing it in pieces, it will.
SET CONSTRAINTS ALL DEFERRED
is what you are looking for in that case. Note that constraints must be marked as DEFERRABLE before they can be deferred. For example:
ALTER TABLE table_name
ADD CONSTRAINT constraint_uk UNIQUE(column_1, column_2)
DEFERRABLE INITIALLY IMMEDIATE;
The constraint can then be deferred in a transaction or function as follows:
CREATE OR REPLACE FUNCTION f() RETURNS void AS
$BODY$
BEGIN
SET CONSTRAINTS ALL DEFERRED;
-- Code that temporarily violates the constraint...
-- UPDATE table_name ...
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
What worked for me was to disable one by one the TRIGGERS of those tables that are gonna be involved in the DELETE operation.
ALTER TABLE reference DISABLE TRIGGER ALL;
DELETE FROM reference WHERE refered_id > 1;
ALTER TABLE reference ENABLE TRIGGER ALL;
Solution is working in version 9.3.16. In my case time went from 45 minutes to 14 seconds executing DELETE operations.
As stated in the comments section by #amphetamachine, you will need to have admin privileges to the tables to perform this task.
If you try DISABLE TRIGGER ALL and get an error like permission denied: "RI_ConstraintTrigger_a_16428" is a system trigger (I got this on Amazon RDS), try this:
set session_replication_role to replica;
If this succeeds, all triggers that underlie table constraints will be disabled. Now it's up to you to make sure your changes leave the DB in a consistent state!
Then when you are done, reenable triggers & constraints for your session with:
set session_replication_role to default;
(This answer assumes your intent is to delete all of the rows of these tables, not just a selection.)
I also had to do this, but as part of a test suite. I found the answer, suggested elsewhere on SO. Use TRUNCATE TABLE as follows:
TRUNCATE TABLE <list-of-table-names> [RESTART IDENTITY] [CASCADE];
The following quickly deletes all rows from tables table1, table2, and table3, provided that there are no references to rows of these tables from tables not listed:
TRUNCATE TABLE table1, table2, table3;
As long as references are between the tables listed, PostgreSQL will delete all the rows without concern for referential integrity. If a table other than those listed references a row of one of these tables, the query will fail.
However, you can qualify the query so that it also truncates all tables with references to the listed tables (although I have not tried this):
TRUNCATE TABLE table1, table2, table3 CASCADE;
By default, the sequences of these tables do not restart numbering. New rows will continue with the next number of the sequence. To restart sequence numbering:
TRUNCATE TABLE table1, table2, table3 RESTART IDENTITY;
My PostgreSQL is 9.6.8.
set session_replication_role to replica;
work for me but I need permission.
I login psql with super user.
sudo -u postgres psql
Then connect to my database
\c myDB
And run:
set session_replication_role to replica;
Now I can delete from table with constraint.
Disable all table constraints
ALTER TABLE TableName NOCHECK CONSTRAINT ConstraintName
-- Enable all table constraints
ALTER TABLE TableName CHECK CONSTRAINT ConstraintName