Skip to content

Materialization is lost from subquery CTEs #114

@freddiescadding-pennylane

Description

We have found a scenario in which a CTE's materialization is lost in the resulting SQL:

When defining using .with.materialized(...) within a UNION ALL subquery, the CTE is ultimately defined without the MATERIALIZED keyword.

User
  .union_all(User.with.materialized(highly_liked: ProfileL.where("likes > 300")))
  .union_all(User.with(barely_liked: ProfileL.where("likes < 100")))

=>

WITH 
  "highly_liked" AS (SELECT "profile_ls".* FROM "profile_ls" WHERE (likes > 300)), 
  "barely_liked" AS (SELECT "profile_ls".* FROM "profile_ls" WHERE (likes < 100)) 
SELECT 
  "users".* 
  FROM (...)

When defining the CTEs at the top level, however, it works as expected:

User
  .with.materialized(highly_liked: ProfileL.where("likes > 300"))
  .with(barely_liked: ProfileL.where("likes < 100"))
  .union_all(...)
  .union_all(...)

=>

WITH 
  "highly_liked" AS MATERIALIZED (SELECT "profile_ls".* FROM "profile_ls" WHERE (likes > 300)), 
  "barely_liked" AS (SELECT "profile_ls".* FROM "profile_ls" WHERE (likes < 100)) 
SELECT 
  "users".* 
  FROM (...)

Is this expected behaviour? I have seen your comment on piping, but I don't think it applies to this particular example.

Many thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions