Skip to content

Keep outer table scope when binding quantified ANY/ALL subqueries - #40071

Open
thswlsqls wants to merge 8 commits into
apache:masterfrom
thswlsqls:40067
Open

thswlsqls wants to merge 8 commits into
apache:masterfrom
thswlsqls:40067

Conversation

@thswlsqls

@thswlsqls thswlsqls commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #40067.

Changes proposed in this pull request:

  • ExpressionSegmentBinder now merges outerTableBinderContexts with tableBinderContexts before binding a QuantifySubqueryExpression, so an ANY/ALL/SOME subquery nested inside another subquery can resolve aliases from every enclosing level instead of failing with Unknown column.
  • This mirrors the existing ExistsSubqueryExpression and SubqueryExpressionSegment branches; the same scope loss was fixed for NotExpressionBinder in Fix is unable to find the outer table in the NotExpressionBinder. #36135.
  • Added ExpressionSegmentBinderTest#assertBindQuantifySubqueryWithOuterTableContext, which checks that the contexts passed to SubquerySegmentBinder include both the outer and the current tables. It fails without the fix.

AI assistance: Claude Code was used to draft the change and its tests in infra/binder/core (binder segment classes and their unit tests), the test/it/binder integration test, and the RELEASE-NOTES.md entry. I reviewed, verified, and take responsibility for every line submitted.


Before committing this PR, I'm sure that I have checked the following options:

  • My code follows the code of conduct of this project.
  • I have self-reviewed the commit code.
  • I have (or in comment I request) added corresponding labels for the pull request. (I don't have permission to add labels.)
  • I have passed maven check locally : ./mvnw clean install -B -T1C -Dmaven.javadoc.skip -Dmaven.jacoco.skip -e. (Not run for the whole repository; I ran spotless:apply, checkstyle:check, and apache-rat:check with -Pcheck -pl infra/binder/core, plus ./mvnw install -pl infra/binder/core -am -B -T1C -Dmaven.javadoc.skip -Dmaven.jacoco.skip -e, all passing. E2E tests were not run.)
  • I have made corresponding changes to the documentation. (No user-facing documentation is affected.)
  • I have added corresponding unit tests for my changes.
  • I have updated the Release Notes of the current development version. For more details, see Update Release Note
  • I have disclosed the tool and affected files or scope for any material AI assistance, as required by the AI-assisted contribution policy.

@terrymanu terrymanu left a comment

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.

Result

Review Result: Not Mergeable
Feedback Mode: Change Request
Blocking Issues: 2

The patch fixes the loss of outer scope but introduces a regression in alias shadowing. The added test also contains an unnecessary line break.

Blocking Issues

  1. [P2] Merging scopes incorrectly treats shadowed aliases as ambiguous

    • Evidence: ExpressionSegmentBinder.java:138–140 retains both the farther and nearer contexts for the same alias. ColumnSegmentBinder subsequently iterates over both contexts and throws AmbiguousColumnException. A local reproduction through the actual binding path confirmed that the same input succeeds at the merge-base and fails at the current head.
    • Impact: When the outer query uses t_order x, the middle query uses t_order_item x, and the innermost ALL subquery references x.user_id, a previously valid statement now fails if both tables contain that column. Under MySQL’s scoping rules, this reference must resolve to the nearer t_order_item.
    • Required Change: Preserve the nearer scope’s shadowing of same-name aliases while retaining other outer aliases. Add a regression test that executes actual column resolution. The added test uses distinct aliases and cannot detect this failure.
  2. [P3] The added invocation does not require wrapping

    • Evidence: The statement at ExpressionSegmentBinderTest.java:119–120 contains 196 characters when reconstructed on one line, including indentation, which is within the repository’s 200-character limit.
    • Impact: This violates the applicable Java line-wrapping rule. Spotless preserves existing wrapping, so passing automated checks does not establish compliance with this manual check.
    • Required Change: Keep the declaration and invocation on one line.

Evidence

  • All 3 tests in ExpressionSegmentBinderTest and all 20 tests in ColumnSegmentBinderTest passed.
  • Cross-level correlation with distinct aliases: the baseline throws ColumnNotFoundException; the current head succeeds.
  • Cross-level correlation with a shadowed alias: the baseline succeeds; the current head throws AmbiguousColumnException.

Coverage

  • Candidate: public PR #40071; head e77e0e2eccf15e93c7dda95a7e62702942f9bc9f; merge-base 7712a28fffeaa6a9569892dcea1cddd62ad64d64. The head and changed-file list were rechecked before completion and remained unchanged. No local candidate delta was included.
  • All 3 files in GitHub’s authoritative changed-file list were reviewed:
    • RELEASE-NOTES.md
    • infra/binder/core/src/main/java/org/apache/shardingsphere/infra/binder/engine/segment/dml/expression/ExpressionSegmentBinder.java
    • infra/binder/core/src/test/java/org/apache/shardingsphere/infra/binder/engine/segment/dml/expression/ExpressionSegmentBinderTest.java
  • Behavior clusters: quantified-subquery scope propagation, regression tests, and release notes. Based on #40067, existing correlated-subquery contracts, and official MySQL semantics, this restores existing behavior without adding a project commitment. The MySQL entry path, MariaDB’s reuse of MySQL, and Doris’s separate entry path were inspected.
  • Root-cause, blast-radius, and tests/runtime reviews, plus the final convergence pass, are complete. No unresolved evidence gaps remain.
  • Local style verification ran against an accurate snapshot of the reviewed head and covered both Java files listed above:
    • Checkstyle: ./mvnw -B -pl infra/binder/core -Dcheckstyle.includes=<exact source-root-relative paths of both files> -Dcheckstyle.includeResources=false -Dcheckstyle.includeTestResources=false checkstyle:check -Pcheck -T1; exit 0. The report confirmed that both files were selected.
    • Spotless: ./mvnw -B -pl infra/binder/core -DspotlessFiles=<exact canonical-path regular expressions for both files> spotless:check -Pcheck -T1; exit 0. Both files were confirmed as checked.
    • RELEASE-NOTES.md: both checks are Not Applicable because the repository configuration does not cover Markdown.
  • This result covers code correctness only; CI was not reviewed. No repository code or remote state was modified.

@thswlsqls

Copy link
Copy Markdown
Contributor Author

@terrymanu Thanks for the review. You're right about the shadowing regression. Instead of dropping outer contexts during the merge, which would also hide columns that exist only in the farther table (such as an unqualified status), ColumnSegmentBinder now resolves an owner-qualified outer reference to the nearest context for that alias. assertBindWithQuantifySubqueryReferencingShadowedOuterAlias binds x.user_id and status inside the ALL subquery through the real binding path and gets t_user and t_order; the first fails on the previous head with AmbiguousColumnException. assertBindWithOwnerFromShadowedOuterTable covers the lookup itself. EXISTS and scalar subqueries share that lookup, so the same shadowing case now works there too. The test invocation is now on one line.

@terrymanu terrymanu left a comment

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.

Result

Review Result: Not Mergeable
Feedback Mode: Change Request
Blocking Issues: 1

The alias-shadowing and line-wrapping issues from the previous review have been fixed. However, the latest commit introduces a binding regression for same-name tables within one query scope.

Blocking Issues

  1. [P2] Preserve same-name tables within the same query scope

    • Evidence: ColumnSegmentBinder.java:207–210 uses Iterables.getLast(...), retaining only the last outer context. However, SimpleTableSegmentBinder registers both db1.t and db2.t under the key t when they appear in the same query. These tables do not represent alias shadowing across nested scopes. The MySQL documentation explicitly supports these table references.
    • Impact: With db1.t containing only1 and db2.t containing only2, the valid query SELECT only1 FROM db1.t, db2.t WHERE EXISTS (SELECT db1.t.only1) checks only db2.t and throws ColumnNotFoundException. A reproduction through the actual SelectStatementBinder entry point successfully binds to db1.t.only1 at the baseline but fails at the current head. This regression also affects EXISTS and scalar subqueries.
    • Required Change: Apply alias shadowing by query nesting level while preserving every same-name table context within the nearest matching scope. Add a regression test for this scenario.
    • Origin: Introduced by latest commits.

Coverage

  • Candidate: public PR #40071, with no local code delta.
  • Latest head: 82bf8393d5b56d16096bb7e4f0efff1960b5f853.
  • Baseline and merge-base: 5756b72bfa9da47c24c4856915fd8159ce60a1be. The head, base, and complete changed-file list were rechecked before completion.
  • Requirements: #40067, existing scope propagation for EXISTS and scalar subqueries, and MySQL correlated-reference rules. This restores existing behavior without introducing a new public API or SPI.
  • All 6 changed files were reviewed: RELEASE-NOTES.md and the following files under infra/binder/core:
    • src/main/java/org/apache/shardingsphere/infra/binder/engine/segment/dml/expression/ExpressionSegmentBinder.java
    • src/main/java/org/apache/shardingsphere/infra/binder/engine/segment/dml/expression/type/ColumnSegmentBinder.java
    • src/test/java/org/apache/shardingsphere/infra/binder/engine/segment/dml/expression/ExpressionSegmentBinderTest.java
    • src/test/java/org/apache/shardingsphere/infra/binder/engine/segment/dml/expression/type/ColumnSegmentBinderTest.java
    • src/test/java/org/apache/shardingsphere/infra/binder/engine/statement/dml/SelectStatementBinderTest.java
  • Behavior clusters: quantified-subquery scope propagation, shared column-name resolution, regression tests, and release notes. Root-cause, blast-radius, and tests/runtime discovery passes, plus an independent review, were completed. Final convergence found no additional independent issue. No unresolved evidence gaps remain.
  • Local verification used an exact snapshot of the current head:
    • All 39 tests across the three relevant test classes passed, exit code 0.
    • Checkstyle: ./mvnw -B -ntp -pl infra/binder/core [exact-file filters] spotless:check checkstyle:check -Pcheck, exit code 0. The result XML confirms coverage of all 5 Java files listed above.
    • Spotless: ./mvnw -B -ntp -pl infra/binder/core -DspotlessFiles="$EXACT_ABSOLUTE_PATH_REGEXES" spotless:check -Pcheck, exit code 0. Canonical-path filters selected exactly the 5 Java files listed above, and the output confirmed that all were clean. Absolute paths have been sanitized.
    • RELEASE-NOTES.md is not governed by the current Checkstyle or Spotless configuration.
  • This result concerns code correctness only. CI was not queried; local style verification was completed.

@thswlsqls

Copy link
Copy Markdown
Contributor Author

@terrymanu Thanks for the review. You're right — Iterables.getLast collapsed same-name tables that share one key within a scope. The owner lookup now walks that owner's outer contexts from the nearest scope outward and takes the first one that has the column, the same rule findInputColumnSegmentFromOuterTable uses for unqualified names. assertBindWithExistsSubqueryReferencingSameNameTableInOuterScope covers SELECT status FROM foo_db.t_order, bar_db.t_order WHERE EXISTS (SELECT foo_db.t_order.status FROM t_user) and fails on the previous head; the alias-shadowing tests still pass.

One difference from strict nesting-level resolution: if the nearest t lacks the column, a farther t that has it is used instead of failing, since the merged outer contexts carry no scope boundary. Tracking scope levels would need a structural change across the binders, so I kept the fix local — happy to go further if you prefer.

@terrymanu terrymanu left a comment

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.

Result

Review Result: Not Mergeable
Feedback Mode: Change Request
Blocking Issues: 2

Outer scopes are now propagated, but two column-resolution defects remain.

Blocking Issues

  1. [P2] Do not fall back past a shadowing alias when its table lacks the column

    • Evidence: ColumnSegmentBinder.java:220–228 scans contexts backward and selects one based on column presence. A reproduction through the real SelectStatementBinder path uses outer t_order x, middle t_user x without status, and an innermost ALL subquery referencing x.status. The current head binds it to the farther t_order.status; the baseline throws ColumnNotFoundException. MySQL’s scoping rules require x to resolve to the nearest alias.
    • Impact: Quantified subqueries bypass alias shadowing and receive incorrect column ownership metadata. The outward lookup rule for unqualified columns cited by the author does not apply to x.status.
    • Required Change: Resolve the nearest owner scope before looking up its column. Preserve the unknown-column error when that scope lacks the column, while retaining valid outward lookup for unqualified names. Add a regression test for this case.
  2. [P2] Preserve database qualification and ambiguity for same-scope tables with shared columns

    • Evidence: The same selection logic returns a singleton prematurely. When both foo_db.t_order and bar_db.t_order contain order_id, SELECT status FROM foo_db.t_order, bar_db.t_order WHERE EXISTS (SELECT foo_db.t_order.order_id FROM t_user) binds the explicitly foo_db-qualified column to bar_db. The baseline reports ambiguity; the current head instead succeeds with incorrect metadata. MySQL’s qualifier rules require the specified database’s table identity to be preserved.
    • Impact: Resolution depends on FROM registration order and bypasses same-scope ambiguity checks. The added test uses status, which exists in only one table, and therefore misses the shared-column case.
    • Required Change: Preserve candidates within the same scope, disambiguate using complete qualifiers, and retain ambiguity errors where applicable. Add shared-column regression coverage. The previously reported same-name-table issue is only partially fixed.

Coverage

  • Candidate: public PR #40071, with no local code delta; head 4d59d3b191996f978a7439ecec7a285146d15f23; baseline and merge-base 00c22f1832839b0b03a5f21fbc6f2279ab90ecd5. The version and scope were rechecked before completion and remained unchanged.
  • All 6 files in GitHub’s authoritative changed-file list were covered: RELEASE-NOTES.md, plus ExpressionSegmentBinder.java, ColumnSegmentBinder.java, ExpressionSegmentBinderTest.java, ColumnSegmentBinderTest.java, and SelectStatementBinderTest.java under infra/binder/core.
  • Requirements: #40067, existing EXISTS/scalar-subquery contracts, and the MySQL rules cited above. This repairs existing binder behavior without adding an API, SPI, or database-support commitment.
  • Behavior clusters: quantified scope propagation, shared column resolution, regression tests, and release notes. Root-cause, blast-radius, and tests/runtime discovery passes, plus final convergence, are complete.
  • One independent review pair reached matching conclusions. Coordinator verification confirmed the two independent fix boundaries above. No unresolved evidence gaps remain.
  • Local style verification used an exact snapshot of the reviewed head and covered all 5 Java files listed above:
    ./mvnw -B -ntp -pl infra/binder/core -DspotlessFiles="$EXACT_JAVA_PATH_REGEXES" -Dcheckstyle.includes="$EXACT_SOURCE_RELATIVE_PATHS" -Dcheckstyle.includeResources=false -Dcheckstyle.includeTestResources=false spotless:check checkstyle:check -Pcheck -T1
    The combined command exited 0. Spotless confirmed 5 files checked and 0 skipped; Checkstyle XML confirmed the same complete scope. The two variables represent exact canonical-path regular expressions and source-root-relative paths for those 5 files.
  • RELEASE-NOTES.md: Checkstyle and Spotless are both Not Applicable because the current configuration does not cover Markdown.
  • All 44 tests across the three relevant test classes passed, exit 0. Additional baseline comparisons exercised the real binder path.
  • This result covers code correctness only; CI was not queried. Local style verification is complete. No repository code or remote state was modified, and review-owned temporary materials were cleaned up.

@thswlsqls

Copy link
Copy Markdown
Contributor Author

@terrymanu Thanks for the review. Both reproduce. The second is a regression from my last commit: returning a single context drops the same-scope ambiguity, and it affects EXISTS too. The first, like the shadowing case from your first review, is not specific to quantified subqueries: on current master, an EXISTS nested in an EXISTS already binds x.status to the farther t_order x and reports x.user_id as ambiguous, because ExpressionSegmentBinder merges every enclosing scope into one flat outerTableBinderContexts map with no scope boundary. Fixing both needs scope-aware outer resolution for EXISTS, scalar, and quantified subqueries alike. Would you like that in this PR, or should I narrow this PR to propagating the outer scope (same as EXISTS today) and open a separate issue for scope-aware resolution? I'll go with whichever you prefer.

@terrymanu

Copy link
Copy Markdown
Member

Please resolve conflicts

@thswlsqls

Copy link
Copy Markdown
Contributor Author

@terrymanu Thanks. Rebased onto master and resolved the conflict in ColumnSegmentBinder, where master changed the signature of getTableBinderContextByOwner; the branch is mergeable again and the binder tests pass locally. The scope question in my previous comment is still open, and I'll follow whichever direction you prefer.

@terrymanu terrymanu left a comment

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.

Result

Review Result: Not Mergeable
Feedback Mode: Change Request
Review Status: Not Converged
Confirmed Blocking Issues: 4

Two binding regressions and two explicit test-standard violations are confirmed. These are a confirmed subset: Git-backed ledger and session validation could not complete because the public-head Git object is unavailable locally.

Blocking Issues

  1. [P2] Stop qualified lookup at the nearest shadowing alias

    • Evidence: infra/binder/core/src/main/java/org/apache/shardingsphere/infra/binder/engine/segment/dml/expression/type/ColumnSegmentBinder.java:225–232 selects a context by column presence. Combined with the scope merge in infra/binder/core/src/main/java/org/apache/shardingsphere/infra/binder/engine/segment/dml/expression/ExpressionSegmentBinder.java:140–144, outer t_order x(status), nearer t_user x without status, and innermost ALL (SELECT x.status FROM t_user) bind to the farther t_order.status. The baseline throws ColumnNotFoundException.
    • Impact: A qualified reference bypasses its shadowing alias and receives incorrect ownership metadata. Existing EXISTS behavior does not invalidate this newly exposed quantified-subquery regression.
    • Required Change: Resolve the nearest owner scope before checking column presence. Preserve outward lookup for unqualified columns and add the missing-column regression case.
  2. [P2] Preserve same-scope table identity and ambiguity

    • Evidence: ColumnSegmentBinder.java:216–229 reduces matching outer contexts to one entry. With both foo_db.t_order and bar_db.t_order containing order_id, EXISTS (SELECT foo_db.t_order.order_id FROM t_user) binds to bar_db. Reversing table registration order selects foo_db. The baseline reports ambiguity.
    • Impact: Explicit database qualification is ignored, and existing ambiguity errors become order-dependent binding success. The added test uses a column unique to foo_db and misses this case.
    • Required Change: Preserve same-scope candidates, respect complete qualifiers, and retain applicable ambiguity errors. Add shared-column regression coverage.
  3. [P3] Use the required identity matcher

    • Evidence: infra/binder/core/src/test/java/org/apache/shardingsphere/infra/binder/engine/segment/dml/expression/ExpressionSegmentBinderTest.java:134 uses is(boundSubquerySegment) for the exact object returned by the mocked binder. SubquerySegment has no value-equality override.
    • Impact: This violates the reference-identity assertion rule in CODE_OF_CONDUCT.md:101.
    • Required Change: Use sameInstance(boundSubquerySegment).
  4. [P3] Inline the single-use mock setup

    • Evidence: infra/binder/core/src/test/java/org/apache/shardingsphere/infra/binder/engine/statement/dml/SelectStatementBinderTest.java:391–403 adds mockMetaDataWithSameNameTable, whose only caller is line 378.
    • Impact: CODE_OF_CONDUCT.md:95 permits private mock helpers only for repeated local setup.
    • Required Change: Inline the new scenario-specific setup into its test while retaining the existing reusable mockMetaData helper.

Coverage

  • Candidate: public PR #40071, no local delta.
  • Head: 588561b6eeaa7d7928a18775a803b99da06a0975.
  • Base and merge-base: 4236a4231b92e7b67547c7cc245cb78322e6dd6c.
  • Head, base, and six-file scope were rechecked before completion. Snapshot file identities matched GitHub’s authoritative blob identities.
  • All six changed files were inspected: the four Java files cited above, infra/binder/core/src/test/java/org/apache/shardingsphere/infra/binder/engine/segment/dml/expression/type/ColumnSegmentBinderTest.java, and RELEASE-NOTES.md.
  • Requirements: issue #40067, existing correlated-subquery contracts, MySQL scope/qualification semantics, and applicable written repository standards. The accepted objective restores correlation behavior without adding an API, SPI, or database-support commitment.
  • Two isolated assessments covered scope propagation, shared column resolution, tests, and release notes through all three discovery lenses and a final semantic pass. Coordinator verification retained the four findings above; no semantic disagreement remains.
  • Exact-head verification:
    • Focused Maven tests for ExpressionSegmentBinderTest,ColumnSegmentBinderTest,SelectStatementBinderTest: 69 passed, exit 0.
    • Checkstyle ran within ./mvnw -B -ntp -pl infra/binder/core [exact-file filters] spotless:check checkstyle:check -Pcheck -T1, exit 0; its XML selected all five changed Java files.
    • Spotless reran with canonical-path filters: ./mvnw -B -ntp -pl infra/binder/core -DspotlessFiles="$JAVA_FILE_REGEXES" spotless:check -Pcheck -T1, exit 0; all five files checked, zero skipped.
    • Both checks are Not Applicable to RELEASE-NOTES.md under the repository configuration.
    • Public binder-entry probes reproduced the correctness findings using fixture metadata and exact-base production-class overlays.
  • Formal ledger initialization failed on the missing head Git object. Session validation and exhaustive formal completion are not claimed.
  • This is a code-correctness review; CI was not reviewed. Repository source and Git state were unchanged.

@thswlsqls

Copy link
Copy Markdown
Contributor Author

@terrymanu Thanks for the review. All four are addressed in 8a679453592:

  1. Quantified subqueries now receive their enclosing contexts as ScopedTableSegmentBinderContexts, which keeps only the nearest declaring scope per owner for qualified lookup and every context for unqualified lookup. x.status against a nearer t_user x now throws ColumnNotFoundException, while unqualified status still resolves to the farther t_order.
  2. The column-presence selection is removed, so same-scope candidates are kept and foo_db.t_order.order_id with order_id in both tables is ambiguous again, as on the baseline. Resolving it by the database qualifier is not done on the baseline either, so I kept that out of this PR — happy to add it here if you'd prefer.
  3. Switched to sameInstance(boundSubquerySegment).
  4. Inlined the bar_db setup into the shared-column test, which replaces the unique-column one.

New tests cover both regressions and fail when either fix is reverted; binder core tests pass locally.

@terrymanu terrymanu left a comment

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.

Summary

This PR fixes the loss of outer table contexts in quantified subqueries and introduces a scoped context type to handle alias shadowing. However, scope information is still lost across EXISTS or scalar subquery boundaries, causing previously valid statements to fail binding.

Result

Review Result: Not Mergeable
Feedback Mode: Change Request
Review Status: Not Converged
Confirmed Blocking Issues: 1

The following is a confirmed subset of findings. Formal verification limitations are documented under Coverage.

Blocking Issues

  1. [P2] Preserve scope boundaries across mixed nested subqueries

    • Evidence: The quantified-subquery branch creates scoped contexts, but the EXISTS and scalar branches subsequently copy them into a plain Multimap, discarding nearest-scope information.
    • Impact: A reproduction through the actual binder path uses outer t_order x → EXISTS t_user x → ALL t_user q → EXISTS (SELECT x.user_id FROM t_user i). The baseline correctly binds the reference to t_user; the current head throws AmbiguousColumnException. Replacing the innermost reference with x.status makes the current head incorrectly bind it to the farther t_order, whereas the baseline correctly reports an unknown column. This violates MySQL’s nearest-alias scoping rule.
    • Required Change: Preserve scope boundaries through EXISTS, scalar, and other context-propagation paths before and after quantified subqueries. Add regression tests that exercise mixed nesting through the actual binding path.

Coverage

  • Public PR head: 8a679453592e491e2d17a8cb58c95cff50cd9aff; baseline: 4236a4231b92e7b67547c7cc245cb78322e6dd6c. Two independent assessments and coordinator verification covered all 8 changed files, with no local code delta.
  • Checkstyle and Spotless passed against an exact source snapshot, covering all 7 Java files. All 73 focused tests passed. All commands exited with code 0. Neither style check applies to the Markdown file.
  • This review covers code correctness only; CI was not queried. The public-head Git object is unavailable locally, preventing ledger initialization and session validation, so an exhaustive blocker set is not claimed. Temporary materials were cleaned up; repository source and Git state were unchanged.

@thswlsqls

Copy link
Copy Markdown
Contributor Author

@terrymanu Thanks for the review. Done in f7d0a140763: EXISTS, scalar and projection subqueries, HAVING and derived tables now pass ScopedTableSegmentBinderContexts like quantified subqueries instead of copying into a plain Multimap, so the nearest declaring scope survives mixed nesting. New SelectStatementBinderTest cases bind t_order x → EXISTS t_user x → ALL t_user q → EXISTS through SelectStatementBinder: x.user_id resolves to t_user and x.status throws ColumnNotFoundException; the scalar, projection, HAVING and derived-table variants resolve x.user_id to t_user as well. Each fails on the previous head. Plain EXISTS→EXISTS nesting now follows the same nearest-scope rule.

@terrymanu terrymanu left a comment

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.

Summary

This PR fixes the loss of outer scopes in ANY/ALL/SOME subqueries. The latest commit fixes alias shadowing across mixed nesting, but still introduces a regression in database-qualified column references.

Result

Review Result: Not Mergeable
Feedback Mode: Change Request
Review Status: Not Converged
Confirmed Blocking Issues: 2

The following findings are a confirmed subset. Formal verification limitations are documented under Coverage.

Blocking Issues

  1. [P2] Preserve database qualifiers when selecting the nearest scope

    • Evidence: ColumnSegmentBinder.java:215–216 selects the nearest scope using only the table name, ignoring the database qualifier.
    • Impact: With outer foo_db.t_order, nearer bar_db.t_order, and an innermost EXISTS referencing foo_db.t_order.status, the current head throws ColumnNotFoundException. The same input correctly binds to foo_db.t_order.status at the baseline. This is a cross-scope regression, distinct from the existing same-scope shared-column ambiguity. See MySQL’s identifier qualification rules.
    • Required Change: Select the outer scope using the complete qualifier, preserve ordinary alias shadowing, and add a regression test through the actual binding path for same-name tables in different databases.
  2. [P2] Add the required annotation to the new high-frequency path

    • Evidence: ScopedTableSegmentBinderContexts.java:30–45 is repeatedly constructed and queried during ordinary JDBC SQL binding, but lacks the HighFrequencyInvocation annotation required by the public CODE_OF_CONDUCT.md:56–63.
    • Impact: This violates an applicable manual coding standard; no measured performance regression is claimed. This standards issue was missed in the previous public review.
    • Required Change: Add the annotation at an appropriate scope covering the new high-frequency construction and lookup paths.

Coverage

  • Public PR head: f7d0a140763b4465f00f0242506070eb5a0d01c3; baseline: 4236a4231b92e7b67547c7cc245cb78322e6dd6c. All 11 changed files were reviewed, with no local code delta. Candidate identity was rechecked before completion.
  • Checkstyle and Spotless passed, covering all 10 Java files. All 86 relevant tests passed; all commands exited with code 0. Neither style check applies to Markdown.
  • Two independent assessments and coordinator verification completed the code-evidence checks. The current Git object is unavailable locally, causing ledger initialization to fail (git merge-base exited 128). Ledger and session validation therefore could not complete, and an exhaustive finding set is not claimed. This result covers code correctness only; CI was not reviewed.

@thswlsqls

Copy link
Copy Markdown
Contributor Author

@terrymanu Thanks for the review. Done in 5c4ce69b665: a database-qualified owner such as foo_db.t_order.status now resolves to the nearest enclosing scope that declares t_order in foo_db (a schema qualifier is matched the same way), while an unqualified owner still takes the nearest scope, so alias shadowing is unchanged. assertBindWithExistsSubqueryInsideQuantifySubqueryReferencingDatabaseQualifiedOuterTable binds the outer foo_db.t_order / nearer bar_db.t_order / innermost EXISTS case through SelectStatementBinder. ScopedTableSegmentBinderContexts is now annotated with @HighFrequencyInvocation. Also rebased onto master to resolve the conflict with #40456.

@terrymanu terrymanu left a comment

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.

Summary

This PR preserves outer scopes for nested ANY/ALL/SOME subqueries and handles alias shadowing across query levels. However, the implementation still treats database and schema qualifiers interchangeably, causing previously valid PostgreSQL queries to fail binding.

Result

Review Result: Not Mergeable
Feedback Mode: Change Request
Review Status: Not Converged
Confirmed Blocking Issues: 1

The following is a confirmed subset of blocking issues. Formal verification limitations are documented under Coverage.

Blocking Issues

  1. [P2] Distinguish schema qualification from database qualification

    • Evidence: ScopedTableSegmentBinderContexts.java:98 matches the qualifier against both originalDatabase and originalSchema. In PostgreSQL, however, schema.table.column explicitly identifies the schema. See the official column-reference rules.

    • Impact: When the current database is foo_db, foo_db.t_order contains status, and public.t_order does not, the following query incorrectly selects the nearer public.t_order. Verification through the actual binding entry point succeeds against the baseline but throws ColumnNotFoundException at the current head.

      SELECT status FROM foo_db.t_order
      WHERE EXISTS (
        SELECT user_id FROM public.t_order
        WHERE EXISTS (
          SELECT foo_db.t_order.status FROM public.t_user
        )
      );
    • Required Change: Match the correct namespace according to the dialect and qualification structure, and add a binder regression test where the database and schema share the same name. The existing schema test does not cover this condition.

Coverage

  • Public head: 5c4ce69b665ac75d05fcf5854774f879f54db2d1; baseline: e1cb0fe656ce074d6bf15bbda227e746ba8c273e. Two independent assessments and coordinator verification covered all 11 files, with no local code delta.
  • Against the exact source snapshot, Checkstyle and Spotless passed for all 10 Java files, and all 93 focused tests passed. All commands exited with code 0. Neither style check applies to Markdown.
  • The head Git object is unavailable locally, causing ledger initialization to fail at git merge-base with exit code 128. Ledger/session validation therefore could not complete, and an exhaustive finding set is not claimed. This review covers code correctness only; CI was not reviewed. Temporary materials were cleaned up.

@thswlsqls

Copy link
Copy Markdown
Contributor Author

@terrymanu Thanks for the review. A qualified owner is now matched against the schema for dialects with schema support and against the database otherwise, so in your example foo_db.t_order.status resolves to the outer foo_db.t_order. assertBindWithNestedExistsSubqueryReferencingSchemaQualifiedOuterTableNamedAsDatabase binds that query on PostgreSQL, with a database and schema sharing the name foo_db, through SelectStatementBinder.

Merging quantified-subquery scopes keeps both contexts for an alias redefined in a nearer query, so ColumnSegmentBinder treated x.user_id as ambiguous. Pick the nearest outer context for an owner-qualified lookup instead, which keeps unqualified columns resolvable in farther scopes and also covers EXISTS and scalar subqueries. Keep the single-line test invocation since it fits within 200 characters.
Iterables.getLast kept only the last outer context for an owner, so same-name tables registered under one key in a single query scope, such as foo_db.t_order and bar_db.t_order, lost all but one candidate and EXISTS, scalar and quantified subqueries failed with ColumnNotFoundException. Walk that owner's outer contexts from the nearest scope outward and take the first one that has the column, the same rule findInputColumnSegmentFromOuterTable applies to unqualified names, so nearer aliases still shadow farther ones.
Quantified ANY/ALL subqueries now receive their enclosing contexts as
ScopedTableSegmentBinderContexts, which keeps every context for
unqualified lookup and, per owner, only the contexts of the nearest
scope that declares it. An owner-qualified column therefore stops at a
shadowing alias (ColumnNotFoundException when that alias lacks the
column) while same-scope tables sharing a name stay candidates.

The previous column-presence selection is removed, so an EXISTS
reference to a column shared by foo_db.t_order and bar_db.t_order is
ambiguous again instead of depending on table registration order.
EXISTS, scalar and projection subqueries, HAVING and derived tables now
pass ScopedTableSegmentBinderContexts instead of copying outer contexts
into a plain Multimap, so owner-qualified columns keep resolving to the
nearest declaring scope through mixed nesting.
The nearest declaring scope was chosen by table name only, so with an
outer foo_db.t_order, a nearer bar_db.t_order and an inner reference to
foo_db.t_order.status, the nearer scope was taken and binding failed with
ColumnNotFoundException. ScopedTableSegmentBinderContexts now keeps the
contexts of each enclosing scope and, for a qualified owner, takes the
nearest scope that declares the table in the qualified database or
schema. Unqualified owners still take the nearest scope, so alias
shadowing is unchanged. The class is marked HighFrequencyInvocation as
it is built and queried for every bound subquery.
A qualified owner such as foo_db.t_order was matched against both the
original database and the original schema of each enclosing scope. On
PostgreSQL the qualifier names a schema, so when the current database
shares that name, a nearer public.t_order was chosen and the column
failed to bind.

Dialects with a default schema now compare the qualifier with the
original schema only, and other dialects with the original database
only, following SimpleTableSegmentBinder.

@terrymanu terrymanu left a comment

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.

Summary

This PR preserves enclosing table scopes for nested ANY/ALL/SOME subqueries and carries scope boundaries through related binders. Ordinary correlated column lookup is covered, but correlated wildcard projections still resolve a shadowed alias incorrectly.

Result

Review Result: Not Mergeable
Feedback Mode: Change Request
Review Status: Not Converged
Confirmed Blocking Issues: 2

These findings are a confirmed subset. Required ledger/session validation could not complete, so an exhaustive finding set is not claimed.

Blocking Issues

  1. [P2] Resolve correlated wildcard projections from the nearest scope

    • Evidence: The quantified-subquery branch now includes farther scopes, but shorthand lookup still selects the first flattened context.

    • Impact: With t_order(order_id,user_id,status) and t_user(user_id), this valid PostgreSQL query expands x.* to one t_user column at the baseline but three t_order columns at the PR head:

      SELECT order_id FROM t_order x WHERE EXISTS (SELECT user_id FROM t_user x WHERE x.user_id = ALL (SELECT x.* FROM t_user p))

      Real SQL parsing through SQLBindEngine confirmed the incorrect table origin and projection count. PostgreSQL’s SELECT-list namespace rules require the nearer alias. This path was missed in earlier reviews.

    • Required Change: Apply nearest-scope resolution to owner-qualified shorthand projections and add regression coverage for this parsed SQL.

  2. [P2] Follow the current internal-helper Javadoc rules

    • Evidence: The new class description describes collection properties, and the method Javadoc adds an explanatory paragraph. The current Javadoc rules prohibit these expansions for ordinary declarations.
    • Impact: The new internal helper violates an applicable manual coding standard.
    • Required Change: Use concise responsibility/action summaries and retain the required parameter and return tags.

Coverage

  • Head: cbd9feaf5532d3f9417ea7fc18c16cba4df90611; baseline: 0d76e38a58243f1b33bdb2218ddfc1e237f8fee0. Two independent assessments and coordinator verification covered all 11 changed files; no local delta was included.
  • Checkstyle and Spotless passed for all 10 changed Java files. All 136 focused tests passed; verification commands exited 0. Markdown is outside the configured style scope.
  • Code correctness only; CI was not reviewed. Ledger initialization exited 1 because git merge-base exited 128 on the unavailable public-head object, preventing session validation. Temporary materials were cleaned up; repository source and Git state were unchanged.

Owner-qualified shorthand projections (x.* and PostgreSQL (x).*) that reference an enclosing alias now take the table binder contexts of the nearest scope declaring the owner, instead of the first flattened outer context, so a shadowed alias expands to the nearer table. Shorten the ScopedTableSegmentBinderContexts Javadocs to responsibility and action summaries.
@thswlsqls

Copy link
Copy Markdown
Contributor Author

@terrymanu Thanks. Both are addressed in f567f45: owner-qualified shorthand projections (x.*, and PostgreSQL (x).*) now resolve through ScopedTableSegmentBinderContexts#getNearestScopeTableBinderContexts, so your query expands x.* to the single t_user column. QuantifySubqueryShadowedOuterAliasBinderIT parses that SQL and fails on the previous head (3 columns instead of 1). The ScopedTableSegmentBinderContexts Javadocs are now one-line summaries with the required tags.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SQL binder loses outer table scope for ANY/ALL subqueries nested inside another subquery

2 participants