sqlfluff / sqlfluff

A modular SQL linter and auto-formatter with support for multiple dialects and templated code.

Home Page:https://www.sqlfluff.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ST04: Nested simple CASE statements are incorrectly flattened

VacuousTruth0 opened this issue · comments

Search before asking

  • I searched the issues and found no similar issues.

What Happened

Nested simple CASE statements are always flattened when running sqlfluff fix with rule ST04.

Expected Behaviour

A nested simple CASE statement should only be flattened when the outer CASE statement is a simple CASE with the same selector statement.

Observed Behaviour

A nested simple CASE statement is still flattened when the outer CASE statement is a searched CASE or a simple CASE with a different selector statement.

SELECT
    CASE
        WHEN DayOfMonth IN (11, 12, 13) THEN 'TH'
        WHEN 1 THEN 'ST'
        WHEN 2 THEN 'ND'
        WHEN 3 THEN 'RD'
        ELSE 'TH'
    END AS OrdinalSuffix
FROM Calendar;

SELECT
    CASE DayOfMonth
        WHEN 11 THEN 'TH'
        WHEN 12 THEN 'TH'
        WHEN 13 THEN 'TH'
        WHEN 1 THEN 'ST'
        WHEN 2 THEN 'ND'
        WHEN 3 THEN 'RD'
        ELSE 'TH'
    END AS OrdinalSuffix
FROM Calendar;

How to reproduce

Run sqlfluff fix on:

SELECT
    CASE
        WHEN DayOfMonth IN (11, 12, 13) THEN 'TH'
        ELSE
            CASE MOD(DayOfMonth, 10)
                WHEN 1 THEN 'ST'
                WHEN 2 THEN 'ND'
                WHEN 3 THEN 'RD'
                ELSE 'TH'
            END
    END AS OrdinalSuffix
FROM Calendar;

SELECT
    CASE DayOfMonth
        WHEN 11 THEN 'TH'
        WHEN 12 THEN 'TH'
        WHEN 13 THEN 'TH'
        ELSE
            CASE MOD(DayOfMonth, 10)
                WHEN 1 THEN 'ST'
                WHEN 2 THEN 'ND'
                WHEN 3 THEN 'RD'
                ELSE 'TH'
            END
    END AS OrdinalSuffix
FROM Calendar;

Dialect

BigQuery

Version

2.3.5

Python version: 3.11.4

Configuration

Default

Are you willing to work on and submit a PR to address the issue?

  • Yes I am willing to submit a PR!

Code of Conduct

I can confirm this is also a problem under SQLFluff version 3.0.3, dialect DB2:

This working SQL…

select
  case 3
    when 0 then
      'zero'
    else
      case
        when 3 < 10 then
          'less than 10'
        else
          'greater or equal to 10'
      end
  end as msg
from
  sysibm.sysdummy1

…gets turned into this non-working SQL when rule ST04 (structure.nested_case) is applied:

select
  case 3
    when 0 then
      'zero'
    when 3 < 10 then
      'less than 10'
    else
      'greater or equal to 10'
  end as msg
from
  sysibm.sysdummy1