xiangfu0 commented on code in PR #20187:
URL: https://github.com/apache/pinot/pull/20187#discussion_r4705277318


##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/PinotHelixResourceManager.java:
##########
@@ -2053,7 +2081,10 @@ public void addTable(TableConfig tableConfig, 
List<StreamMetadata> streamMetadat
 
     // Add table config
     LOGGER.info("Adding table {}: Creating table config in the property 
store", tableNameWithType);
-    if (!ZKMetadataProvider.createTableConfig(_propertyStore, tableConfig)) {
+    if (requireRawNameAbsent) {
+      createFirstTableConfig(getOrBuildMultiWriteZkClient(), 
PropertyPathBuilder.propertyStore(_helixClusterName),
+          tableConfig);

Review Comment:
   Removed the dedicated ZooKeeper publisher and schema fence in 2ace7bc0ea. 
CREATE TABLE LIKE now uses the existing addSchema and addTable calls, so a 
config write and its read-back use the Helix property store. The new controller 
test copies a hybrid table, verifies both variants and fresh consuming 
segments, and retries with IF NOT EXISTS.



##########
pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotDdlRestletResource.java:
##########
@@ -253,6 +262,249 @@ public Response executeDdl(
     }
   }
 
+  // 
-------------------------------------------------------------------------------------------
+  // Table DDL: CREATE TABLE LIKE
+  // 
-------------------------------------------------------------------------------------------
+
+  private Response executeCreateLike(CompiledCreateTableLike create, String 
database, boolean dryRun,
+      HttpHeaders headers, Request httpRequest) {
+    if (TableNameBuilder.isTableResource(create.getRawTableName())
+        || TableNameBuilder.isTableResource(create.getSourceRawTableName())) {
+      throw badRequest("CREATE TABLE LIKE requires raw table names without 
_OFFLINE or _REALTIME suffixes. "
+          + "Use TYPE OFFLINE or TYPE REALTIME to select a source variant.");
+    }
+    String targetName = translateTableNameForDdl(create.getDatabaseName() == 
null
+        ? create.getRawTableName()
+        : create.getDatabaseName() + "." + create.getRawTableName(), headers);
+    // An explicit source qualifier is independent of the target's 
database/header. An unqualified
+    // source uses the request database, never the explicit target qualifier.
+    String sourceDatabase = create.getSourceDatabaseName();
+    if (sourceDatabase == null && headers != null) {
+      sourceDatabase = headers.getHeaderString(DATABASE);
+    }
+    String sourceName;
+    try {
+      sourceName = 
DatabaseUtils.translateTableName(create.getSourceRawTableName(), 
sourceDatabase);
+    } catch (DatabaseConflictException | IllegalArgumentException e) {
+      throw badRequest("Invalid source table reference: " + e.getMessage());
+    }
+
+    TableType sourceType = create.getTableType();
+    List<TableType> sourceTypes = sourceType == null
+        ? List.of(TableType.OFFLINE, TableType.REALTIME)
+        : List.of(sourceType);
+    for (TableType candidate : sourceTypes) {
+      
ResourceUtils.checkPermissionAndAccess(TableNameBuilder.forType(candidate).tableNameWithType(sourceName),
+          httpRequest, headers, AccessType.READ, 
Actions.Table.GET_TABLE_CONFIG, _accessControlFactory, LOGGER);
+    }
+    // LIKE creates a new raw-name identity. Its existence/no-op policy 
considers both destination
+    // variants even with an explicit source TYPE, so authorize both before 
looking at either.
+    for (TableType candidate : List.of(TableType.OFFLINE, TableType.REALTIME)) 
{
+      
ResourceUtils.checkPermissionAndAccess(TableNameBuilder.forType(candidate).tableNameWithType(targetName),
+          httpRequest, headers, AccessType.CREATE, Actions.Table.CREATE_TABLE, 
_accessControlFactory, LOGGER);
+    }
+    List<String> createdTables = new ArrayList<>(2);
+    DdlExecutionResponse response = new DdlExecutionResponse()
+        .setOperation(DdlOperation.CREATE_TABLE_LIKE)
+        .setDatabaseName(database)
+        .setTableName(targetName)
+        .setSourceTableName(sourceName)
+        .setDryRun(dryRun)
+        .setIfNotExists(create.isIfNotExists())
+        .setCreatedTables(createdTables);
+    Response existingTarget = existingCreateLikeTarget(create, targetName, 
response);
+    if (existingTarget != null) {
+      return existingTarget;
+    }
+
+    if (_pinotHelixResourceManager.getLogicalTableConfig(sourceName) != null) {
+      throw badRequest("CREATE TABLE LIKE does not support a logical table as 
its source: " + sourceName);
+    }
+    // Read templates, rather than resolved variables or decorator output, so 
the new definition
+    // keeps its declarative settings and does not persist source-side 
resolved credentials.
+    TableConfig offline = sourceType == TableType.REALTIME
+        ? null
+        : readCreateLikeTableConfig(sourceName, TableType.OFFLINE);
+    TableConfig realtime = sourceType == TableType.OFFLINE
+        ? null
+        : readCreateLikeTableConfig(sourceName, TableType.REALTIME);
+    if (offline == null && realtime == null) {
+      throw new ControllerApplicationException(LOGGER,
+          "Source table not found: " + sourceName + (sourceType == null ? "" : 
" TYPE " + sourceType),
+          Response.Status.NOT_FOUND);
+    }
+    if ((offline != null && offline.isMaterializedView()) || (realtime != null 
&& realtime.isMaterializedView())) {
+      throw badRequest("CREATE TABLE LIKE does not support a materialized view 
as its source: " + sourceName);
+    }
+    Schema sourceSchema = readCreateLikeSchema(sourceName);
+    if (sourceSchema == null) {
+      throw new ControllerApplicationException(LOGGER, "Source schema not 
found: " + sourceName,
+          Response.Status.NOT_FOUND);
+    }
+
+    TableConfigs copied;
+    try {
+      // TableConfig's copy constructor shares nested configs, maps, and 
lists. Deep-copy the
+      // entire bundle before renaming, tuning, or validating it.
+      copied = JsonUtils.stringToObject(
+          new TableConfigs(sourceName, sourceSchema, offline, 
realtime).toJsonString(), TableConfigs.class);
+    } catch (Exception e) {
+      throw new ControllerApplicationException(LOGGER, "Failed to copy source 
table definition: " + sourceName,
+          Response.Status.INTERNAL_SERVER_ERROR, e);
+    }
+    copied.setTableName(targetName);
+    Schema schema = copied.getSchema();
+    Schema storedSchema = readCreateLikeSchema(targetName);
+    checkCreateLikeSchema(schema, storedSchema);
+    validateCreateLikeConfigs(copied, storedSchema);
+    response.setTableConfigs(toJson(copied));
+    if (dryRun) {
+      return Response.ok(response.setMessage("Dry run: validated CREATE TABLE 
LIKE without persisting.")).build();
+    }
+
+    try {
+      if (storedSchema == null) {
+        try {
+          _pinotHelixResourceManager.addSchema(schema, false, false);
+        } catch (SchemaAlreadyExistsException e) {
+          Schema racedSchema = readCreateLikeSchema(targetName);
+          if (racedSchema == null) {
+            throw e;
+          }
+          checkCreateLikeSchema(schema, racedSchema);
+        }
+      }
+      // Recheck logical tables, materialized views and partially deleted 
targets after the schema write.
+      Response racedTarget = existingCreateLikeTarget(create, targetName, 
response);
+      if (racedTarget != null) {
+        return racedTarget;
+      }
+      TableConfig firstConfig = copied.getOffline() != null ? 
copied.getOffline() : copied.getRealtime();
+      _pinotHelixResourceManager.addTableIfRawNameAbsent(firstConfig);
+      createdTables.add(firstConfig.getTableName());
+      // Only the request which created the OFFLINE half may add its REALTIME 
sibling.
+      if (copied.getOffline() != null && copied.getRealtime() != null) {
+        _pinotHelixResourceManager.addTable(copied.getRealtime());
+        createdTables.add(copied.getRealtime().getTableName());
+      }
+      return Response.status(Response.Status.CREATED)
+          .entity(response.setMessage("Successfully created table " + 
targetName + " LIKE " + sourceName)).build();
+    } catch (TableAlreadyExistsException e) {
+      if (createdTables.isEmpty() && create.isIfNotExists()) {
+        Response racedTarget = existingCreateLikeTarget(create, targetName, 
response);
+        if (racedTarget != null) {
+          return racedTarget;
+        }
+      }
+      return createLikeFailure(response, 
Response.Status.CONFLICT.getStatusCode(), e);
+    } catch (SchemaAlreadyExistsException e) {
+      return createLikeFailure(response, 
Response.Status.CONFLICT.getStatusCode(), e);
+    } catch (ControllerApplicationException e) {
+      return createLikeFailure(response, e.getResponse().getStatus(), e);
+    } catch (Exception e) {
+      return createLikeFailure(response, 
Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e);
+    }
+  }
+
+  @Nullable
+  private Schema readCreateLikeSchema(String rawTableName) {
+    try {
+      return _pinotHelixResourceManager.getSchemaStrict(rawTableName);
+    } catch (IOException | RuntimeException e) {
+      throw new ControllerApplicationException(LOGGER, "Failed to read schema: 
" + rawTableName,
+          Response.Status.INTERNAL_SERVER_ERROR, e);
+    }
+  }
+
+  @Nullable
+  private TableConfig readCreateLikeTableConfig(String rawTableName, TableType 
tableType) {
+    String tableNameWithType = 
TableNameBuilder.forType(tableType).tableNameWithType(rawTableName);
+    try {
+      return _pinotHelixResourceManager.getRawTableConfig(tableNameWithType);
+    } catch (IOException | RuntimeException e) {
+      throw new ControllerApplicationException(LOGGER,
+          "Failed to read table config: " + tableNameWithType,
+          Response.Status.INTERNAL_SERVER_ERROR, e);
+    }
+  }
+
+  @Nullable
+  private Response existingCreateLikeTarget(CompiledCreateTableLike create, 
String targetName,
+      DdlExecutionResponse response) {
+    if (_pinotHelixResourceManager.getLogicalTableConfig(targetName) != null) {
+      throw new ControllerApplicationException(LOGGER, "Logical table already 
exists: " + targetName,
+          Response.Status.CONFLICT);
+    }
+    TableConfig offline = readCreateLikeTableConfig(targetName, 
TableType.OFFLINE);
+    TableConfig realtime = readCreateLikeTableConfig(targetName, 
TableType.REALTIME);
+    if ((offline != null && offline.isMaterializedView()) || (realtime != null 
&& realtime.isMaterializedView())) {
+      throw badRequest("Cannot create table '" + targetName + "': a 
materialized view already exists at this name.");
+    }
+    if (offline == null && realtime == null && 
!_pinotHelixResourceManager.hasOfflineTable(targetName)
+        && !_pinotHelixResourceManager.hasRealtimeTable(targetName)) {
+      return null;
+    }
+    if (create.isIfNotExists()) {
+      return Response.ok(response.setTableConfigs(null)
+          .setMessage("Table " + targetName + " already exists; CREATE IF NOT 
EXISTS is a no-op.")).build();
+    }
+    throw new ControllerApplicationException(LOGGER, "Table " + targetName + " 
already exists.",
+        Response.Status.CONFLICT);
+  }
+
+  private static void checkCreateLikeSchema(Schema copiedSchema, @Nullable 
Schema storedSchema) {
+    if (storedSchema != null && !copiedSchema.equals(storedSchema)) {
+      throw new ControllerApplicationException(LOGGER,
+          "Schema '" + copiedSchema.getSchemaName() + "' already exists and 
does not match the complete source schema.",
+          Response.Status.CONFLICT);
+    }
+  }
+
+  private void validateCreateLikeConfigs(TableConfigs copied, @Nullable Schema 
storedSchema) {
+    try {
+      Schema schema = copied.getSchema();
+      TableConfig[] configs = {copied.getOffline(), copied.getRealtime()};
+      for (TableConfig tableConfig : configs) {
+        if (tableConfig != null) {
+          TableConfigTunerUtils.applyTunerConfigs(_pinotHelixResourceManager, 
tableConfig, schema, Map.of());
+        }
+      }
+      boolean ignoreCase = 
_pinotHelixResourceManager.getTableCache().isIgnoreCase();
+      if (storedSchema == null) {
+        // A new schema must pass the same admission rules as a POST to 
/schemas.
+        SchemaUtils.validate(schema, List.of(), ignoreCase);
+      } else {
+        // A matching legacy schema still needs to be loadable, even when it 
predates the admission rules.
+        checkCreateLikeSchema(schema, storedSchema);
+        SchemaUtils.validate(schema, ignoreCase);
+      }
+      for (TableConfig tableConfig : configs) {
+        if (tableConfig != null) {
+          validateTableConfig(schema, tableConfig);
+          PinotTableRestletResource.tableTasksValidation(tableConfig, 
_pinotHelixTaskResourceManager);
+        }
+      }
+      if (copied.getOffline() != null && copied.getRealtime() != null) {
+        TableConfigUtils.verifyHybridTableConfigs(copied.getTableName(), 
copied.getOffline(), copied.getRealtime());
+      }
+    } catch (ControllerApplicationException e) {
+      throw e;
+    } catch (IllegalArgumentException | IllegalStateException | 
ConfigValidationException e) {
+      throw new ControllerApplicationException(LOGGER, "CREATE TABLE LIKE 
validation failed: " + e.getMessage(),
+          Response.Status.BAD_REQUEST, e);
+    }
+  }
+
+  private static Response createLikeFailure(DdlExecutionResponse response, int 
status, Exception cause) {
+    // Never delete by raw name here: a concurrent request may own a sibling 
variant or schema.
+    // Preserve completed creates and report them even when a later variant 
failed.
+    LOGGER.error("CREATE TABLE LIKE failed for {}; completed variants: {}", 
response.getTableName(),
+        response.getCreatedTables(), cause);
+    response.setMessage("Failed to create table " + response.getTableName() + 
": " + cause.getMessage()
+        + ". Completed variants: " + response.getCreatedTables());
+    return Response.status(status).entity(response).build();
+  }

Review Comment:
   Fixed in 2ace7bc0ea. Write failures return code and error, with 
createdTables and schemaCreated for partial progress. The response omits the 
copied configs. The controller logs expected conflicts at INFO and confirms a 
new schema by reading it back before reporting it. The regression tests also 
decode the response with the same error class Pinot’s HTTP client uses.



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