Skip to content

fix(engine): exclude the CTE table when source node checking #1083

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 10, 2025

Conversation

goldmedal
Copy link
Contributor

@goldmedal goldmedal commented Mar 7, 2025

Description

Fix the following SQL syntax

select count(*) from (with orders_custkey as (select custkey from Orders) select * from orders_custkey) 

We should exclude the CTE table when we check if a table is a source table.

Summary by CodeRabbit

  • New Features

    • Improved SQL query processing by enhancing the resolution of table names for more accurate rewriting.
  • Tests

    • Added a new test to validate SQL generation for counting queries involving nested common table expressions.

Copy link

coderabbitai bot commented Mar 7, 2025

Walkthrough

This pull request enhances the SQL rewriting process and expands testing. In the SQL rewrite logic, a new private method tryGetTableName(Node node) is introduced to extract table names from node instances. The apply method in WrenSqlRewrite is modified to check the current node’s scope for named queries before falling back to its legacy source node processing. Additionally, a new test method in TestMDLResourceV2 validates SQL generation from a manifest involving models and nested CTEs.

Changes

File(s) Change Summary
wren-base/.../WrenSqlRewrite.java • Added tryGetTableName(Node node) to retrieve a table name.
• Modified the apply method: now obtains a Scope from the Analysis object to check for named query table names before proceeding with existing logic to fetch the source node and update tableRequiredFields.
wren-tests/.../TestMDLResourceV2.java • Added testPlanCountWithClause() to build a manifest with models and relationships, encode it, set up a DryPlanDtoV2 with a counting query against a CTE, and assert that the generated SQL matches the expected nested CTE structure.

Sequence Diagram(s)

sequenceDiagram
    participant N as Node
    participant RS as Rewrite (WrenSqlRewrite)
    participant A as Analysis
    participant S as Scope
    participant T as TableRequiredFields

    N->>RS: apply(node)
    RS->>A: getScope(node)
    A-->>RS: returns scope
    RS->>S: lookup table name in named queries
    alt Table name found
        S-->>RS: return table name
        RS->>T: update tableRequiredFields using named query table
    else Table name not found
        RS->>N: get source node name
        Note right of RS: Proceed with existing logic
        RS->>T: update tableRequiredFields using source node
    end
Loading

Poem

I hop through lines of structured code,
Sniffing out tables in every node.
With scope and query guiding my bound,
I leap through tests where CTEs are found.
A code rabbit’s joy, in every new mode.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2ea6996 and f8edda3.

📒 Files selected for processing (2)
  • wren-base/src/main/java/io/wren/base/sqlrewrite/WrenSqlRewrite.java (3 hunks)
  • wren-tests/src/test/java/io/wren/testing/TestMDLResourceV2.java (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: ci
🔇 Additional comments (3)
wren-tests/src/test/java/io/wren/testing/TestMDLResourceV2.java (1)

250-310: Great test case for CTE handling!

This test effectively validates the fix for excluding CTE tables when source node checking. The test creates a query that uses a nested CTE structure (with orders_custkey as (select custkey from "Orders")) and verifies that the SQL generation correctly handles this scenario. The assertion confirms that the generated SQL properly nests the CTE within the final query structure.

wren-base/src/main/java/io/wren/base/sqlrewrite/WrenSqlRewrite.java (2)

149-156: Good utility method to extract table names.

This helper method cleanly encapsulates the logic for extracting a table name from a Node, following good separation of concerns. It returns an Optional which is a safe approach for handling the case when the node is not a Table instance.


102-111: Fix implemented correctly to exclude CTE tables.

The implementation now properly checks if a table name can be found in the scope's named queries before proceeding with source node processing. This effectively addresses the issue mentioned in the PR objectives by excluding Common Table Expressions (CTEs) from being considered as source tables.

The modified logic:

  1. Retrieves the scope for the current node
  2. Tries to get the table name and checks if it exists in the named queries (CTEs)
  3. Only proceeds with source node processing if it's not a named query

This change ensures that SQL statements with CTEs like the example in the PR description will work correctly.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@douenergy douenergy left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @goldmedal
LGTM 👍

@douenergy douenergy merged commit 0392984 into Canner:main Mar 10, 2025
7 checks passed
@goldmedal goldmedal deleted the fix/count-sub-with branch March 10, 2025 05:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants