pgschema
pgschema copied to clipboard
NULLIF function is removed from view definitions when planning
I have an odd bug here that is somewhat hard to explain, but given the following database definition:
create table some_table(
id serial primary key,
value integer not null
);
create table some_other_table(
id serial primary key,
value integer not null
);
create view some_view as (
select
a.id,
(a.value - b.value) as value_change,
((a.value - b.value) / nullif(b.value, 0)) as value_change_percentage
from some_table a join some_other_table b using (id)
);
we get a correct output from pgschema dump:
--
-- pgschema database dump
--
-- Dumped from database version PostgreSQL 17.0
-- Dumped by pgschema version 1.4.0
--
-- Name: some_other_table; Type: TABLE; Schema: -; Owner: -
--
CREATE TABLE IF NOT EXISTS some_other_table (
id SERIAL,
value integer NOT NULL,
CONSTRAINT some_other_table_pkey PRIMARY KEY (id)
);
--
-- Name: some_table; Type: TABLE; Schema: -; Owner: -
--
CREATE TABLE IF NOT EXISTS some_table (
id SERIAL,
value integer NOT NULL,
CONSTRAINT some_table_pkey PRIMARY KEY (id)
);
--
-- Name: some_view; Type: VIEW; Schema: -; Owner: -
--
CREATE OR REPLACE VIEW some_view AS
SELECT a.id,
a.value - b.value AS value_change,
(a.value - b.value) / NULLIF(b.value, 0) AS value_change_percentage
FROM some_table a
JOIN some_other_table b USING (id);
However when we feed this back into pgschema plan --file dump.sql we get the following suggested 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
a.id,
a.value - b.value AS value_change,
a.value - b.value / b.value = 0 AS value_change_percentage
FROM some_table a
CROSS JOIN some_other_table b;
This new view definition is not correct.
- the
value_change_percentagecolumn is not correct anymore, it appears to change into a boolean column definition - the table join has been changed from a JOIN...USING to a CROSS JOIN
just tested, this works great! thanks!