PostgreSQL drop constraint with unknown name

后端 未结 1 1157
自闭症患者
自闭症患者 2020-12-19 07:30

I have an SQL script that needs to drop several constraints and restore them at the end, but the constraint names are auto-generated and will be different each time the scri

相关标签:
1条回答
  • 2020-12-19 07:38

    To dynamically drop & recreate a foreign key constraint, you could wrap it all in a function or use the DO command:

    DO
    $body$
    DECLARE
       _con text := (
          SELECT quote_ident(conname)
          FROM   pg_constraint
          WHERE  conrelid = 'myschema.mytable'::regclass
          AND    confrelid = 'myschema.myreftable'::regclass
          LIMIT 1 -- there could be multiple fk constraints. Deal with it ...
          );
    
    BEGIN
       EXECUTE '
          ALTER TABLE wuchtel12.bet DROP CONSTRAINT ' || _con;
    
       -- do stuff here
    
       EXECUTE '
          ALTER TABLE myschema.mytable
          ADD CONSTRAINT ' || _con || ' FOREIGN KEY (col)
          REFERENCES myschema.myreftable (col)';
    END
    $body$
    

    You must own the table to use ALTER TABLE.
    Else you can create a function with LANGUAGE plpgsql SECURITY DEFINER (using the same body) and

    ALTER FUNCTION foo() OWNER TO postgres;
    

    postgres being a superuser here - or the owner of the table.
    But be sure to know what the manual has to say about security.

    The manual also has more on dynamic commands.

    0 讨论(0)
提交回复
热议问题