pgschema icon indicating copy to clipboard operation
pgschema copied to clipboard

Named foreign key constraints do not retain their name when dumped

Open whoward opened this issue 1 year ago • 2 comments

Continuing from #59 we've noticed that if a foreign key is installed with a name, as is common in some frameworks such as Ruby on Rails / ActiveRecord the name of the foreign key is not dumped when pgschema dump is used. Here is an example database:

create table some_table (
  id serial primary key,
  name varchar(255) not null
);

create table some_other_table (
  id serial primary key,
  some_table_id integer not null
);

alter table only some_other_table add constraint fk_rails_8bfc3d9c01 foreign key (some_table_id) references some_table(id);

when dumped with pgschema dump we do get a valid SQL file:

-- pgschema database dump
--

-- Dumped from database version PostgreSQL 17.0
-- Dumped by pgschema version 1.3.0


--
-- Name: some_table; Type: TABLE; Schema: -; Owner: -
--

CREATE TABLE IF NOT EXISTS some_table (
    id SERIAL PRIMARY KEY,
    name varchar(255) NOT NULL
);

--
-- Name: some_other_table; Type: TABLE; Schema: -; Owner: -
--

CREATE TABLE IF NOT EXISTS some_other_table (
    id SERIAL PRIMARY KEY,
    some_table_id integer NOT NULL REFERENCES some_table (id)
);

However, when we then attempt to run pgschema plan we are immediately presented with drift where it wants to recreate the foreign key constraint as the generated constraint name doesn't match the explicitly assigned constraint name:

Plan: 1 to modify.

Summary by type:
  tables: 1 to modify

Tables:
  ~ some_other_table
    - fk_rails_8bfc3d9c01 (constraint)
    + some_other_table_some_table_id_fkey (constraint)

DDL to be executed:
--------------------------------------------------

ALTER TABLE some_other_table DROP CONSTRAINT fk_rails_8bfc3d9c01;

ALTER TABLE some_other_table
ADD CONSTRAINT some_other_table_some_table_id_fkey FOREIGN KEY (some_table_id) REFERENCES some_table (id) NOT VALID;

ALTER TABLE some_other_table VALIDATE CONSTRAINT some_other_table_some_table_id_fkey;

While we probably could just reconcile this I think it makes sense that pgschema should attempt to preserve explicit constraint names if they are defined. Ideally pgschema dump should only optimize the foreign key constraint definition if there is no explicit name given to it.

whoward avatar Oct 14 '25 20:10 whoward

thinking on it more, you'd definitely want to support explicitly defined constraint names as auto generated ones often tend to exceed the 63 character limit of postgres identifiers, which is probably why rails does this by default.

whoward avatar Oct 14 '25 20:10 whoward

I've tested this one and it works great! thanks for taking care of this!

whoward avatar Oct 16 '25 18:10 whoward