File size: 45,856 Bytes
5a9e79d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 | diff --git a/docs/content/docs/sql/reference/queries/changelog.md b/docs/content/docs/sql/reference/queries/changelog.md
--- a/docs/content/docs/sql/reference/queries/changelog.md
+++ b/docs/content/docs/sql/reference/queries/changelog.md
@@ -30,9 +30,119 @@ Flink SQL provides built-in process table functions (PTFs) for working with chan
| Function | Description |
|:---------|:------------|
+| [FROM_CHANGELOG](#from_changelog) | Converts an append-only table with operation codes into a (potentially updating) dynamic table |
| [TO_CHANGELOG](#to_changelog) | Converts a dynamic table into an append-only table with explicit operation codes |
-<!-- Placeholder for future FROM_CHANGELOG function -->
+## FROM_CHANGELOG
+
+The `FROM_CHANGELOG` PTF converts an append-only table with an explicit operation code column into a (potentially updating) dynamic table. Each input row is expected to have a string column that indicates the change operation. The operation column is interpreted by the engine and removed from the output.
+
+This is useful when consuming Change Data Capture (CDC) streams from systems like Debezium where events arrive as flat append-only records with an explicit operation field. It's also useful to be used in combination with the TO_CHANGELOG function, when converting the append-only table back into an updating table after doing some specific transformation to the events.
+
+Note: This version requires that your CDC data encodes updates using a full image (i.e. providing separate events for before and after the update). Please double-check whether your source provides both UPDATE_BEFORE and UPDATE_AFTER events. FROM_CHANGELOG is a very powerful function but might produce incorrect results in subsequent operations and tables, if not configured correctly.
+
+### Syntax
+
+```sql
+SELECT * FROM FROM_CHANGELOG(
+ input => TABLE source_table,
+ [op => DESCRIPTOR(op_column_name),]
+ [op_mapping => MAP[
+ 'c, r', 'INSERT',
+ 'ub', 'UPDATE_BEFORE',
+ 'ua', 'UPDATE_AFTER',
+ 'd', 'DELETE'
+ ]]
+)
+```
+
+### Parameters
+
+| Parameter | Required | Description |
+|:-------------|:---------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| `input` | Yes | The input table. Must be append-only. |
+| `op` | No | A `DESCRIPTOR` with a single column name for the operation code column. Defaults to `op`. The column must exist in the input table and be of type STRING. |
+| `op_mapping` | No | A `MAP<STRING, STRING>` mapping user-defined codes to Flink change operation names. Keys are user-defined codes (e.g., `'c'`, `'u'`, `'d'`), values are Flink change operation names (`INSERT`, `UPDATE_BEFORE`, `UPDATE_AFTER`, `DELETE`). Keys can contain comma-separated codes to map multiple codes to the same operation (e.g., `'c, r'`). When provided, only mapped codes are forwarded - unmapped codes are dropped. Each change operation may appear at most once across all entries. |
+
+#### Default op_mapping
+
+When `op_mapping` is omitted, the following standard names are used. They allow a reverse conversion from TO_CHANGELOG by default.
+
+| Input code | Change operation |
+|:-------------------|:------------------|
+| `'INSERT'` | INSERT |
+| `'UPDATE_BEFORE'` | UPDATE_BEFORE |
+| `'UPDATE_AFTER'` | UPDATE_AFTER |
+| `'DELETE'` | DELETE |
+
+### Output Schema
+
+The output contains all input columns except the operation code (e.g., op) column, which is interpreted by Flink's SQL engine and removed. Each output row carries the appropriate change operation (INSERT, UPDATE_BEFORE, UPDATE_AFTER, or DELETE).
+
+```
+[all_input_columns_without_op]
+```
+
+### Examples
+
+#### Basic usage with standard op names
+
+```sql
+-- Input (append-only):
+-- +I[id:1, op:'INSERT', name:'Alice']
+-- +I[id:1, op:'UPDATE_BEFORE', name:'Alice']
+-- +I[id:1, op:'UPDATE_AFTER', name:'Alice2']
+-- +I[id:2, op:'DELETE', name:'Bob']
+
+SELECT * FROM FROM_CHANGELOG(
+ input => TABLE cdc_stream
+)
+
+-- Output (updating table):
+-- +I[id:1, name:'Alice']
+-- -U[id:1, name:'Alice']
+-- +U[id:1, name:'Alice2']
+-- -D[id:2, name:'Bob']
+
+-- Table state after all events:
+-- | id | name |
+-- |----|--------|
+-- | 1 | Alice2 |
+```
+
+#### Custom operation column name
+
+```sql
+-- Source schema: id INT, operation STRING, name STRING
+SELECT * FROM FROM_CHANGELOG(
+ input => TABLE cdc_stream,
+ op => DESCRIPTOR(operation)
+)
+-- The operation column named 'operation' is used instead of 'op'
+```
+
+#### Table API
+
+```java
+Table cdcStream = ...;
+
+// Default: reads 'op' column with standard change operation names
+Table result = cdcStream.fromChangelog();
+
+// With custom op column name
+Table result = cdcStream.fromChangelog(
+ descriptor("operation").asArgument("op")
+);
+
+// With custom op_mapping
+Table result = cdcStream.fromChangelog(
+ descriptor("op").asArgument("op"),
+ map("c, r", "INSERT",
+ "ub", "UPDATE_BEFORE",
+ "ua", "UPDATE_AFTER",
+ "d", "DELETE").asArgument("op_mapping")
+);
+```
## TO_CHANGELOG
diff --git a/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/Table.java b/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/Table.java
--- a/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/Table.java
+++ b/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/Table.java
@@ -1454,4 +1454,31 @@ default TableResult executeInsert(
* @return an append-only {@link Table} with an {@code op} column prepended to the input columns
*/
Table toChangelog(Expression... arguments);
+
+ /**
+ * Converts this append-only table with an explicit operation code column into a dynamic table
+ * using the built-in {@code FROM_CHANGELOG} process table function.
+ *
+ * <p>Each input row is expected to have a string operation code column (default: {@code "op"})
+ * that indicates the change operation (e.g., INSERT, UPDATE_AFTER, UPDATE_BEFORE, DELETE). The
+ * output table is a dynamic table backed by a changelog stream.
+ *
+ * <p>Optional arguments can be passed using named expressions:
+ *
+ * <pre>{@code
+ * // Default: reads 'op' column with standard change operation names
+ * table.fromChangelog();
+ *
+ * // Custom op column name and mapping (Debezium-style codes)
+ * table.fromChangelog(
+ * descriptor("__op").asArgument("op"),
+ * map("c, r", "INSERT", "u", "UPDATE_AFTER", "d", "DELETE").asArgument("op_mapping")
+ * );
+ * }</pre>
+ *
+ * @param arguments optional named arguments for {@code op} and {@code op_mapping}
+ * @return a dynamic {@link Table} with the op column removed and proper change operation
+ * semantics
+ */
+ Table fromChangelog(Expression... arguments);
}
diff --git a/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/TableImpl.java b/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/TableImpl.java
--- a/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/TableImpl.java
+++ b/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/TableImpl.java
@@ -497,6 +497,11 @@ public PartitionedTable partitionBy(Expression... fields) {
return new PartitionedTableImpl(this, Arrays.asList(fields));
}
+ @Override
+ public Table fromChangelog(Expression... arguments) {
+ return process(BuiltInFunctionDefinitions.FROM_CHANGELOG.getName(), (Object[]) arguments);
+ }
+
@Override
public ApiExpression asArgument(String name) {
return createArgumentExpression(operationTree, tableEnvironment, name);
diff --git a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/BuiltInFunctionDefinition.java b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/BuiltInFunctionDefinition.java
--- a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/BuiltInFunctionDefinition.java
+++ b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/BuiltInFunctionDefinition.java
@@ -72,6 +72,8 @@ public final class BuiltInFunctionDefinition implements SpecializedFunction {
private final SqlCallSyntax sqlCallSyntax;
+ private final @Nullable ChangelogModeStrategy changelogModeStrategy;
+
private final String sqlName;
private BuiltInFunctionDefinition(
@@ -84,7 +86,8 @@ private BuiltInFunctionDefinition(
boolean isDeterministic,
boolean isRuntimeProvided,
String runtimeClass,
- boolean isInternal) {
+ boolean isInternal,
+ @Nullable ChangelogModeStrategy changelogModeStrategy) {
this.name = checkNotNull(name, "Name must not be null.");
this.sqlName = sqlName;
this.version = isInternal ? null : version;
@@ -95,6 +98,7 @@ private BuiltInFunctionDefinition(
this.runtimeClass = runtimeClass;
this.isInternal = isInternal;
this.sqlCallSyntax = sqlCallSyntax;
+ this.changelogModeStrategy = changelogModeStrategy;
validateFunction(this.name, this.version, this.isInternal);
}
@@ -131,6 +135,14 @@ public boolean isInternal() {
return isInternal;
}
+ /**
+ * Returns the optional {@link ChangelogModeStrategy} for built-in PTFs that emit updates (e.g.,
+ * FROM_CHANGELOG). The planner uses this to determine the output changelog mode.
+ */
+ public Optional<ChangelogModeStrategy> getChangelogModeStrategy() {
+ return Optional.ofNullable(changelogModeStrategy);
+ }
+
public String getQualifiedName() {
if (isInternal) {
return name;
@@ -253,6 +265,8 @@ public static final class Builder {
private SqlCallSyntax sqlCallSyntax = SqlCallSyntax.FUNCTION;
+ private @Nullable ChangelogModeStrategy changelogModeStrategy;
+
public Builder() {
// default constructor to allow a fluent definition
}
@@ -399,6 +413,15 @@ public Builder sqlName(String name) {
return this;
}
+ /**
+ * Sets the {@link ChangelogModeStrategy} that determines the output changelog mode for this
+ * built-in PTF. Only needed for PTFs that emit updates (e.g., FROM_CHANGELOG).
+ */
+ public Builder changelogModeStrategy(ChangelogModeStrategy changelogModeStrategy) {
+ this.changelogModeStrategy = changelogModeStrategy;
+ return this;
+ }
+
public BuiltInFunctionDefinition build() {
return new BuiltInFunctionDefinition(
name,
@@ -410,7 +433,8 @@ public BuiltInFunctionDefinition build() {
isDeterministic,
isRuntimeProvided,
runtimeClass,
- isInternal);
+ isInternal,
+ changelogModeStrategy);
}
}
}
diff --git a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/BuiltInFunctionDefinitions.java b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/BuiltInFunctionDefinitions.java
--- a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/BuiltInFunctionDefinitions.java
+++ b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/BuiltInFunctionDefinitions.java
@@ -27,6 +27,7 @@
import org.apache.flink.table.api.JsonType;
import org.apache.flink.table.api.JsonValueOnEmptyOrError;
import org.apache.flink.table.api.TableException;
+import org.apache.flink.table.connector.ChangelogMode;
import org.apache.flink.table.expressions.TimeIntervalUnit;
import org.apache.flink.table.expressions.TimePointUnit;
import org.apache.flink.table.expressions.ValueLiteralExpression;
@@ -106,6 +107,7 @@
import static org.apache.flink.table.types.inference.TypeStrategies.varyingString;
import static org.apache.flink.table.types.inference.strategies.SpecificInputTypeStrategies.ARRAY_ELEMENT_ARG;
import static org.apache.flink.table.types.inference.strategies.SpecificInputTypeStrategies.ARRAY_FULLY_COMPARABLE;
+import static org.apache.flink.table.types.inference.strategies.SpecificInputTypeStrategies.FROM_CHANGELOG_INPUT_TYPE_STRATEGY;
import static org.apache.flink.table.types.inference.strategies.SpecificInputTypeStrategies.INDEX;
import static org.apache.flink.table.types.inference.strategies.SpecificInputTypeStrategies.JSON_ARGUMENT;
import static org.apache.flink.table.types.inference.strategies.SpecificInputTypeStrategies.ML_PREDICT_INPUT_TYPE_STRATEGY;
@@ -115,6 +117,7 @@
import static org.apache.flink.table.types.inference.strategies.SpecificInputTypeStrategies.percentage;
import static org.apache.flink.table.types.inference.strategies.SpecificInputTypeStrategies.percentageArray;
import static org.apache.flink.table.types.inference.strategies.SpecificTypeStrategies.ARRAY_APPEND_PREPEND;
+import static org.apache.flink.table.types.inference.strategies.SpecificTypeStrategies.FROM_CHANGELOG_OUTPUT_TYPE_STRATEGY;
import static org.apache.flink.table.types.inference.strategies.SpecificTypeStrategies.ML_PREDICT_OUTPUT_TYPE_STRATEGY;
import static org.apache.flink.table.types.inference.strategies.SpecificTypeStrategies.TO_CHANGELOG_OUTPUT_TYPE_STRATEGY;
@@ -809,6 +812,30 @@ ANY, and(logical(LogicalTypeRoot.BOOLEAN), LITERAL)
"org.apache.flink.table.runtime.functions.ptf.ToChangelogFunction")
.build();
+ public static final BuiltInFunctionDefinition FROM_CHANGELOG =
+ BuiltInFunctionDefinition.newBuilder()
+ .name("FROM_CHANGELOG")
+ .kind(PROCESS_TABLE)
+ .staticArguments(
+ StaticArgument.table(
+ "input",
+ Row.class,
+ false,
+ EnumSet.of(
+ StaticArgumentTrait.TABLE,
+ StaticArgumentTrait.ROW_SEMANTIC_TABLE)),
+ StaticArgument.scalar("op", DataTypes.DESCRIPTOR(), true),
+ StaticArgument.scalar(
+ "op_mapping",
+ DataTypes.MAP(DataTypes.STRING(), DataTypes.STRING()),
+ true))
+ .changelogModeStrategy(ctx -> ChangelogMode.all())
+ .inputTypeStrategy(FROM_CHANGELOG_INPUT_TYPE_STRATEGY)
+ .outputTypeStrategy(FROM_CHANGELOG_OUTPUT_TYPE_STRATEGY)
+ .runtimeClass(
+ "org.apache.flink.table.runtime.functions.ptf.FromChangelogFunction")
+ .build();
+
public static final BuiltInFunctionDefinition GREATEST =
BuiltInFunctionDefinition.newBuilder()
.name("GREATEST")
diff --git a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/ChangelogModeStrategy.java b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/ChangelogModeStrategy.java
new file mode 100644
--- /dev/null
+++ b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/ChangelogModeStrategy.java
@@ -0,0 +1,37 @@
+/*
+ * 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.flink.table.functions;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.table.connector.ChangelogMode;
+import org.apache.flink.table.functions.ChangelogFunction.ChangelogContext;
+import org.apache.flink.table.types.inference.TypeStrategy;
+
+/**
+ * Strategy for determining the output {@link ChangelogMode} of a built-in process table function.
+ *
+ * <p>Similar to {@link TypeStrategy}, this is used to declare changelog semantics in the function
+ * definition rather than implementing the {@link ChangelogFunction} interface.
+ */
+@Internal
+public interface ChangelogModeStrategy {
+
+ /** Infers the output {@link ChangelogMode} based on the given {@link ChangelogContext}. */
+ ChangelogMode inferChangelogMode(ChangelogContext changelogContext);
+}
diff --git a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/FromChangelogTypeStrategy.java b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/FromChangelogTypeStrategy.java
new file mode 100644
--- /dev/null
+++ b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/FromChangelogTypeStrategy.java
@@ -0,0 +1,253 @@
+/*
+ * 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.flink.table.types.inference.strategies;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.table.api.DataTypes;
+import org.apache.flink.table.api.DataTypes.Field;
+import org.apache.flink.table.api.ValidationException;
+import org.apache.flink.table.functions.TableSemantics;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.inference.CallContext;
+import org.apache.flink.table.types.inference.InputTypeStrategy;
+import org.apache.flink.table.types.inference.TypeStrategy;
+import org.apache.flink.table.types.logical.LogicalTypeFamily;
+import org.apache.flink.types.ColumnList;
+import org.apache.flink.types.RowKind;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/** Type strategies for the {@code FROM_CHANGELOG} process table function. */
+@Internal
+public final class FromChangelogTypeStrategy {
+
+ private static final String DEFAULT_OP_COLUMN_NAME = "op";
+
+ private static final Set<String> VALID_ROW_KIND_NAMES =
+ Set.of("INSERT", "UPDATE_BEFORE", "UPDATE_AFTER", "DELETE");
+
+ // --------------------------------------------------------------------------------------------
+ // Input validation
+ // --------------------------------------------------------------------------------------------
+
+ public static final InputTypeStrategy INPUT_TYPE_STRATEGY =
+ new ValidationOnlyInputTypeStrategy() {
+ @Override
+ public Optional<List<DataType>> inferInputTypes(
+ final CallContext callContext, final boolean throwOnFailure) {
+ return validateInputs(callContext, throwOnFailure);
+ }
+ };
+
+ // --------------------------------------------------------------------------------------------
+ // Output type inference
+ // --------------------------------------------------------------------------------------------
+
+ public static final TypeStrategy OUTPUT_TYPE_STRATEGY =
+ callContext -> {
+ final TableSemantics tableSemantics =
+ callContext
+ .getTableSemantics(0)
+ .orElseThrow(
+ () ->
+ new ValidationException(
+ "First argument must be a table for FROM_CHANGELOG."));
+
+ final String opColumnName = resolveOpColumnName(callContext);
+
+ final List<Field> outputFields = buildOutputFields(tableSemantics, opColumnName);
+
+ return Optional.of(DataTypes.ROW(outputFields).notNull());
+ };
+ private static final String UPDATE_BEFORE = RowKind.UPDATE_BEFORE.name();
+ private static final String UPDATE_AFTER = RowKind.UPDATE_AFTER.name();
+
+ // --------------------------------------------------------------------------------------------
+ // Helpers
+ // --------------------------------------------------------------------------------------------
+
+ @SuppressWarnings("rawtypes")
+ private static Optional<List<DataType>> validateInputs(
+ final CallContext callContext, final boolean throwOnFailure) {
+ Optional<List<DataType>> error;
+
+ error = validateTableArg(callContext, throwOnFailure);
+ if (error.isPresent()) {
+ return error;
+ }
+
+ error = validateOpDescriptor(callContext, throwOnFailure);
+ if (error.isPresent()) {
+ return error;
+ }
+
+ error = validateOpColumn(callContext, throwOnFailure);
+ if (error.isPresent()) {
+ return error;
+ }
+
+ error = validateOpMapping(callContext, throwOnFailure);
+ if (error.isPresent()) {
+ return error;
+ }
+
+ return Optional.of(callContext.getArgumentDataTypes());
+ }
+
+ private static Optional<List<DataType>> validateTableArg(
+ final CallContext callContext, final boolean throwOnFailure) {
+ if (callContext.getTableSemantics(0).isEmpty()) {
+ return callContext.fail(
+ throwOnFailure, "First argument must be a table for FROM_CHANGELOG.");
+ }
+ return Optional.empty();
+ }
+
+ private static Optional<List<DataType>> validateOpDescriptor(
+ final CallContext callContext, final boolean throwOnFailure) {
+ final Optional<ColumnList> opDescriptor = callContext.getArgumentValue(1, ColumnList.class);
+ if (opDescriptor.isPresent() && opDescriptor.get().getNames().size() != 1) {
+ return callContext.fail(
+ throwOnFailure,
+ "The descriptor for argument 'op' must contain exactly one column name.");
+ }
+ return Optional.empty();
+ }
+
+ /** Validates that the op column exists in the input schema and is of STRING type. */
+ private static Optional<List<DataType>> validateOpColumn(
+ final CallContext callContext, final boolean throwOnFailure) {
+
+ final TableSemantics tableSemantics = callContext.getTableSemantics(0).get();
+ final String opColumnName = resolveOpColumnName(callContext);
+ final List<Field> inputFields = DataType.getFields(tableSemantics.dataType());
+ final Optional<Field> opField =
+ inputFields.stream().filter(f -> f.getName().equals(opColumnName)).findFirst();
+ if (opField.isEmpty()) {
+ return callContext.fail(
+ throwOnFailure,
+ String.format(
+ "The op column '%s' does not exist in the input schema.",
+ opColumnName));
+ }
+ if (!opField.get().getDataType().getLogicalType().is(LogicalTypeFamily.CHARACTER_STRING)) {
+ return callContext.fail(
+ throwOnFailure,
+ String.format(
+ "The op column '%s' must be of STRING type, but was '%s'.",
+ opColumnName, opField.get().getDataType().getLogicalType()));
+ }
+ return Optional.empty();
+ }
+
+ /** Validates op_mapping is a literal and its values are valid change operation names. */
+ @SuppressWarnings("unchecked")
+ private static Optional<List<DataType>> validateOpMapping(
+ final CallContext callContext, final boolean throwOnFailure) {
+ final boolean hasMappingArgProvided = !callContext.isArgumentNull(2);
+ final boolean isMappingArgLiteral = callContext.isArgumentLiteral(2);
+ if (hasMappingArgProvided && !isMappingArgLiteral) {
+ return callContext.fail(
+ throwOnFailure, "The 'op_mapping' argument must be a constant MAP literal.");
+ }
+
+ final Optional<Map> opMapping = callContext.getArgumentValue(2, Map.class);
+ if (opMapping.isPresent()) {
+ final Map<String, String> mapping = opMapping.get();
+ final Optional<List<DataType>> validationError =
+ validateOpMappingValues(callContext, mapping, throwOnFailure);
+ if (validationError.isPresent()) {
+ return validationError;
+ }
+
+ final boolean hasUpdateBefore =
+ mapping.values().stream().anyMatch(v -> UPDATE_BEFORE.equals(v.trim()));
+ final boolean hasUpdateAfter =
+ mapping.values().stream().anyMatch(v -> UPDATE_AFTER.equals(v.trim()));
+ if (hasUpdateAfter && !hasUpdateBefore) {
+ return callContext.fail(
+ throwOnFailure,
+ "The 'op_mapping' must include UPDATE_BEFORE for retract mode. "
+ + "Upsert mode (without UPDATE_BEFORE) is not supported "
+ + "in this version.");
+ }
+ }
+ return Optional.empty();
+ }
+
+ /**
+ * Validates op_mapping values. Values must be valid Flink change operation names. Each name
+ * must appear at most once across all entries.
+ */
+ private static Optional<List<DataType>> validateOpMappingValues(
+ final CallContext callContext,
+ final Map<String, String> opMapping,
+ final boolean throwOnFailure) {
+ final Set<String> allRowKindsSeen = new HashSet<>();
+
+ for (final String value : opMapping.values()) {
+ final String rowKindName = value.trim();
+ if (!VALID_ROW_KIND_NAMES.contains(rowKindName)) {
+ return callContext.fail(
+ throwOnFailure,
+ String.format(
+ "Invalid target mapping for argument 'op_mapping'. "
+ + "Unknown change operation: '%s'. Valid values are: %s.",
+ rowKindName, VALID_ROW_KIND_NAMES));
+ }
+ final boolean isDuplicate = !allRowKindsSeen.add(rowKindName);
+ if (isDuplicate) {
+ return callContext.fail(
+ throwOnFailure,
+ String.format(
+ "Invalid target mapping for argument 'op_mapping'. "
+ + "Duplicate change operation: '%s'. "
+ + "Use comma-separated keys to map multiple codes to the same operation "
+ + "(e.g., MAP['c, r', 'INSERT']).",
+ rowKindName));
+ }
+ }
+ return Optional.empty();
+ }
+
+ private static String resolveOpColumnName(final CallContext callContext) {
+ return callContext
+ .getArgumentValue(1, ColumnList.class)
+ .filter(cl -> !cl.getNames().isEmpty())
+ .map(cl -> cl.getNames().get(0))
+ .orElse(DEFAULT_OP_COLUMN_NAME);
+ }
+
+ private static List<Field> buildOutputFields(
+ final TableSemantics tableSemantics, final String opColumnName) {
+ final List<Field> inputFields = DataType.getFields(tableSemantics.dataType());
+
+ // Exclude the op column (becomes RowKind), keep all other columns
+ return inputFields.stream()
+ .filter(f -> !f.getName().equals(opColumnName))
+ .collect(Collectors.toList());
+ }
+
+ private FromChangelogTypeStrategy() {}
+}
diff --git a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/SpecificInputTypeStrategies.java b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/SpecificInputTypeStrategies.java
--- a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/SpecificInputTypeStrategies.java
+++ b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/SpecificInputTypeStrategies.java
@@ -126,6 +126,10 @@ public static InputTypeStrategy windowTimeIndicator() {
public static final InputTypeStrategy TO_CHANGELOG_INPUT_TYPE_STRATEGY =
ToChangelogTypeStrategy.INPUT_TYPE_STRATEGY;
+ /** Input strategy for {@link BuiltInFunctionDefinitions#FROM_CHANGELOG}. */
+ public static final InputTypeStrategy FROM_CHANGELOG_INPUT_TYPE_STRATEGY =
+ FromChangelogTypeStrategy.INPUT_TYPE_STRATEGY;
+
/** See {@link ExtractInputTypeStrategy}. */
public static final InputTypeStrategy EXTRACT = new ExtractInputTypeStrategy();
diff --git a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/SpecificTypeStrategies.java b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/SpecificTypeStrategies.java
--- a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/SpecificTypeStrategies.java
+++ b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/SpecificTypeStrategies.java
@@ -202,6 +202,10 @@ public final class SpecificTypeStrategies {
public static final TypeStrategy TO_CHANGELOG_OUTPUT_TYPE_STRATEGY =
ToChangelogTypeStrategy.OUTPUT_TYPE_STRATEGY;
+ /** Type strategy specific for {@link BuiltInFunctionDefinitions#FROM_CHANGELOG}. */
+ public static final TypeStrategy FROM_CHANGELOG_OUTPUT_TYPE_STRATEGY =
+ FromChangelogTypeStrategy.OUTPUT_TYPE_STRATEGY;
+
private SpecificTypeStrategies() {
// no instantiation
}
diff --git a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/ValidationOnlyInputTypeStrategy.java b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/ValidationOnlyInputTypeStrategy.java
new file mode 100644
--- /dev/null
+++ b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/ValidationOnlyInputTypeStrategy.java
@@ -0,0 +1,49 @@
+/*
+ * 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.flink.table.types.inference.strategies;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.table.functions.FunctionDefinition;
+import org.apache.flink.table.types.inference.ArgumentCount;
+import org.apache.flink.table.types.inference.ConstantArgumentCount;
+import org.apache.flink.table.types.inference.InputTypeStrategy;
+import org.apache.flink.table.types.inference.Signature;
+import org.apache.flink.table.types.inference.StaticArgument;
+
+import java.util.List;
+
+/**
+ * Base class for input type strategies that only perform validation. Argument count and signatures
+ * are handled by {@link StaticArgument}s in the function definition.
+ *
+ * <p>Subclasses only need to implement {@link #inferInputTypes} for custom validation logic.
+ */
+@Internal
+public abstract class ValidationOnlyInputTypeStrategy implements InputTypeStrategy {
+
+ @Override
+ public ArgumentCount getArgumentCount() {
+ return ConstantArgumentCount.any();
+ }
+
+ @Override
+ public List<Signature> getExpectedSignatures(FunctionDefinition definition) {
+ return List.of(Signature.of());
+ }
+}
diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/optimize/program/FlinkChangelogModeInferenceProgram.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/optimize/program/FlinkChangelogModeInferenceProgram.scala
--- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/optimize/program/FlinkChangelogModeInferenceProgram.scala
+++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/optimize/program/FlinkChangelogModeInferenceProgram.scala
@@ -23,7 +23,7 @@ import org.apache.flink.table.api.InsertConflictStrategy.ConflictBehavior
import org.apache.flink.table.api.config.ExecutionConfigOptions
import org.apache.flink.table.api.config.ExecutionConfigOptions.UpsertMaterialize
import org.apache.flink.table.connector.ChangelogMode
-import org.apache.flink.table.functions.ChangelogFunction
+import org.apache.flink.table.functions.{BuiltInFunctionDefinition, ChangelogFunction}
import org.apache.flink.table.functions.ChangelogFunction.ChangelogContext
import org.apache.flink.table.planner.calcite.{FlinkTypeFactory, RexTableArgCall}
import org.apache.flink.table.planner.plan.`trait`._
@@ -1711,24 +1711,44 @@ class FlinkChangelogModeInferenceProgram extends FlinkOptimizeProgram[StreamOpti
val changelogContext =
toPtfChangelogContext(process, inputChangelogModes, requiredChangelogMode)
val changelogMode = changelogFunction.getChangelogMode(changelogContext)
- if (!changelogMode.containsOnly(RowKind.INSERT)) {
- verifyPtfTableArgsForUpdates(call)
- }
+ verifyPtfTableArgsForUpdates(call, changelogMode)
+ toTraitSet(changelogMode)
+ case builtIn: BuiltInFunctionDefinition if builtIn.getChangelogModeStrategy.isPresent =>
+ val inputChangelogModes = children.map(toChangelogMode(_, None, None))
+ val changelogContext =
+ toPtfChangelogContext(process, inputChangelogModes, requiredChangelogMode)
+ val changelogMode =
+ builtIn.getChangelogModeStrategy.get().inferChangelogMode(changelogContext)
+ verifyPtfTableArgsForUpdates(call, changelogMode)
toTraitSet(changelogMode)
case _ =>
defaultTraitSet
}
}
- private def verifyPtfTableArgsForUpdates(call: RexCall): Unit = {
+ /**
+ * Verifies that PTFs with upsert output (without UPDATE_BEFORE) use set semantics.
+ *
+ * Retract mode (with UPDATE_BEFORE) is self-describing — each update carries either the old and
+ * new value, so downstream can process it without a key. Row semantics is safe.
+ *
+ * Upsert mode (without UPDATE_BEFORE) requires a key to look up previous values, so set semantics
+ * with PARTITION BY is required.
+ */
+ private def verifyPtfTableArgsForUpdates(call: RexCall, changelogMode: ChangelogMode): Unit = {
+ if (
+ changelogMode.containsOnly(RowKind.INSERT) || changelogMode.contains(RowKind.UPDATE_BEFORE)
+ ) {
+ return
+ }
StreamPhysicalProcessTableFunction
.getProvidedInputArgs(call)
.map(_.e)
.foreach {
tableArg =>
if (tableArg.is(StaticArgumentTrait.ROW_SEMANTIC_TABLE)) {
throw new ValidationException(
- s"PTFs that take table arguments with row semantics don't support updating output. " +
+ s"PTFs that take table arguments with row semantics don't support upsert output. " +
s"Table argument '${tableArg.getName}' of function '${call.getOperator.toString}' " +
s"must use set semantics.")
}
diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/FromChangelogFunction.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/FromChangelogFunction.java
new file mode 100644
--- /dev/null
+++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/FromChangelogFunction.java
@@ -0,0 +1,147 @@
+/*
+ * 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.flink.table.runtime.functions.ptf;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.table.data.MapData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.StringData;
+import org.apache.flink.table.data.utils.ProjectedRowData;
+import org.apache.flink.table.functions.BuiltInFunctionDefinitions;
+import org.apache.flink.table.functions.FunctionContext;
+import org.apache.flink.table.functions.SpecializedFunction.SpecializedContext;
+import org.apache.flink.table.functions.TableSemantics;
+import org.apache.flink.table.types.inference.CallContext;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.types.ColumnList;
+import org.apache.flink.types.RowKind;
+
+import javax.annotation.Nullable;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+/**
+ * Runtime implementation of {@link BuiltInFunctionDefinitions#FROM_CHANGELOG}.
+ *
+ * <p>Converts each append-only input row (which contains an operation code column) back into a
+ * changelog stream with proper {@link RowKind} annotations. The output schema excludes the
+ * operation code column and partition key columns (which are prepended by the framework
+ * automatically).
+ *
+ * <p>This is the reverse operation of {@link ToChangelogFunction}.
+ */
+@Internal
+public class FromChangelogFunction extends BuiltInProcessTableFunction<RowData> {
+
+ private static final long serialVersionUID = 1L;
+
+ private static final String DEFAULT_OP_COLUMN_NAME = "op";
+ private static final Map<String, RowKind> DEFAULT_OP_MAPPING =
+ Map.of(
+ "INSERT", RowKind.INSERT,
+ "UPDATE_BEFORE", RowKind.UPDATE_BEFORE,
+ "UPDATE_AFTER", RowKind.UPDATE_AFTER,
+ "DELETE", RowKind.DELETE);
+
+ private final Map<String, RowKind> rawOpMap;
+ private final int opColumnIndex;
+ private final int[] outputIndices;
+
+ private transient HashMap<StringData, RowKind> opMap;
+ private transient ProjectedRowData projectedOutput;
+
+ public FromChangelogFunction(final SpecializedContext context) {
+ super(BuiltInFunctionDefinitions.FROM_CHANGELOG, context);
+ final CallContext callContext = context.getCallContext();
+
+ final TableSemantics tableSemantics =
+ callContext
+ .getTableSemantics(0)
+ .orElseThrow(() -> new IllegalStateException("Table argument expected."));
+
+ final RowType inputType = (RowType) tableSemantics.dataType().getLogicalType();
+ final String opColumnName = resolveOpColumnName(callContext);
+ this.opColumnIndex = inputType.getFieldNames().indexOf(opColumnName);
+
+ // Exclude only the op column from output — all other columns pass through
+ this.outputIndices =
+ IntStream.range(0, inputType.getFieldCount())
+ .filter(i -> i != opColumnIndex)
+ .toArray();
+
+ this.rawOpMap = buildOpMap(callContext);
+ }
+
+ @Override
+ public void open(final FunctionContext context) throws Exception {
+ super.open(context);
+ opMap = new HashMap<>();
+ rawOpMap.forEach((code, kind) -> opMap.put(StringData.fromString(code), kind));
+ projectedOutput = ProjectedRowData.from(outputIndices);
+ }
+
+ private static String resolveOpColumnName(final CallContext callContext) {
+ return callContext
+ .getArgumentValue(1, ColumnList.class)
+ .map(cl -> cl.getNames().get(0))
+ .orElse(DEFAULT_OP_COLUMN_NAME);
+ }
+
+ /**
+ * Builds a String-to-RowKind map. Keys in the provided mapping may be comma-separated (e.g.,
+ * "INSERT, UPDATE_AFTER") to map multiple input codes to the same RowKind.
+ */
+ private static Map<String, RowKind> buildOpMap(CallContext callContext) {
+ return callContext
+ .getArgumentValue(2, Map.class)
+ .map(FromChangelogFunction::parseOpMapping)
+ .orElse(DEFAULT_OP_MAPPING);
+ }
+
+ private static Map<String, RowKind> parseOpMapping(Map<String, String> opMapping) {
+ return opMapping.entrySet().stream()
+ .flatMap(
+ e -> {
+ final RowKind kind = RowKind.valueOf(e.getValue().trim());
+ return Arrays.stream(e.getKey().split(","))
+ .map(code -> Map.entry(code.trim(), kind));
+ })
+ .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
+ }
+
+ public void eval(
+ final Context ctx,
+ final RowData input,
+ @Nullable final ColumnList op,
+ @Nullable final MapData opMapping) {
+ final StringData opCode = input.getString(opColumnIndex);
+ final RowKind rowKind = opMap.get(opCode);
+ if (rowKind == null) {
+ return;
+ }
+
+ projectedOutput.replaceRow(input);
+ projectedOutput.setRowKind(rowKind);
+ collect(projectedOutput);
+ }
+}
|