hello-stephen commented on code in PR #71298: URL: https://github.com/apache/doris/pull/71298#discussion_r4798333268
########## fs_brokers/cdc_client/src/main/java/org/apache/doris/cdcclient/utils/PostgresTypeMapper.java: ########## @@ -0,0 +1,122 @@ +// 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.utils; + +import org.apache.doris.cdcclient.common.DorisType; +import org.apache.doris.cdcclient.source.schema.CdcSourceColumn; + +import java.util.Locale; + +import static org.apache.doris.cdcclient.utils.CdcTypeMapper.charToDorisType; +import static org.apache.doris.cdcclient.utils.CdcTypeMapper.require; +import static org.apache.doris.cdcclient.utils.CdcTypeMapper.value; + +public final class PostgresTypeMapper implements CdcTypeMapper { + @Override + public String mapType(CdcSourceColumn column) { + boolean array = column.getArrayDimensions() != null; + String nativeType = column.getNativeType(); + if (array) { + require(column.getArrayDimensions() == 1, column, "one-dimensional array element"); + nativeType = nativeType.substring(1); + } + Integer precision = + "numeric".equalsIgnoreCase(nativeType) ? column.getPrecision() : column.getLength(); + String type = pgType(nativeType, value(precision), value(column.getScale())); + if (array) { + // Keep bpchar elements as strings; table arrays cannot contain JSON. + String elementType = + "bpchar".equalsIgnoreCase(nativeType) || DorisType.JSON.equals(type) + ? DorisType.STRING + : type; + return DorisType.ARRAY + "<" + elementType + ">"; + } + return type; + } + + /** Map a PostgreSQL native type name to a Doris type string. */ + private static String pgType(String pgTypeName, int length, int scale) { + switch (pgTypeName.toLowerCase(Locale.ROOT)) { + case "bool": + return DorisType.BOOLEAN; + case "bit": + return length == 1 ? DorisType.BOOLEAN : DorisType.STRING; + case "int2": + case "smallserial": + return DorisType.SMALLINT; + case "int4": + case "serial": + return DorisType.INT; + case "int8": + case "bigserial": + return DorisType.BIGINT; + case "float4": + return DorisType.FLOAT; + case "float8": + return DorisType.DOUBLE; + case "numeric": + { + if (length <= 0 + || length > MAX_DECIMAL128_PRECISION + || scale < 0 + || scale > length) { + return DorisType.STRING; + } + return DorisType.DECIMAL + "(" + length + "," + scale + ")"; + } + case "bpchar": + return charToDorisType(length); + case "date": + return DorisType.DATE; + case "timestamp": + case "timestamptz": + { + int timeScale = scale >= 0 && scale <= 6 ? scale : 6; + return DorisType.DATETIME + "(" + timeScale + ")"; + } + // All remaining types map to STRING (aligned with JdbcPostgreSQLClient) + case "point": + case "line": + case "lseg": + case "box": + case "path": + case "polygon": + case "circle": + case "varchar": + case "text": + case "time": + case "timetz": + case "interval": + case "cidr": + case "inet": + case "macaddr": + case "macaddr8": + case "varbit": + case "uuid": + case "bytea": + case "xml": + case "hstore": + return DorisType.STRING; + case "json": + case "jsonb": + return DorisType.JSON; Review Comment: [P2] Preserve exact decimals in PostgreSQL JSON documents A PostgreSQL JSONB value such as `{"n":1.2345678901234567890123456789}` was preserved as text by the previous STRING mapping. The new JSON mapping sends it through the BE JSONB parser, which stores fractional numbers as binary64 doubles and silently rounds this value. Both automatic target creation and CDC TVF reads now take that path. Preserve a lossless mapping or make the conversion opt-in, and assert the exact nested decimal through a real Doris sink. The mock contract test uses an integer that fits in int64. ########## 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(); + var future = BackendServiceProxy.getInstance().requestCdcClient( + new TNetworkAddress(backend.getHost(), backend.getBrpcPort()), rpc, + Config.streaming_cdc_heavy_rpc_timeout_sec); + if (future == null) { + throw new JobException("Failed to start source schema RPC on backend " + backend.getId()); + } + var result = future.get(Config.streaming_cdc_heavy_rpc_timeout_sec, TimeUnit.SECONDS); + if (TStatusCode.findByValue(result.getStatus().getStatusCode()) != TStatusCode.OK) { + throw new JobException("Source schema RPC failed on backend " + backend.getId() + + ": " + result.getStatus().getErrorMsgsList()); + } + return parseResponse(result.getResponse(), request); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new JobException("Source schema RPC interrupted", e); + } catch (JobException e) { + throw e; + } catch (Exception e) { + throw new JobException("Source schema RPC failed on backend " + backend.getId() + ": " + e, e); + } + } + + static List<CdcTableSchema> parseResponse(String response, GetTableSchemasRequest request) throws JobException { + GetTableSchemasResult result; + try { + JsonNode envelope = MAPPER.readTree(response); + // Validate the envelope before binding: an absent code must not become a success by default. + if (envelope == null || !envelope.isObject() || !envelope.path("code").isInt()) { + throw new JobException("Invalid getTableSchemas response; ensure FE and CDC client versions match"); + } + if (envelope.get("code").asInt() != 0) { + throw new JobException("Source schema inspection failed: " + envelope.path("data").asText("CDC error")); + } + result = MAPPER.treeToValue(envelope.get("data"), GetTableSchemasResult.class); + } catch (JsonProcessingException e) { + throw new JobException("Invalid getTableSchemas response; ensure FE and CDC client versions match", e); + } + if (result == null || result.getTables() == null || result.getTables().isEmpty()) { + throw new JobException("Empty getTableSchemas response"); + } + Set<String> tables = new HashSet<>(); + for (CdcTableSchema table : result.getTables()) { + validateTableSchema(table, request); + if (!tables.add(table.getTableName())) { + throw new JobException("Duplicate source table in getTableSchemas response: " + table.getTableName()); + } + } + return result.getTables(); + } + + private static void validateTableSchema(CdcTableSchema table, GetTableSchemasRequest request) throws JobException { + if (table == null || StringUtils.isEmpty(table.getTableName())) { + throw new JobException("Missing source table name in getTableSchemas response"); + } + // MySQL uses database/table; PG uses database/schema/table and may take its database from the URL. + boolean postgres = "POSTGRES".equalsIgnoreCase(request.getDataSource()); + String schema = postgres ? request.getConfig().get(DataSourceConfigKeys.SCHEMA) : null; + String database = request.getConfig().get(DataSourceConfigKeys.DATABASE); + boolean databaseMatches = Objects.equals(database, table.getDatabaseName()); + if (!databaseMatches && database != null + && "MYSQL".equalsIgnoreCase(request.getDataSource())) { + // CDC validates the source case setting before returning a lowercase TVF database. + databaseMatches = database.toLowerCase(Locale.ROOT).equals(table.getDatabaseName()); + } + if (StringUtils.isBlank(table.getDatabaseName()) + || ((database != null || !postgres) && !databaseMatches) Review Comment: [P2] Preserve the URL database when a PostgreSQL TVF supplies an empty database Existing `cdc_stream` SQL can expressly set `"database"=""`. The PostgreSQL reader treats the empty value as omitted and connects to the database in `jdbc_url`. The discovery connection only falls back for null, and this validation rejects a response with the URL database because it compares it with the empty string. Normalize the optional database consistently and add a saved TVF job test for this form. ########## fs_brokers/cdc_client/src/main/java/org/apache/doris/cdcclient/utils/PostgresTypeMapper.java: ########## @@ -0,0 +1,122 @@ +// 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.utils; + +import org.apache.doris.cdcclient.common.DorisType; +import org.apache.doris.cdcclient.source.schema.CdcSourceColumn; + +import java.util.Locale; + +import static org.apache.doris.cdcclient.utils.CdcTypeMapper.charToDorisType; +import static org.apache.doris.cdcclient.utils.CdcTypeMapper.require; +import static org.apache.doris.cdcclient.utils.CdcTypeMapper.value; + +public final class PostgresTypeMapper implements CdcTypeMapper { + @Override + public String mapType(CdcSourceColumn column) { + boolean array = column.getArrayDimensions() != null; + String nativeType = column.getNativeType(); + if (array) { + require(column.getArrayDimensions() == 1, column, "one-dimensional array element"); + nativeType = nativeType.substring(1); + } + Integer precision = + "numeric".equalsIgnoreCase(nativeType) ? column.getPrecision() : column.getLength(); + String type = pgType(nativeType, value(precision), value(column.getScale())); + if (array) { + // Keep bpchar elements as strings; table arrays cannot contain JSON. + String elementType = + "bpchar".equalsIgnoreCase(nativeType) || DorisType.JSON.equals(type) + ? DorisType.STRING + : type; + return DorisType.ARRAY + "<" + elementType + ">"; + } + return type; + } + + /** Map a PostgreSQL native type name to a Doris type string. */ + private static String pgType(String pgTypeName, int length, int scale) { + switch (pgTypeName.toLowerCase(Locale.ROOT)) { + case "bool": + return DorisType.BOOLEAN; + case "bit": + return length == 1 ? DorisType.BOOLEAN : DorisType.STRING; + case "int2": + case "smallserial": + return DorisType.SMALLINT; + case "int4": + case "serial": + return DorisType.INT; + case "int8": + case "bigserial": + return DorisType.BIGINT; + case "float4": + return DorisType.FLOAT; + case "float8": + return DorisType.DOUBLE; + case "numeric": + { + if (length <= 0 + || length > MAX_DECIMAL128_PRECISION + || scale < 0 + || scale > length) { + return DorisType.STRING; + } + return DorisType.DECIMAL + "(" + length + "," + scale + ")"; + } + case "bpchar": + return charToDorisType(length); + case "date": + return DorisType.DATE; + case "timestamp": + case "timestamptz": + { + int timeScale = scale >= 0 && scale <= 6 ? scale : 6; + return DorisType.DATETIME + "(" + timeScale + ")"; + } + // All remaining types map to STRING (aligned with JdbcPostgreSQLClient) + case "point": + case "line": + case "lseg": + case "box": + case "path": + case "polygon": + case "circle": + case "varchar": + case "text": + case "time": + case "timetz": + case "interval": + case "cidr": + case "inet": + case "macaddr": + case "macaddr8": + case "varbit": + case "uuid": Review Comment: [P2] Preserve UUID comparison semantics in existing CDC TVF queries A PostgreSQL TVF column containing `550e8400-e29b-41d4-a716-446655440000` previously matched the SQL predicate `u = '550E8400-E29B-41D4-A716-446655440000'` because Nereids coerced the literal to UUID. This mapping turns that predicate into string equality against the canonical lowercase value, so replanning the same saved INSERT can silently omit matching rows. Preserve native UUID output for the TVF or provide a compatibility path for these predicates. ########## fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/AlterJobCommand.java: ########## @@ -346,7 +348,8 @@ private void checkUnmodifiableProperties(String originExecuteSql) throws Analysi "The '%s' property cannot be modified in ALTER JOB for cdc_stream", unmodifiable); } // Validate merged resource properties as the ALTER caller, before schema discovery. - new CdcStreamTableValuedFunction(inputTvf.getProperties().getMap()).checkAuth(ConnectContext.get()); + new CdcStreamTableValuedFunction(inputTvf.getProperties().getMap(), false) Review Comment: [P2] Resolve CDC TVF certificates in the job database during ALTER A paused job created in database A can be altered from database B while keeping the INSERT target fully qualified. This constructor resolves `FILE:ca.pem` in the ALTER session’s database, while provider refresh and execution resolve it in the job’s stored database A. A credential rotation can fail when the cert exists only in A, or validate a cert in B that the job cannot use. Resolve the reference against the stored job database while checking privileges as the ALTER caller. ########## fe/fe-core/src/main/java/org/apache/doris/httpv2/rest/StreamingJobAction.java: ########## @@ -83,30 +88,60 @@ public Object reportTaskFailure(@RequestBody TaskFailureRequest failureRequest, } @RequestMapping(path = "/api/streaming/schema_change", method = RequestMethod.POST) - public Object executeSchemaChange(@RequestBody Map<String, String> body, HttpServletRequest request) { + public Object executeSchemaChange(@RequestBody AlterTableRequest body, HttpServletRequest request) { checkAuth(request); if (!Env.getCurrentEnv().isMaster()) { return ResponseEntityBuilder.okWithCommonError("Schema change must be executed on the master FE"); } - String stmt = body.get("stmt"); - if (Strings.isNullOrEmpty(stmt)) { - return ResponseEntityBuilder.badRequest("Missing statement request body"); + StreamingInsertJob job = getStreamingJob(request); + ConnectContext ctx = createJobContext(job, request); + AlterTableCommand command; + try { + if (Strings.isNullOrEmpty(job.getTargetDb()) || job.getSyncTables() == null) { + throw new IllegalArgumentException("Schema change requires a FROM-TO streaming job"); + } + command = StreamingJobUtils.toCdcAlterTableCommand(job.getTargetDb(), body); + Map<String, String> properties = job.getSourceProperties() == null + ? Collections.emptyMap() : job.getSourceProperties(); + String target = command.getTbl().getTbl(); + boolean inScope = job.getSyncTables().stream() + .map(source -> StreamingJobUtils.resolveTargetTableName(job.getTargetDb(), properties, source)) + .anyMatch(target::equals); + if (!inScope) { + throw new IllegalArgumentException("Table is outside streaming job scope: " + body.getTableName()); + } + } catch (IllegalArgumentException e) { + return ResponseEntityBuilder.badRequest(e.getMessage()); } - ConnectContext ctx = createJobContext(request); + String sql = command.toSql(); + LOG.info("Executing schema change for job {}: {}", job.getJobId(), sql); try (AutoCloseConnectContext ignored = new AutoCloseConnectContext(ctx)) { - if (!(new NereidsParser().parseSingle(stmt) instanceof AlterTableCommand)) { - return ResponseEntityBuilder.badRequest("Only one ALTER TABLE statement is allowed"); - } - StmtExecutor executor = new StmtExecutor(ctx, stmt); - executor.execute(); + ctx.setDatabase(job.getTargetDb()); + command.run(ctx, new StmtExecutor(ctx, sql)); Review Comment: [P2] Honor blocked ALTER commands during CDC schema changes The previous endpoint used `StmtExecutor.execute()`, which applies `block_sql_ast_names` to `AlterTableCommand` before running it. With that class blocked, the direct `command.run()` still performs automatic ADD or DROP for a streaming job whose creator has ALTER privileges. Apply the same AST block check to the typed command and cover this operator setting in the handler test. -- 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]
