github-actions[bot] commented on code in PR #62183:
URL: https://github.com/apache/doris/pull/62183#discussion_r3084392705


##########
fe/fe-core/src/main/java/org/apache/doris/datasource/PluginDrivenExternalCatalog.java:
##########
@@ -0,0 +1,244 @@
+// 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.api.Connector;
+import org.apache.doris.connector.api.ConnectorSession;
+import org.apache.doris.connector.api.ConnectorTestResult;
+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);
+
+    private transient 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() {
+        if (connector != null) {
+            transactionManager = new PluginDrivenTransactionManager();
+            initPreExecutionAuthenticator();
+            return;
+        }
+        // After GSON deserialization, recreate the Connector from catalog 
properties.
+        String catalogType = 
catalogProperty.getOrDefault(CatalogMgr.CATALOG_TYPE_PROP, "");
+        connector = ConnectorFactory.createConnector(catalogType,
+                catalogProperty.getProperties(),
+                new DefaultConnectorContext(name, id));
+        if (connector == null) {
+            throw new RuntimeException("No ConnectorProvider found for 
plugin-driven catalog: "
+                    + name + ", type: " + catalogType
+                    + ". Ensure the connector plugin is installed.");
+        }
+        LOG.info("Recreated connector for plugin-driven catalog {}:{}, 
type={}",
+                name, id, catalogType);
+        transactionManager = new PluginDrivenTransactionManager();
+        initPreExecutionAuthenticator();
+    }
+
+    @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 {
+        boolean testConnection = Boolean.parseBoolean(
+                catalogProperty.getOrDefault(ExternalCatalog.TEST_CONNECTION,
+                        
String.valueOf(ExternalCatalog.DEFAULT_TEST_CONNECTION)));
+        if (!testConnection) {
+            return;
+        }
+        // Delegate 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);
+    }
+
+    @Override
+    public void notifyPropertiesUpdated(Map<String, String> updatedProps) {
+        super.notifyPropertiesUpdated(updatedProps);

Review Comment:
   `super.notifyPropertiesUpdated()` has already called 
`resetToUninitialized(false)` here. That opens a race with concurrent readers: 
another thread can reinitialize the catalog and install connector A before this 
method reaches `Connector oldConnector = connector; connector = newConnector; 
oldConnector.close()`. In that case `oldConnector` is the freshly reinitialized 
connector A, so we close the connector that an in-flight query is actively 
using. This violates the datasource reset guideline about not exposing a 
partially torn-down catalog to readers. The recreate/swap/close sequence needs 
to be synchronized end-to-end, or otherwise made safe against concurrent 
`makeSureInitialized()`/query access.



##########
fe/fe-core/src/main/java/org/apache/doris/connector/ConnectorSessionImpl.java:
##########
@@ -0,0 +1,128 @@
+// 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;
+
+import org.apache.doris.connector.api.ConnectorSession;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * Immutable implementation of {@link ConnectorSession}.
+ *
+ * <p>Instances are created via {@link ConnectorSessionBuilder}.
+ */
+public class ConnectorSessionImpl implements ConnectorSession {
+
+    private final String queryId;
+    private final String user;
+    private final String timeZone;
+    private final String locale;
+    private final long catalogId;
+    private final String catalogName;
+    private final Map<String, String> catalogProperties;
+    private final Map<String, String> sessionProperties;
+
+    ConnectorSessionImpl(String queryId, String user, String timeZone, String 
locale,
+            long catalogId, String catalogName, Map<String, String> 
catalogProperties,
+            Map<String, String> sessionProperties) {
+        this.queryId = queryId != null ? queryId : "";
+        this.user = user != null ? user : "";
+        this.timeZone = timeZone != null ? timeZone : "UTC";
+        this.locale = locale != null ? locale : "en_US";
+        this.catalogId = catalogId;
+        this.catalogName = catalogName != null ? catalogName : "";
+        this.catalogProperties = catalogProperties != null
+                ? Collections.unmodifiableMap(catalogProperties) : 
Collections.emptyMap();
+        this.sessionProperties = sessionProperties != null
+                ? Collections.unmodifiableMap(sessionProperties) : 
Collections.emptyMap();
+    }
+
+    @Override
+    public String getQueryId() {
+        return queryId;
+    }
+
+    @Override
+    public String getUser() {
+        return user;
+    }
+
+    @Override
+    public String getTimeZone() {
+        return timeZone;
+    }
+
+    @Override
+    public String getLocale() {
+        return locale;
+    }
+
+    @Override
+    public long getCatalogId() {
+        return catalogId;
+    }
+
+    @Override
+    public String getCatalogName() {
+        return catalogName;
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public <T> T getProperty(String name, Class<T> type) {
+        Objects.requireNonNull(name, "name");
+        Objects.requireNonNull(type, "type");
+        String value = catalogProperties.get(name);

Review Comment:
   `ConnectorSessionBuilder` stores per-query overrides in `sessionProperties`, 
but `getProperty()` only reads `catalogProperties`. That makes the typed 
accessor unusable for session-scoped settings. This already breaks the new Hive 
path: `HiveScanPlanProvider.getTargetSplitSize()` calls 
`session.getProperty("file_split_size", String.class)`, so `SET file_split_size 
= ...` is silently ignored and planning falls back to 
`DEFAULT_TARGET_SPLIT_SIZE`. Either `getProperty()` needs to consult 
`sessionProperties` first (or merge both maps), or all connector call sites 
need to stop using the typed accessor for session variables.



##########
fe/fe-core/src/main/java/org/apache/doris/datasource/PluginDrivenExternalTable.java:
##########
@@ -0,0 +1,217 @@
+// 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;
+import org.apache.doris.catalog.TableIf.TableType;
+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.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);
+    }
+
+    @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() {
+        try {
+            makeSureInitialized();
+        } catch (Exception e) {
+            LOG.warn("Failed to initialize table {}.{}.{}", catalog.getName(), 
dbName, name, e);
+            return TableIf.UNKNOWN_ROW_COUNT;
+        }
+        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);
+            return "";
+        }
+    }
+
+    @Override
+    public void gsonPostProcess() throws IOException {
+        super.gsonPostProcess();
+        // After deserializing a migrated old table (e.g., EsExternalTable → 
PluginDrivenExternalTable),
+        // fix the table type so that BindRelation routes to LogicalFileScan 
(new path).
+        if (type != TableType.PLUGIN_EXTERNAL_TABLE) {

Review Comment:
   This replay-time migration changes legacy `EsExternalTable` / 
`JdbcExternalTable` objects into runtime type `PLUGIN_EXTERNAL_TABLE`, but the 
parallel `ALTER TABLE` path was not updated. `Alter.processAlterTable()` still 
handles `ES_EXTERNAL_TABLE` / `JDBC_EXTERNAL_TABLE` explicitly and does not 
include `PLUGIN_EXTERNAL_TABLE`, so after FE restart/checkpoint replay an 
existing ES/JDBC external table will start failing `ALTER TABLE` with `Do not 
support alter PLUGIN_EXTERNAL_TABLE ...`. If the migration is kept, every 
downstream switch on `TableType` that supported ES/JDBC external tables before 
replay needs an equivalent plugin-table path.



-- 
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]

Reply via email to