Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[SPARK-48355][SQL] Support for CASE statement
### What changes were proposed in this pull request? Add support for [case statements](https://docs.google.com/document/d/1cpSuR3KxRuTSJ4ZMQ73FJ4_-hjouNNU2zfI4vri6yhs/edit#heading=h.ofijhkunigv) to sql scripting. There are 2 types of case statement - simple and searched (EXAMPLES BELOW). Proposed changes are: - Add `caseStatement` grammar rule to SqlBaseParser.g4 - Add visit case statement methods to `AstBuilder` - Add `SearchedCaseStatement` and `SearchedCaseStatementExec` classes, to enable them to be run in sql scripts. The reason only searched case nodes are added is that, in the current implementation, a simple case is parsed into a searched case, by creating internal `EqualTo` expressions to compare the main case expression to the expressions in the when clauses. This approach is similar to the existing case **expressions**, which are parsed in the same way. The problem with this approach is that the main expression is unnecessarily evaluated N times, where N is the number of when clauses, which can be quite inefficient, for example if the expression is a complex query. Optimally, the main expression would be evaluated once, and then compared to the other expressions. I'm open to suggestions as to what the best approach to achieve this would be. Simple case compares one expression (case variable) to others, until an equal one is found. Else clause is optional. ``` BEGIN CASE 1 WHEN 1 THEN SELECT 1; WHEN 2 THEN SELECT 2; ELSE SELECT 3; END CASE; END ``` Searched case evaluates boolean expressions. Else clause is optional. ``` BEGIN CASE WHEN 1 = 1 THEN SELECT 1; WHEN 2 IN (1,2,3) THEN SELECT 2; ELSE SELECT 3; END CASE; END ``` ### Why are the changes needed? Case statements are currently not implemented in sql scripting. ### Does this PR introduce _any_ user-facing change? Yes, users will now be able to use case statements in their sql scripts. ### How was this patch tested? Tests for both simple and searched case statements are added to SqlScriptingParserSuite, SqlScriptingExecutionNodeSuite and SqlScriptingInterpreterSuite. ### Was this patch authored or co-authored using generative AI tooling? No Closes #47672 from dusantism-db/sql-scripting-case-statement. Authored-by: Dušan Tišma <[email protected]> Signed-off-by: Max Gekk <[email protected]>
- Loading branch information