Skip to content

CTE in view is lost during planning when CASE is used #106

@whoward

Description

@whoward

Here's another oddball issue in planning. Given the following database:

create table some_table(
  id serial primary key,
  start_date date,
  report_date date,
  type varchar(20)
);

CREATE VIEW some_view AS
WITH months AS (
  select generate_series as start_date from generate_series('2025-03-01'::date, NOW()::date, '1 month')
)
SELECT
  CASE
    WHEN (some_table.type IS NULL) THEN some_table.report_date
    ELSE NULL::date
  END AS previous_report_date
  FROM some_table
     JOIN months month ON month.start_date = some_table.start_date
  ;

pgschema dump will produce the correct output:

--
-- pgschema database dump
--

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


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

CREATE TABLE IF NOT EXISTS some_table (
    id SERIAL,
    start_date date,
    report_date date,
    type varchar(20),
    CONSTRAINT some_table_pkey PRIMARY KEY (id)
);

--
-- Name: some_view; Type: VIEW; Schema: -; Owner: -
--

CREATE OR REPLACE VIEW some_view AS
 WITH months AS (
         SELECT generate_series.generate_series AS start_date
           FROM generate_series('2025-03-01'::date::timestamp with time zone, now()::date::timestamp with time zone, '1 mon'::interval) generate_series(generate_series)
        )
 SELECT
        CASE
            WHEN some_table.type IS NULL THEN some_table.report_date
            ELSE NULL::date
        END AS previous_report_date
   FROM some_table
     JOIN months month ON month.start_date = some_table.start_date;

However when we feed this back into pgschema plan --file dump.sql we get the following plan:

Plan: 1 to modify.

Summary by type:
  views: 1 to modify

Views:
  ~ some_view

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

CREATE OR REPLACE VIEW some_view AS
 SELECT
    CASE WHEN some_table.type IS NULL THEN some_table.report_date ELSE NULL END AS previous_report_date
   FROM some_table
     JOIN months month ON month.start_date = some_table.start_date;

It seems the planner has stripped out the CTE for some reason

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions