github-actions[bot] commented on code in PR #62183: URL: https://github.com/apache/doris/pull/62183#discussion_r3089609073
########## fe/fe-core/src/main/java/org/apache/doris/datasource/PluginDrivenExternalCatalog.java: ########## @@ -0,0 +1,332 @@ +// 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.doris.datasource; + +import org.apache.doris.common.DdlException; +import org.apache.doris.connector.ConnectorFactory; +import org.apache.doris.connector.ConnectorSessionBuilder; +import org.apache.doris.connector.DefaultConnectorContext; +import org.apache.doris.connector.DefaultConnectorValidationContext; +import org.apache.doris.connector.api.Connector; +import org.apache.doris.connector.api.ConnectorSession; +import org.apache.doris.connector.api.ConnectorTestResult; +import org.apache.doris.datasource.property.metastore.MetastoreProperties; +import org.apache.doris.qe.ConnectContext; +import org.apache.doris.transaction.PluginDrivenTransactionManager; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +/** + * An {@link ExternalCatalog} backed by a Connector SPI plugin. + * + * <p>This adapter bridges the connector SPI ({@link Connector}) with the existing + * ExternalCatalog hierarchy. Metadata operations are delegated to the connector's + * {@link org.apache.doris.connector.api.ConnectorMetadata} implementation.</p> + * + * <p>When created via {@link CatalogFactory}, the Connector instance is provided + * directly. After GSON deserialization (FE restart), the Connector is recreated + * from catalog properties during {@link #initLocalObjectsImpl()}.</p> + */ +public class PluginDrivenExternalCatalog extends ExternalCatalog { + + private static final Logger LOG = LogManager.getLogger(PluginDrivenExternalCatalog.class); + + // Volatile for cross-thread visibility; all mutations also happen under synchronized(this). + private transient volatile Connector connector; + + // When true, onClose() skips closing the connector because notifyPropertiesUpdated() + // manages the connector lifecycle (create-before-swap pattern). + private transient volatile boolean connectorSwapInProgress = false; + + /** No-arg constructor for GSON deserialization. */ + public PluginDrivenExternalCatalog() { + } + + /** + * Creates a plugin-driven catalog with an already-created Connector. + * + * @param catalogId unique catalog id + * @param name catalog name + * @param resource optional resource name + * @param props catalog properties + * @param comment catalog comment + * @param connector the SPI connector instance + */ + public PluginDrivenExternalCatalog(long catalogId, String name, String resource, + Map<String, String> props, String comment, Connector connector) { + super(catalogId, name, InitCatalogLog.Type.PLUGIN, comment); + this.catalogProperty = new CatalogProperty(resource, props); + this.connector = connector; + } + + @Override + protected void initLocalObjectsImpl() { + // Always (re-)create the connector so it gets the proper engine context, + // including the catalog's execution authenticator for Kerberos/secured HMS. + // The connector created by CatalogFactory used a lightweight context + // without auth (the catalog didn't exist yet); we replace it now. + Connector newConnector = createConnectorFromProperties(); + if (newConnector != null) { + connector = newConnector; + } + if (connector == null) { + String catalogType = catalogProperty.getOrDefault(CatalogMgr.CATALOG_TYPE_PROP, ""); + throw new RuntimeException("No ConnectorProvider found for plugin-driven catalog: " + + name + ", type: " + catalogType + + ". Ensure the connector plugin is installed."); + } + transactionManager = new PluginDrivenTransactionManager(); + initPreExecutionAuthenticator(); + } + + @Override + protected synchronized void initPreExecutionAuthenticator() { + if (executionAuthenticator != null) { + return; + } + try { + MetastoreProperties msp = catalogProperty.getMetastoreProperties(); + if (msp != null) { + executionAuthenticator = msp.getExecutionAuthenticator(); + return; + } + } catch (Exception ignored) { + // Not all catalog types have metastore properties (e.g., JDBC, ES) + } + super.initPreExecutionAuthenticator(); + } + + /** + * Creates a new Connector from catalog properties. Extracted as a protected method + * so tests can override without depending on the static ConnectorFactory registry. + */ + protected Connector createConnectorFromProperties() { + String catalogType = catalogProperty.getOrDefault(CatalogMgr.CATALOG_TYPE_PROP, ""); + return ConnectorFactory.createConnector(catalogType, + catalogProperty.getProperties(), + new DefaultConnectorContext(name, id, this::getExecutionAuthenticator)); + } + + @Override + public void checkProperties() throws DdlException { + super.checkProperties(); + String catalogType = catalogProperty.getOrDefault(CatalogMgr.CATALOG_TYPE_PROP, ""); + try { + ConnectorFactory.validateProperties(catalogType, catalogProperty.getProperties()); + } catch (IllegalArgumentException e) { + throw new DdlException(e.getMessage()); + } + // Validate function_rules JSON if present (shared across all connector types). + String functionRules = catalogProperty.getOrDefault("function_rules", null); + ExternalFunctionRules.check(functionRules); + } + + @Override + public void checkWhenCreating() throws DdlException { + // Let the connector perform its type-specific pre-creation validation + // (e.g., JDBC driver security, checksum computation). + DefaultConnectorValidationContext validationCtx = + new DefaultConnectorValidationContext(getId(), catalogProperty); + try { + connector.preCreateValidation(validationCtx); + } catch (DdlException e) { + throw e; + } catch (Exception e) { + throw new DdlException(e.getMessage(), e); + } + + boolean testConnection = Boolean.parseBoolean( + catalogProperty.getOrDefault(ExternalCatalog.TEST_CONNECTION, + String.valueOf(ExternalCatalog.DEFAULT_TEST_CONNECTION))); + if (!testConnection) { + return; + } + // Delegate FE→external connectivity testing to the connector SPI. + ConnectorSession session = buildConnectorSession(); + ConnectorTestResult result = connector.testConnection(session); + if (!result.isSuccess()) { + throw new DdlException("Connectivity test failed for catalog '" + + name + "': " + result.getMessage()); + } + LOG.info("Connectivity test passed for plugin-driven catalog '{}': {}", name, result); + + // Execute any BE→external connectivity test the connector registered. + validationCtx.executePendingBeTests(); + } + + /** + * Handles catalog property updates with a create-before-swap pattern to avoid + * race conditions between ALTER CATALOG and concurrent queries. + * + * <p>The old implementation had a TOCTOU race: {@code super.notifyPropertiesUpdated()} + * called {@code resetToUninitialized()} which closed the connector via {@code onClose()}, + * leaving a window where concurrent queries could trigger {@code initLocalObjectsImpl()} + * and create an orphaned connector that was immediately overwritten.</p> + * + * <p>New approach: + * <ol> + * <li>Create the replacement connector <b>first</b> (outside lock — may involve I/O).</li> + * <li>Atomically swap the connector and set {@code connectorSwapInProgress} to suppress + * {@code onClose()} from closing the new connector during reset.</li> + * <li>Let the parent reset catalog state (caches, objectCreated, etc.).</li> + * <li>Close the old connector <b>after</b> the swap, outside any lock.</li> + * </ol></p> + */ + @Override + public void notifyPropertiesUpdated(Map<String, String> updatedProps) { + // 1. Create replacement connector FIRST (may involve I/O — outside any lock). + Connector newConnector = createConnectorFromProperties(); + if (newConnector == null) { + LOG.warn("Failed to create replacement connector for catalog '{}', " + + "falling back to full reset", name); + super.notifyPropertiesUpdated(updatedProps); + return; + } + + // 2. Atomically swap connector and suppress onClose() from closing it during reset. + Connector oldConnector; + synchronized (this) { + oldConnector = connector; + connector = newConnector; + connectorSwapInProgress = true; + } + try { + // 3. Let parent reset catalog state (caches, objectCreated, etc.). + // resetToUninitialized() → onClose() sees connectorSwapInProgress and skips close. + // After reset, concurrent makeSureInitialized() will find connector != null + // and reuse the new connector without creating an orphan. + super.notifyPropertiesUpdated(updatedProps); Review Comment: This still races with concurrent `makeSureInitialized()`. `super.notifyPropertiesUpdated()` calls `resetToUninitialized()`, which flips `objectCreated=false` but leaves the swapped connector alive because `onClose()` is suppressed. The next query then enters the production `initLocalObjectsImpl()`, which unconditionally calls `createConnectorFromProperties()` again and overwrites `connector`, leaking the connector that was just swapped in. Can we either reuse the already-swapped connector in `initLocalObjectsImpl()` or keep `objectCreated` true across this reset path? ########## fe/fe-connector/fe-connector-jdbc/src/main/java/org/apache/doris/connector/jdbc/JdbcQueryBuilder.java: ########## @@ -0,0 +1,633 @@ +// 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.doris.connector.jdbc; + +import org.apache.doris.connector.api.ConnectorType; +import org.apache.doris.connector.api.handle.ConnectorColumnHandle; +import org.apache.doris.connector.api.pushdown.ConnectorAnd; +import org.apache.doris.connector.api.pushdown.ConnectorBetween; +import org.apache.doris.connector.api.pushdown.ConnectorColumnRef; +import org.apache.doris.connector.api.pushdown.ConnectorComparison; +import org.apache.doris.connector.api.pushdown.ConnectorExpression; +import org.apache.doris.connector.api.pushdown.ConnectorFunctionCall; +import org.apache.doris.connector.api.pushdown.ConnectorIn; +import org.apache.doris.connector.api.pushdown.ConnectorIsNull; +import org.apache.doris.connector.api.pushdown.ConnectorLike; +import org.apache.doris.connector.api.pushdown.ConnectorLiteral; +import org.apache.doris.connector.api.pushdown.ConnectorNot; +import org.apache.doris.connector.api.pushdown.ConnectorOr; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.StringJoiner; + +/** + * Converts {@link ConnectorExpression} trees into SQL WHERE clauses + * with database-specific formatting. + * + * <p>Handles column quoting, date literal formatting, LIMIT syntax + * differences, function pushdown validation, function name rewriting, + * and time arithmetic conversion across supported JDBC database types.</p> + */ +public final class JdbcQueryBuilder { + + private static final Logger LOG = LogManager.getLogger(JdbcQueryBuilder.class); + + private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + private static final DateTimeFormatter DATETIME_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + private final JdbcDbType dbType; + private final JdbcFunctionPushdownConfig functionConfig; + private final boolean clickhouseQueryFinal; + private final boolean oracleNullPredicatePushDown; + + public JdbcQueryBuilder(JdbcDbType dbType) { + this(dbType, null, Collections.emptyMap()); + } + + /** + * Creates a query builder with full pushdown configuration. + * + * @param dbType the JDBC database type + * @param functionConfig function pushdown rules (null disables function pushdown) + * @param sessionProperties session variables map for query modifiers + */ + public JdbcQueryBuilder(JdbcDbType dbType, + JdbcFunctionPushdownConfig functionConfig, + Map<String, String> sessionProperties) { + this.dbType = dbType; + this.functionConfig = functionConfig; + this.clickhouseQueryFinal = Boolean.parseBoolean( + sessionProperties.getOrDefault("jdbc_clickhouse_query_final", "false")); + this.oracleNullPredicatePushDown = Boolean.parseBoolean( + sessionProperties.getOrDefault("enable_jdbc_oracle_null_predicate_push_down", "false")); + } + + /** + * Builds a complete SELECT query from table coordinates, columns, filter, and limit. + * + * @param remoteDbName the remote database name + * @param remoteTableName the remote table name + * @param columns the columns to select (empty = SELECT *) + * @param filter the optional filter expression + * @param limit the row limit, or -1 for no limit + * @return the complete SQL query string + */ + public String buildQuery(String remoteDbName, String remoteTableName, + List<ConnectorColumnHandle> columns, + Optional<ConnectorExpression> filter, long limit) { + // Build local→remote column name mapping from column handles + Map<String, String> colMapping = new HashMap<>(); + for (ConnectorColumnHandle col : columns) { + if (col instanceof JdbcColumnHandle) { + JdbcColumnHandle jch = (JdbcColumnHandle) col; + colMapping.put(jch.getLocalName(), jch.getRemoteName()); + } + } + + List<String> filterClauses = new ArrayList<>(); + boolean allFiltersCollected = true; + if (filter.isPresent()) { + allFiltersCollected = collectFilters(filter.get(), filterClauses, colMapping); + } + + StringBuilder sql = new StringBuilder("SELECT "); + + // Oracle uses ROWNUM in WHERE clause for TOP-N + if (shouldPushDownLimit(limit, allFiltersCollected, filter) + && (dbType == JdbcDbType.ORACLE || dbType == JdbcDbType.OCEANBASE_ORACLE)) { + filterClauses.add("ROWNUM <= " + limit); + } + + // SQL Server uses SELECT TOP N + if (shouldPushDownLimit(limit, allFiltersCollected, filter) && dbType == JdbcDbType.SQLSERVER) { + sql.append("TOP ").append(limit).append(" "); + } + + // Column list + if (columns.isEmpty()) { + sql.append("*"); + } else { + StringJoiner colJoiner = new StringJoiner(", "); + for (ConnectorColumnHandle col : columns) { + if (col instanceof JdbcColumnHandle) { + colJoiner.add(JdbcIdentifierQuoter.quoteRemoteIdentifier( + dbType, ((JdbcColumnHandle) col).getRemoteName())); + } + } + String colStr = colJoiner.toString(); + sql.append(colStr.isEmpty() ? "*" : colStr); + } + + // FROM clause + sql.append(" FROM "); + sql.append(JdbcIdentifierQuoter.quoteFullTableName(dbType, remoteDbName, remoteTableName)); + + // WHERE clause + if (!filterClauses.isEmpty()) { + sql.append(" WHERE ("); + sql.append(String.join(") AND (", filterClauses)); + sql.append(")"); + } + + // LIMIT clause (MySQL, PostgreSQL, ClickHouse, etc.) + if (shouldPushDownLimit(limit, allFiltersCollected, filter) && supportsLimitClause()) { + sql.append(" LIMIT ").append(limit); + } + + // ClickHouse FINAL: ensures reads from ReplacingMergeTree see deduplicated rows + if (clickhouseQueryFinal && dbType == JdbcDbType.CLICKHOUSE) { + sql.append(" SETTINGS final = 1"); + } + + return sql.toString(); + } + + private boolean shouldPushDownLimit(long limit, boolean allFiltersCollected, + Optional<ConnectorExpression> filter) { + if (limit <= 0) { + return false; + } + // Only push down limit when all filters were successfully converted. + // If any filter was dropped (evaluated locally), pushing LIMIT to remote + // would cause remote to truncate rows before local filtering, producing + // fewer results than expected. + if (!filter.isPresent()) { + return true; + } + return allFiltersCollected; + } + + private boolean supportsLimitClause() { + switch (dbType) { + case MYSQL: + case POSTGRESQL: + case CLICKHOUSE: + case SAP_HANA: + case TRINO: + case PRESTO: + case OCEANBASE: + case GBASE: + return true; + default: + return false; + } + } + + /** + * Recursively collects individual filter clauses from a ConnectorExpression. + * Top-level AND nodes are flattened into separate clauses. + * Applies conjunct-level guards (e.g. Oracle NULL literal exclusion). + * + * @return true if all expressions were successfully converted to SQL, + * false if any sub-expression was dropped (not pushed down) + */ + private boolean collectFilters(ConnectorExpression expr, List<String> clauses, + Map<String, String> colMapping) { + if (expr instanceof ConnectorAnd) { + ConnectorAnd and = (ConnectorAnd) expr; + boolean allCollected = true; + for (ConnectorExpression child : and.getChildren()) { + if (!collectFilters(child, clauses, colMapping)) { + allCollected = false; + } + } + return allCollected; + } else { + if (!shouldPushDownExpression(expr)) { + return false; + } + String sql = expressionToSql(expr, colMapping); + if (sql != null && !sql.isEmpty()) { + clauses.add(sql); + return true; + } + return false; + } + } + + /** + * Determines whether a single conjunct should be pushed down. + * Mirrors the old JdbcScanNode.shouldPushDownConjunct() guards. + */ + private boolean shouldPushDownExpression(ConnectorExpression expr) { + // Guard: Oracle NULL literal exclusion + if (!oracleNullPredicatePushDown + && (dbType == JdbcDbType.ORACLE || dbType == JdbcDbType.OCEANBASE_ORACLE) + && containsNullLiteral(expr)) { + return false; + } + + // Guard: function-containing expressions need DB-type support + if (containsFunctionCall(expr)) { + if (functionConfig == null) { + return false; + } + // Only MySQL, ClickHouse, Oracle have function pushdown support + switch (dbType) { + case MYSQL: + case CLICKHOUSE: + case ORACLE: + case OCEANBASE_ORACLE: + return functionConfig != null; + default: + return false; + } + } + + return true; + } + + private static boolean containsNullLiteral(ConnectorExpression expr) { + if (expr instanceof ConnectorLiteral && ((ConnectorLiteral) expr).isNull()) { + return true; + } + for (ConnectorExpression child : expr.getChildren()) { + if (containsNullLiteral(child)) { + return true; + } + } + return false; + } + + private static boolean containsFunctionCall(ConnectorExpression expr) { + if (expr instanceof ConnectorFunctionCall) { + return true; + } + for (ConnectorExpression child : expr.getChildren()) { + if (containsFunctionCall(child)) { + return true; + } + } + return false; + } + + /** + * Converts a single ConnectorExpression into a SQL string. + * Returns null if the expression cannot be converted. + */ + private String expressionToSql(ConnectorExpression expr, Map<String, String> colMapping) { + if (expr instanceof ConnectorComparison) { + return comparisonToSql((ConnectorComparison) expr, colMapping); + } else if (expr instanceof ConnectorAnd) { + return andToSql((ConnectorAnd) expr, colMapping); + } else if (expr instanceof ConnectorOr) { + return orToSql((ConnectorOr) expr, colMapping); + } else if (expr instanceof ConnectorNot) { + return notToSql((ConnectorNot) expr, colMapping); + } else if (expr instanceof ConnectorIn) { + return inToSql((ConnectorIn) expr, colMapping); + } else if (expr instanceof ConnectorIsNull) { + return isNullToSql((ConnectorIsNull) expr, colMapping); + } else if (expr instanceof ConnectorLike) { + return likeToSql((ConnectorLike) expr, colMapping); + } else if (expr instanceof ConnectorBetween) { + return betweenToSql((ConnectorBetween) expr, colMapping); + } else if (expr instanceof ConnectorFunctionCall) { + return functionCallToSql((ConnectorFunctionCall) expr, colMapping); + } else if (expr instanceof ConnectorColumnRef) { + return columnToSql((ConnectorColumnRef) expr, colMapping); + } else if (expr instanceof ConnectorLiteral) { + return literalToSql((ConnectorLiteral) expr); + } + return null; + } + + private String comparisonToSql(ConnectorComparison comp, Map<String, String> colMapping) { + String left = expressionToSql(comp.getLeft(), colMapping); + String right = expressionToSql(comp.getRight(), colMapping); + if (left == null || right == null) { + return null; + } + + // Handle date literal formatting for the right side + if (comp.getRight() instanceof ConnectorLiteral) { + ConnectorLiteral lit = (ConnectorLiteral) comp.getRight(); + String dateSql = formatDateLiteral(lit); + if (dateSql != null) { + right = dateSql; + } + } + + return left + " " + comp.getOperator().getSymbol() + " " + right; + } + + private String andToSql(ConnectorAnd and, Map<String, String> colMapping) { + List<String> parts = new ArrayList<>(); + for (ConnectorExpression child : and.getChildren()) { + String childSql = expressionToSql(child, colMapping); + if (childSql == null) { + return null; + } + parts.add("(" + childSql + ")"); + } + return String.join(" AND ", parts); + } + + private String orToSql(ConnectorOr or, Map<String, String> colMapping) { + List<String> parts = new ArrayList<>(); + for (ConnectorExpression child : or.getChildren()) { + String childSql = expressionToSql(child, colMapping); + if (childSql == null) { + return null; + } + parts.add("(" + childSql + ")"); + } + return String.join(" OR ", parts); + } + + private String notToSql(ConnectorNot not, Map<String, String> colMapping) { + String childSql = expressionToSql(not.getOperand(), colMapping); + if (childSql == null) { + return null; + } + return "NOT (" + childSql + ")"; + } + + private String inToSql(ConnectorIn in, Map<String, String> colMapping) { + String valueSql = expressionToSql(in.getValue(), colMapping); + if (valueSql == null) { + return null; + } + StringJoiner joiner = new StringJoiner(", "); + for (ConnectorExpression item : in.getInList()) { + String itemSql; + if (item instanceof ConnectorLiteral) { + String dateSql = formatDateLiteral((ConnectorLiteral) item); + itemSql = dateSql != null ? dateSql : expressionToSql(item, colMapping); + } else { + itemSql = expressionToSql(item, colMapping); + } + if (itemSql == null) { + return null; + } + joiner.add(itemSql); + } + return valueSql + (in.isNegated() ? " NOT IN (" : " IN (") + joiner + ")"; + } + + private String isNullToSql(ConnectorIsNull isNull, Map<String, String> colMapping) { + String operandSql = expressionToSql(isNull.getOperand(), colMapping); + if (operandSql == null) { + return null; + } + return operandSql + (isNull.isNegated() ? " IS NOT NULL" : " IS NULL"); + } + + private String likeToSql(ConnectorLike like, Map<String, String> colMapping) { + String valueSql = expressionToSql(like.getValue(), colMapping); + String patternSql = expressionToSql(like.getPattern(), colMapping); + if (valueSql == null || patternSql == null) { + return null; + } + String keyword = like.getOperator() == ConnectorLike.Operator.REGEXP ? "REGEXP" : "LIKE"; + return valueSql + " " + keyword + " " + patternSql; + } + + private String betweenToSql(ConnectorBetween between, Map<String, String> colMapping) { + String valueSql = expressionToSql(between.getValue(), colMapping); + String lowerSql = expressionToSql(between.getLower(), colMapping); + String upperSql = expressionToSql(between.getUpper(), colMapping); + if (valueSql == null || lowerSql == null || upperSql == null) { + return null; + } + // Apply date formatting for lower/upper if they are date literals + if (between.getLower() instanceof ConnectorLiteral) { + String dateSql = formatDateLiteral((ConnectorLiteral) between.getLower()); + if (dateSql != null) { + lowerSql = dateSql; + } + } + if (between.getUpper() instanceof ConnectorLiteral) { + String dateSql = formatDateLiteral((ConnectorLiteral) between.getUpper()); + if (dateSql != null) { + upperSql = dateSql; + } + } + return valueSql + " BETWEEN " + lowerSql + " AND " + upperSql; + } + + /** + * Converts a function call expression to SQL. + * + * <p>Handles three categories:</p> + * <ol> + * <li>Time arithmetic functions (years_add, months_sub, etc.) + * → DATE_ADD/DATE_SUB with INTERVAL syntax</li> + * <li>Regular functions with name rewriting and pushdown validation</li> + * <li>Unsupported functions → returns null (filter evaluated locally)</li> + * </ol> + */ + private static final Set<String> ARITHMETIC_OPERATORS = new HashSet<>( + Arrays.asList("+", "-", "*", "/", "%", "DIV", "&", "|", "^")); + private static final Set<String> UNARY_OPERATORS = Collections.singleton("~"); + + private String functionCallToSql(ConnectorFunctionCall func, Map<String, String> colMapping) { + String funcName = func.getFunctionName(); + + // 0. Handle arithmetic operators rendered as infix: (arg1 + arg2) + if (ARITHMETIC_OPERATORS.contains(funcName) && func.getArguments().size() == 2) { + String left = expressionToSql(func.getArguments().get(0), colMapping); + String right = expressionToSql(func.getArguments().get(1), colMapping); + if (left == null || right == null) { + return null; + } + return "(" + left + " " + funcName + " " + right + ")"; + } + if (UNARY_OPERATORS.contains(funcName) && func.getArguments().size() == 1) { + String operand = expressionToSql(func.getArguments().get(0), colMapping); + if (operand == null) { + return null; + } + return "(" + funcName + operand + ")"; + } + + // 0b. Fallback expressions with no arguments are pre-rendered SQL fragments + if (func.getArguments().isEmpty() && !funcName.matches("^[a-zA-Z_][a-zA-Z0-9_]*$")) { + // The function name is actually a SQL snippet from Expr.toSql() fallback + return funcName; + } + + // 1. Check for time arithmetic patterns (years_add → DATE_ADD) + JdbcFunctionPushdownConfig.TimeArithmeticInfo timeInfo = + JdbcFunctionPushdownConfig.parseTimeArithmetic(funcName); + if (timeInfo != null && func.getArguments().size() == 2) { + String arg1 = expressionToSql(func.getArguments().get(0), colMapping); + String arg2 = expressionToSql(func.getArguments().get(1), colMapping); + if (arg1 == null || arg2 == null) { + return null; + } + return timeInfo.getBaseFunction() + "(" + arg1 + + ", INTERVAL " + arg2 + " " + timeInfo.getTimeUnit() + ")"; + } + + // 2. Check pushdown rules + if (functionConfig == null || !functionConfig.canPushDown(funcName)) { + if (LOG.isDebugEnabled()) { + LOG.debug("Function '{}' cannot be pushed down for DB type {}", funcName, dbType); + } + return null; + } + + // 3. Apply name rewriting + String rewrittenName = functionConfig.rewriteFunctionName(funcName); + + // 4. Render function call SQL + StringJoiner argJoiner = new StringJoiner(", "); + for (ConnectorExpression arg : func.getArguments()) { + String argSql = expressionToSql(arg, colMapping); + if (argSql == null) { + return null; + } + argJoiner.add(argSql); + } + return rewrittenName + "(" + argJoiner + ")"; + } + + private String columnToSql(ConnectorColumnRef col, Map<String, String> colMapping) { + String remoteName = colMapping.getOrDefault( + col.getColumnName(), col.getColumnName()); + return JdbcIdentifierQuoter.quoteRemoteIdentifier(dbType, remoteName); + } + + private String literalToSql(ConnectorLiteral lit) { + if (lit.isNull()) { + return "NULL"; + } + Object val = lit.getValue(); + if (val instanceof String) { + return "'" + escapeSql((String) val) + "'"; + } else if (val instanceof Boolean) { + return ((Boolean) val) ? "1" : "0"; + } else if (val instanceof Double) { + double d = (Double) val; + if (d == Math.floor(d) && !Double.isInfinite(d)) { + return Long.toString((long) d); + } + return val.toString(); + } else if (val instanceof BigDecimal || val instanceof Integer + || val instanceof Long) { + return val.toString(); + } else if (val instanceof LocalDate || val instanceof LocalDateTime) { + // Date/datetime formatting is handled by formatDateLiteral when in comparison context + return formatDateLiteralDirect(lit); + } + return val.toString(); + } + + /** + * Formats a date/datetime literal with database-specific syntax. + * Returns null if the literal is not a date/datetime type. + */ + private String formatDateLiteral(ConnectorLiteral lit) { + if (lit.isNull() || lit.getValue() == null) { + return null; + } + ConnectorType type = lit.getType(); + String typeName = type.getTypeName().toUpperCase(); + if (!typeName.contains("DATE") && !typeName.contains("TIME")) { + return null; + } + return formatDateLiteralDirect(lit); + } + + private String formatDateLiteralDirect(ConnectorLiteral lit) { + Object val = lit.getValue(); + ConnectorType type = lit.getType(); + String typeName = type.getTypeName().toUpperCase(); + boolean isDatetime = typeName.contains("TIME") || val instanceof LocalDateTime; + + switch (dbType) { + case ORACLE: + case OCEANBASE_ORACLE: + return formatOracleDate(val, isDatetime); + case TRINO: + case PRESTO: + return formatTrinoDate(val, isDatetime); + case SQLSERVER: + return formatSqlServerDate(val, isDatetime); + default: + return formatGenericDate(val, isDatetime); + } + } + + private String formatOracleDate(Object val, boolean isDatetime) { + if (isDatetime && val instanceof LocalDateTime) { + String dateStr = ((LocalDateTime) val).format(DATETIME_FMT); + int nanos = ((LocalDateTime) val).getNano(); + if (nanos > 0) { + String fracStr = String.valueOf(nanos / 1000); Review Comment: `LocalDateTime.getNano()` preserves leading-zero microseconds, but `String.valueOf(nanos / 1000)` drops them. For example, `00:00:00.000001` becomes `.1`, so Oracle/OceanBase will parse a completely different timestamp with `FF6`. Predicate pushdown on sub-second values will return wrong results unless this is left-padded to 6 digits. ########## fe/fe-connector/fe-connector-es/src/main/java/org/apache/doris/connector/es/EsScanPlanProvider.java: ########## @@ -0,0 +1,378 @@ +// 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.doris.connector.es; + +import org.apache.doris.connector.api.ConnectorSession; +import org.apache.doris.connector.api.handle.ConnectorColumnHandle; +import org.apache.doris.connector.api.handle.ConnectorTableHandle; +import org.apache.doris.connector.api.handle.NamedColumnHandle; +import org.apache.doris.connector.api.pushdown.ConnectorExpression; +import org.apache.doris.connector.api.scan.ConnectorScanPlanProvider; +import org.apache.doris.connector.api.scan.ConnectorScanRange; +import org.apache.doris.connector.api.scan.ConnectorScanRangeType; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * ES scan plan provider — generates shard-level scan ranges and node-level properties. + * + * <p>This replaces the scan planning logic from fe-core's {@code EsScanNode}. + * It fetches shard routing from the ES cluster and builds query DSL from + * the connector expression filter.</p> + * + * <p>The provider produces:</p> + * <ul> + * <li><b>Per-range:</b> one {@link EsScanRange} per shard with host routing</li> + * <li><b>Per-node properties:</b> query DSL, auth info, doc_values_mode, + * docvalue_context and fields_context (JSON-serialized)</li> + * </ul> + */ +public class EsScanPlanProvider implements ConnectorScanPlanProvider { + + private static final Logger LOG = LogManager.getLogger(EsScanPlanProvider.class); + + // Cache TTL: metadata is shared within a single query planning cycle + // (planScan and getScanNodeProperties are called in rapid succession). + // 10 seconds avoids redundant REST calls without serving stale data + // across different queries. + static final long METADATA_CACHE_TTL_MS = 10_000; + + private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); + + public static final String PROP_QUERY_DSL = "query_dsl"; + public static final String PROP_USER = "user"; + public static final String PROP_PASSWORD = "password"; + public static final String PROP_HTTP_SSL_ENABLED = "http_ssl_enabled"; + public static final String PROP_DOC_VALUES_MODE = "doc_values_mode"; + public static final String PROP_NOT_PUSHED_INDICES = "_not_pushed_conjunct_indices"; + + public static final String PROP_DOCVALUE_CONTEXT_JSON = "docvalue_context_json"; + public static final String PROP_FIELDS_CONTEXT_JSON = "fields_context_json"; + + private final EsConnectorRestClient restClient; + private final Map<String, String> properties; + private final ConcurrentHashMap<String, CachedMetadata> metadataCache = new ConcurrentHashMap<>(); + + /** Timestamped wrapper for cached metadata state. */ + private static final class CachedMetadata { + final EsMetadataState state; + final long timestampMs; + + CachedMetadata(EsMetadataState state) { + this.state = state; + this.timestampMs = System.currentTimeMillis(); + } + + boolean isExpired() { + return System.currentTimeMillis() - timestampMs > METADATA_CACHE_TTL_MS; + } + } + + public EsScanPlanProvider(EsConnectorRestClient restClient, + Map<String, String> properties) { + this.restClient = restClient; + this.properties = properties; + } + + @Override + public ConnectorScanRangeType getScanRangeType() { + return ConnectorScanRangeType.ES_SCAN; + } + + @Override + public List<ConnectorScanRange> planScan( + ConnectorSession session, + ConnectorTableHandle handle, + List<ConnectorColumnHandle> columns, + Optional<ConnectorExpression> filter) { + EsTableHandle esHandle = (EsTableHandle) handle; + String indexName = esHandle.getIndexName(); + + EsMetadataState state = fetchMetadataState(esHandle, columns); + EsShardPartitions shardPartitions = state.getShardPartitions(); + if (shardPartitions == null) { + LOG.warn("No shard partitions found for index {}", indexName); + return Collections.emptyList(); + } + + String mappingType = properties.getOrDefault( + EsConnectorProperties.MAPPING_TYPE, null); + + boolean enableParallelScroll = Boolean.parseBoolean( + session.getSessionProperties() + .getOrDefault("enable_es_parallel_scroll", "true")); + + List<ConnectorScanRange> ranges = new ArrayList<>(); + Map<Integer, List<EsShardRouting>> routingsMap = shardPartitions.getShardRoutings(); + + if (!enableParallelScroll) { + // Single query mode: one scan range for the whole index + List<String> hosts = collectAllHosts(routingsMap); + ranges.add(new EsScanRange( + shardPartitions.getIndexName(), mappingType, -1, hosts)); + } else { + // Parallel scroll mode: one scan range per shard + for (Map.Entry<Integer, List<EsShardRouting>> entry : routingsMap.entrySet()) { + List<EsShardRouting> shardRouting = entry.getValue(); + if (shardRouting.isEmpty()) { + continue; + } + List<String> hosts = new ArrayList<>(); + for (EsShardRouting routing : shardRouting) { + hosts.add(routing.getHttpHost() + ":" + routing.getHttpPort()); Review Comment: `FederationBackendPolicy` matches preferred locations against `Backend.getHost()` only. Here the preferred host strings are `host:port` and, when SSL is enabled, sometimes `https://host:port`, so they never match any backend hostname. That means the new ES path silently loses the old colocated-backend scheduling behavior from `EsScanNode` and falls back to random remote selection. Please pass plain hostnames via `getHosts()` and keep the full `host:port` list only in `es.hosts`. ########## fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/PluginDrivenInsertExecutor.java: ########## @@ -0,0 +1,147 @@ +// 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.doris.nereids.trees.plans.commands.insert; + +import org.apache.doris.catalog.Column; +import org.apache.doris.common.UserException; +import org.apache.doris.connector.api.Connector; +import org.apache.doris.connector.api.ConnectorColumn; +import org.apache.doris.connector.api.ConnectorMetadata; +import org.apache.doris.connector.api.ConnectorSession; +import org.apache.doris.connector.api.ConnectorWriteOps; +import org.apache.doris.connector.api.handle.ConnectorInsertHandle; +import org.apache.doris.connector.api.handle.ConnectorTableHandle; +import org.apache.doris.connector.api.write.ConnectorWriteType; +import org.apache.doris.datasource.ConnectorColumnConverter; +import org.apache.doris.datasource.ExternalTable; +import org.apache.doris.datasource.PluginDrivenExternalCatalog; +import org.apache.doris.nereids.NereidsPlanner; +import org.apache.doris.qe.ConnectContext; +import org.apache.doris.transaction.TransactionType; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +/** + * Insert executor for plugin-driven connector catalogs. + * Delegates the write lifecycle to the connector's ConnectorWriteOps SPI. + */ +public class PluginDrivenInsertExecutor extends BaseExternalTableInsertExecutor { Review Comment: For JDBC this inheritance changes the old success semantics in a dangerous way. `BaseExternalTableInsertExecutor.onComplete()` calls `doAfterCommit()` after the remote write has already succeeded and treats any later refresh/auth error as a statement failure, but the rollback path here plus `PluginDrivenTransactionManager` cannot undo a committed JDBC write. That means a transient `handleRefreshTable()` failure can now surface as a failed `INSERT` even though rows are already committed remotely, and retrying can duplicate data. We need to preserve the old JDBC behavior or make post-commit refresh best-effort for `JDBC_WRITE`. -- 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]
