pgschema icon indicating copy to clipboard operation
pgschema copied to clipboard

Renaming table used in materialized view generates DDL in wrong order.

Open antonlunden opened this issue 1 year ago • 0 comments

Hi. We've encountered what I believe is a bug, when renaming a table used in a materialized view.

Here is a minimal example to reproduce, using pgschema 1.4.3 & postgres 17.

Given the initial schema:

CREATE TABLE users (
    id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name text NOT NULL
);

CREATE MATERIALIZED VIEW unique_names AS
    SELECT DISTINCT
        name
    FROM
        users;

After applying this to a fresh database. Rename users table to userz and update the materialzed view to use the new userz table. New schema:

CREATE TABLE userz (
    id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name text NOT NULL
);

CREATE MATERIALIZED VIEW unique_names AS
    SELECT DISTINCT
        name
    FROM
        userz;

This generates the following plan

DROP TABLE IF EXISTS users CASCADE;

CREATE TABLE IF NOT EXISTS userz (
    id integer GENERATED ALWAYS AS IDENTITY,
    name text NOT NULL,
    CONSTRAINT userz_pkey PRIMARY KEY (id)
);

DROP MATERIALIZED VIEW unique_names RESTRICT;

CREATE MATERIALIZED VIEW IF NOT EXISTS unique_names AS
 SELECT DISTINCT name
   FROM userz;

Which fails with the following error

Executing group 1/1...
  Executing 4 statements in implicit transaction
Error: failed to execute concatenated statements in group 1: ERROR: materialized view "unique_names" does not exist (SQLSTATE 42P01)

This errors occurs since the DROP TABLE IF EXISTS users CASCADE; has implicitly already dropped the unique_names view. However, if we also rename the materialzed view to unique_namez in the new schema:

CREATE TABLE userz (
    id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name text NOT NULL
);

CREATE MATERIALIZED VIEW unique_namez AS
    SELECT DISTINCT
        name
    FROM
        userz;

The generated plan will drop in the correct order

DROP MATERIALIZED VIEW unique_names RESTRICT;

DROP TABLE IF EXISTS users CASCADE;

CREATE TABLE IF NOT EXISTS userz (
    id integer GENERATED ALWAYS AS IDENTITY,
    name text NOT NULL,
    CONSTRAINT userz_pkey PRIMARY KEY (id)
);

CREATE MATERIALIZED VIEW IF NOT EXISTS unique_namez AS
 SELECT DISTINCT name
   FROM userz
  GROUP BY name;

antonlunden avatar Dec 02 '25 15:12 antonlunden