This is an automated email from the ASF dual-hosted git repository.

xiangfu0 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pinot.git


The following commit(s) were added to refs/heads/master by this push:
     new 36cd9143d02 Add scope-aware discovery of referenced table identifiers 
(#20305)
36cd9143d02 is described below

commit 36cd9143d0263a4991c0b69c5879b0c7c61da7c7
Author: Xiang Fu <[email protected]>
AuthorDate: Wed Nov 18 16:28:30 2026 -0800

    Add scope-aware discovery of referenced table identifiers (#20305)
---
 .../sql/parsers/parser/TableNameExtractor.java     | 106 +++++++++++++++++++++
 .../sql/parsers/parser/TableNameExtractorTest.java |  40 ++++++++
 2 files changed, 146 insertions(+)

diff --git 
a/pinot-common/src/main/java/org/apache/pinot/sql/parsers/parser/TableNameExtractor.java
 
b/pinot-common/src/main/java/org/apache/pinot/sql/parsers/parser/TableNameExtractor.java
index edce1054533..4cff1852a88 100644
--- 
a/pinot-common/src/main/java/org/apache/pinot/sql/parsers/parser/TableNameExtractor.java
+++ 
b/pinot-common/src/main/java/org/apache/pinot/sql/parsers/parser/TableNameExtractor.java
@@ -18,10 +18,14 @@
  */
 package org.apache.pinot.sql.parsers.parser;
 
+import java.util.EnumSet;
 import java.util.HashSet;
+import java.util.List;
 import java.util.Set;
+import java.util.function.Consumer;
 import javax.annotation.Nullable;
 import org.apache.calcite.sql.SqlBasicCall;
+import org.apache.calcite.sql.SqlCall;
 import org.apache.calcite.sql.SqlIdentifier;
 import org.apache.calcite.sql.SqlJoin;
 import org.apache.calcite.sql.SqlKind;
@@ -60,6 +64,13 @@ public class TableNameExtractor {
     }
   }
 
+  /// Visits referenced table identifiers in an already parsed query, 
preserving their name components and spelling.
+  /// Only referenced CTE definitions are visited, using the scope in which 
each definition was declared.
+  /// The visitor may receive the same table more than once. This syntactic 
walk does not validate or plan the query.
+  public static void visitReferencedTableIdentifiers(SqlNode query, 
Consumer<SqlIdentifier> visitor) {
+    new ReferencedTableVisitor(visitor).visit(query, null, false);
+  }
+
   /// Extracts table names from a multi-stage query using Calcite SQL AST 
traversal.
   ///
   /// @param sqlNode The root SqlNode of the parsed query
@@ -281,4 +292,99 @@ public class TableNameExtractor {
       throw new SqlCompilationException("Exception encountered while visiting 
node operands: " + node, e);
     }
   }
+
+  /// A per-query visitor that keeps table identifiers intact and expands each 
referenced CTE once.
+  private static final class ReferencedTableVisitor {
+    private static final Set<SqlKind> RELATION_WRAPPERS = 
EnumSet.of(SqlKind.AS, SqlKind.EXTEND, SqlKind.TABLE_REF,
+        SqlKind.TABLESAMPLE, SqlKind.LATERAL, SqlKind.SNAPSHOT, SqlKind.PIVOT, 
SqlKind.UNPIVOT,
+        SqlKind.MATCH_RECOGNIZE);
+
+    private final Consumer<SqlIdentifier> _visitor;
+    private final Set<CteBinding> _expanded = new HashSet<>();
+
+    ReferencedTableVisitor(Consumer<SqlIdentifier> visitor) {
+      _visitor = visitor;
+    }
+
+    void visit(@Nullable SqlNode node, @Nullable CteBinding scope, boolean 
relation) {
+      if (node instanceof SqlIdentifier) {
+        if (relation) {
+          visitRelation((SqlIdentifier) node, scope);
+        }
+      } else if (node instanceof SqlWith) {
+        SqlWith with = (SqlWith) node;
+        for (SqlNode definition : with.withList) {
+          SqlWithItem item = (SqlWithItem) definition;
+          scope = new CteBinding(item.name.getSimple(), item, scope);
+        }
+        visit(with.body, scope, false);
+      } else if (node instanceof SqlSelect) {
+        SqlSelect select = (SqlSelect) node;
+        for (SqlNode operand : select.getOperandList()) {
+          visit(operand, scope, operand == select.getFrom());
+        }
+      } else if (node instanceof SqlJoin) {
+        SqlJoin join = (SqlJoin) node;
+        visit(join.getLeft(), scope, true);
+        visit(join.getRight(), scope, true);
+        visit(join.getCondition(), scope, false);
+      } else if (node instanceof SqlCall) {
+        visitCall((SqlCall) node, scope, relation);
+      } else if (node instanceof SqlNodeList) {
+        for (SqlNode item : (SqlNodeList) node) {
+          visit(item, scope, false);
+        }
+      }
+    }
+
+    private void visitRelation(SqlIdentifier identifier, @Nullable CteBinding 
scope) {
+      CteBinding binding = scope != null && identifier.isSimple() ? 
scope.lookup(identifier.getSimple()) : null;
+      if (binding == null) {
+        _visitor.accept(identifier);
+      } else if (_expanded.add(binding)) {
+        SqlWithItem item = binding._item;
+        if (item.recursive.booleanValue() && item.query.getKind() == 
SqlKind.UNION) {
+          // Only the recursive term can see its own CTE name. The seed can 
still refer to a physical table.
+          SqlCall union = (SqlCall) item.query;
+          visit(union.operand(0), binding._parent, false);
+          visit(union.operand(1), binding, false);
+        } else {
+          visit(item.query, binding._parent, false);
+        }
+      }
+    }
+
+    private void visitCall(SqlCall call, @Nullable CteBinding scope, boolean 
relation) {
+      SqlKind kind = call.getKind();
+      boolean wrapsRelation = kind == SqlKind.EXPLICIT_TABLE || relation && 
RELATION_WRAPPERS.contains(kind);
+      List<SqlNode> operands = call.getOperandList();
+      for (int i = 0; i < operands.size(); i++) {
+        visit(operands.get(i), scope, wrapsRelation && i == 0);
+      }
+    }
+  }
+
+  /// A CTE binding shares its preceding and outer scopes.
+  private static final class CteBinding {
+    private final String _name;
+    private final SqlWithItem _item;
+    @Nullable
+    private final CteBinding _parent;
+
+    CteBinding(String name, SqlWithItem item, @Nullable CteBinding parent) {
+      _name = name;
+      _item = item;
+      _parent = parent;
+    }
+
+    @Nullable
+    CteBinding lookup(String alias) {
+      for (CteBinding scope = this; scope != null; scope = scope._parent) {
+        if (scope._name.equals(alias)) {
+          return scope;
+        }
+      }
+      return null;
+    }
+  }
 }
diff --git 
a/pinot-common/src/test/java/org/apache/pinot/sql/parsers/parser/TableNameExtractorTest.java
 
b/pinot-common/src/test/java/org/apache/pinot/sql/parsers/parser/TableNameExtractorTest.java
index 4eaa3f8ab93..0ca3933fd6a 100644
--- 
a/pinot-common/src/test/java/org/apache/pinot/sql/parsers/parser/TableNameExtractorTest.java
+++ 
b/pinot-common/src/test/java/org/apache/pinot/sql/parsers/parser/TableNameExtractorTest.java
@@ -20,7 +20,9 @@ package org.apache.pinot.sql.parsers.parser;
 
 import java.util.Arrays;
 import java.util.HashSet;
+import java.util.List;
 import java.util.Set;
+import org.apache.pinot.sql.parsers.CalciteSqlParser;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
 
@@ -33,6 +35,44 @@ import static org.testng.Assert.assertTrue;
 /// Tests for the TableNameExtractor class.
 public class TableNameExtractorTest {
 
+  @Test
+  public void testVisitReferencedTableIdentifiersPreservesNameComponents() {
+    assertEquals(referencedTableNames("SELECT * FROM \"Analytics\".events JOIN 
\"Analytics.events\" ON 1 = 1"),
+        Set.of(List.of("Analytics", "events"), List.of("Analytics.events")));
+    assertEquals(referencedTableNames("WITH events AS (SELECT * FROM unused) 
SELECT * FROM analytics.events"),
+        Set.of(List.of("analytics", "events")));
+    assertEquals(referencedTableNames("SELECT * FROM analytics.events EXTEND 
(extra BIGINT)"),
+        Set.of(List.of("analytics", "events")));
+  }
+
+  @Test
+  public void testVisitReferencedTableIdentifiersResolvesCteScopes() {
+    String sql = "WITH t AS (SELECT * FROM analytics.events), chained AS 
(SELECT * FROM t), "
+        + "unused AS (SELECT * FROM ignored) SELECT * FROM "
+        + "(WITH t AS (SELECT * FROM logs.events) SELECT * FROM t) inner_t 
JOIN chained outer_t ON 1 = 1";
+    assertEquals(referencedTableNames(sql), Set.of(List.of("analytics", 
"events"), List.of("logs", "events")));
+    assertEquals(Set.of(TableNameExtractor.resolveTableName(sql)), 
Set.of("events", "ignored"));
+
+    assertEquals(referencedTableNames("SELECT * FROM (WITH t AS (SELECT * FROM 
source) SELECT * FROM t) nested "
+        + "JOIN t outer_t ON 1 = 1"), Set.of(List.of("source"), List.of("t")));
+    assertEquals(referencedTableNames("WITH t AS (SELECT * FROM t) SELECT * 
FROM t"), Set.of(List.of("t")));
+  }
+
+  @Test
+  public void testVisitReferencedTableIdentifiersSkipsRecursiveAlias() {
+    String sql = "WITH RECURSIVE t AS (SELECT id FROM analytics.seed UNION ALL 
SELECT id FROM t) SELECT * FROM t";
+    assertEquals(referencedTableNames(sql), Set.of(List.of("analytics", 
"seed")));
+    String sameNameSeed = "WITH RECURSIVE t AS (SELECT id FROM t UNION ALL 
SELECT id FROM t) SELECT * FROM t";
+    assertEquals(referencedTableNames(sameNameSeed), Set.of(List.of("t")));
+  }
+
+  private static Set<List<String>> referencedTableNames(String sql) {
+    Set<List<String>> tableNames = new HashSet<>();
+    
TableNameExtractor.visitReferencedTableIdentifiers(CalciteSqlParser.compileToSqlNodeAndOptions(sql).getSqlNode(),
+        identifier -> tableNames.add(identifier.names));
+    return tableNames;
+  }
+
   @Test
   public void testResolveTableNameWithSingleQuery() {
     // Test that single queries work correctly


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to