xiangfu0 commented on code in PR #16480: URL: https://github.com/apache/pinot/pull/16480#discussion_r2249114124
########## pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/TableNameExtractor.java: ########## @@ -0,0 +1,386 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.client; + +import java.lang.reflect.Field; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import javax.annotation.Nullable; +import org.apache.calcite.sql.SqlBasicCall; +import org.apache.calcite.sql.SqlIdentifier; +import org.apache.calcite.sql.SqlJoin; +import org.apache.calcite.sql.SqlNode; +import org.apache.calcite.sql.SqlNodeList; +import org.apache.calcite.sql.SqlOrderBy; +import org.apache.calcite.sql.SqlSelect; +import org.apache.calcite.sql.SqlWith; +import org.apache.calcite.sql.SqlWithItem; +import org.apache.pinot.sql.parsers.CalciteSqlParser; +import org.apache.pinot.sql.parsers.SqlNodeAndOptions; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * Helper class to extract table names from Calcite SqlNode tree. + */ +public class TableNameExtractor { + private static final Logger LOGGER = LoggerFactory.getLogger(TableNameExtractor.class); + // Constant for the SQL parser constants class name + private static final String SQL_PARSER_IMPL_CONSTANTS_CLASS = + "org.apache.pinot.sql.parsers.parser.SqlParserImplConstants"; + + // Static set of SQL operators for efficient lookup + private static final Set<String> OPERATORS = Set.of( + "=", ">", "<", ">=", "<=", "<>", "!=", "+", "-", "*", "/", "%", "||", "->", "..", "(", ")", + "{", "}", "[", "]", ";", ".", ",", "?", ":", "|", "^", "$", "/*", "*/", "/*+" + ); + + // Static map of reserved SQL keywords loaded from config file + private static final Map<String, Boolean> RESERVED_KEYWORDS = loadReservedKeywords(); + + /** + * Returns the name of all the tables used in a sql query. + * + * @param query The SQL query string to analyze + * @return name of all the tables used in a sql query, or null if parsing fails + */ + @Nullable + public static String[] resolveTableName(String query) { + SqlNodeAndOptions sqlNodeAndOptions; + try { + sqlNodeAndOptions = CalciteSqlParser.compileToSqlNodeAndOptions(query); + } catch (Exception e) { + LOGGER.error("Cannot parse table name from query: {}. Fallback to broker selector default.", query, e); + return null; + } + try { + Set<String> tableNames = extractTableNamesFromMultiStageQuery(sqlNodeAndOptions.getSqlNode()); + if (tableNames != null) { + return tableNames.toArray(new String[0]); + } + } catch (Exception e) { + LOGGER.error("Cannot extract table name from query: {}. Fallback to broker selector default.", query, e); + } + return null; + } + + /** + * Extracts table names from a multi-stage query using Calcite SQL AST traversal. + * + * @param sqlNode The root SqlNode of the parsed query + * @return Set of table names found in the query + */ + private static Set<String> extractTableNamesFromMultiStageQuery(SqlNode sqlNode) { + TableNameExtractor extractor = new TableNameExtractor(); + try { + extractor.extractTableNames(sqlNode); + return extractor.getTableNames(); + } catch (Exception e) { + LOGGER.debug("Failed to extract table names from multi-stage query", e); + return Collections.emptySet(); + } + } + + private final Set<String> _tableNames = new HashSet<>(); + private final Set<String> _cteNames = new HashSet<>(); + private boolean _inFromClause = false; + + public Set<String> getTableNames() { + return _tableNames; + } + + public void extractTableNames(SqlNode node) { Review Comment: While I initially attempted to implement the SqlVisitor pattern, there were compatibility issues with the Calcite version used. The current implementation uses manual AST traversal which is more reliable and maintainable for this specific use case, just extracting table name. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
