github-actions[bot] commented on code in PR #62183: URL: https://github.com/apache/doris/pull/62183#discussion_r3098867250
########## fe/fe-core/src/main/java/org/apache/doris/datasource/PluginDrivenExternalTable.java: ########## @@ -0,0 +1,248 @@ +// 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.catalog.Column; +import org.apache.doris.catalog.Env; +import org.apache.doris.catalog.TableIf.TableType; +import org.apache.doris.connector.api.Connector; +import org.apache.doris.connector.api.ConnectorCapability; +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.ConnectorTableSchema; +import org.apache.doris.connector.api.ConnectorTableStatistics; +import org.apache.doris.connector.api.handle.ConnectorTableHandle; +import org.apache.doris.statistics.AnalysisInfo; +import org.apache.doris.statistics.BaseAnalysisTask; +import org.apache.doris.statistics.ExternalAnalysisTask; +import org.apache.doris.thrift.TTableDescriptor; +import org.apache.doris.thrift.TTableType; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * Generic {@link ExternalTable} for plugin-driven catalogs. + * + * <p>Provides table implementation that fetches schema from the connector SPI. + * Connector-specific behavior is accessed through the parent catalog's + * {@link org.apache.doris.connector.api.Connector} using opaque handles.</p> + */ +public class PluginDrivenExternalTable extends ExternalTable { + + private static final Logger LOG = LogManager.getLogger(PluginDrivenExternalTable.class); + + /** No-arg constructor for GSON deserialization. */ + public PluginDrivenExternalTable() { + } + + public PluginDrivenExternalTable(long id, String name, String remoteName, + ExternalCatalog catalog, ExternalDatabase db) { + super(id, name, remoteName, catalog, db, TableType.PLUGIN_EXTERNAL_TABLE); + } + + /** + * Returns whether the underlying connector supports multiple concurrent writers. + * Used by the planner to decide GATHER (single writer) vs parallel distribution. + */ + public boolean supportsParallelWrite() { + if (!(catalog instanceof PluginDrivenExternalCatalog)) { + return false; + } + Connector connector = ((PluginDrivenExternalCatalog) catalog).getConnector(); + return connector != null + && connector.getCapabilities().contains(ConnectorCapability.SUPPORTS_PARALLEL_WRITE); + } + + @Override + public Optional<SchemaCacheValue> initSchema() { + PluginDrivenExternalCatalog pluginCatalog = (PluginDrivenExternalCatalog) catalog; + Connector connector = pluginCatalog.getConnector(); + ConnectorSession session = pluginCatalog.buildConnectorSession(); + ConnectorMetadata metadata = connector.getMetadata(session); + + String dbName = db != null ? db.getRemoteName() : ""; + String tableName = getRemoteName(); + Optional<ConnectorTableHandle> handleOpt = metadata.getTableHandle(session, dbName, tableName); + if (!handleOpt.isPresent()) { + LOG.warn("Table handle not found for plugin-driven table: {}.{}", dbName, tableName); + return Optional.empty(); + } + + ConnectorTableSchema tableSchema = metadata.getTableSchema(session, handleOpt.get()); + + // Apply identifier mapping to column names (lowercase / explicit mapping) + List<ConnectorColumn> mappedColumns = new ArrayList<>(tableSchema.getColumns().size()); + for (ConnectorColumn col : tableSchema.getColumns()) { + String mappedName = metadata.fromRemoteColumnName(session, dbName, tableName, col.getName()); + if (!mappedName.equals(col.getName())) { + mappedColumns.add(new ConnectorColumn(mappedName, col.getType(), + col.getComment(), col.isNullable(), col.getDefaultValue(), col.isKey())); + } else { + mappedColumns.add(col); + } + } + + List<Column> columns = ConnectorColumnConverter.convertColumns(mappedColumns); + return Optional.of(new SchemaCacheValue(columns)); + } + + @Override + protected synchronized void makeSureInitialized() { + super.makeSureInitialized(); + if (!objectCreated) { + objectCreated = true; + } + } + + @Override + public long getCachedRowCount() { + // Do NOT call makeSureInitialized() here. + // ExternalTable.getCachedRowCount() intentionally returns -1 for uninitialized tables + // so that SHOW TABLE STATUS / information_schema.tables stays non-blocking. + if (!isObjectCreated()) { + return -1; + } + return Env.getCurrentEnv().getExtMetaCacheMgr().getRowCountCache() + .getCachedRowCount(catalog.getId(), dbId, id); + } + + @Override + public String getComment() { + return getComment(false); + } + + @Override + public String getComment(boolean escapeQuota) { + try { + PluginDrivenExternalCatalog pluginCatalog = (PluginDrivenExternalCatalog) catalog; + Connector connector = pluginCatalog.getConnector(); + ConnectorSession session = pluginCatalog.buildConnectorSession(); + ConnectorMetadata metadata = connector.getMetadata(session); + String dbName = db != null ? db.getRemoteName() : ""; + String tableName = getRemoteName(); + String comment = metadata.getTableComment(session, dbName, tableName); + if (escapeQuota && comment != null) { + return comment.replace("'", "\\'"); + } + return comment != null ? comment : ""; + } catch (Exception e) { + LOG.debug("Failed to get table comment for {}.{}", dbName, name, e); Review Comment: `dbName` is declared inside the `try`, so the `catch` block cannot see it. As written this new file does not compile (`cannot find symbol: variable dbName`), which blocks the whole FE build. Please hoist the declaration before the `try` or avoid referencing it from the `catch`. ########## fe/fe-connector/fe-connector-jdbc/src/main/java/org/apache/doris/connector/jdbc/JdbcDorisConnector.java: ########## @@ -0,0 +1,322 @@ +// 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.Connector; +import org.apache.doris.connector.api.ConnectorCapability; +import org.apache.doris.connector.api.ConnectorMetadata; +import org.apache.doris.connector.api.ConnectorSession; +import org.apache.doris.connector.api.ConnectorTestResult; +import org.apache.doris.connector.api.ConnectorValidationContext; +import org.apache.doris.connector.api.DorisConnectorException; +import org.apache.doris.connector.api.scan.ConnectorScanPlanProvider; +import org.apache.doris.connector.jdbc.client.JdbcConnectorClient; +import org.apache.doris.connector.spi.ConnectorContext; +import org.apache.doris.thrift.TJdbcTable; +import org.apache.doris.thrift.TOdbcTableType; +import org.apache.doris.thrift.TTableDescriptor; +import org.apache.doris.thrift.TTableType; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.thrift.TSerializer; + +import java.io.IOException; +import java.util.Collections; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * JDBC connector implementation. Manages the lifecycle of + * {@link JdbcConnectorClient} (HikariCP data source, JDBC driver classloader). + */ +public class JdbcDorisConnector implements Connector { + + private static final Logger LOG = LogManager.getLogger(JdbcDorisConnector.class); + + private final Map<String, String> properties; + private final ConnectorContext context; + private volatile JdbcConnectorClient client; + private volatile JdbcScanPlanProvider scanPlanProvider; + private volatile boolean closed; + + static final String JDBC_PROPERTIES_PREFIX = "jdbc."; + + public JdbcDorisConnector(Map<String, String> properties, ConnectorContext context) { + Map<String, String> normalized = new HashMap<>(); + // Strip "jdbc." prefix from property keys for backward compatibility. + // Users may write "jdbc.jdbc_url" or "jdbc.user" in CREATE CATALOG; + // internally we use the short form ("jdbc_url", "user"). + for (Map.Entry<String, String> entry : properties.entrySet()) { + String key = entry.getKey(); + if (key.startsWith(JDBC_PROPERTIES_PREFIX)) { + String shortKey = key.substring(JDBC_PROPERTIES_PREFIX.length()); + // Only strip if the short key is not already present + if (!properties.containsKey(shortKey)) { + normalized.put(shortKey, entry.getValue()); + continue; + } + } + normalized.put(key, entry.getValue()); + } + String rawUrl = normalized.get(JdbcConnectorProperties.JDBC_URL); + if (rawUrl != null && !rawUrl.isEmpty()) { + JdbcDbType dbType = JdbcDbType.parseFromUrl(rawUrl); + normalized.put(JdbcConnectorProperties.JDBC_URL, + JdbcUrlNormalizer.normalize(rawUrl, dbType, context.getEnvironment())); + } + this.properties = Collections.unmodifiableMap(normalized); + this.context = context; + } + + @Override + public ConnectorMetadata getMetadata(ConnectorSession session) { + return new JdbcConnectorMetadata(getOrCreateClient(), properties); + } + + @Override + public Set<ConnectorCapability> getCapabilities() { + return EnumSet.of( + ConnectorCapability.SUPPORTS_INSERT, + ConnectorCapability.SUPPORTS_PASSTHROUGH_QUERY + ); + } + + @Override + public boolean defaultTestConnection() { + return true; + } + + @Override + public ConnectorScanPlanProvider getScanPlanProvider() { + if (scanPlanProvider == null) { + synchronized (this) { + if (closed) { + throw new DorisConnectorException("JdbcDorisConnector has been closed"); + } + if (scanPlanProvider == null) { + // Use client's effective dbType instead of static URL parsing, + // so OceanBase Oracle mode is detected correctly + JdbcDbType dbType = getOrCreateClient().getDbType(); + scanPlanProvider = new JdbcScanPlanProvider( + dbType, properties, context.getCatalogId()); + } + } + } + return scanPlanProvider; + } + + @Override + public void preCreateValidation(ConnectorValidationContext context) throws Exception { + // 1. Validate/resolve JDBC driver — format, whitelist, secure_path, file existence. + String driverUrl = properties.get(JdbcConnectorProperties.DRIVER_URL); + if (driverUrl != null && !driverUrl.isEmpty()) { + context.validateAndResolveDriverPath(driverUrl); + + // 2. Compute and verify checksum. + String computedChecksum = context.computeDriverChecksum(driverUrl); + String providedChecksum = context.getProperty(JdbcConnectorProperties.DRIVER_CHECKSUM); + if (providedChecksum != null && !providedChecksum.isEmpty()) { + if (!providedChecksum.equals(computedChecksum)) { + throw new DorisConnectorException( + "The provided checksum (" + providedChecksum + + ") does not match the computed checksum (" + computedChecksum + + ") for the driver_url."); + } + } else { + context.storeProperty(JdbcConnectorProperties.DRIVER_CHECKSUM, computedChecksum); + } + } + + // 3. Test BE→JDBC connectivity via BRPC (only when test_connection is enabled). + // The connector builds the serialized payload; the engine sends it after validation. + boolean testConnection = Boolean.parseBoolean( + properties.getOrDefault("test_connection", "true")); + if (testConnection) { + TTableDescriptor testThrift = buildTestTableDescriptor(context); + TOdbcTableType tableType = parseOdbcType(); + byte[] serialized = new TSerializer().serialize(testThrift); + context.requestBeConnectivityTest(serialized, tableType.getValue(), getTestQuery()); + } + } + + @Override + public ConnectorTestResult testConnection(ConnectorSession session) { + try { + JdbcConnectorClient c = getOrCreateClient(); + List<String> dbs = c.getDatabaseNameList(); + LOG.info("JDBC connection test succeeded, found {} databases", dbs.size()); + return ConnectorTestResult.success( + "Connected successfully, found " + dbs.size() + " databases"); + } catch (Exception e) { + LOG.warn("JDBC connection test failed", e); + return ConnectorTestResult.failure("JDBC connection failed: " + e.getMessage()); + } + } + + private JdbcConnectorClient getOrCreateClient() { + if (closed) { + throw new DorisConnectorException("JdbcDorisConnector has been closed"); + } + if (client == null) { + synchronized (this) { + if (closed) { + throw new DorisConnectorException("JdbcDorisConnector has been closed"); + } + if (client == null) { + client = createClient(); + } + } + } + return client; + } + + private JdbcConnectorClient createClient() { + String jdbcUrl = properties.get(JdbcConnectorProperties.JDBC_URL); + if (jdbcUrl == null || jdbcUrl.isEmpty()) { + throw new DorisConnectorException("JDBC URL ('" + JdbcConnectorProperties.JDBC_URL + "') is required"); + } + JdbcDbType dbType = JdbcDbType.parseFromUrl(jdbcUrl); + String user = properties.getOrDefault(JdbcConnectorProperties.USER, ""); + String password = properties.getOrDefault(JdbcConnectorProperties.PASSWORD, ""); + String driverUrl = resolveDriverUrl(properties.get(JdbcConnectorProperties.DRIVER_URL)); + String driverClass = properties.get(JdbcConnectorProperties.DRIVER_CLASS); + int poolMinSize = JdbcConnectorProperties.getInt( + properties, JdbcConnectorProperties.CONNECTION_POOL_MIN_SIZE, + JdbcConnectorProperties.DEFAULT_POOL_MIN_SIZE); + int poolMaxSize = JdbcConnectorProperties.getInt( + properties, JdbcConnectorProperties.CONNECTION_POOL_MAX_SIZE, + JdbcConnectorProperties.DEFAULT_POOL_MAX_SIZE); + int poolMaxWaitTime = JdbcConnectorProperties.getInt( + properties, JdbcConnectorProperties.CONNECTION_POOL_MAX_WAIT_TIME, + JdbcConnectorProperties.DEFAULT_POOL_MAX_WAIT_TIME); + int poolMaxLifeTime = JdbcConnectorProperties.getInt( + properties, JdbcConnectorProperties.CONNECTION_POOL_MAX_LIFE_TIME, + JdbcConnectorProperties.DEFAULT_POOL_MAX_LIFE_TIME); + boolean onlySpecifiedDatabase = Boolean.parseBoolean( + properties.getOrDefault(JdbcConnectorProperties.ONLY_SPECIFIED_DATABASE, "false")); + boolean enableMappingVarbinary = Boolean.parseBoolean( + properties.getOrDefault(JdbcConnectorProperties.ENABLE_MAPPING_VARBINARY, "false")); + boolean enableMappingTimestampTz = Boolean.parseBoolean( + properties.getOrDefault(JdbcConnectorProperties.ENABLE_MAPPING_TIMESTAMP_TZ, "false")); + + LOG.info("Creating JDBC connector client for dbType={}, url={}", dbType, jdbcUrl); + return JdbcConnectorClient.create( + dbType, context.getCatalogName(), jdbcUrl, user, password, + driverUrl, driverClass, + poolMinSize, poolMaxSize, poolMaxWaitTime, poolMaxLifeTime, + onlySpecifiedDatabase, properties, + enableMappingVarbinary, enableMappingTimestampTz, + context::sanitizeJdbcUrl); + } + + @Override + public void close() throws IOException { + synchronized (this) { + closed = true; + JdbcConnectorClient c = client; + client = null; + scanPlanProvider = null; + if (c != null) { + c.close(); + } + } + } + + /** + * Resolves driver URL using the environment from ConnectorContext. + * If the URL is a plain filename (e.g., "mysql-connector-j-8.4.0.jar"), + * resolves it using the jdbc_drivers_dir from the environment. + */ + private String resolveDriverUrl(String driverUrl) { + if (driverUrl == null || driverUrl.isEmpty()) { + return driverUrl; + } + if (driverUrl.startsWith("file://") || driverUrl.startsWith("http://") + || driverUrl.startsWith("https://") || driverUrl.startsWith("/")) { + return driverUrl; + } + // Plain filename — resolve using jdbc_drivers_dir from environment Review Comment: `preCreateValidation()` still validates/checksums plain jar names through `JdbcResource.getFullDriverUrl()`, which preserves the old `$DORIS_HOME/jdbc_drivers` fallback. This runtime resolver drops that compatibility path and always rewrites `foo.jar` to `${Config.jdbc_drivers_dir}/foo.jar`. On upgraded clusters with existing JDBC catalogs that still have the driver only in the old default directory, metadata/query access now fails even though the same `driver_url` worked before. Please reuse `JdbcResource.getFullDriverUrl()` here instead of duplicating a narrower resolver. ########## fe/fe-core/src/main/java/org/apache/doris/datasource/PluginDrivenExternalCatalog.java: ########## @@ -0,0 +1,300 @@ +// 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.Locale; +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 happen under synchronized(this) + // via makeSureInitialized() → initLocalObjectsImpl(), or resetToUninitialized() → onClose(). + private transient volatile Connector connector; + + /** 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) { Review Comment: We overwrite the validation-time `connector` here without closing it first. `CatalogFactory` hands a live connector into the catalog, `checkWhenCreating()` calls `connector.testConnection(session)`, and the JDBC implementation leaves a `JdbcConnectorClient`/Hikari pool in that instance. On the first `makeSureInitialized()` we assign `connector = newConnector` and lose the old one forever, leaking the pool/classloader for every successfully created catalog. Please either reuse the existing connector or close it before replacing it. ########## fe/fe-connector/fe-connector-jdbc/src/main/java/org/apache/doris/connector/jdbc/JdbcQueryBuilder.java: ########## @@ -0,0 +1,652 @@ +// 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.time.format.DateTimeFormatterBuilder; +import java.time.temporal.ChronoField; +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"); + + /** + * Formatter that preserves fractional seconds (up to microsecond precision). + * Used for non-Oracle paths where the previous JDBC scan path emitted + * {@code expr.getStringValue()}, keeping DATETIMEV2 literals intact. + */ + private static final DateTimeFormatter DATETIME_FRAC_FMT; + + static { + DATETIME_FRAC_FMT = new DateTimeFormatterBuilder() + .appendPattern("yyyy-MM-dd HH:mm:ss") + .optionalStart() + .appendFraction(ChronoField.NANO_OF_SECOND, 0, 6, true) + .optionalEnd() + .toFormatter(); + } + + 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) { Review Comment: `ExprToConnectorExpressionConverter` produces real boolean literals for predicates like `flag = true`, but this path rewrites every boolean to `1`/`0`. That is not compatible with the old JDBC pushdown path, which emitted `TRUE`/`FALSE`. On PostgreSQL/Trino catalogs the remote SQL becomes `... WHERE "flag" = 1`, which fails with a boolean-vs-integer type error. Boolean literal rendering needs to be database-specific here instead of hardcoding numeric values. ########## fe/fe-connector/fe-connector-jdbc/src/main/java/org/apache/doris/connector/jdbc/JdbcDorisConnector.java: ########## @@ -0,0 +1,322 @@ +// 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.Connector; +import org.apache.doris.connector.api.ConnectorCapability; +import org.apache.doris.connector.api.ConnectorMetadata; +import org.apache.doris.connector.api.ConnectorSession; +import org.apache.doris.connector.api.ConnectorTestResult; +import org.apache.doris.connector.api.ConnectorValidationContext; +import org.apache.doris.connector.api.DorisConnectorException; +import org.apache.doris.connector.api.scan.ConnectorScanPlanProvider; +import org.apache.doris.connector.jdbc.client.JdbcConnectorClient; +import org.apache.doris.connector.spi.ConnectorContext; +import org.apache.doris.thrift.TJdbcTable; +import org.apache.doris.thrift.TOdbcTableType; +import org.apache.doris.thrift.TTableDescriptor; +import org.apache.doris.thrift.TTableType; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.thrift.TSerializer; + +import java.io.IOException; +import java.util.Collections; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * JDBC connector implementation. Manages the lifecycle of + * {@link JdbcConnectorClient} (HikariCP data source, JDBC driver classloader). + */ +public class JdbcDorisConnector implements Connector { + + private static final Logger LOG = LogManager.getLogger(JdbcDorisConnector.class); + + private final Map<String, String> properties; + private final ConnectorContext context; + private volatile JdbcConnectorClient client; + private volatile JdbcScanPlanProvider scanPlanProvider; + private volatile boolean closed; + + static final String JDBC_PROPERTIES_PREFIX = "jdbc."; + + public JdbcDorisConnector(Map<String, String> properties, ConnectorContext context) { + Map<String, String> normalized = new HashMap<>(); + // Strip "jdbc." prefix from property keys for backward compatibility. + // Users may write "jdbc.jdbc_url" or "jdbc.user" in CREATE CATALOG; + // internally we use the short form ("jdbc_url", "user"). + for (Map.Entry<String, String> entry : properties.entrySet()) { + String key = entry.getKey(); + if (key.startsWith(JDBC_PROPERTIES_PREFIX)) { + String shortKey = key.substring(JDBC_PROPERTIES_PREFIX.length()); + // Only strip if the short key is not already present + if (!properties.containsKey(shortKey)) { + normalized.put(shortKey, entry.getValue()); + continue; + } + } + normalized.put(key, entry.getValue()); + } + String rawUrl = normalized.get(JdbcConnectorProperties.JDBC_URL); + if (rawUrl != null && !rawUrl.isEmpty()) { + JdbcDbType dbType = JdbcDbType.parseFromUrl(rawUrl); + normalized.put(JdbcConnectorProperties.JDBC_URL, + JdbcUrlNormalizer.normalize(rawUrl, dbType, context.getEnvironment())); + } + this.properties = Collections.unmodifiableMap(normalized); + this.context = context; + } + + @Override + public ConnectorMetadata getMetadata(ConnectorSession session) { + return new JdbcConnectorMetadata(getOrCreateClient(), properties); + } + + @Override + public Set<ConnectorCapability> getCapabilities() { + return EnumSet.of( + ConnectorCapability.SUPPORTS_INSERT, + ConnectorCapability.SUPPORTS_PASSTHROUGH_QUERY + ); + } + + @Override + public boolean defaultTestConnection() { + return true; + } + + @Override + public ConnectorScanPlanProvider getScanPlanProvider() { + if (scanPlanProvider == null) { + synchronized (this) { + if (closed) { + throw new DorisConnectorException("JdbcDorisConnector has been closed"); + } + if (scanPlanProvider == null) { + // Use client's effective dbType instead of static URL parsing, + // so OceanBase Oracle mode is detected correctly + JdbcDbType dbType = getOrCreateClient().getDbType(); + scanPlanProvider = new JdbcScanPlanProvider( + dbType, properties, context.getCatalogId()); + } + } + } + return scanPlanProvider; + } + + @Override + public void preCreateValidation(ConnectorValidationContext context) throws Exception { + // 1. Validate/resolve JDBC driver — format, whitelist, secure_path, file existence. + String driverUrl = properties.get(JdbcConnectorProperties.DRIVER_URL); + if (driverUrl != null && !driverUrl.isEmpty()) { + context.validateAndResolveDriverPath(driverUrl); + + // 2. Compute and verify checksum. + String computedChecksum = context.computeDriverChecksum(driverUrl); + String providedChecksum = context.getProperty(JdbcConnectorProperties.DRIVER_CHECKSUM); + if (providedChecksum != null && !providedChecksum.isEmpty()) { + if (!providedChecksum.equals(computedChecksum)) { + throw new DorisConnectorException( + "The provided checksum (" + providedChecksum + + ") does not match the computed checksum (" + computedChecksum + + ") for the driver_url."); + } + } else { + context.storeProperty(JdbcConnectorProperties.DRIVER_CHECKSUM, computedChecksum); + } + } + + // 3. Test BE→JDBC connectivity via BRPC (only when test_connection is enabled). + // The connector builds the serialized payload; the engine sends it after validation. + boolean testConnection = Boolean.parseBoolean( + properties.getOrDefault("test_connection", "true")); + if (testConnection) { + TTableDescriptor testThrift = buildTestTableDescriptor(context); + TOdbcTableType tableType = parseOdbcType(); Review Comment: This BE connectivity test is assembled before `JdbcOceanBaseConnectorClient` has a chance to detect compatibility mode. For `jdbc:oceanbase:` URLs `parseFromUrl()` still returns `OCEANBASE`, so Oracle-mode catalogs are validated with `TOdbcTableType.OCEANBASE` plus `SELECT 1` instead of `OCEANBASE_ORACLE` plus `SELECT 1 FROM DUAL`. The old `JdbcExternalCatalog` path derived both values from the initialized client, so `CREATE CATALOG ... test_connection=true` used to work for OceanBase Oracle mode. -- 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]
