Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Computed columns and CTEs sometimes lead to missing column #5354

@Fanaen

Description

@Fanaen

What happened?

When a query results in several CTEs, a computed column may be duplicated in a child CTE without its' column sources. This leads to Referenced column "..." not found as the column is not there anymore.

PRQL input

prql target:sql.postgres

from employees
derive `year` = s'EXTRACT(year from {`hire_date`})'
derive { `year_label` = f"Year {`year`}" }
derive { `city` = case [ this.`city` == "Calgary" => "A city", true => this.`city` ] }
derive { `city` = case [ this.`city` == "Edmonton" => "Another city", true => this.`city` ] }
group {`year`, `year_label`} (take 1)
select {this.`year_label`}

SQL output

WITH table_0 AS (
  SELECT
    CONCAT(
      'Year ',
      EXTRACT(
        year
        from
          hire_date
      )
    ) AS year_label,
    CASE
      WHEN city = 'Calgary' THEN 'A city'
      ELSE city
    END AS _expr_0,
    city
  FROM
    employees
)
SELECT
  DISTINCT ON (
    EXTRACT(
      year
      from
        hire_date
    ),
    year_label
  ) year_label
FROM
  table_0

Expected SQL output

WITH table_0 AS (
  SELECT
    CONCAT(
      'Year ',
      EXTRACT(
        year
        from
          hire_date
      )
    ) AS year_label,
    EXTRACT(
      year
      from
        hire_date
    ) as year_or_expr_1_or_something,
    CASE
      WHEN city = 'Calgary' THEN 'A city'
      ELSE city
    END AS _expr_0,
    city
  FROM
    employees
)
SELECT
  DISTINCT ON (
    year_or_expr_1_or_something,
    year_label
  ) year_label
FROM
  table_0

MVCE confirmation

  • Minimal example
  • New issue

Anything else?

Example is reproducible in the playground. Removing the last select is enough to get out of the CTE topology and therefore to not fail.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugInvalid compiler output or panic

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions