Module qualify_to_where_transformer

Module qualify_to_where_transformer 

Source
Expand description

QUALIFY to WHERE clause transformer

This transformer converts QUALIFY clauses (Snowflake-style window function filtering) into WHERE clauses that work with lifted window functions.

§Problem

Users want to filter on window function results without writing subqueries:

SELECT region, sales_amount,
       ROW_NUMBER() OVER (PARTITION BY region ORDER BY sales_amount DESC) AS rn
FROM sales
QUALIFY rn <= 3  -- Cleaner than WHERE in a subquery!

§Solution

The transformer works in conjunction with ExpressionLifter:

  1. ExpressionLifter runs first, lifting window functions to CTE
  2. QualifyToWhereTransformer runs second, converting QUALIFY → WHERE

§Algorithm

  1. Check if statement has a QUALIFY clause
  2. If yes, move it to WHERE clause
  3. If WHERE already exists, combine with AND
  4. Set qualify field to None

§Example Transformation

After ExpressionLifter:

WITH _lifted AS (
    SELECT region, sales_amount,
           ROW_NUMBER() OVER (...) AS rn
    FROM sales
)
SELECT * FROM _lifted
QUALIFY rn <= 3

After QualifyToWhereTransformer:

WITH _lifted AS (
    SELECT region, sales_amount,
           ROW_NUMBER() OVER (...) AS rn
    FROM sales
)
SELECT * FROM _lifted
WHERE rn <= 3

Structs§

QualifyToWhereTransformer
Transformer that converts QUALIFY clauses to WHERE clauses