hello-stephen commented on code in PR #71298:
URL: https://github.com/apache/doris/pull/71298#discussion_r4796383990
##########
fe/fe-core/src/main/java/org/apache/doris/tablefunction/CdcStreamTableValuedFunction.java:
##########
@@ -130,6 +159,9 @@ public static void validateProperties(Map<String, String>
properties) throws Ana
if (StringUtils.isEmpty(properties.get(DataSourceConfigKeys.TABLE))) {
throw new AnalysisException("table is required");
}
+ if (properties.containsKey(DataSourceConfigKeys.INCLUDE_TABLES)) {
Review Comment:
[P2] Preserve saved CDC TVF jobs with a redundant include_tables value
The base accepted a CDC TVF with `table=t` and `include_tables=t`. Its
schema lookup and `ConfigUtil.getTableList()` both selected `t`, so this
configuration could run and be persisted. After upgrade,
`StreamingInsertTask.before()` replans the saved SQL and this unconditional
check rejects it, even in the internal task context. Keep the unambiguous
legacy form readable during replanning and continue to reject conflicting table
selections.
##########
fe/fe-core/src/main/java/org/apache/doris/tablefunction/CdcStreamTableValuedFunction.java:
##########
@@ -223,24 +255,33 @@ private void generateFileStatus() {
@Override
public List<Column> getTableColumns() throws AnalysisException {
- DataSourceType dataSourceType =
-
DataSourceType.valueOf(processedParams.get(DataSourceConfigKeys.TYPE).toUpperCase());
- JdbcClient jdbcClient =
StreamingJobUtils.getJdbcClient(dataSourceType, processedParams);
+ DataSourceType sourceType = DataSourceType.valueOf(
+ processedParams.get(DataSourceConfigKeys.TYPE).toUpperCase());
try {
- String database =
StreamingJobUtils.getRemoteDbName(dataSourceType, processedParams);
- String table = processedParams.get(DataSourceConfigKeys.TABLE);
- if (!jdbcClient.isTableExist(database, table)) {
- throw new AnalysisException("Table does not exist: " + table);
+ String computeGroup = Config.isCloudMode() ?
ConnectContext.get().getCloudCluster() : null;
Review Comment:
[P2] Discover CDC TVF schemas on the requested job compute group
`CreateJobInfo.analyzeAndCreateStreamingInsertJob()` plans the INSERT before
constructing the job that applies its `compute_group` property. With session
group A and `compute_group=B`, this lookup goes to A. If the source is
reachable from B alone, CREATE fails during planning even though the job's
subsequent validation and execution would use B. Apply the validated job group
to the planning context and cover a CREATE where the session and job groups
differ.
##########
fe/fe-core/src/main/java/org/apache/doris/job/util/CdcSchemaClient.java:
##########
@@ -0,0 +1,176 @@
+// 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.job.util;
+
+import org.apache.doris.catalog.Env;
+import org.apache.doris.cloud.catalog.CloudEnv;
+import org.apache.doris.common.Config;
+import org.apache.doris.job.cdc.CdcColumn;
+import org.apache.doris.job.cdc.CdcTableSchema;
+import org.apache.doris.job.cdc.DataSourceConfigKeys;
+import org.apache.doris.job.cdc.request.GetTableSchemasRequest;
+import org.apache.doris.job.cdc.response.GetTableSchemasResult;
+import org.apache.doris.job.exception.JobException;
+import org.apache.doris.proto.InternalService;
+import org.apache.doris.rpc.BackendServiceProxy;
+import org.apache.doris.system.Backend;
+import org.apache.doris.thrift.TNetworkAddress;
+import org.apache.doris.thrift.TStatusCode;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.lang3.StringUtils;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+
+/** Fetches source schemas through a BE and its CDC client; FE does not
connect to the source. */
+public final class CdcSchemaClient {
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private CdcSchemaClient() {
+ }
+
+ public static List<CdcTableSchema> getTableSchemas(GetTableSchemasRequest
request,
+ String computeGroup) throws JobException {
+ if (Config.isCloudMode()) {
+ if (StringUtils.isBlank(computeGroup)) {
+ throw new JobException("compute_group is required for source
schema inspection");
+ }
+ try {
+ ((CloudEnv)
Env.getCurrentEnv()).checkCloudClusterPriv(computeGroup);
+ } catch (Exception e) {
+ throw new JobException("No access to compute_group: " +
computeGroup, e);
+ }
+ }
+ Backend backend = StreamingJobUtils.selectBackend(computeGroup);
+ try {
+ InternalService.PRequestCdcClientRequest rpc =
InternalService.PRequestCdcClientRequest.newBuilder()
+
.setApi("/api/getTableSchemas").setParams(MAPPER.writeValueAsString(request)).build();
Review Comment:
[P1] Keep existing CDC TVF jobs running during FE-first upgrades
The base CDC client has no `/api/getTableSchemas` handler. After FE is
upgraded, this call sends the new API to a single load-available BE regardless
of the CDC client version on it. `StreamingInsertTask.before()` replans the TVF
every batch, so an existing job can pause on ordinary DML while BEs still run
the old client. Once the first BE is upgraded, round-robin selection can still
hit an old client. Preserve a discovery path throughout the rollout and cover a
running TVF job with mixed-version BEs.
##########
regression-test/suites/job_p0/streaming_job/cdc/test_streaming_mysql_type_contract.groovy:
##########
@@ -0,0 +1,132 @@
+// 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.
+
+
+import org.awaitility.Awaitility
+
+import static java.util.concurrent.TimeUnit.SECONDS
+
+suite("test_streaming_mysql_type_contract",
"p0,external,mysql,external_docker,external_docker_mysql,nondatalake") {
+ if
(!context.config.otherConfigs.get("enableJdbcTest")?.equalsIgnoreCase("true")) {
+ return
+ }
+ def currentDb = (sql "SELECT DATABASE()")[0][0]
+ def host = context.config.otherConfigs.get("externalEnvIp")
+ def port = context.config.otherConfigs.get("mysql_57_port")
+ def jdbcUrl = "jdbc:mysql://${host}:${port}"
+ sql "DROP JOB IF EXISTS WHERE jobname='mysql_type_contract_job'"
+ sql "DROP TABLE IF EXISTS cdc_type_contract_mysql FORCE"
+ sql "DROP JOB IF EXISTS WHERE jobname='mysql_type_contract_tvf_job'"
+ sql "DROP TABLE IF EXISTS cdc_type_contract_mysql_tvf FORCE"
+ connect("root", "123456", jdbcUrl) {
+ sql "CREATE DATABASE IF NOT EXISTS test_cdc_db"
+ sql "DROP TABLE IF EXISTS test_cdc_db.cdc_type_contract_mysql"
+ sql "DROP TABLE IF EXISTS test_cdc_db.cdcXtypeXcontractXmysql"
+ sql """CREATE TABLE test_cdc_db.cdc_type_contract_mysql (
+ id INT PRIMARY KEY, doc JSON, amount DECIMAL(20,6),
+ event_time DATETIME(6), unsigned_value BIGINT UNSIGNED,
+ p38 DECIMAL(38,6), p39 DECIMAL(39,6), u37 DECIMAL(37,6)
UNSIGNED,
+ u38 DECIMAL(38,6) UNSIGNED, time_default DATETIME,
+ c85 CHAR(85) CHARACTER SET utf8mb4, c86 CHAR(86) CHARACTER SET
utf8mb4,
+ v21844 VARCHAR(21844), v21845 VARCHAR(21845)) DEFAULT
CHARSET=latin1"""
+ // JDBC '_' patterns must not mix columns from this other table into
the schema.
+ sql "CREATE TABLE test_cdc_db.cdcXtypeXcontractXmysql (alien INT
PRIMARY KEY)"
+ sql """INSERT INTO
test_cdc_db.cdc_type_contract_mysql(id,doc,amount,event_time,unsigned_value)
VALUES
+ (1,'{"v":1}',12345678901234.123456,'2026-01-02
03:04:05.123456',18446744073709551615)"""
+ sql """UPDATE test_cdc_db.cdc_type_contract_mysql SET
+ p38=99999999999999999999999999999999.999999,
+ p39=999999999999999999999999999999999.999999,
+ u37=9999999999999999999999999999999.999999,
+ u38=99999999999999999999999999999999.999999,
+ time_default='2026-01-02
03:04:05',c85=REPEAT('中',85),c86=REPEAT('文',86),
+ v21844=REPEAT('x',21844),CAST(v21845=REPEAT('y',21845) AS INT)
WHERE id=1"""
Review Comment:
[P2] Fix the MySQL fixture assignment
The second expression after the comma is `CAST(...)`, but MySQL requires
another `column = expression` assignment in this `UPDATE ... SET` list. The
suite stops during fixture setup before creating either CDC job. Use
`v21845=REPEAT('y',21845)` here and keep the cast in the later SELECT assertion.
##########
fs_brokers/cdc_client/src/main/java/org/apache/doris/cdcclient/service/TableSchemaService.java:
##########
@@ -0,0 +1,459 @@
+// 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.cdcclient.service;
+
+import org.apache.doris.cdcclient.common.Env;
+import org.apache.doris.cdcclient.source.factory.DataSource;
+import org.apache.doris.cdcclient.source.schema.CdcSourceColumn;
+import org.apache.doris.cdcclient.utils.CdcTypeMapper;
+import org.apache.doris.cdcclient.utils.ConfigUtil;
+import org.apache.doris.cdcclient.utils.PostgresNumericUtils;
+import org.apache.doris.job.cdc.CdcColumn;
+import org.apache.doris.job.cdc.CdcTableSchema;
+import org.apache.doris.job.cdc.DataSourceConfigKeys;
+import org.apache.doris.job.cdc.request.GetTableSchemasRequest;
+import org.apache.doris.job.cdc.response.GetTableSchemasResult;
+
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Types;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Properties;
+import java.util.TreeMap;
+import java.util.stream.Collectors;
+
+import com.mysql.cj.conf.ConnectionUrl;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Service;
+
+/** Stateless source inspection and table-change preparation, without reader
registration. */
+@Service
+public class TableSchemaService {
+ private static final Duration DEFAULT_JDBC_TIMEOUT = Duration.ofMinutes(1);
+
+ public GetTableSchemasResult getTableSchemas(GetTableSchemasRequest
request)
+ throws SQLException {
+ DataSource source =
DataSource.valueOf(request.getDataSource().toUpperCase(Locale.ROOT));
+ Map<String, String> config = request.getConfig();
+ if (request.getFrontendAddress() != null) {
+
Env.getCurrentEnv().setFeMasterAddress(request.getFrontendAddress());
+ }
+ String schema =
+ config.get(
+ source == DataSource.POSTGRES
+ ? DataSourceConfigKeys.SCHEMA
+ : DataSourceConfigKeys.DATABASE);
+ if (schema == null || schema.isEmpty()) {
+ throw new IllegalArgumentException("Source database/schema is
required");
+ }
+ try (Connection connection = openConnection(source, config)) {
+ if (source == DataSource.MYSQL
+ &&
StringUtils.isNotBlank(config.get(DataSourceConfigKeys.TABLE))
+ && connection.getMetaData().storesLowerCaseIdentifiers()) {
+ // Match MySQL lower_case_table_names=1 without rewriting the
TVF reader config.
+ config = new LinkedHashMap<>(config);
+ schema = schema.toLowerCase(Locale.ROOT);
+ config.put(
+ DataSourceConfigKeys.TABLE,
+
config.get(DataSourceConfigKeys.TABLE).toLowerCase(Locale.ROOT));
+ }
+ if (source == DataSource.OCEANBASE) {
+ validateOceanBase(connection);
+ }
+ List<String> tables = selectTables(discoverTables(connection,
source, schema), config);
Review Comment:
[P3] Limit explicit table discovery to the requested names
A single-table `cdc_stream` now calls `discoverTables()` with a null
table-name pattern and materializes every table name in the source schema, then
filters to one. The old TVF passed the requested table to
`JdbcClient.isTableExist()`. On schemas with many tables this adds metadata
work to each statement and every replanned streaming batch. Use a targeted
metadata lookup for explicit single-table requests and retain full enumeration
for jobs that discover all tables.
##########
fs_brokers/cdc_client/src/main/java/org/apache/doris/cdcclient/service/TableSchemaService.java:
##########
@@ -0,0 +1,459 @@
+// 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.cdcclient.service;
+
+import org.apache.doris.cdcclient.common.Env;
+import org.apache.doris.cdcclient.source.factory.DataSource;
+import org.apache.doris.cdcclient.source.schema.CdcSourceColumn;
+import org.apache.doris.cdcclient.utils.CdcTypeMapper;
+import org.apache.doris.cdcclient.utils.ConfigUtil;
+import org.apache.doris.cdcclient.utils.PostgresNumericUtils;
+import org.apache.doris.job.cdc.CdcColumn;
+import org.apache.doris.job.cdc.CdcTableSchema;
+import org.apache.doris.job.cdc.DataSourceConfigKeys;
+import org.apache.doris.job.cdc.request.GetTableSchemasRequest;
+import org.apache.doris.job.cdc.response.GetTableSchemasResult;
+
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Types;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Properties;
+import java.util.TreeMap;
+import java.util.stream.Collectors;
+
+import com.mysql.cj.conf.ConnectionUrl;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Service;
+
+/** Stateless source inspection and table-change preparation, without reader
registration. */
+@Service
+public class TableSchemaService {
+ private static final Duration DEFAULT_JDBC_TIMEOUT = Duration.ofMinutes(1);
+
+ public GetTableSchemasResult getTableSchemas(GetTableSchemasRequest
request)
+ throws SQLException {
+ DataSource source =
DataSource.valueOf(request.getDataSource().toUpperCase(Locale.ROOT));
+ Map<String, String> config = request.getConfig();
+ if (request.getFrontendAddress() != null) {
+
Env.getCurrentEnv().setFeMasterAddress(request.getFrontendAddress());
+ }
+ String schema =
+ config.get(
+ source == DataSource.POSTGRES
+ ? DataSourceConfigKeys.SCHEMA
+ : DataSourceConfigKeys.DATABASE);
+ if (schema == null || schema.isEmpty()) {
+ throw new IllegalArgumentException("Source database/schema is
required");
+ }
+ try (Connection connection = openConnection(source, config)) {
+ if (source == DataSource.MYSQL
+ &&
StringUtils.isNotBlank(config.get(DataSourceConfigKeys.TABLE))
+ && connection.getMetaData().storesLowerCaseIdentifiers()) {
+ // Match MySQL lower_case_table_names=1 without rewriting the
TVF reader config.
+ config = new LinkedHashMap<>(config);
+ schema = schema.toLowerCase(Locale.ROOT);
+ config.put(
+ DataSourceConfigKeys.TABLE,
+
config.get(DataSourceConfigKeys.TABLE).toLowerCase(Locale.ROOT));
+ }
+ if (source == DataSource.OCEANBASE) {
+ validateOceanBase(connection);
+ }
+ List<String> tables = selectTables(discoverTables(connection,
source, schema), config);
+ if (source == DataSource.POSTGRES && !request.isAlterTables()) {
+ PostgresSourceValidator.validate(
+ connection,
+ config,
+ request.getJobId(),
+ schema,
+ tables,
+ request.isCreateJob());
+ }
+ List<CdcTableSchema> schemas = new ArrayList<>();
+ for (String table : tables) {
+ List<String> keys = primaryKeys(connection, source, schema,
table);
+ // Reject keyless job tables before changing the source
publication.
+ if (request.isAlterTables() && keys.isEmpty()) {
+ throw new IllegalArgumentException(
+ "Source table requires a primary key: " + schema +
"." + table);
+ }
+ List<CdcSourceColumn> columns = readColumns(connection,
source, schema, table);
+ if (columns.isEmpty()) {
+ throw new IllegalArgumentException(
+ "Source schema is empty or inaccessible: " +
schema + "." + table);
+ }
+ schemas.add(
+ mapTable(
+ source,
+ source == DataSource.POSTGRES ?
connection.getCatalog() : schema,
+ source == DataSource.POSTGRES ? schema : null,
+ table,
+ columns,
+ keys));
+ }
+ if (source == DataSource.POSTGRES && request.isAlterTables()) {
+ PostgresSourceValidator.ensurePublicationCoversTables(
+ connection, config, request.getJobId(), schema,
tables);
+ }
+ GetTableSchemasResult result = new GetTableSchemasResult();
+ result.setTables(schemas);
+ return result;
+ } catch (SQLException e) {
+ // Driver messages may contain URL credentials; expose stage and
SQL state instead.
+ throw new SQLException(
Review Comment:
[P2] Update MySQL negative tests for schema discovery errors
This boundary returns a sanitized SQL-state message for JDBC failures, but
`test_streaming_mysql_job_create_alter.groovy` still expects `Access denied for
user` and `test_cdc_stream_tvf_mysql.groovy` expects `can not connect to jdbc`.
Their missing-table cases also expect the old JDBC wording. The regression
harness matches these substrings literally, so enabled suites fail even when
discovery rejects the input as intended. Update the assertions to check the
current sanitized diagnostics.
##########
regression-test/suites/job_p0/streaming_job/cdc/test_streaming_postgres_negative_scale.groovy:
##########
@@ -0,0 +1,83 @@
+// 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.
+
+
+import org.awaitility.Awaitility
+
+import static java.util.concurrent.TimeUnit.SECONDS
+
+suite("test_streaming_postgres_negative_scale",
"p0,external,pg,external_docker,external_docker_pg,nondatalake") {
+ if
(!context.config.otherConfigs.get("enableJdbcTest")?.equalsIgnoreCase("true")) {
+ return
+ }
+ def host = context.config.otherConfigs.get("externalEnvIp")
+ def port = context.config.otherConfigs.get("pg_16_port")
+ ?: context.config.otherConfigs.get("pg_15_port") ?:
context.config.otherConfigs.get("pg_14_port")
+ def jdbcUrl = "jdbc:postgresql://${host}:${port}/postgres"
+ int version
+ connect("postgres", "123456", jdbcUrl) {
+ version = (sql "SHOW server_version_num")[0][0].toString().toInteger()
+ }
+ if (version < 150000) {
+ log.info("Skipping negative numeric scale: PostgreSQL 15 or later is
required")
+ return
+ }
+ def currentDb = (sql "SELECT DATABASE()")[0][0]
+ sql "DROP JOB IF EXISTS WHERE jobname='pg_negative_scale_job'"
+ sql "DROP TABLE IF EXISTS cdc_negative_scale_pg FORCE"
+ sql "DROP TABLE IF EXISTS cdc_negative_scale_pg_tvf FORCE"
+ connect("postgres", "123456", jdbcUrl) {
+ sql "CREATE SCHEMA IF NOT EXISTS cdc_test"
+ sql "DROP TABLE IF EXISTS cdc_test.cdc_negative_scale_pg"
+ sql "CREATE TABLE cdc_test.cdc_negative_scale_pg(id INT PRIMARY KEY,
amount NUMERIC(8,-2))"
+ sql "INSERT INTO cdc_test.cdc_negative_scale_pg
VALUES(1,12345),(2,-12345)"
+ }
+ def waitFor = { Closure predicate ->
+ Awaitility.await().atMost(300, SECONDS).pollInterval(2,
SECONDS).until(predicate)
+ }
+ try {
+ sql """CREATE JOB pg_negative_scale_job PROPERTIES
("max_interval"="5") ON STREAMING
+ FROM POSTGRES ("jdbc_url"="${jdbcUrl}", "user"="postgres",
"password"="123456",
+ "database"="postgres", "schema"="cdc_test",
"include_tables"="cdc_negative_scale_pg",
+ "offset"="initial")
+ TO DATABASE ${currentDb}
("table.create.properties.replication_num"="1")"""
+ waitFor { (sql "SELECT COUNT(*) FROM cdc_negative_scale_pg")[0][0] ==
2 }
+ qt_initial_type """SELECT column_name,lower(column_type) FROM
information_schema.columns
+ WHERE table_schema='${currentDb}' AND
table_name='cdc_negative_scale_pg'
+ AND column_name='amount'"""
+ qt_snapshot "SELECT id,amount FROM cdc_negative_scale_pg ORDER BY id"
+ sql """CREATE TABLE cdc_negative_scale_pg_tvf PROPERTIES
("replication_num"="1") AS
+ SELECT * FROM cdc_stream("type"="postgres",
"jdbc_url"="${jdbcUrl}",
+ "user"="postgres", "password"="123456",
"database"="postgres", "schema"="cdc_test",
+ "table"="cdc_negative_scale_pg", "offset"="initial")"""
Review Comment:
[P2] Supply split metadata for the negative-scale TVF snapshot
This CTAS reads a standalone `cdc_stream`. It sends neither a task ID nor
split metadata, so `PipelineCoordinator.generateMeta()` rejects
`offset=initial` before the TVF snapshot and schema-evolution assertions. Use
the same approach as the neighboring PostgreSQL contract suite, with `LIMIT 0`
for CTAS and a streaming INSERT job that supplies snapshot splits.
##########
fs_brokers/cdc_client/src/main/java/org/apache/doris/cdcclient/service/TableSchemaService.java:
##########
@@ -0,0 +1,459 @@
+// 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.cdcclient.service;
+
+import org.apache.doris.cdcclient.common.Env;
+import org.apache.doris.cdcclient.source.factory.DataSource;
+import org.apache.doris.cdcclient.source.schema.CdcSourceColumn;
+import org.apache.doris.cdcclient.utils.CdcTypeMapper;
+import org.apache.doris.cdcclient.utils.ConfigUtil;
+import org.apache.doris.cdcclient.utils.PostgresNumericUtils;
+import org.apache.doris.job.cdc.CdcColumn;
+import org.apache.doris.job.cdc.CdcTableSchema;
+import org.apache.doris.job.cdc.DataSourceConfigKeys;
+import org.apache.doris.job.cdc.request.GetTableSchemasRequest;
+import org.apache.doris.job.cdc.response.GetTableSchemasResult;
+
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Types;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Properties;
+import java.util.TreeMap;
+import java.util.stream.Collectors;
+
+import com.mysql.cj.conf.ConnectionUrl;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Service;
+
+/** Stateless source inspection and table-change preparation, without reader
registration. */
+@Service
+public class TableSchemaService {
+ private static final Duration DEFAULT_JDBC_TIMEOUT = Duration.ofMinutes(1);
+
+ public GetTableSchemasResult getTableSchemas(GetTableSchemasRequest
request)
+ throws SQLException {
+ DataSource source =
DataSource.valueOf(request.getDataSource().toUpperCase(Locale.ROOT));
+ Map<String, String> config = request.getConfig();
+ if (request.getFrontendAddress() != null) {
+
Env.getCurrentEnv().setFeMasterAddress(request.getFrontendAddress());
+ }
+ String schema =
+ config.get(
+ source == DataSource.POSTGRES
+ ? DataSourceConfigKeys.SCHEMA
+ : DataSourceConfigKeys.DATABASE);
+ if (schema == null || schema.isEmpty()) {
+ throw new IllegalArgumentException("Source database/schema is
required");
+ }
+ try (Connection connection = openConnection(source, config)) {
+ if (source == DataSource.MYSQL
+ &&
StringUtils.isNotBlank(config.get(DataSourceConfigKeys.TABLE))
+ && connection.getMetaData().storesLowerCaseIdentifiers()) {
+ // Match MySQL lower_case_table_names=1 without rewriting the
TVF reader config.
+ config = new LinkedHashMap<>(config);
+ schema = schema.toLowerCase(Locale.ROOT);
+ config.put(
+ DataSourceConfigKeys.TABLE,
+
config.get(DataSourceConfigKeys.TABLE).toLowerCase(Locale.ROOT));
+ }
+ if (source == DataSource.OCEANBASE) {
+ validateOceanBase(connection);
+ }
+ List<String> tables = selectTables(discoverTables(connection,
source, schema), config);
+ if (source == DataSource.POSTGRES && !request.isAlterTables()) {
+ PostgresSourceValidator.validate(
+ connection,
+ config,
+ request.getJobId(),
+ schema,
+ tables,
+ request.isCreateJob());
+ }
+ List<CdcTableSchema> schemas = new ArrayList<>();
+ for (String table : tables) {
+ List<String> keys = primaryKeys(connection, source, schema,
table);
+ // Reject keyless job tables before changing the source
publication.
+ if (request.isAlterTables() && keys.isEmpty()) {
+ throw new IllegalArgumentException(
+ "Source table requires a primary key: " + schema +
"." + table);
+ }
+ List<CdcSourceColumn> columns = readColumns(connection,
source, schema, table);
+ if (columns.isEmpty()) {
+ throw new IllegalArgumentException(
+ "Source schema is empty or inaccessible: " +
schema + "." + table);
+ }
+ schemas.add(
+ mapTable(
+ source,
+ source == DataSource.POSTGRES ?
connection.getCatalog() : schema,
+ source == DataSource.POSTGRES ? schema : null,
+ table,
+ columns,
+ keys));
+ }
+ if (source == DataSource.POSTGRES && request.isAlterTables()) {
+ PostgresSourceValidator.ensurePublicationCoversTables(
+ connection, config, request.getJobId(), schema,
tables);
+ }
+ GetTableSchemasResult result = new GetTableSchemasResult();
+ result.setTables(schemas);
+ return result;
+ } catch (SQLException e) {
+ // Driver messages may contain URL credentials; expose stage and
SQL state instead.
+ throw new SQLException(
+ "Failed to inspect source schema "
+ + schema
+ + " (SQL state "
+ + e.getSQLState()
+ + ")",
+ e.getSQLState(),
+ e);
+ }
+ }
+
+ static List<String> selectTables(List<String> tables, Map<String, String>
config) {
+ String selected = config.get(DataSourceConfigKeys.INCLUDE_TABLES);
+ if (selected == null || selected.trim().isEmpty()) {
+ selected = config.get(DataSourceConfigKeys.TABLE);
+ }
+ List<String> include = names(selected);
+ List<String> exclude =
names(config.get(DataSourceConfigKeys.EXCLUDE_TABLES));
+ for (String name : include) {
+ if (!tables.contains(name)) {
+ throw new IllegalArgumentException(
+ "Source table does not exist or is inaccessible: " +
name);
+ }
+ }
+ List<String> result =
+ tables.stream()
+ .filter(
+ t ->
+ !include.isEmpty()
+ ? include.contains(t)
+ : !exclude.contains(t))
+ .collect(Collectors.toList());
+ if (result.isEmpty()) {
+ throw new IllegalArgumentException("No matching source tables
found");
+ }
+ return result;
+ }
+
+ private static List<String> names(String value) {
+ return value == null || value.trim().isEmpty()
+ ? Collections.emptyList()
+ : Arrays.stream(value.split(","))
+ .map(String::trim)
+ .filter(s -> !s.isEmpty())
+ .collect(Collectors.toList());
+ }
+
+ static List<String> discoverTables(Connection connection, DataSource
source, String schema)
+ throws SQLException {
+ boolean postgres = source == DataSource.POSTGRES;
+ String catalog = postgres ? connection.getCatalog() : schema;
+ String[] tableTypes =
+ postgres ? new String[] {"TABLE", "PARTITIONED TABLE"} : new
String[] {"TABLE"};
+ DatabaseMetaData metadata = connection.getMetaData();
+ String schemaPattern = schema;
+ if (postgres) {
+ String escape = metadata.getSearchStringEscape();
+ schemaPattern = schema.replace(escape, escape + escape);
+ }
+ List<String> tables = new ArrayList<>();
+ // Connector/J uses either catalog or schema according to databaseTerm.
+ try (ResultSet rs = metadata.getTables(catalog, schemaPattern, null,
tableTypes)) {
+ while (rs.next()) {
+ if (schema.equals(rs.getString("TABLE_SCHEM"))
+ || (!postgres &&
schema.equals(rs.getString("TABLE_CAT")))) {
+ tables.add(rs.getString("TABLE_NAME"));
+ }
+ }
+ }
+ return tables;
+ }
+
+ static List<String> primaryKeys(
+ Connection connection, DataSource source, String schema, String
table)
+ throws SQLException {
+ Map<Integer, String> keys = new TreeMap<>();
+ try (ResultSet rs =
+ connection
+ .getMetaData()
+ .getPrimaryKeys(
+ source == DataSource.POSTGRES ?
connection.getCatalog() : schema,
+ schema,
+ table)) {
+ while (rs.next()) {
+ keys.put(rs.getInt("KEY_SEQ"), rs.getString("COLUMN_NAME"));
+ }
+ }
+ return new ArrayList<>(keys.values());
+ }
+
+ private static List<CdcSourceColumn> readColumns(
+ Connection connection, DataSource source, String schema, String
table)
+ throws SQLException {
+ return source == DataSource.POSTGRES
+ ? readPostgresColumns(connection, schema, table)
+ : readMysqlColumns(connection, schema, table);
+ }
+
+ static List<CdcSourceColumn> readPostgresColumns(
+ Connection connection, String schema, String table) throws
SQLException {
+ List<CdcSourceColumn> columns = new ArrayList<>();
+ DatabaseMetaData metadata = connection.getMetaData();
+ String escape = metadata.getSearchStringEscape();
+ try (ResultSet rs =
+ metadata.getColumns(
+ connection.getCatalog(),
+ schema.replace(escape, escape + escape),
+ table.replace(escape, escape + escape),
+ null)) {
+ while (rs.next()) {
+ // JDBC schema/table arguments are patterns, so retain only
the exact source table.
+ if (!schema.equals(rs.getString("TABLE_SCHEM"))
+ || !table.equals(rs.getString("TABLE_NAME"))) {
+ continue;
+ }
+ String type = rs.getString("TYPE_NAME");
+ Integer scale = integer(rs, "DECIMAL_DIGITS");
+ if (scale != null && (type.equals("numeric") ||
type.equals("_numeric"))) {
+ scale = PostgresNumericUtils.normalizeScale(scale);
+ }
+ Integer size = integer(rs, "COLUMN_SIZE");
+ CdcSourceColumn column =
+ CdcSourceColumn.builder()
+ .name(rs.getString("COLUMN_NAME"))
+ .nativeType(type)
+ .length(size)
+ .precision(size)
+ .scale(scale)
+
.nullable("YES".equals(rs.getString("IS_NULLABLE")))
+ .comment(rs.getString("REMARKS"))
+ .build();
+ if (rs.getInt("DATA_TYPE") == Types.ARRAY) {
+ column.setArrayDimensions(
+ readPostgresArrayDimensions(
+ connection, schema, table,
column.getName()));
+ }
+ columns.add(column);
+ }
+ }
+ return columns;
+ }
+
+ private static int readPostgresArrayDimensions(
+ Connection connection, String schema, String table, String column)
throws SQLException {
+ // JDBC exposes element precision/scale, but not the declared array
dimensions.
+ String query =
+ "SELECT a.attndims FROM pg_catalog.pg_attribute a "
Review Comment:
[P2] Preserve one-dimensional data in PostgreSQL array columns
PostgreSQL permits a column declared `INT[][]` to contain a one-dimensional
value such as `ARRAY[1,2]`. For a table with that single non-null value, the
old JDBC lookup sampled `array_ndims()` and inferred `ARRAY<INT>`. Here
`attndims` returns 2 and the mapper rejects the column, blocking a new job or a
TVF query against previously supported data. Determine supported shape from the
values or otherwise preserve this case, and check both mismatches between
declaration and stored shape.
##########
fs_brokers/cdc_client/src/main/java/org/apache/doris/cdcclient/source/reader/postgres/PostgresNumericConverter.java:
##########
@@ -0,0 +1,130 @@
+// 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.cdcclient.source.reader.postgres;
+
+import org.apache.doris.cdcclient.utils.PostgresNumericUtils;
+
+import org.apache.kafka.connect.data.Schema;
+import org.apache.kafka.connect.data.SchemaBuilder;
+import org.apache.kafka.connect.errors.ConnectException;
+
+import java.math.BigDecimal;
+import java.sql.Array;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Types;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+
+import io.debezium.connector.postgresql.PgOid;
+import io.debezium.connector.postgresql.PostgresValueConverter;
+import io.debezium.data.SpecialValueDecimal;
+import io.debezium.data.VariableScaleDecimal;
+import io.debezium.jdbc.JdbcValueConverters.DecimalMode;
+import io.debezium.spi.converter.CustomConverter;
+import io.debezium.spi.converter.RelationalColumn;
+
+/** Preserves finite PostgreSQL numerics and maps special values to NULL. */
+public class PostgresNumericConverter implements
CustomConverter<SchemaBuilder, RelationalColumn> {
+ // Unconstrained numeric metadata may report the JDBC display length
instead of precision.
+ private static final int VARIABLE_SCALE_DECIMAL_LENGTH = 131089;
+
+ @Override
+ public void configure(Properties properties) {}
+
+ /**
+ * Schema selection adapted from
PostgresValueConverter.numericSchema/isVariableScaleDecimal in
+ * Debezium 1.9.8.Final, with normalized scale and nullable special values.
+ */
+ @Override
+ public void converterFor(
+ RelationalColumn field, ConverterRegistration<SchemaBuilder>
registration) {
+ boolean array = field.nativeType() == PgOid.NUMERIC_ARRAY;
+ if (!array && field.nativeType() != PgOid.NUMERIC) {
+ return;
+ }
+ int scale =
PostgresNumericUtils.normalizeScale(field.scale().orElse(0));
+ int precision = field.length().orElse(-1);
+ boolean variable =
+ (precision == 0 || precision == VARIABLE_SCALE_DECIMAL_LENGTH)
&& scale == 0;
+ SchemaBuilder decimal =
+ variable
+ ? VariableScaleDecimal.builder()
+ : SpecialValueDecimal.builder(DecimalMode.PRECISE,
precision, scale);
+ // Special values can produce NULL even for a NOT NULL source column.
+ Schema elementSchema = decimal.optional().build();
+ SchemaBuilder schema = array ? SchemaBuilder.array(elementSchema) :
decimal;
+ registration.register(
+ schema,
+ value -> {
+ if (value == null) {
+ return null;
+ }
+ return array
+ ? numericArray((Array) value, elementSchema,
variable, scale)
+ : decimal(value, elementSchema, variable, scale);
+ });
+ }
+
+ /**
+ * Adapted from PostgresValueConverter.convertDecimal and
+ * JdbcValueConverters.withScaleAdjustedIfNeeded in Debezium 1.9.8.Final.
Maps special values to
+ * NULL and also aligns negative scales.
+ */
+ private static Object decimal(Object value, Schema schema, boolean
variable, int scale) {
+ if (value instanceof SpecialValueDecimal) {
+ value = ((SpecialValueDecimal)
value).getDecimalValue().orElse(null);
+ }
+ if (value == null) {
+ return null;
+ }
+ BigDecimal decimal = (BigDecimal) value;
+ if (variable) {
+ decimal = decimal.stripTrailingZeros();
+ if (decimal.scale() < 0) {
+ decimal = decimal.setScale(0);
+ }
+ return VariableScaleDecimal.fromLogical(schema, decimal);
+ }
+ return scale < 0 || scale > decimal.scale() ? decimal.setScale(scale)
: decimal;
Review Comment:
[P2] Preserve plain text for negative-scale PostgreSQL numerics
A `NUMERIC(8,-2)` value stored in PostgreSQL as `12300` gets a `BigDecimal`
scale of `-2` here. The default Jackson writer emits `1.23E+4`.
`PostgresTypeMapper` chooses a Doris STRING column and the BE JSON reader
preserves the numeric token as text, so the stored value differs from the new
suite's `12300` expectation. The mock integration test compares numeric values
and misses the difference. Emit plain decimal text for this fallback and assert
the exact value at the Doris target.
##########
fs_brokers/cdc_client/src/main/java/org/apache/doris/cdcclient/service/TableSchemaService.java:
##########
@@ -0,0 +1,459 @@
+// 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.cdcclient.service;
+
+import org.apache.doris.cdcclient.common.Env;
+import org.apache.doris.cdcclient.source.factory.DataSource;
+import org.apache.doris.cdcclient.source.schema.CdcSourceColumn;
+import org.apache.doris.cdcclient.utils.CdcTypeMapper;
+import org.apache.doris.cdcclient.utils.ConfigUtil;
+import org.apache.doris.cdcclient.utils.PostgresNumericUtils;
+import org.apache.doris.job.cdc.CdcColumn;
+import org.apache.doris.job.cdc.CdcTableSchema;
+import org.apache.doris.job.cdc.DataSourceConfigKeys;
+import org.apache.doris.job.cdc.request.GetTableSchemasRequest;
+import org.apache.doris.job.cdc.response.GetTableSchemasResult;
+
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Types;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Properties;
+import java.util.TreeMap;
+import java.util.stream.Collectors;
+
+import com.mysql.cj.conf.ConnectionUrl;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Service;
+
+/** Stateless source inspection and table-change preparation, without reader
registration. */
+@Service
+public class TableSchemaService {
+ private static final Duration DEFAULT_JDBC_TIMEOUT = Duration.ofMinutes(1);
+
+ public GetTableSchemasResult getTableSchemas(GetTableSchemasRequest
request)
+ throws SQLException {
+ DataSource source =
DataSource.valueOf(request.getDataSource().toUpperCase(Locale.ROOT));
+ Map<String, String> config = request.getConfig();
+ if (request.getFrontendAddress() != null) {
+
Env.getCurrentEnv().setFeMasterAddress(request.getFrontendAddress());
+ }
+ String schema =
+ config.get(
+ source == DataSource.POSTGRES
+ ? DataSourceConfigKeys.SCHEMA
+ : DataSourceConfigKeys.DATABASE);
+ if (schema == null || schema.isEmpty()) {
+ throw new IllegalArgumentException("Source database/schema is
required");
+ }
+ try (Connection connection = openConnection(source, config)) {
+ if (source == DataSource.MYSQL
+ &&
StringUtils.isNotBlank(config.get(DataSourceConfigKeys.TABLE))
+ && connection.getMetaData().storesLowerCaseIdentifiers()) {
+ // Match MySQL lower_case_table_names=1 without rewriting the
TVF reader config.
+ config = new LinkedHashMap<>(config);
+ schema = schema.toLowerCase(Locale.ROOT);
+ config.put(
+ DataSourceConfigKeys.TABLE,
+
config.get(DataSourceConfigKeys.TABLE).toLowerCase(Locale.ROOT));
+ }
+ if (source == DataSource.OCEANBASE) {
+ validateOceanBase(connection);
+ }
+ List<String> tables = selectTables(discoverTables(connection,
source, schema), config);
+ if (source == DataSource.POSTGRES && !request.isAlterTables()) {
+ PostgresSourceValidator.validate(
+ connection,
+ config,
+ request.getJobId(),
+ schema,
+ tables,
+ request.isCreateJob());
+ }
+ List<CdcTableSchema> schemas = new ArrayList<>();
+ for (String table : tables) {
+ List<String> keys = primaryKeys(connection, source, schema,
table);
+ // Reject keyless job tables before changing the source
publication.
+ if (request.isAlterTables() && keys.isEmpty()) {
+ throw new IllegalArgumentException(
+ "Source table requires a primary key: " + schema +
"." + table);
+ }
+ List<CdcSourceColumn> columns = readColumns(connection,
source, schema, table);
+ if (columns.isEmpty()) {
+ throw new IllegalArgumentException(
+ "Source schema is empty or inaccessible: " +
schema + "." + table);
+ }
+ schemas.add(
+ mapTable(
+ source,
+ source == DataSource.POSTGRES ?
connection.getCatalog() : schema,
+ source == DataSource.POSTGRES ? schema : null,
+ table,
+ columns,
+ keys));
+ }
+ if (source == DataSource.POSTGRES && request.isAlterTables()) {
+ PostgresSourceValidator.ensurePublicationCoversTables(
Review Comment:
[P2] Validate target changes before extending the PostgreSQL publication
For a paused job with a Doris-owned publication, add a source table that has
a primary key and a `money` column, with no precreated Doris target. The client
records the unsupported type, adds the table to the publication here, and
returns the schema. FE then rejects the mapping in
`StreamingJobUtils.generateCreateTableCmds()`. ALTER fails and the job keeps
its old table list, but PostgreSQL has committed the publication change. Keep
discovery read-only until FE has validated the mapping and prepared the targets.
--
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]