pgschema icon indicating copy to clipboard operation
pgschema copied to clipboard

skip constraints for foreign keys referencing ignored tables (.pgschemaignore)

Open lebedev-nikita opened this issue 7 months ago • 0 comments

Problem Example

We have a partitioned table "session" and another table "event" (for simplicity, it is not partitioned). Our app creates partitions automatically, so there is no need to keep them in schema.sql

Let's initialize database:

-- init-schema.sql

CREATE TABLE session (
  id                  bigint      NOT NULL,
  started_at          timestamptz NOT NULL,
  -- other columns skipped
  PRIMARY KEY (id, started_at)
) PARTITION BY RANGE (started_at);

CREATE TABLE event (
  session_id          bigint NOT NULL,
  session_started_at  timestamptz NOT NULL,
  -- other columns skipped
  FOREIGN KEY (session_id, session_started_at) REFERENCES session (id, started_at)
);

CREATE TABLE session_2026_01
  PARTITION OF session
  FOR VALUES FROM ('2026-01-01') TO ('2026-02-01');

CREATE TABLE session_2026_02
  PARTITION OF session
  FOR VALUES FROM ('2026-02-01') TO ('2026-03-01');

Trying to ignore everything related to partitions when dumping schema.sql

# .pgschemaignore

[tables]
patterns = ["session_20*"]

Execute pgschema dump > schema.sql (comments skipped)

-- schema.sql

CREATE TABLE IF NOT EXISTS session (
    id bigint,
    started_at timestamptz,
    CONSTRAINT session_pkey PRIMARY KEY (started_at, id)
) PARTITION BY RANGE (started_at);

CREATE TABLE IF NOT EXISTS event (
    session_id bigint NOT NULL,
    session_started_at timestamptz NOT NULL,
    CONSTRAINT event_session_id_session_started_at_fkey FOREIGN KEY (session_id, session_started_at) REFERENCES session (id, started_at)
);

ALTER TABLE event
ADD CONSTRAINT event_session_id_session_started_at_fkey1 FOREIGN KEY (session_id, session_started_at) REFERENCES session_2026_01 (id, started_at);

ALTER TABLE event
ADD CONSTRAINT event_session_id_session_started_at_fkey2 FOREIGN KEY (session_id, session_started_at) REFERENCES session_2026_02 (id, started_at);

As we can see, there are two constraints for foreign keys referencing skipped tables

lebedev-nikita avatar Apr 25 '26 21:04 lebedev-nikita