Skip to content

fix: enhance CTE resolution with identifier normalization#19519

Merged
alamb merged 5 commits intoapache:mainfrom
kysshsy:fix_18932
Jan 13, 2026
Merged

fix: enhance CTE resolution with identifier normalization#19519
alamb merged 5 commits intoapache:mainfrom
kysshsy:fix_18932

Conversation

@kysshsy
Copy link
Copy Markdown
Contributor

@kysshsy kysshsy commented Dec 28, 2025

Which issue does this PR close?

Rationale for this change

  • Quoted CTE references (e.g., WITH barbaz AS (...) SELECT * FROM "barbaz") were being collected as table refs and could fall through to catalog lookup instead of resolving to the CTE, especially with custom providers.

What changes are included in this PR?

  • Normalize CTE and table references consistently during collection (preserve quote style; only lowercase unquoted idents when enabled).
  • Avoid double-normalization when converting to TableReference in the resolve path.

Are these changes tested?

Yes

Are there any user-facing changes?

  • Behavior fix for quoted CTE references; no API changes.

@github-actions github-actions Bot added the sql SQL Planner label Dec 28, 2025
@kysshsy
Copy link
Copy Markdown
Contributor Author

kysshsy commented Jan 3, 2026

@alamb @comphead Could you take a look or suggest an alternative approach? Thanks!

Copy link
Copy Markdown
Contributor

@alamb alamb left a comment

Choose a reason for hiding this comment

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

Thanks @kysshsy -- this looks like a good start.

FYI @jonahgao -- perhaps you would have some time to review this PR

Comment thread datafusion/sql/src/resolve.rs Outdated
}

impl RelationVisitor {
fn normalize_object_name(&self, name: &ObjectName) -> ObjectName {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could you please add some comments that explain what this is doing and the rationale (the WHY)? I think you can adapt your PR description.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

updated

Comment thread datafusion/sql/src/resolve.rs Outdated
.relations
.into_iter()
.map(|x| object_name_to_table_reference(x, enable_ident_normalization))
.map(|x| object_name_to_table_reference(x, false))
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

why is this always false now?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It’s false because references are already normalized when collected, so we only need to convert to TableReference here and avoid normalizing twice.
Per the suggestion, the visitor now collects TableReference directly.

assert_eq!(ctes.len(), 1);
assert_eq!(ctes[0].to_string(), "FOObar");
assert_eq!(table_refs.len(), 0);
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can you also please add some .slt tests so we can see this working when running end to end in queries?

Instructions are here: https://github.com/apache/datafusion/tree/main/datafusion/sqllogictest

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the suggestion — I’ve added an end-to-end .slt regression

Comment thread datafusion/sql/src/resolve.rs Outdated
.relations
.into_iter()
.map(|x| object_name_to_table_reference(x, enable_ident_normalization))
.map(|x| object_name_to_table_reference(x, false))
Copy link
Copy Markdown
Member

@jonahgao jonahgao Jan 8, 2026

Choose a reason for hiding this comment

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

Can RelationVisitor directly collect normalized table references instead of object names so that there is no need for a second normalization here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I updated RelationVisitor to collect normalized TableReferences directly, so we don’t need a second normalization pass.
The only downside is error handling becomes a bit more involved, since converting to TableReference can fail and we now need to propagate that Error during visiting.

Add `cte_quoted_reference.slt` and a strict `CatalogProvider`/`SchemaProvider`
used only for that file. The provider panics on unexpected table lookups so
we can observe when a CTE reference is maybe incorrectly treated as a catalog
lookup.

Refs: apache#18932
@github-actions github-actions Bot added the sqllogictest SQL Logic Tests (.slt) label Jan 11, 2026
@kysshsy
Copy link
Copy Markdown
Contributor Author

kysshsy commented Jan 11, 2026

Thanks for the thorough review and the helpful suggestions. @alamb @jonahgao

@kysshsy kysshsy requested review from alamb and jonahgao January 11, 2026 16:15
Copy link
Copy Markdown
Member

@jonahgao jonahgao left a comment

Choose a reason for hiding this comment

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

LGTM, thank you @kysshsy . I have fixed the ci failures in 168baba

@@ -0,0 +1,70 @@
# Licensed to the Apache Software Foundation (ASF) under one
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Since this test is small, I think we can consolidate it into cte.slt. Maybe in next PR.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Good idea -- I filed this ticket to track the idea:

@alamb
Copy link
Copy Markdown
Contributor

alamb commented Jan 13, 2026

Thanks again @kysshsy and @jonahgao

Merged via the queue into apache:main with commit 4e1bc79 Jan 13, 2026
28 checks passed
github-merge-queue Bot pushed a commit that referenced this pull request Mar 22, 2026
## Which issue does this PR close?

N/A

## Rationale for this change

PR #19519 introduces new tests
to verify that DataFusion won't unexpectedly lookup CTE names from the
catalog. It registers a strict SchemaProvider that panics with
unexpected table lookups.

https://github.com/apache/datafusion/blob/d138c36cb08c2dc028b29bbd20853b24cf0f3b8b/datafusion/sqllogictest/src/test_context.rs#L230-L241

The problem is that PR #19862 skips registering the strict
SchemaProvider and bypasses the unexpected lookup check. Therefore,
there tests become meaningless.


<!--
Why are you proposing this change? If this is already explained clearly
in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand
your changes and offer better suggestions for fixes.
-->

## What changes are included in this PR?

Re-register the strict SchemaProvider into cte.slt.

<!--
There is no need to duplicate the description in the issue here but it
is sometimes worth providing a summary of the individual changes in this
PR.
-->

## Are these changes tested?
Yes. 

I also backported these new tests to tag 52.0.0, which does not include
the fix in #19519, and they
failed as expected.
```sh
$ cargo test --profile release-nonlto --test sqllogictests -- cte
   Compiling datafusion-sqllogictest v52.0.0 (/Users/jonah/Work/datafusion/datafusion/sqllogictest)
    Finished `release-nonlto` profile [optimized] target(s) in 19.50s
     Running bin/sqllogictests.rs (/Users/jonah/Work/datafusion/target/release-nonlto/deps/sqllogictests-f9c15c7896eb5af9)
[00:00:00] ####------------------------------------       6/75      "cte.slt"
thread 'tokio-runtime-worker' (486408) panicked at datafusion/sqllogictest/src/test_context.rs:215:22:
unexpected table lookup: barbaz. This maybe indicates a CTE reference was incorrectly treated as a catalog table reference.
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Completed 3 test files in 0 seconds                                                                                                                                                          failure in cte.slt for sql with barbaz as (select * from orders) select * from "barbaz";
caused by
External error: task 13 panicked with message "unexpected table lookup: barbaz. This maybe indicates a CTE reference was incorrectly treated as a catalog table reference."
Error: Execution("1 failures")
error: test failed, to rerun pass `-p datafusion-sqllogictest --test sqllogictests`
```

<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
2. Serve as another way to document the expected behavior of the code

If tests are not included in your PR, please explain why (for example,
are they covered by existing tests)?
-->

## Are there any user-facing changes?
No.
<!--
If there are user-facing changes then we may require documentation to be
updated before approving the PR.
-->

<!--
If there are any breaking changes to public APIs, please add the `api
change` label.
-->

---------

Co-authored-by: Martin Grigorov <martin-g@users.noreply.github.com>
de-bgunter pushed a commit to de-bgunter/datafusion that referenced this pull request Mar 24, 2026
## Which issue does this PR close?

<!--
We generally require a GitHub issue to be filed for all bug fixes and
enhancements and this helps us generate change logs for our releases.
You can link an issue to this PR using the GitHub syntax. For example
`Closes apache#123` indicates that this PR will close issue apache#123.
-->

- Closes apache#18932 

## Rationale for this change
- Quoted CTE references (e.g., `WITH barbaz AS (...) SELECT * FROM
"barbaz"`) were being collected as table refs and could fall through to
catalog lookup instead of resolving to the CTE, especially with custom
providers.

<!--
Why are you proposing this change? If this is already explained clearly
in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand
your changes and offer better suggestions for fixes.
-->

## What changes are included in this PR?
- Normalize CTE and table references consistently during collection
(preserve quote style; only lowercase unquoted idents when enabled).
- Avoid double-normalization when converting to `TableReference` in the
resolve path.

<!--
There is no need to duplicate the description in the issue here but it
is sometimes worth providing a summary of the individual changes in this
PR.
-->

## Are these changes tested?
Yes
<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
2. Serve as another way to document the expected behavior of the code

If tests are not included in your PR, please explain why (for example,
are they covered by existing tests)?
-->

## Are there any user-facing changes?
- Behavior fix for quoted CTE references; no API changes.

<!--
If there are user-facing changes then we may require documentation to be
updated before approving the PR.
-->

<!--
If there are any breaking changes to public APIs, please add the `api
change` label.
-->

---------

Co-authored-by: jonahgao <jonahgao@msn.com>
de-bgunter pushed a commit to de-bgunter/datafusion that referenced this pull request Mar 24, 2026
## Which issue does this PR close?

N/A

## Rationale for this change

PR apache#19519 introduces new tests
to verify that DataFusion won't unexpectedly lookup CTE names from the
catalog. It registers a strict SchemaProvider that panics with
unexpected table lookups.

https://github.com/apache/datafusion/blob/d138c36cb08c2dc028b29bbd20853b24cf0f3b8b/datafusion/sqllogictest/src/test_context.rs#L230-L241

The problem is that PR apache#19862 skips registering the strict
SchemaProvider and bypasses the unexpected lookup check. Therefore,
there tests become meaningless.


<!--
Why are you proposing this change? If this is already explained clearly
in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand
your changes and offer better suggestions for fixes.
-->

## What changes are included in this PR?

Re-register the strict SchemaProvider into cte.slt.

<!--
There is no need to duplicate the description in the issue here but it
is sometimes worth providing a summary of the individual changes in this
PR.
-->

## Are these changes tested?
Yes. 

I also backported these new tests to tag 52.0.0, which does not include
the fix in apache#19519, and they
failed as expected.
```sh
$ cargo test --profile release-nonlto --test sqllogictests -- cte
   Compiling datafusion-sqllogictest v52.0.0 (/Users/jonah/Work/datafusion/datafusion/sqllogictest)
    Finished `release-nonlto` profile [optimized] target(s) in 19.50s
     Running bin/sqllogictests.rs (/Users/jonah/Work/datafusion/target/release-nonlto/deps/sqllogictests-f9c15c7896eb5af9)
[00:00:00] ####------------------------------------       6/75      "cte.slt"
thread 'tokio-runtime-worker' (486408) panicked at datafusion/sqllogictest/src/test_context.rs:215:22:
unexpected table lookup: barbaz. This maybe indicates a CTE reference was incorrectly treated as a catalog table reference.
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Completed 3 test files in 0 seconds                                                                                                                                                          failure in cte.slt for sql with barbaz as (select * from orders) select * from "barbaz";
caused by
External error: task 13 panicked with message "unexpected table lookup: barbaz. This maybe indicates a CTE reference was incorrectly treated as a catalog table reference."
Error: Execution("1 failures")
error: test failed, to rerun pass `-p datafusion-sqllogictest --test sqllogictests`
```

<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
2. Serve as another way to document the expected behavior of the code

If tests are not included in your PR, please explain why (for example,
are they covered by existing tests)?
-->

## Are there any user-facing changes?
No.
<!--
If there are user-facing changes then we may require documentation to be
updated before approving the PR.
-->

<!--
If there are any breaking changes to public APIs, please add the `api
change` label.
-->

---------

Co-authored-by: Martin Grigorov <martin-g@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

sql SQL Planner sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implementing CatalogProvider breaks quoted CTE names

3 participants