{"record":{"id":"e5f8f6ceea60a03c","repo":"apache/shardingsphere","slug":"31","errorCode":"31","errorMessage":"Can not update sharding value for table '%s'.","messagePattern":"Can not update sharding value for table '(.+?)'\\.","errorType":"exception","errorClass":"UnsupportedUpdatingShardingValueException","httpStatus":null,"severity":"error","filePath":"features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/dml/ShardingInsertRouteContextChecker.java","lineNumber":69,"sourceCode":"    \n    @Override\n    public void check(final ShardingRule shardingRule, final QueryContext queryContext,\n                      final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) {\n        SQLStatementContext sqlStatementContext = queryContext.getSqlStatementContext();\n        InsertStatement insertStatement = (InsertStatement) sqlStatementContext.getSqlStatement();\n        Optional<SubquerySegment> insertSelect = insertStatement.getInsertSelect();\n        String tableName = insertStatement.getTable().map(optional -> optional.getTableName().getIdentifier().getValue()).orElse(\"\");\n        if (insertSelect.isPresent() && shardingConditions.isNeedMerge()) {\n            boolean singleRoutingOrSameShardingCondition = routeContext.isSingleRouting() || shardingConditions.isSameShardingCondition();\n            ShardingSpherePreconditions.checkState(singleRoutingOrSameShardingCondition, () -> new UnsupportedShardingOperationException(\"INSERT ... SELECT ...\", tableName));\n        }\n        Collection<ColumnAssignmentSegment> assignments = insertStatement.getOnDuplicateKeyColumns().map(OnDuplicateKeyColumnsSegment::getColumns).orElse(Collections.emptyList());\n        Optional<ShardingConditions> onDuplicateKeyShardingConditions =\n                ShardingRouteContextCheckUtils.createShardingConditions(sqlStatementContext, shardingRule, assignments, queryContext.getParameters());\n        Optional<RouteContext> onDuplicateKeyRouteContext = onDuplicateKeyShardingConditions\n                .map(optional -> new ShardingStandardRouteEngine(tableName, optional, sqlStatementContext, queryContext.getHintValueContext(), props).route(shardingRule));\n        if (onDuplicateKeyRouteContext.isPresent() && !ShardingRouteContextCheckUtils.isSameRouteContext(routeContext, onDuplicateKeyRouteContext.get())) {\n            throw new UnsupportedUpdatingShardingValueException(tableName);\n        }\n        if (!routeContext.isSingleRouting()) {\n            boolean isSingleDataNode = routeContext.getOriginalDataNodes().stream().allMatch(dataNodes -> 1 == dataNodes.size());\n            ShardingSpherePreconditions.checkState(isSingleDataNode, () -> new DuplicateInsertDataRecordException(shardingConditions, tableName));\n        }\n    }\n}\n","sourceCodeStart":51,"sourceCodeEnd":77,"githubUrl":"https://github.com/apache/shardingsphere/blob/e952770a215630a3659c75d64369168cd3e26b82/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/dml/ShardingInsertRouteContextChecker.java#L51-L77","documentation":"UnsupportedUpdatingShardingValueException is thrown by ShardingInsertRouteContextChecker during INSERT ... ON DUPLICATE KEY UPDATE. The checker builds a second route context from sharding conditions extracted out of the ON DUPLICATE KEY assignment columns; if that route context differs from the original one (ShardingRouteContextCheckUtils.isSameRouteContext false), the UPDATE would move the row to a different shard than the INSERT, which ShardingSphere cannot execute atomically, so it fails with 'Can not update sharding value for table'.","triggerScenarios":"INSERT INTO t (...) VALUES (...) ON DUPLICATE KEY UPDATE <sharding_column> = <new_value> where the new sharding value routes to a different data node/table than the INSERT values. The checker re-routes using conditions derived from the assignments and compares.","commonSituations":"Upsert code that also 'corrects' the sharding key (e.g. ON DUPLICATE KEY UPDATE tenant_id = VALUES(tenant_id)); changing sharding-column values as part of dedupe logic; migrating single-DB upserts unchanged into a sharded schema.","solutions":["Remove the sharding column from the ON DUPLICATE KEY UPDATE assignment list — sharding keys must be immutable.","If the sharding key must change, split into DELETE (by old key) + INSERT (with new key) inside one application transaction.","Verify the INSERT values themselves produce a consistent route (all rows in one multi-row INSERT target the same shard)."],"exampleFix":"-- before: updating the sharding column\nINSERT INTO t_order(order_id,cust_id,status) VALUES(?,?,?)\nON DUPLICATE KEY UPDATE cust_id=VALUES(cust_id), status=VALUES(status);\n-- cust_id is the sharding key -> error when VALUES differ\n\n-- after: sharding key excluded from the update\nINSERT INTO t_order(order_id,cust_id,status) VALUES(?,?,?)\nON DUPLICATE KEY UPDATE status=VALUES(status);","handlingStrategy":"validation","validationCode":"// Strip sharding columns from ON DUPLICATE KEY UPDATE before executing\nString shardingColumn = \"cust_id\";\nString insertSql = \"INSERT INTO t_order(order_id,cust_id,status) VALUES(?,?,?) ON DUPLICATE KEY UPDATE status=VALUES(status)\";\n// ensure shardingColumn never appears after 'ON DUPLICATE KEY UPDATE'\nString tail = insertSql.substring(insertSql.toUpperCase(Locale.ROOT).indexOf(\"ON DUPLICATE KEY UPDATE\") + 22);\nif (tail.toUpperCase(Locale.ROOT).contains(shardingColumn.toUpperCase(Locale.ROOT))) {\n    throw new IllegalArgumentException(\"Sharding key must not be updated: \" + shardingColumn);\n}","typeGuard":null,"tryCatchPattern":"try {\n    ps.executeUpdate();\n} catch (final UnsupportedUpdatingShardingValueException ex) {\n    // rewrite to DELETE by old key + INSERT with new key inside one transaction\n}","preventionTips":["Treat sharding keys as immutable columns in your data model and ORM mappings.","For key changes, use an explicit delete-then-insert transaction with both old and new key values."],"tags":["sharding","insert","on-duplicate-key","upsert","sharding-key"],"backgroundTag":null,"analyzedSha":"e952770a215630a3659c75d64369168cd3e26b82","analyzedAt":"2026-08-14T13:54:53.392Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}