SET CONSTRAINTS ALL DEFERRED not working as expected

前端 未结 2 1053
猫巷女王i
猫巷女王i 2021-01-01 18:31

In a PostgreSQL 9.3 database, if I define tables a and b as follows:

CREATE TABLE a(i integer);
ALTER TABLE a ADD CONSTRAINT pkey_a         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-01 19:17

    I agree with others that the right way to do it is in the right order - but there are just times when that is not a feasible option and something easier is needed to get the job done within the time budget.

    In case this helps anyone, I made a procedure that will automate adding the deferred option to all FKs so that the

    SET CONSTRAINTS ALL DEFERRED;

    command will work. Use it only as necessary of course.

    DO
    $$
    DECLARE
        temp_rec RECORD;
        sql_exe TEXT;
    BEGIN
    
    sql_exe := $sql$
    ALTER TABLE %1$s ALTER CONSTRAINT %2$s DEFERRABLE;
    $sql$
    ;
    
    FOR temp_rec IN 
    
    (select constraint_name, table_name from information_schema.table_constraints where constraint_type = 'FOREIGN KEY')
    
    LOOP
        EXECUTE format(sql_exe, temp_rec.table_name, temp_rec.constraint_name);
    END LOOP;
    
    END;
    $$
    LANGUAGE plpgsql
    ;
    

提交回复
热议问题