You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by "raminqaf (via GitHub)" <gi...@apache.org> on 2026/05/22 15:23:28 UTC
[PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
raminqaf opened a new pull request, #28235:
URL: https://github.com/apache/flink/pull/28235
## What is the purpose of the change
Adds the built-in `TO_CHANGELOG` process table function (PTF) introduced in FLIP-564. The function converts a table (insert-only, retract, or upsert) into a changelog view that surfaces the row-kind (`INSERT`, `UPDATE_BEFORE`, `UPDATE_AFTER`, `DELETE`) as an explicit `op` column.
A new `produces_full_deletes` boolean parameter controls how DELETE rows are emitted. When `false` (default), the function emits partial DELETEs: the upsert-key columns of the input table are preserved and the remaining columns are nulled. When `true`, full DELETE rows are passed through unchanged. Partial deletes match the contract of most upsert sinks and avoid forcing users to retain full pre-image state.
## Brief change log
- Added `BuiltInFunctionDefinitions.TO_CHANGELOG` and the corresponding `ToChangelogFunction` runtime in `flink-table-api-java`.
- Added `StreamPhysicalToChangelog` / `StreamExecToChangelog` exec nodes wired through `FlinkRelMdChangelogMode` and `FlinkRelMdUpsertKeys` so the planner picks the correct downstream changelog mode.
- Computed the input upsert key at planning time via `FlinkRelMetadataQuery.getUpsertKeys(input)` collapsed to one candidate via `UpsertKeyUtil.smallestKey(...)`, and threaded it through the codegen path so the runtime knows which columns to keep on DELETE.
- Implemented row-semantics and set-semantics variants; `PARTITION BY` over a row-semantics input forwards the partitioning column as the upsert key.
- Added compiled-plan JSON support for `StreamExecProcessTableFunction` (new `inputUpsertKeys` field with a per-input empty-array default for back-compat with older plans).
## Verifying this change
This change added tests and can be verified as follows:
- New unit tests for the planner pieces in `ToChangelogTest`.
- New end-to-end semantic tests in `ToChangelogSemanticTests` covering: insert-only inputs, retract inputs with a derivable upsert key (partial DELETE), retract inputs with `produces_full_deletes=true` (full DELETE pass-through), `PARTITION BY` over a non-leading column, single-column upsert key from the input PK, and row semantics where the upsert key comes from the PK constraint rather than `PARTITION BY`.
- New restore test in `ToChangelogRestoreTest` validates the compiled-plan + savepoint round trip for a retract source.
- Validation tests for misuse: missing `input` argument, wrong argument type, conflicting `PARTITION BY` and upsert key.
- Run with: `mvn -pl flink-table/flink-table-planner test -Dtest='ToChangelogTest,ToChangelogSemanticTests,ToChangelogRestoreTest'`. Result: 50 pass, 1 skip (existing savepoint stub).
## Does this pull request potentially affect one of the following parts:
- Dependencies (does it add or upgrade a dependency): no
- The public API, i.e., is any changed class annotated with `@Public(Evolving)`: yes (new `BuiltInFunctionDefinitions.TO_CHANGELOG`; new compiled-plan JSON field on `StreamExecProcessTableFunction` with a back-compat default)
- The serializers: no
- The runtime per-record code paths (performance sensitive): yes (the `ToChangelogFunction` operator runs per record, but it only writes the row kind plus a projected key on DELETE; no extra state)
- Anything that affects deployment or recovery: JobManager (and its components), Checkpointing, Kubernetes/Yarn, ZooKeeper: no
- The S3 file system connector: no
## Documentation
- Does this pull request introduce a new feature? yes
- If yes, how is the feature documented? docs + JavaDocs (built-in function docs page entry plus `BuiltInFunctionDefinitions.TO_CHANGELOG` JavaDoc)
---
##### Was generative AI tooling used to co-author this PR?
- [X] Yes
Generated-by: Claude Opus 4.7
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "gustavodemorais (via GitHub)" <gi...@apache.org>.
gustavodemorais commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3304882090
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -397,6 +399,48 @@ SELECT * FROM TO_CHANGELOG(
-- UPDATE_BEFORE is dropped (not in the mapping)
```
+#### Delete handling
+
+The `produces_full_deletes` argument controls how DELETE rows are emitted and what the planner requires from the input. The behavior depends on whether `PARTITION BY` is used (set semantics) or not (row semantics).
+
+**With `produces_full_deletes => true`.** The planner requires the input to produce DELETE rows with all columns populated. For upsert sources, a `ChangelogNormalize` operator is inserted to materialize the full pre-image from state. The function then emits fully-populated DELETE rows downstream.
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
+-- Output: +I[op:'DELETE', id:5, name:'Alice']
+SELECT * FROM TO_CHANGELOG(
+ input => TABLE upsert_source,
+ produces_full_deletes => true
+)
+```
+
+**With `produces_full_deletes => false` (default).** The planner does not require fully-populated DELETE rows on the input. For upsert sources that emit key-only deletes (e.g. Kafka compacted topics), this avoids the stateful `ChangelogNormalize` operator that would otherwise materialize the full pre-image of each deleted row.
+
+In **row semantics** (no `PARTITION BY`), the function preserves the upsert key columns of the input on DELETE rows and nulls the rest. The upsert key is the one the planner already derives from the input (typically a declared `PRIMARY KEY`), so no `PARTITION BY` is required to get partial DELETEs.
+
+```sql
+-- Source 't' declares PRIMARY KEY (id). Source emits -D[id:5, name:'Alice'] (full pre-image).
+-- Output: +I[op:'DELETE', id:5, name:null]
+SELECT * FROM TO_CHANGELOG(input => TABLE t)
+```
+
+When the input has no derivable upsert key (e.g. a pure append-only source, or an upstream operator that erased the key), there is no identifying column to preserve. The function then passes the input through unchanged.
+
+```sql
+-- Source emits -D[id:5] (key-only, no declared key).
+-- Output: +I[op:'DELETE', id:5, name:null]
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source)
+```
Review Comment:
The example here is not matching what you want to show. You mention it passes through unchanged but the example does name:null
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "gustavodemorais (via GitHub)" <gi...@apache.org>.
gustavodemorais commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3311467478
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/ToChangelogTestPrograms.java:
##########
@@ -187,7 +187,8 @@ public class ToChangelogTestPrograms {
public static final TableTestProgram UPSERT_PARTITION_BY =
TableTestProgram.of(
"to-changelog-upsert-partition-by",
- "PARTITION BY upsert key + mapping without UB skips ChangelogNormalize")
+ "PARTITION BY upsert key + mapping without UB skips ChangelogNormalize; "
+ + "default produces_full_deletes=false nulls non-key columns on DELETE")
Review Comment:
"default produces_full_deletes=false" is wrong and not relevant to the test. I think you can just delete this additional description you added
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/PartitionedTable.java:
##########
@@ -204,9 +204,17 @@ public interface PartitionedTable {
* descriptor("deleted").asArgument("op"),
* map("INSERT, UPDATE_AFTER", "false", "DELETE", "true").asArgument("op_mapping")
* );
+ *
+ * // Opt out of full-delete semantics. When `true` (default), DELETE rows carry the full
+ * // pre-image. When `false`, only the identifying key columns are preserved and the rest
+ * // are nulled. See [Delete handling](#delete-handling) for more details.
Review Comment:
I added the suggestion manually so didn't paste the proper link. Can you make sure you add the proper link and formatting for both partitionedtable and table?
```suggestion
* // are nulled. See [Full or partial deletes](<correct link>) for more details.
```
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -434,6 +520,15 @@ Table result = myTable.toChangelog(
map("INSERT, UPDATE_AFTER", "false", "DELETE", "true").asArgument("op_mapping")
);
+// Require fully-populated DELETE rows from the input (inserts a ChangelogNormalize for
+// upsert sources). When false (default), no full-delete requirement is enforced; in row
Review Comment:
"When false (default)" still out of date. Can you double check we changed the default and adjusted docs everywhere?
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "gustavodemorais (via GitHub)" <gi...@apache.org>.
gustavodemorais commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3304943274
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/BuiltInFunctionDefinitions.java:
##########
@@ -840,25 +840,35 @@ ANY, and(logical(LogicalTypeRoot.BOOLEAN), LITERAL)
"UPDATE_BEFORE"))))
.withConditionalTrait(
StaticArgumentTrait.REQUIRE_FULL_DELETE,
- TraitCondition.or(
- // op_mapping omitted: default mapping includes
- // DELETE.
- TraitCondition.not(
- TraitCondition.argIsPresent(
- "op_mapping")),
- TraitCondition.argMatches(
- "op_mapping",
- Map.class,
- mapping ->
- opMappingContainsKey(
- (Map<String, String>)
- mapping,
- "DELETE")))),
+ // Require full deletes only when the user explicitly
+ // asks for them via produces_full_deletes=TRUE *and*
+ // the active op_mapping includes DELETE. Otherwise the
+ // planner can skip ChangelogNormalize for upsert
+ // sources that emit key-only deletes.
+ TraitCondition.and(
+ TraitCondition.argIsEqualTo(
+ "produces_full_deletes", Boolean.TRUE),
Review Comment:
Let's go with produces_full_deletes yes as default (adjustment from the flip). This aligns with what we added in the first versions and I think it's a better default behavior than the opposite.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3311157138
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/Table.java:
##########
@@ -1459,9 +1459,19 @@ default TableResult executeInsert(
* descriptor("deleted").asArgument("op"),
* map("INSERT, UPDATE_AFTER", "false", "DELETE", "true").asArgument("op_mapping")
* );
+ *
+ * // Opt out of full-delete semantics. The default (true) requires fully-populated DELETE
+ * // rows and inserts a ChangelogNormalize for upsert sources. When false, the function
+ * // emits partial DELETE rows: row semantics preserves the planner-derived upsert key
+ * // columns and nulls the rest; set semantics preserves the partition key. Requires an
+ * // upsert key or PARTITION BY; otherwise the call is rejected.
Review Comment:
Done
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3310127287
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -397,6 +399,48 @@ SELECT * FROM TO_CHANGELOG(
-- UPDATE_BEFORE is dropped (not in the mapping)
```
+#### Delete handling
+
+The `produces_full_deletes` argument controls how DELETE rows are emitted and what the planner requires from the input. The behavior depends on whether `PARTITION BY` is used (set semantics) or not (row semantics).
+
+**With `produces_full_deletes => true`.** The planner requires the input to produce DELETE rows with all columns populated. For upsert sources, a `ChangelogNormalize` operator is inserted to materialize the full pre-image from state. The function then emits fully-populated DELETE rows downstream.
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
+-- Output: +I[op:'DELETE', id:5, name:'Alice']
+SELECT * FROM TO_CHANGELOG(
+ input => TABLE upsert_source,
+ produces_full_deletes => true
+)
+```
+
+**With `produces_full_deletes => false` (default).** The planner does not require fully-populated DELETE rows on the input. For upsert sources that emit key-only deletes (e.g. Kafka compacted topics), this avoids the stateful `ChangelogNormalize` operator that would otherwise materialize the full pre-image of each deleted row.
+
+In **row semantics** (no `PARTITION BY`), the function preserves the upsert key columns of the input on DELETE rows and nulls the rest. The upsert key is the one the planner already derives from the input (typically a declared `PRIMARY KEY`), so no `PARTITION BY` is required to get partial DELETEs.
+
+```sql
+-- Source 't' declares PRIMARY KEY (id). Source emits -D[id:5, name:'Alice'] (full pre-image).
+-- Output: +I[op:'DELETE', id:5, name:null]
+SELECT * FROM TO_CHANGELOG(input => TABLE t)
+```
+
+When the input has no derivable upsert key (e.g. a pure append-only source, or an upstream operator that erased the key), there is no identifying column to preserve. The function then passes the input through unchanged.
+
+```sql
+-- Source emits -D[id:5] (key-only, no declared key).
+-- Output: +I[op:'DELETE', id:5, name:null]
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source)
+```
Review Comment:
I re-wrote the docs on deletion. Explaining
<table>
<tr>
<td> /
<td> <b>produces_full_deletes=true</b>
<td> <b>produces_full_deletes=false</b>
<tr>
<td> <b>Set Semantic (PARTITION BY)</b>
<td> Source emits Upsert/Retract + (No)Need ChangelogNormalizer + Output
<td> Source emits Upsert/Retract + (No)Need ChangelogNormalizer + Output
<tr>
<td> <b>Row Semantic (no PARTITION BY)</b>
<td> Source emits Upsert/Retract + (No)Need ChangelogNormalizer + Output
<td> Source emits Upsert/Retract + (No)Need ChangelogNormalizer + Output
</table>
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3310134162
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/ToChangelogFunction.java:
##########
@@ -65,11 +70,16 @@ public class ToChangelogFunction extends BuiltInProcessTableFunction<RowData> {
private final Map<RowKind, String> rawOpMap;
private final int[] outputIndices;
+ private final RowType inputRowType;
+ private final boolean producesFullDelete;
+ private final boolean[] preserveOnDelete;
Review Comment:
Renamed to `upsertKeyColumn`. WDYT?
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3317908572
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/ToChangelogTypeStrategy.java:
##########
@@ -187,12 +198,63 @@ private static Optional<List<DataType>> validateOpMappingKeys(
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);
+ @SuppressWarnings("rawtypes")
+ private static Optional<List<DataType>> validateProducesFullDeletes(
+ final CallContext callContext, final boolean throwOnFailure) {
+ final boolean isExplicit = !callContext.isArgumentNull(ARG_PRODUCES_FULL_DELETES);
+ if (!isExplicit) {
+ return Optional.empty();
+ }
+ if (!callContext.isArgumentLiteral(ARG_PRODUCES_FULL_DELETES)) {
+ return callContext.fail(
+ throwOnFailure,
+ "The 'produces_full_deletes' argument must be a constant BOOLEAN literal.");
+ }
+ final boolean producesFullDeletes =
+ callContext.getArgumentValue(ARG_PRODUCES_FULL_DELETES, Boolean.class).orElse(true);
+ if (!producesFullDeletes) {
+ return Optional.empty();
+ }
+ // The check against the input changelog mode lives in the function constructor since
+ // TableSemantics#changelogMode() returns empty here at type-inference time. The mapping
+ // check below only needs the literal op_mapping argument, so it lives here. Only runs
+ // when the user explicitly set produces_full_deletes=true; the default true is not
+ // validated since it is a safe no-op for any input.
+ final Optional<Map> opMapping = callContext.getArgumentValue(ARG_OP_MAPPING, Map.class);
+ if (opMapping.isPresent() && !mapsDelete((Map<String, String>) opMapping.get())) {
Review Comment:
As discussed removed this validation
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3311151419
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/PartitionedTable.java:
##########
@@ -204,9 +204,18 @@ public interface PartitionedTable {
* descriptor("deleted").asArgument("op"),
* map("INSERT, UPDATE_AFTER", "false", "DELETE", "true").asArgument("op_mapping")
* );
+ *
+ * // Opt out of full-delete semantics. The default (true) requires fully-populated DELETE
+ * // rows and inserts a ChangelogNormalize for upsert sources. When false, the function
+ * // preserves the partition key on DELETE rows and nulls the rest, which avoids the
+ * // stateful normalization operator upstream.
+ * Table result = table
+ * .partitionBy($("id"))
+ * .toChangelog(lit(false).asArgument("produces_full_deletes"));
Review Comment:
Made it simpler
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "gustavodemorais (via GitHub)" <gi...@apache.org>.
gustavodemorais commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3312237978
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/ToChangelogTestPrograms.java:
##########
@@ -157,7 +157,7 @@ public class ToChangelogTestPrograms {
public static final TableTestProgram UPSERT =
TableTestProgram.of(
"to-changelog-upsert-input",
- "upsert input gets ChangelogNormalize for UPDATE_BEFORE and full deletes")
+ "upsert input in row semantics gets ChangelogNormalize for UPDATE_BEFORE and emits partial deletes")
Review Comment:
Says "emits partial deletes" but the test doesn't pass produces_full_deletes → defaults to true → output is +I[DELETE, Bob, 20] (full row). The original "and full deletes" was right
```suggestion
"upsert input in row semantics gets ChangelogNormalize for UPDATE_BEFORE and emits full deletes")
```
##########
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/process/ProcessSetTableOperatorInterruptibleTimersTest.java:
##########
@@ -246,7 +246,8 @@ private static RuntimeTableSemantics tableSemantics() {
RuntimeChangelogMode.serialize(ChangelogMode.insertOnly()),
/* passColumnsThrough */ false,
/* hasSetSemantics */ true,
- /* timeColumn */ 1);
+ /* timeColumn */ 1,
+ /* upsertKeyColumns */ new int[0]);
Review Comment:
I think this will not compile, old type
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecProcessTableFunction.java:
##########
@@ -121,6 +123,10 @@ public class StreamExecProcessTableFunction extends ExecNodeBase<RowData>
@JsonProperty(FIELD_NAME_OUTPUT_CHANGELOG_MODE)
private final ChangelogMode outputChangelogMode;
+ @JsonProperty(FIELD_NAME_INPUT_UPSERT_KEYS)
+ @JsonInclude(JsonInclude.Include.NON_EMPTY)
+ private final List<int[]> inputUpsertKeys;
Review Comment:
TableSemantics is per-input - users access it via callContext.getTableSemantics(pos) and partitionByColumns() / changelogMode() / timeColumn() are already scoped to one input.
upsertKeyColumns() breaks the pattern: StreamPhysicalProcessTableFunction does .flatMap(List::stream) across all inputs, and OperatorBindingCallContext.getTableSemantics hands the whole flat list to every position. Single-input TO_CHANGELOG hides this (only one input, both numbers are 1) but any multi-input PTF would see other inputs' keys mixed in. Field should be List<List<int[]>> indexed by input position, then sliced like inputChangelogModes.get(tableArgCall.getInputIndex()).
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3312247530
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecProcessTableFunction.java:
##########
@@ -121,6 +123,10 @@ public class StreamExecProcessTableFunction extends ExecNodeBase<RowData>
@JsonProperty(FIELD_NAME_OUTPUT_CHANGELOG_MODE)
private final ChangelogMode outputChangelogMode;
+ @JsonProperty(value = FIELD_NAME_INPUT_UPSERT_KEYS, defaultValue = "[]")
+ @JsonInclude(JsonInclude.Include.NON_DEFAULT)
Review Comment:
Good catch! It is addressed
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3311155353
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -397,6 +399,76 @@ SELECT * FROM TO_CHANGELOG(
-- UPDATE_BEFORE is dropped (not in the mapping)
```
+#### Delete handling
+
+The `produces_full_deletes` argument controls how DELETE rows are emitted and what the planner requires from the input. The matrix below shows each combination with `PARTITION BY` (set semantics) and without (row semantics).
+
+##### `produces_full_deletes => true` (default)
+
+The planner requires fully-populated DELETE rows on the input. For upsert sources that emit key-only deletes, a `ChangelogNormalize` operator is inserted upstream to materialize the full pre-image from state. For sources that already emit a full pre-image (e.g. retract), the flag is a no-op. The function then passes the input row through unchanged on DELETE.
+
+**Row semantics** (no `PARTITION BY`):
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
+-- Output: +I[op:'DELETE', id:5, name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source)
+
+-- Retract source: -D[id:5, name:'Alice'] (full pre-image).
+-- No ChangelogNormalize inserted; the input row is passed through unchanged.
+-- Output: +I[op:'DELETE', id:5, name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source)
+```
+
+**Set semantics** (`PARTITION BY`):
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
+-- Output: +I[id:5, op:'DELETE', name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source PARTITION BY id)
+
+-- Retract source: -D[id:5, name:'Alice'] (full pre-image).
+-- No ChangelogNormalize inserted; the input row is passed through unchanged.
+-- Output: +I[id:5, op:'DELETE', name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source PARTITION BY id)
+```
+
+##### `produces_full_deletes => false`
+
+The planner skips `ChangelogNormalize` and the function emits partial DELETE rows. This avoids the stateful normalization operator for upsert sources (e.g. Kafka compacted topics) where the full pre-image is not needed downstream. Requires an upsert key (row semantics) or `PARTITION BY` (set semantics); otherwise the call is rejected with a validation error.
+
+**Row semantics** (no `PARTITION BY`): the function preserves the planner-derived upsert key columns on DELETE rows and nulls the rest. The upsert key is typically a declared `PRIMARY KEY`.
+
+```sql
+-- Upsert source with PRIMARY KEY (id): -D[id:5] (key-only).
+-- Output: +I[op:'DELETE', id:5, name:null]
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source, produces_full_deletes => false)
+
+-- Retract source with PRIMARY KEY (id): -D[id:5, name:'Alice'] (full pre-image).
+-- Output: +I[op:'DELETE', id:5, name:null]
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source, produces_full_deletes => false)
+```
+
+**Set semantics** (`PARTITION BY`): the function preserves the partition key and nulls every non-partition-key column on DELETE rows. This matches the shape expected by upsert sinks and Kafka compacted topics.
Review Comment:
done
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -296,17 +296,19 @@ This is useful when you need to materialize changelog events into a downstream s
SELECT * FROM TO_CHANGELOG(
input => TABLE source_table [PARTITION BY key_col],
[op => DESCRIPTOR(op_column_name),]
- [op_mapping => MAP['INSERT', 'I', 'DELETE', 'D', ...]]
+ [op_mapping => MAP['INSERT', 'I', 'DELETE', 'D', ...],]
+ [produces_full_deletes => BOOLEAN]
)
```
### Parameters
-| Parameter | Required | Description |
-|:-------------|:---------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| `input` | Yes | The input table. With `PARTITION BY`, rows with the same key are co-located and run in the same operator instance. Without `PARTITION BY`, each row is processed independently. Accepts insert-only, retract, and upsert tables. For upsert tables, the provided `PARTITION BY` key should match or be a subset of the upsert key of the subquery. |
-| `op` | No | A `DESCRIPTOR` with a single column name for the operation code column. Defaults to `op`. |
-| `op_mapping` | No | A `MAP<STRING, STRING>` mapping change operation names to custom output codes. Keys can contain comma-separated names to map multiple operations to the same code (e.g., `'INSERT, UPDATE_AFTER'`). When provided, only mapped operations are forwarded - unmapped events are dropped. Each change operation may appear at most once across all entries. |
+| Parameter | Required | Description |
+|:------------------------|:---------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| `input` | Yes | The input table. With `PARTITION BY`, rows with the same key are co-located and run in the same operator instance. Without `PARTITION BY`, each row is processed independently. Accepts insert-only, retract, and upsert tables. For upsert tables, the provided `PARTITION BY` key should match or be a subset of the upsert key of the subquery. |
+| `op` | No | A `DESCRIPTOR` with a single column name for the operation code column. Defaults to `op`. |
+| `op_mapping` | No | A `MAP<STRING, STRING>` mapping change operation names to custom output codes. Keys can contain comma-separated names to map multiple operations to the same code (e.g., `'INSERT, UPDATE_AFTER'`). When provided, only mapped operations are forwarded - unmapped events are dropped. Each change operation may appear at most once across all entries. |
+| `produces_full_deletes` | No | A `BOOLEAN` literal that controls how DELETE rows are emitted. When `true` (default), the function requires fully-populated DELETE rows from the input. The planner inserts a `ChangelogNormalize` operator for upsert sources that emit key-only deletes, so downstream sees the full pre-image on DELETE. When `false`, the function instead emits partial DELETE rows: in row semantics it preserves the planner-derived upsert key columns of the input and nulls the rest; in set semantics (`PARTITION BY`) it preserves the partition key and nulls the rest. Requires that the input declares an upsert key or that the call uses `PARTITION BY`; otherwise the function has no identifying columns to preserve and the call is rejected. |
Review Comment:
Done
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3311145532
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/ToChangelogTypeStrategy.java:
##########
@@ -187,12 +198,63 @@ private static Optional<List<DataType>> validateOpMappingKeys(
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);
+ @SuppressWarnings("rawtypes")
+ private static Optional<List<DataType>> validateProducesFullDeletes(
+ final CallContext callContext, final boolean throwOnFailure) {
+ final boolean isExplicit = !callContext.isArgumentNull(ARG_PRODUCES_FULL_DELETES);
+ if (!isExplicit) {
+ return Optional.empty();
+ }
+ if (!callContext.isArgumentLiteral(ARG_PRODUCES_FULL_DELETES)) {
+ return callContext.fail(
+ throwOnFailure,
+ "The 'produces_full_deletes' argument must be a constant BOOLEAN literal.");
+ }
+ final boolean producesFullDeletes =
+ callContext.getArgumentValue(ARG_PRODUCES_FULL_DELETES, Boolean.class).orElse(true);
+ if (!producesFullDeletes) {
+ return Optional.empty();
+ }
+ // The check against the input changelog mode lives in the function constructor since
+ // TableSemantics#changelogMode() returns empty here at type-inference time. The mapping
+ // check below only needs the literal op_mapping argument, so it lives here. Only runs
+ // when the user explicitly set produces_full_deletes=true; the default true is not
+ // validated since it is a safe no-op for any input.
+ final Optional<Map> opMapping = callContext.getArgumentValue(ARG_OP_MAPPING, Map.class);
+ if (opMapping.isPresent() && !mapsDelete((Map<String, String>) opMapping.get())) {
+ return callContext.fail(
+ throwOnFailure,
+ "Invalid 'produces_full_deletes' for TO_CHANGELOG: the active 'op_mapping' "
+ + "does not map DELETE rows, so no DELETE rows are emitted. Remove "
+ + "the 'produces_full_deletes' argument or add a DELETE entry to "
+ + "'op_mapping'.");
+ }
+ return Optional.empty();
+ }
+
+ /**
+ * Returns {@code true} when at least one {@code op_mapping} key references {@code DELETE}. Keys
+ * may be comma-separated (e.g., {@code "INSERT, DELETE"}) per the user-facing contract.
+ */
+ private static boolean mapsDelete(final Map<String, String> opMapping) {
+ for (final String key : opMapping.keySet()) {
+ for (final String rawName : key.split(",")) {
+ if (DELETE.equals(rawName.trim())) {
Review Comment:
added
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/ToChangelogTypeStrategy.java:
##########
Review Comment:
added
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3310087898
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/inference/CallBindingCallContext.java:
##########
@@ -312,6 +312,11 @@ public int timeColumn() {
public Optional<ChangelogMode> changelogMode() {
return Optional.empty();
}
+
+ @Override
+ public int[] upsertKeyColumns() {
+ return new int[0];
Review Comment:
I have updated the docs on this and hopefully makes it more clear now
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3310128400
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/ToChangelogFunction.java:
##########
@@ -84,7 +94,48 @@ public ToChangelogFunction(final SpecializedContext context) {
if (opMapping != null) {
validateOpMap(this.rawOpMap, tableSemantics);
}
+ final boolean producesFullDeletesArg =
+ callContext.getArgumentValue(3, Boolean.class).orElse(false);
Review Comment:
Good catch updated
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "gustavodemorais (via GitHub)" <gi...@apache.org>.
gustavodemorais commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3304872652
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/ToChangelogFunction.java:
##########
@@ -84,7 +94,48 @@ public ToChangelogFunction(final SpecializedContext context) {
if (opMapping != null) {
validateOpMap(this.rawOpMap, tableSemantics);
}
+ final boolean producesFullDeletesArg =
+ callContext.getArgumentValue(3, Boolean.class).orElse(false);
Review Comment:
Didn't we add constant for these indexes?
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3312031991
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -434,6 +520,15 @@ Table result = myTable.toChangelog(
map("INSERT, UPDATE_AFTER", "false", "DELETE", "true").asArgument("op_mapping")
);
+// Require fully-populated DELETE rows from the input (inserts a ChangelogNormalize for
+// upsert sources). When false (default), no full-delete requirement is enforced; in row
Review Comment:
Updated all the docs and everything should be aligned now!
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/PartitionedTable.java:
##########
@@ -204,9 +204,17 @@ public interface PartitionedTable {
* descriptor("deleted").asArgument("op"),
* map("INSERT, UPDATE_AFTER", "false", "DELETE", "true").asArgument("op_mapping")
* );
+ *
+ * // Opt out of full-delete semantics. When `true` (default), DELETE rows carry the full
+ * // pre-image. When `false`, only the identifying key columns are preserved and the rest
+ * // are nulled. See [Delete handling](#delete-handling) for more details.
Review Comment:
Fixed!
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3311143540
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/ToChangelogTestPrograms.java:
##########
@@ -598,4 +599,220 @@ public class ToChangelogTestPrograms {
ValidationException.class,
"Duplicate change operation: 'DELETE'")
.build();
+
+ public static final TableTestProgram PRODUCES_FULL_DELETES_ON_APPEND_ONLY_INPUT =
+ TableTestProgram.of(
+ "to-changelog-produces-full-deletes-on-append-only-input",
+ "fails when produces_full_deletes=true on an input that never emits DELETE rows")
+ .setupTableSource(SIMPLE_SOURCE)
+ .runFailingSql(
+ "SELECT * FROM TO_CHANGELOG("
+ + "input => TABLE t, "
+ + "produces_full_deletes => true)",
+ ValidationException.class,
+ "the input table only produces [INSERT] and never emits DELETE rows")
+ .build();
+
+ // --------------------------------------------------------------------------------------------
+ // Row semantics x delete handling matrix
+ // --------------------------------------------------------------------------------------------
+
+ public static final TableTestProgram ROW_SEM_PARTIAL_DELETES =
+ TableTestProgram.of(
+ "to-changelog-row-sem-partial-deletes",
+ "row semantics: produces_full_deletes=false skips ChangelogNormalize and a partial DELETE row from the input passes through unchanged")
+ .setupTableSource(
+ SourceTestStep.newBuilder("t")
+ .addSchema(
+ "name STRING PRIMARY KEY NOT ENFORCED", "score BIGINT")
+ .addMode(ChangelogMode.all())
+ .producedValues(
+ Row.ofKind(RowKind.INSERT, "Alice", 10L),
+ Row.ofKind(RowKind.INSERT, "Bob", 20L),
+ Row.ofKind(RowKind.UPDATE_BEFORE, "Alice", 10L),
+ Row.ofKind(RowKind.UPDATE_AFTER, "Alice", 30L),
+ Row.ofKind(RowKind.DELETE, "Bob", null))
+ .build())
+ .setupTableSink(
+ SinkTestStep.newBuilder("sink")
+ .addSchema("op STRING", "name STRING", "score BIGINT")
+ .consumedValues(
+ "+I[INSERT, Alice, 10]",
+ "+I[INSERT, Bob, 20]",
+ "+I[UPDATE_BEFORE, Alice, 10]",
+ "+I[UPDATE_AFTER, Alice, 30]",
+ "+I[DELETE, Bob, null]")
+ .build())
+ .runSql(
+ "INSERT INTO sink SELECT * FROM TO_CHANGELOG("
+ + "input => TABLE t, "
+ + "produces_full_deletes => false)")
+ .build();
+
+ public static final TableTestProgram ROW_SEM_FORCE_FULL_DELETES =
+ TableTestProgram.of(
+ "to-changelog-row-sem-force-full-deletes",
+ "row semantics: produces_full_deletes=true forces ChangelogNormalize to materialize the full DELETE row from an upsert source emitting key-only deletes")
+ .setupTableSource(
+ SourceTestStep.newBuilder("t")
+ .addSchema(
+ "name STRING PRIMARY KEY NOT ENFORCED", "score BIGINT")
+ .addMode(ChangelogMode.upsert())
+ .producedValues(
+ Row.ofKind(RowKind.INSERT, "Alice", 10L),
+ // Key-only delete: ChangelogNormalize fills the row.
+ Row.ofKind(RowKind.DELETE, "Alice", null))
+ .build())
+ .setupTableSink(
+ SinkTestStep.newBuilder("sink")
+ .addSchema("op STRING", "name STRING", "score BIGINT")
+ .consumedValues(
+ "+I[INSERT, Alice, 10]", "+I[DELETE, Alice, 10]")
+ .build())
+ .runSql(
+ "INSERT INTO sink SELECT * FROM TO_CHANGELOG("
+ + "input => TABLE t, "
+ + "produces_full_deletes => true)")
+ .build();
+
+ public static final TableTestProgram ROW_SEM_PARTIAL_DELETES_VIA_UPSERT_KEY =
+ TableTestProgram.of(
+ "to-changelog-row-sem-partial-deletes-via-upsert-key",
+ "row semantics with single-column upsert key + "
+ + "produces_full_deletes=false: DELETE preserves the key "
+ + "column and nulls the rest without requiring PARTITION BY")
+ .setupTableSource(
+ SourceTestStep.newBuilder("t")
+ .addSchema(
+ "name STRING PRIMARY KEY NOT ENFORCED", "score BIGINT")
+ .addMode(ChangelogMode.upsert())
+ .producedValues(
+ Row.ofKind(RowKind.INSERT, "Alice", 10L),
+ Row.ofKind(RowKind.DELETE, "Alice", 10L))
+ .build())
+ .setupTableSink(
+ SinkTestStep.newBuilder("sink")
+ .addSchema("op STRING", "name STRING", "score BIGINT")
+ .consumedValues(
+ "+I[INSERT, Alice, 10]", "+I[DELETE, Alice, null]")
+ .build())
+ .runSql(
+ "INSERT INTO sink SELECT * FROM TO_CHANGELOG("
+ + "input => TABLE t, "
+ + "produces_full_deletes => false)")
+ .build();
+
+ // --------------------------------------------------------------------------------------------
+ // Set semantics x delete handling matrix
+ // --------------------------------------------------------------------------------------------
+
+ public static final TableTestProgram SET_SEM_FORCE_PARTIAL_DELETES =
+ TableTestProgram.of(
+ "to-changelog-set-sem-force-partial-deletes",
+ "set semantics: produces_full_deletes=false nulls non-partition-key columns on DELETE even when the input row is fully populated")
+ .setupTableSource(
+ SourceTestStep.newBuilder("t")
+ .addSchema(
+ "name STRING PRIMARY KEY NOT ENFORCED", "score BIGINT")
+ .addMode(ChangelogMode.all())
+ .producedValues(
+ Row.ofKind(RowKind.INSERT, "Alice", 10L),
+ Row.ofKind(RowKind.INSERT, "Bob", 20L),
+ Row.ofKind(RowKind.UPDATE_AFTER, "Alice", 30L),
+ Row.ofKind(RowKind.DELETE, "Bob", 20L))
+ .build())
+ .setupTableSink(
+ SinkTestStep.newBuilder("sink")
+ .addSchema("name STRING", "op STRING", "score BIGINT")
+ .consumedValues(
+ "+I[Alice, INSERT, 10]",
+ "+I[Bob, INSERT, 20]",
+ "+I[Alice, UPDATE_AFTER, 30]",
+ "+I[Bob, DELETE, null]")
+ .build())
+ .runSql(
+ "INSERT INTO sink SELECT * FROM TO_CHANGELOG("
+ + "input => TABLE t PARTITION BY name,"
+ + "produces_full_deletes => false)")
+ .build();
+
+ public static final TableTestProgram SET_SEM_PARTIAL_DELETES =
+ TableTestProgram.of(
+ "to-changelog-set-sem-partial-deletes",
+ "set semantics: produces_full_deletes=false (default) lets a partial DELETE row from the input pass through with non-partition-key columns null")
Review Comment:
Corrected
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/ToChangelogTestPrograms.java:
##########
@@ -598,4 +599,220 @@ public class ToChangelogTestPrograms {
ValidationException.class,
"Duplicate change operation: 'DELETE'")
.build();
+
+ public static final TableTestProgram PRODUCES_FULL_DELETES_ON_APPEND_ONLY_INPUT =
+ TableTestProgram.of(
+ "to-changelog-produces-full-deletes-on-append-only-input",
+ "fails when produces_full_deletes=true on an input that never emits DELETE rows")
+ .setupTableSource(SIMPLE_SOURCE)
+ .runFailingSql(
+ "SELECT * FROM TO_CHANGELOG("
+ + "input => TABLE t, "
+ + "produces_full_deletes => true)",
+ ValidationException.class,
+ "the input table only produces [INSERT] and never emits DELETE rows")
+ .build();
+
+ // --------------------------------------------------------------------------------------------
+ // Row semantics x delete handling matrix
+ // --------------------------------------------------------------------------------------------
+
+ public static final TableTestProgram ROW_SEM_PARTIAL_DELETES =
Review Comment:
Renamed
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "gustavodemorais (via GitHub)" <gi...@apache.org>.
gustavodemorais commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3289465994
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/ToChangelogFunction.java:
##########
@@ -85,6 +100,33 @@ public ToChangelogFunction(final SpecializedContext context) {
validateOpMap(this.rawOpMap, tableSemantics);
}
this.outputIndices = ChangelogTypeStrategyUtils.computeOutputIndices(tableSemantics);
+ this.inputRowType = (RowType) tableSemantics.dataType().getLogicalType();
+ final boolean producesFullDeletes =
+ callContext.getArgumentValue(3, Boolean.class).orElse(false);
+ final int[] upsertKeys = tableSemantics.upsertKeyColumns();
+ final boolean hasPartitionBy = tableSemantics.partitionByColumns().length > 0;
+ // We emit partial deletes when the caller did not ask for full ones and we know which
+ // input columns identify a row. The framework prepends partition-key columns to the
+ // output without consulting the function, so in set semantics partition keys are
+ // preserved on DELETE rows for free. In row semantics we rely on the input table's
+ // upsert key to preserve identifying columns on DELETE; without one we cannot null
+ // anything safely and pass the input through unchanged.
+ this.nullPayloadOnDelete =
+ !producesFullDeletes && (hasPartitionBy || upsertKeys.length > 0);
Review Comment:
Also, do we want to throw a nice validation error if the user asks for producesFullDeletes and we can't produce it
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "gustavodemorais (via GitHub)" <gi...@apache.org>.
gustavodemorais commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3318588333
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/PartitionedTable.java:
##########
@@ -204,9 +204,18 @@ public interface PartitionedTable {
* descriptor("deleted").asArgument("op"),
* map("INSERT, UPDATE_AFTER", "false", "DELETE", "true").asArgument("op_mapping")
* );
+ *
+ * // Opt out of full-delete semantics. When `true` (default), DELETE rows carry the full
+ * // pre-image. When `false`, only the identifying key columns are preserved and the rest
+ * // are nulled. See in documentation.
+ * // for more details.
Review Comment:
wrong "See in documentation.
* // for more details."
##########
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/inference/strategies/ToChangelogOutputTypeStrategyTest.java:
##########
@@ -0,0 +1,110 @@
+/*
+ * 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.table.api.DataTypes;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.inference.TypeStrategiesTestBase;
+import org.apache.flink.table.types.inference.utils.TableSemanticsMock;
+import org.apache.flink.types.ColumnList;
+
+import java.util.List;
+import java.util.stream.Stream;
+
+import static org.apache.flink.table.types.inference.strategies.SpecificTypeStrategies.TO_CHANGELOG_OUTPUT_TYPE_STRATEGY;
+import static org.apache.flink.table.types.inference.strategies.ToChangelogTypeStrategy.ARG_OP;
+import static org.apache.flink.table.types.inference.strategies.ToChangelogTypeStrategy.ARG_OP_MAPPING;
+import static org.apache.flink.table.types.inference.strategies.ToChangelogTypeStrategy.ARG_PRODUCES_FULL_DELETES;
+import static org.apache.flink.table.types.inference.strategies.ToChangelogTypeStrategy.ARG_TABLE;
+
+/** Tests for {@link ToChangelogTypeStrategy#OUTPUT_TYPE_STRATEGY}. */
+class ToChangelogOutputTypeStrategyTest extends TypeStrategiesTestBase {
+
+ private static final DataType TABLE_TYPE_NOT_NULL_SCORE =
+ DataTypes.ROW(
+ DataTypes.FIELD("name", DataTypes.STRING().notNull()),
+ DataTypes.FIELD("score", DataTypes.BIGINT().notNull()));
+
+ private static final DataType DESCRIPTOR_TYPE = DataTypes.DESCRIPTOR();
+ private static final DataType MAP_TYPE = DataTypes.MAP(DataTypes.STRING(), DataTypes.STRING());
+ private static final DataType BOOLEAN_TYPE = DataTypes.BOOLEAN();
+
+ @Override
+ protected Stream<TestSpec> testData() {
+ return Stream.of(
+ TestSpec.forStrategy(
+ "produces_full_deletes=true preserves NOT NULL on input columns",
Review Comment:
Nice, the row-semantics widening is well-covered (preserved key keeps NOT NULL, conservative widening when no upsert key). I think no case exercises set semantics, could you also add those?
We have two logics for masking things both in the function and in the type strategy so testing in this case is a good idea to make sure we don't break it by accident when iterating on it in the future
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/PartitionedTable.java:
##########
@@ -204,9 +204,18 @@ public interface PartitionedTable {
* descriptor("deleted").asArgument("op"),
* map("INSERT, UPDATE_AFTER", "false", "DELETE", "true").asArgument("op_mapping")
* );
+ *
+ * // Opt out of full-delete semantics. When `true` (default), DELETE rows carry the full
+ * // pre-image. When `false`, only the identifying key columns are preserved and the rest
+ * // are nulled. See in documentation.
+ * // for more details.
Review Comment:
Also, you still have the link in table.java "See [Full vs partial deletes](
* // https://nightlies.apache.org/flink/flink-docs-master/docs/dev/table/sql/queries/changelog/#full-vs-partial-deletes)
* // for more details."
Could you fix and align both?
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3320499712
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/PartitionedTable.java:
##########
@@ -204,9 +204,18 @@ public interface PartitionedTable {
* descriptor("deleted").asArgument("op"),
* map("INSERT, UPDATE_AFTER", "false", "DELETE", "true").asArgument("op_mapping")
* );
+ *
+ * // Opt out of full-delete semantics. When `true` (default), DELETE rows carry the full
+ * // pre-image. When `false`, only the identifying key columns are preserved and the rest
+ * // are nulled. See in documentation.
+ * // for more details.
Review Comment:
Yeah, thanks for pointing this out. It is fixed now
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "gustavodemorais (via GitHub)" <gi...@apache.org>.
gustavodemorais commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3304570806
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/ToChangelogFunction.java:
##########
@@ -65,11 +70,16 @@ public class ToChangelogFunction extends BuiltInProcessTableFunction<RowData> {
private final Map<RowKind, String> rawOpMap;
private final int[] outputIndices;
+ private final RowType inputRowType;
+ private final boolean producesFullDelete;
+ private final boolean[] preserveOnDelete;
Review Comment:
Something like this probably makes more sense
```suggestion
private final boolean[] upsertKeyIndex;
```
Or upsertKeysAtIndex? or let me know if you have a better idea
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "gustavodemorais (via GitHub)" <gi...@apache.org>.
gustavodemorais commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3304550608
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/ToChangelogFunction.java:
##########
@@ -84,7 +94,48 @@ public ToChangelogFunction(final SpecializedContext context) {
if (opMapping != null) {
validateOpMap(this.rawOpMap, tableSemantics);
}
+ final boolean producesFullDeletesArg =
+ callContext.getArgumentValue(3, Boolean.class).orElse(false);
+ validateProducesFullDeletes(producesFullDeletesArg, tableSemantics);
+
this.outputIndices = ChangelogTypeStrategyUtils.computeOutputIndices(tableSemantics);
+ this.inputRowType = (RowType) tableSemantics.dataType().getLogicalType();
+ final int[] upsertKeys = tableSemantics.upsertKeyColumns();
+ this.producesFullDelete = resolveProducesFullDelete(producesFullDeletesArg, tableSemantics);
+ this.preserveOnDelete = computePreserveOnDelete(this.outputIndices, upsertKeys);
+ }
+
+ /**
+ * Decides whether this function emits full DELETE rows (input passed through unchanged) or
+ * partial DELETE rows (only identifying columns preserved, rest nulled).
+ *
+ * <p>The framework prepends partition-key columns to the output without consulting this
+ * function, so in set semantics partition keys are preserved on DELETE rows for free. In row
+ * semantics we rely on the input table's upsert key to identify columns. Without either signal
+ * we cannot null anything safely and fall back to passing the input through unchanged, which is
+ * equivalent to a full delete.
+ */
+ private static boolean resolveProducesFullDelete(
Review Comment:
Is this resolving to saying that we produce partial deletes as default?
- I think we should probably go with full deletes as default
- If the user specify partial delete, we try to accomodate. If we can't, we throw an error
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3310136213
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/ToChangelogFunction.java:
##########
@@ -84,7 +94,48 @@ public ToChangelogFunction(final SpecializedContext context) {
if (opMapping != null) {
validateOpMap(this.rawOpMap, tableSemantics);
}
+ final boolean producesFullDeletesArg =
+ callContext.getArgumentValue(3, Boolean.class).orElse(false);
+ validateProducesFullDeletes(producesFullDeletesArg, tableSemantics);
+
this.outputIndices = ChangelogTypeStrategyUtils.computeOutputIndices(tableSemantics);
+ this.inputRowType = (RowType) tableSemantics.dataType().getLogicalType();
+ final int[] upsertKeys = tableSemantics.upsertKeyColumns();
+ this.producesFullDelete = resolveProducesFullDelete(producesFullDeletesArg, tableSemantics);
+ this.preserveOnDelete = computePreserveOnDelete(this.outputIndices, upsertKeys);
+ }
+
+ /**
+ * Decides whether this function emits full DELETE rows (input passed through unchanged) or
+ * partial DELETE rows (only identifying columns preserved, rest nulled).
+ *
+ * <p>The framework prepends partition-key columns to the output without consulting this
+ * function, so in set semantics partition keys are preserved on DELETE rows for free. In row
+ * semantics we rely on the input table's upsert key to identify columns. Without either signal
+ * we cannot null anything safely and fall back to passing the input through unchanged, which is
+ * equivalent to a full delete.
+ */
+ private static boolean resolveProducesFullDelete(
Review Comment:
Changed to full deletes by default now!
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3312025239
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/ToChangelogTestPrograms.java:
##########
@@ -187,7 +187,8 @@ public class ToChangelogTestPrograms {
public static final TableTestProgram UPSERT_PARTITION_BY =
TableTestProgram.of(
"to-changelog-upsert-partition-by",
- "PARTITION BY upsert key + mapping without UB skips ChangelogNormalize")
+ "PARTITION BY upsert key + mapping without UB skips ChangelogNormalize; "
+ + "default produces_full_deletes=false nulls non-key columns on DELETE")
Review Comment:
Removed.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "twalthr (via GitHub)" <gi...@apache.org>.
twalthr commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3318613773
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/ToChangelogTypeStrategy.java:
##########
@@ -46,39 +42,30 @@
@Internal
public final class ToChangelogTypeStrategy {
- private static final String DEFAULT_OP_COLUMN_NAME = "op";
+ // Positional argument indexes for TO_CHANGELOG. Must match the order of StaticArguments
+ // registered in BuiltInFunctionDefinitions#TO_CHANGELOG; changing one without the other
+ // silently breaks argument resolution.
+ public static final int ARG_TABLE = 0;
Review Comment:
but the arg name is `input => `, and not `table => `
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "gustavodemorais (via GitHub)" <gi...@apache.org>.
gustavodemorais commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3289462696
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/ToChangelogFunction.java:
##########
@@ -85,6 +100,33 @@ public ToChangelogFunction(final SpecializedContext context) {
validateOpMap(this.rawOpMap, tableSemantics);
}
this.outputIndices = ChangelogTypeStrategyUtils.computeOutputIndices(tableSemantics);
+ this.inputRowType = (RowType) tableSemantics.dataType().getLogicalType();
+ final boolean producesFullDeletes =
+ callContext.getArgumentValue(3, Boolean.class).orElse(false);
+ final int[] upsertKeys = tableSemantics.upsertKeyColumns();
+ final boolean hasPartitionBy = tableSemantics.partitionByColumns().length > 0;
+ // We emit partial deletes when the caller did not ask for full ones and we know which
+ // input columns identify a row. The framework prepends partition-key columns to the
+ // output without consulting the function, so in set semantics partition keys are
+ // preserved on DELETE rows for free. In row semantics we rely on the input table's
+ // upsert key to preserve identifying columns on DELETE; without one we cannot null
+ // anything safely and pass the input through unchanged.
+ this.nullPayloadOnDelete =
+ !producesFullDeletes && (hasPartitionBy || upsertKeys.length > 0);
Review Comment:
Move this to a small function so that the constructor is still easy to read
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "gustavodemorais (via GitHub)" <gi...@apache.org>.
gustavodemorais commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3289451977
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/ToChangelogFunction.java:
##########
@@ -65,11 +69,22 @@ public class ToChangelogFunction extends BuiltInProcessTableFunction<RowData> {
private final Map<RowKind, String> rawOpMap;
private final int[] outputIndices;
+ private final RowType inputRowType;
+ private final boolean nullPayloadOnDelete;
Review Comment:
Should we reuse the param name and adjust the logic?
```suggestion
private final boolean producesFullDelete;
```
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3311159207
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/TableSemantics.java:
##########
@@ -128,6 +128,28 @@ public interface TableSemantics {
*/
Optional<ChangelogMode> changelogMode();
+ /**
+ * Upsert key columns derived from the passed table's metadata.
+ *
+ * <p>Returns 0-based column indices that uniquely identify a row for upsert semantics. This is
+ * distinct from {@link #partitionByColumns()}: partition keys describe distribution and
+ * co-location, upsert keys describe row identity. Useful for functions that need to emit
+ * key-only deletes, match UPDATE_BEFORE / UPDATE_AFTER pairs, or route CDC events without
+ * forcing the caller to repeat the key via {@code PARTITION BY}.
Review Comment:
Updated with the new List<int[]> API
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "gustavodemorais (via GitHub)" <gi...@apache.org>.
gustavodemorais commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3304924981
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/inference/CallBindingCallContext.java:
##########
@@ -312,6 +312,11 @@ public int timeColumn() {
public Optional<ChangelogMode> changelogMode() {
return Optional.empty();
}
+
+ @Override
+ public int[] upsertKeyColumns() {
+ return new int[0];
Review Comment:
Can't we run into a out of index exception here? Can we guarantee that int[0] is the shortest key?
What happens if the user has for example two primary keys defined for a table and they're both of length 1? We randomly pick one? I first thought we would expose all upsertKeys. If we only expose one, we have to make it clear in the documentation and explain which one we expose to the user
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3318068891
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/bridging/BridgingSqlFunction.java:
##########
@@ -348,14 +348,29 @@ public CallContext toCallContext(
@Nullable List<Integer> inputTimeColumns,
@Nullable List<ChangelogMode> inputChangelogModes,
@Nullable ChangelogMode outputChangelogMode) {
+ return toCallContext(
+ call, inputTimeColumns, inputChangelogModes, outputChangelogMode, null);
+ }
+
+ /**
+ * Variant that additionally exposes the call's input upsert keys. Used by the streaming codegen
+ * path so PTFs can specialize themselves on the input's row-identity information.
+ */
+ public CallContext toCallContext(
Review Comment:
It is used by `ProcessTableRunnerGenerator.scala:81` for the streaming codegen path where upsert keys are available.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "twalthr (via GitHub)" <gi...@apache.org>.
twalthr commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3316605228
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -397,6 +399,90 @@ SELECT * FROM TO_CHANGELOG(
-- UPDATE_BEFORE is dropped (not in the mapping)
```
+#### Upsert key
+
+An **upsert key** is a column or set of columns that uniquely identifies a row across its lifecycle in a changelog. It is what downstream operators and sinks use to decide which earlier row a new INSERT, UPDATE_AFTER, or DELETE refers to.
+
+The planner derives the upsert key from the input table:
+
+* A declared `PRIMARY KEY` on the source table when reading directly.
+* The grouping columns of an upstream `GROUP BY <key>`.
+* The keys propagated by operators that preserve them (e.g. lookup joins, calc-projections that keep the key columns).
Review Comment:
```suggestion
* The grouping columns of an upstream `GROUP BY <key>` or `PARTITION BY <key>`.
* The keys propagated by operators that preserve them (e.g. lookup joins, projections that keep the key columns).
```
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -397,6 +399,90 @@ SELECT * FROM TO_CHANGELOG(
-- UPDATE_BEFORE is dropped (not in the mapping)
```
+#### Upsert key
+
+An **upsert key** is a column or set of columns that uniquely identifies a row across its lifecycle in a changelog. It is what downstream operators and sinks use to decide which earlier row a new INSERT, UPDATE_AFTER, or DELETE refers to.
+
+The planner derives the upsert key from the input table:
+
+* A declared `PRIMARY KEY` on the source table when reading directly.
+* The grouping columns of an upstream `GROUP BY <key>`.
+* The keys propagated by operators that preserve them (e.g. lookup joins, calc-projections that keep the key columns).
+
+When no upsert key can be derived (e.g. a plain append-only source with no key constraint and no grouping upstream), the input has no row identity and downstream operators must treat it as append-only or fall back to retract semantics.
+
+`TO_CHANGELOG` consumes the upsert key to decide which columns to preserve when emitting partial DELETE rows. See [Full vs partial deletes](#full-vs-partial-deletes) below.
+
+#### Full vs partial deletes
+
+The `produces_full_deletes` argument controls how DELETE rows are emitted and what the planner requires from the input. The matrix below shows each combination with `PARTITION BY` (set semantics) and without (row semantics). When `false`, the function relies on the input table's [upsert key](#upsert-key) to decide which columns to preserve.
+
+##### `produces_full_deletes => true` (default)
+
+The planner requires fully-populated DELETE rows on the input. For upsert sources that emit key-only deletes, a `ChangelogNormalize` operator is inserted upstream to materialize the full pre-image from state. For sources that already emit a full pre-image (e.g. retract), the flag is a no-op. The function then passes the input row through unchanged on DELETE.
Review Comment:
```suggestion
The planner requires fully-populated DELETE rows on the input. For upsert sources that emit key-only deletes, a `ChangelogNormalize` operator is inserted upstream to calculate the full pre-image from state. For sources that already emit a full pre-image (e.g. retract), the flag is a no-op. The function then passes the input row through unchanged on DELETE.
```
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -397,6 +399,90 @@ SELECT * FROM TO_CHANGELOG(
-- UPDATE_BEFORE is dropped (not in the mapping)
```
+#### Upsert key
+
+An **upsert key** is a column or set of columns that uniquely identifies a row across its lifecycle in a changelog. It is what downstream operators and sinks use to decide which earlier row a new INSERT, UPDATE_AFTER, or DELETE refers to.
+
+The planner derives the upsert key from the input table:
+
+* A declared `PRIMARY KEY` on the source table when reading directly.
+* The grouping columns of an upstream `GROUP BY <key>`.
+* The keys propagated by operators that preserve them (e.g. lookup joins, calc-projections that keep the key columns).
+
+When no upsert key can be derived (e.g. a plain append-only source with no key constraint and no grouping upstream), the input has no row identity and downstream operators must treat it as append-only or fall back to retract semantics.
+
+`TO_CHANGELOG` consumes the upsert key to decide which columns to preserve when emitting partial DELETE rows. See [Full vs partial deletes](#full-vs-partial-deletes) below.
Review Comment:
I would drop this paragraph. Imho it doesn't contain any interesting information.
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -397,6 +399,90 @@ SELECT * FROM TO_CHANGELOG(
-- UPDATE_BEFORE is dropped (not in the mapping)
```
+#### Upsert key
+
+An **upsert key** is a column or set of columns that uniquely identifies a row across its lifecycle in a changelog. It is what downstream operators and sinks use to decide which earlier row a new INSERT, UPDATE_AFTER, or DELETE refers to.
+
+The planner derives the upsert key from the input table:
+
+* A declared `PRIMARY KEY` on the source table when reading directly.
+* The grouping columns of an upstream `GROUP BY <key>`.
+* The keys propagated by operators that preserve them (e.g. lookup joins, calc-projections that keep the key columns).
+
+When no upsert key can be derived (e.g. a plain append-only source with no key constraint and no grouping upstream), the input has no row identity and downstream operators must treat it as append-only or fall back to retract semantics.
+
+`TO_CHANGELOG` consumes the upsert key to decide which columns to preserve when emitting partial DELETE rows. See [Full vs partial deletes](#full-vs-partial-deletes) below.
+
+#### Full vs partial deletes
+
+The `produces_full_deletes` argument controls how DELETE rows are emitted and what the planner requires from the input. The matrix below shows each combination with `PARTITION BY` (set semantics) and without (row semantics). When `false`, the function relies on the input table's [upsert key](#upsert-key) to decide which columns to preserve.
+
+##### `produces_full_deletes => true` (default)
+
+The planner requires fully-populated DELETE rows on the input. For upsert sources that emit key-only deletes, a `ChangelogNormalize` operator is inserted upstream to materialize the full pre-image from state. For sources that already emit a full pre-image (e.g. retract), the flag is a no-op. The function then passes the input row through unchanged on DELETE.
+
+**Row semantics** (no `PARTITION BY`):
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
Review Comment:
I think this would make it clearer.
```suggestion
-- Upsert source: -D[id:5, name:null] (key-only).
```
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -397,6 +399,90 @@ SELECT * FROM TO_CHANGELOG(
-- UPDATE_BEFORE is dropped (not in the mapping)
```
+#### Upsert key
+
+An **upsert key** is a column or set of columns that uniquely identifies a row across its lifecycle in a changelog. It is what downstream operators and sinks use to decide which earlier row a new INSERT, UPDATE_AFTER, or DELETE refers to.
+
+The planner derives the upsert key from the input table:
+
+* A declared `PRIMARY KEY` on the source table when reading directly.
+* The grouping columns of an upstream `GROUP BY <key>`.
+* The keys propagated by operators that preserve them (e.g. lookup joins, calc-projections that keep the key columns).
+
+When no upsert key can be derived (e.g. a plain append-only source with no key constraint and no grouping upstream), the input has no row identity and downstream operators must treat it as append-only or fall back to retract semantics.
+
+`TO_CHANGELOG` consumes the upsert key to decide which columns to preserve when emitting partial DELETE rows. See [Full vs partial deletes](#full-vs-partial-deletes) below.
+
+#### Full vs partial deletes
+
+The `produces_full_deletes` argument controls how DELETE rows are emitted and what the planner requires from the input. The matrix below shows each combination with `PARTITION BY` (set semantics) and without (row semantics). When `false`, the function relies on the input table's [upsert key](#upsert-key) to decide which columns to preserve.
+
+##### `produces_full_deletes => true` (default)
+
+The planner requires fully-populated DELETE rows on the input. For upsert sources that emit key-only deletes, a `ChangelogNormalize` operator is inserted upstream to materialize the full pre-image from state. For sources that already emit a full pre-image (e.g. retract), the flag is a no-op. The function then passes the input row through unchanged on DELETE.
+
+**Row semantics** (no `PARTITION BY`):
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
+-- Output: +I[op:'DELETE', id:5, name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source)
+
+-- Retract source: -D[id:5, name:'Alice'] (full pre-image).
+-- No ChangelogNormalize inserted; the input row is passed through unchanged.
+-- Output: +I[op:'DELETE', id:5, name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source)
+```
+
+**Set semantics** (`PARTITION BY`):
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
+-- Output: +I[id:5, op:'DELETE', name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source PARTITION BY id)
+
+-- Retract source: -D[id:5, name:'Alice'] (full pre-image).
+-- No ChangelogNormalize inserted; the input row is passed through unchanged.
+-- Output: +I[id:5, op:'DELETE', name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source PARTITION BY id)
+```
+
+##### `produces_full_deletes => false`
+
+The planner skips `ChangelogNormalize` and the function emits partial DELETE rows. This avoids the stateful normalization operator for upsert sources (e.g. Kafka compacted topics) where the full pre-image is not needed downstream. Requires an [upsert key](#upsert-key) to be present for the input table (row semantics) or `PARTITION BY` (set semantics); otherwise the call is rejected with a validation error.
Review Comment:
```suggestion
The planner skips `ChangelogNormalize` and the function emits partial DELETE rows. This avoids the stateful normalization operator for upsert sources (e.g. Kafka compacted topics) where the full pre-image is not needed downstream. This requires an [upsert key](#upsert-key) to be present for the input table (row semantics) or `PARTITION BY` (set semantics); otherwise the call is rejected with a validation error.
```
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/ToChangelogTypeStrategy.java:
##########
@@ -46,39 +42,30 @@
@Internal
public final class ToChangelogTypeStrategy {
- private static final String DEFAULT_OP_COLUMN_NAME = "op";
+ // Positional argument indexes for TO_CHANGELOG. Must match the order of StaticArguments
+ // registered in BuiltInFunctionDefinitions#TO_CHANGELOG; changing one without the other
+ // silently breaks argument resolution.
+ public static final int ARG_TABLE = 0;
Review Comment:
```suggestion
public static final int ARG_INPUT = 0;
```
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/TableSemantics.java:
##########
@@ -128,6 +129,29 @@ public interface TableSemantics {
*/
Optional<ChangelogMode> changelogMode();
+ /**
+ * Upsert key candidates derived from the passed table's metadata.
+ *
+ * <p>Returns a list of 0-based column index arrays that uniquely identify a row for upsert
+ * semantics. This is distinct from {@link #partitionByColumns()}: partition keys describe
+ * distribution and co-location, upsert keys describe row identity. Useful for functions that
+ * need to emit key-only deletes, match UPDATE_BEFORE / UPDATE_AFTER pairs, or want to have a
+ * unique identifier to interact with state.
+ *
+ * <p>Returns an empty list when no upsert key is derivable, or when the planner has not yet
Review Comment:
Instead of much text. An example might be useful here to show the difference between PARTITION BY and upsert key
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/TableSemantics.java:
##########
@@ -128,6 +129,29 @@ public interface TableSemantics {
*/
Optional<ChangelogMode> changelogMode();
+ /**
+ * Upsert key candidates derived from the passed table's metadata.
+ *
+ * <p>Returns a list of 0-based column index arrays that uniquely identify a row for upsert
+ * semantics. This is distinct from {@link #partitionByColumns()}: partition keys describe
+ * distribution and co-location, upsert keys describe row identity. Useful for functions that
+ * need to emit key-only deletes, match UPDATE_BEFORE / UPDATE_AFTER pairs, or want to have a
+ * unique identifier to interact with state.
+ *
+ * <p>Returns an empty list when no upsert key is derivable, or when the planner has not yet
+ * computed metadata (during type inference).
+ *
+ * <p>When the planner derives multiple candidate upsert keys for the same input (e.g., a table
+ * with several primary key constraints), all of them are returned. Picking which candidate to
Review Comment:
> several primary key constraints
a table can have only one primary key constraint, do we have a better example?
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/bridging/BridgingSqlFunction.java:
##########
@@ -348,14 +348,29 @@ public CallContext toCallContext(
@Nullable List<Integer> inputTimeColumns,
@Nullable List<ChangelogMode> inputChangelogModes,
@Nullable ChangelogMode outputChangelogMode) {
+ return toCallContext(
+ call, inputTimeColumns, inputChangelogModes, outputChangelogMode, null);
+ }
+
+ /**
+ * Variant that additionally exposes the call's input upsert keys. Used by the streaming codegen
+ * path so PTFs can specialize themselves on the input's row-identity information.
+ */
+ public CallContext toCallContext(
Review Comment:
is the old function still used, otherwise we can drop the overload. I have seen Claude doing this regularly.
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/ToChangelogTypeStrategy.java:
##########
@@ -187,12 +198,63 @@ private static Optional<List<DataType>> validateOpMappingKeys(
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);
+ @SuppressWarnings("rawtypes")
+ private static Optional<List<DataType>> validateProducesFullDeletes(
+ final CallContext callContext, final boolean throwOnFailure) {
+ final boolean isExplicit = !callContext.isArgumentNull(ARG_PRODUCES_FULL_DELETES);
+ if (!isExplicit) {
+ return Optional.empty();
+ }
+ if (!callContext.isArgumentLiteral(ARG_PRODUCES_FULL_DELETES)) {
+ return callContext.fail(
+ throwOnFailure,
+ "The 'produces_full_deletes' argument must be a constant BOOLEAN literal.");
+ }
+ final boolean producesFullDeletes =
+ callContext.getArgumentValue(ARG_PRODUCES_FULL_DELETES, Boolean.class).orElse(true);
+ if (!producesFullDeletes) {
+ return Optional.empty();
+ }
+ // The check against the input changelog mode lives in the function constructor since
+ // TableSemantics#changelogMode() returns empty here at type-inference time. The mapping
+ // check below only needs the literal op_mapping argument, so it lives here. Only runs
+ // when the user explicitly set produces_full_deletes=true; the default true is not
+ // validated since it is a safe no-op for any input.
+ final Optional<Map> opMapping = callContext.getArgumentValue(ARG_OP_MAPPING, Map.class);
+ if (opMapping.isPresent() && !mapsDelete((Map<String, String>) opMapping.get())) {
Review Comment:
I find this check a bit confusing. If I set `produces_full_deletes => true`, I'm allowed to NOT contain DELETE, But if I set `produces_full_deletes => false`, I'm not allowed to. Remove this check all together, or `produces_partial_deletes => false` which defaults to false, at it would be common for option arguments.
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/ToChangelogTestPrograms.java:
##########
@@ -598,4 +598,192 @@ public class ToChangelogTestPrograms {
ValidationException.class,
"Duplicate change operation: 'DELETE'")
.build();
+
+ public static final TableTestProgram INVALID_PRODUCES_FULL_DELETES_FOR_APPEND_ONLY =
+ TableTestProgram.of(
+ "to-changelog-invalid-produces-full-deletes-for-append-only",
+ "fails when produces_full_deletes=true on an input that never emits DELETE rows")
+ .setupTableSource(SIMPLE_SOURCE)
+ .runFailingSql(
+ "SELECT * FROM TO_CHANGELOG("
+ + "input => TABLE t, "
+ + "produces_full_deletes => true)",
+ ValidationException.class,
+ "the input table only produces [INSERT] and never emits DELETE rows")
+ .build();
+
+ // --------------------------------------------------------------------------------------------
+ // Full vs partial deletes matrix (input kind x PARTITION BY x produces_full_deletes)
+ // --------------------------------------------------------------------------------------------
+
+ public static final TableTestProgram RETRACT_PRODUCES_PARTIAL_DELETES =
+ TableTestProgram.of(
+ "to-changelog-retract-produces-partial-deletes",
+ "retract input in row semantics with produces_full_deletes=false: skips ChangelogNormalize and the partial DELETE row from the input passes through unchanged")
+ .setupTableSource(
+ SourceTestStep.newBuilder("t")
+ .addSchema(
+ "name STRING PRIMARY KEY NOT ENFORCED", "score BIGINT")
Review Comment:
add a test with NOT NULL on input columns
```suggestion
"name STRING PRIMARY KEY NOT ENFORCED", "score BIGINT NOT NULL")
```
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecProcessTableFunction.java:
##########
@@ -310,17 +326,21 @@ private RuntimeTableSemantics createRuntimeTableSemantics(
final int timeColumn = inputTimeColumns.get(tableArgCall.getInputIndex());
+ final int inputIndex = tableArgCall.getInputIndex();
Review Comment:
put this variable higher and also improve the line above
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -397,6 +399,90 @@ SELECT * FROM TO_CHANGELOG(
-- UPDATE_BEFORE is dropped (not in the mapping)
```
+#### Upsert key
+
+An **upsert key** is a column or set of columns that uniquely identifies a row across its lifecycle in a changelog. It is what downstream operators and sinks use to decide which earlier row a new INSERT, UPDATE_AFTER, or DELETE refers to.
+
+The planner derives the upsert key from the input table:
+
+* A declared `PRIMARY KEY` on the source table when reading directly.
+* The grouping columns of an upstream `GROUP BY <key>`.
+* The keys propagated by operators that preserve them (e.g. lookup joins, calc-projections that keep the key columns).
+
+When no upsert key can be derived (e.g. a plain append-only source with no key constraint and no grouping upstream), the input has no row identity and downstream operators must treat it as append-only or fall back to retract semantics.
+
+`TO_CHANGELOG` consumes the upsert key to decide which columns to preserve when emitting partial DELETE rows. See [Full vs partial deletes](#full-vs-partial-deletes) below.
+
+#### Full vs partial deletes
+
+The `produces_full_deletes` argument controls how DELETE rows are emitted and what the planner requires from the input. The matrix below shows each combination with `PARTITION BY` (set semantics) and without (row semantics). When `false`, the function relies on the input table's [upsert key](#upsert-key) to decide which columns to preserve.
+
+##### `produces_full_deletes => true` (default)
+
+The planner requires fully-populated DELETE rows on the input. For upsert sources that emit key-only deletes, a `ChangelogNormalize` operator is inserted upstream to materialize the full pre-image from state. For sources that already emit a full pre-image (e.g. retract), the flag is a no-op. The function then passes the input row through unchanged on DELETE.
+
+**Row semantics** (no `PARTITION BY`):
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
Review Comment:
```suggestion
-- ChangelogNormalize calculates the full pre-image from state.
```
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -397,6 +399,90 @@ SELECT * FROM TO_CHANGELOG(
-- UPDATE_BEFORE is dropped (not in the mapping)
```
+#### Upsert key
+
+An **upsert key** is a column or set of columns that uniquely identifies a row across its lifecycle in a changelog. It is what downstream operators and sinks use to decide which earlier row a new INSERT, UPDATE_AFTER, or DELETE refers to.
+
+The planner derives the upsert key from the input table:
+
+* A declared `PRIMARY KEY` on the source table when reading directly.
+* The grouping columns of an upstream `GROUP BY <key>`.
+* The keys propagated by operators that preserve them (e.g. lookup joins, calc-projections that keep the key columns).
+
+When no upsert key can be derived (e.g. a plain append-only source with no key constraint and no grouping upstream), the input has no row identity and downstream operators must treat it as append-only or fall back to retract semantics.
+
+`TO_CHANGELOG` consumes the upsert key to decide which columns to preserve when emitting partial DELETE rows. See [Full vs partial deletes](#full-vs-partial-deletes) below.
+
+#### Full vs partial deletes
+
+The `produces_full_deletes` argument controls how DELETE rows are emitted and what the planner requires from the input. The matrix below shows each combination with `PARTITION BY` (set semantics) and without (row semantics). When `false`, the function relies on the input table's [upsert key](#upsert-key) to decide which columns to preserve.
+
+##### `produces_full_deletes => true` (default)
+
+The planner requires fully-populated DELETE rows on the input. For upsert sources that emit key-only deletes, a `ChangelogNormalize` operator is inserted upstream to materialize the full pre-image from state. For sources that already emit a full pre-image (e.g. retract), the flag is a no-op. The function then passes the input row through unchanged on DELETE.
+
+**Row semantics** (no `PARTITION BY`):
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
+-- Output: +I[op:'DELETE', id:5, name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source)
+
+-- Retract source: -D[id:5, name:'Alice'] (full pre-image).
+-- No ChangelogNormalize inserted; the input row is passed through unchanged.
+-- Output: +I[op:'DELETE', id:5, name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source)
+```
+
+**Set semantics** (`PARTITION BY`):
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
+-- Output: +I[id:5, op:'DELETE', name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source PARTITION BY id)
+
+-- Retract source: -D[id:5, name:'Alice'] (full pre-image).
+-- No ChangelogNormalize inserted; the input row is passed through unchanged.
+-- Output: +I[id:5, op:'DELETE', name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source PARTITION BY id)
+```
+
+##### `produces_full_deletes => false`
+
+The planner skips `ChangelogNormalize` and the function emits partial DELETE rows. This avoids the stateful normalization operator for upsert sources (e.g. Kafka compacted topics) where the full pre-image is not needed downstream. Requires an [upsert key](#upsert-key) to be present for the input table (row semantics) or `PARTITION BY` (set semantics); otherwise the call is rejected with a validation error.
+
+**Row semantics** (no `PARTITION BY`): the function preserves the planner-derived upsert key columns on DELETE rows and nulls the rest. The upsert key is typically a declared `PRIMARY KEY` when directly reading from a source or the key provided in a `GROUP BY <key>`.
+
+```sql
+-- Upsert source with PRIMARY KEY (id): -D[id:5] (key-only).
+-- Output: +I[op:'DELETE', id:5, name:null]
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source, produces_full_deletes => false)
+
+-- Retract source with PRIMARY KEY (id): -D[id:5, name:'Alice'] (full pre-image).
+-- Output: +I[op:'DELETE', id:5, name:null]
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source, produces_full_deletes => false)
+```
+
+**Set semantics** (`PARTITION BY`): the function preserves the partition key and nulls every non-partition-key column on DELETE rows. The key used as the partition-key column should be the unique key that will be used as the record identifier. This matches the shape expected by upsert sinks and Kafka compacted topics.
Review Comment:
```suggestion
**Set semantics** (`PARTITION BY`): the function preserves the partition key and nulls every non-partition-key column on DELETE rows. The key used as the partition-key column should be the unique key that will be used as the record identifier. This matches the shape expected by upsert sinks such as Kafka compacted topics.
```
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/expressions/resolver/rules/ResolveCallByArgumentsRule.java:
##########
@@ -781,6 +781,11 @@ public Optional<ChangelogMode> changelogMode() {
return Optional.empty();
}
+ @Override
+ public List<int[]> upsertKeyColumns() {
Review Comment:
Usually we use array of array for index paths. All connector interfaces do it this way.
```suggestion
public int[][] upsertKeyColumns() {
```
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/PartitionedTable.java:
##########
@@ -204,9 +204,19 @@ public interface PartitionedTable {
* descriptor("deleted").asArgument("op"),
* map("INSERT, UPDATE_AFTER", "false", "DELETE", "true").asArgument("op_mapping")
* );
+ *
+ * // Opt out of full-delete semantics. When `true` (default), DELETE rows carry the full
+ * // pre-image. When `false`, only the identifying key columns are preserved and the rest
+ * // are nulled. See [Full vs partial deletes](
+ * // https://nightlies.apache.org/flink/flink-docs-master/docs/dev/table/sql/queries/changelog/#full-vs-partial-deletes)
Review Comment:
This links in code are outdated rather quickly.
```suggestion
* in documentation.
```
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/ToChangelogTypeStrategy.java:
##########
@@ -187,12 +198,63 @@ private static Optional<List<DataType>> validateOpMappingKeys(
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);
+ @SuppressWarnings("rawtypes")
+ private static Optional<List<DataType>> validateProducesFullDeletes(
+ final CallContext callContext, final boolean throwOnFailure) {
+ final boolean isExplicit = !callContext.isArgumentNull(ARG_PRODUCES_FULL_DELETES);
+ if (!isExplicit) {
+ return Optional.empty();
+ }
+ if (!callContext.isArgumentLiteral(ARG_PRODUCES_FULL_DELETES)) {
+ return callContext.fail(
+ throwOnFailure,
+ "The 'produces_full_deletes' argument must be a constant BOOLEAN literal.");
+ }
+ final boolean producesFullDeletes =
+ callContext.getArgumentValue(ARG_PRODUCES_FULL_DELETES, Boolean.class).orElse(true);
+ if (!producesFullDeletes) {
+ return Optional.empty();
+ }
+ // The check against the input changelog mode lives in the function constructor since
Review Comment:
```suggestion
// The check against the input changelog mode lives in the runtime function constructor since
```
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "twalthr (via GitHub)" <gi...@apache.org>.
twalthr commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3316718915
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/expressions/resolver/rules/ResolveCallByArgumentsRule.java:
##########
@@ -781,6 +781,11 @@ public Optional<ChangelogMode> changelogMode() {
return Optional.empty();
}
+ @Override
+ public List<int[]> upsertKeyColumns() {
Review Comment:
Usually we use array of array for index paths. All connector interfaces do it this way.
```suggestion
public int[][] upsertKeyColumns() {
```
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "gustavodemorais (via GitHub)" <gi...@apache.org>.
gustavodemorais commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3310091406
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/PartitionedTable.java:
##########
@@ -204,9 +204,18 @@ public interface PartitionedTable {
* descriptor("deleted").asArgument("op"),
* map("INSERT, UPDATE_AFTER", "false", "DELETE", "true").asArgument("op_mapping")
* );
+ *
+ * // Opt out of full-delete semantics. The default (true) requires fully-populated DELETE
+ * // rows and inserts a ChangelogNormalize for upsert sources. When false, the function
+ * // preserves the partition key on DELETE rows and nulls the rest, which avoids the
+ * // stateful normalization operator upstream.
+ * Table result = table
+ * .partitionBy($("id"))
+ * .toChangelog(lit(false).asArgument("produces_full_deletes"));
Review Comment:
```suggestion
* // Opt out of full-delete semantics. When `true` (default), DELETE rows carry the full pre-image.
* // When `false`, only the identifying key columns are preserved and the rest are nulled.
* // See [Delete handling](#delete-handling) for more details.
* Table result = table
* .partitionBy($("id"))
* .toChangelog(lit(false).asArgument("produces_full_deletes"));
```
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -397,6 +399,76 @@ SELECT * FROM TO_CHANGELOG(
-- UPDATE_BEFORE is dropped (not in the mapping)
```
+#### Delete handling
+
+The `produces_full_deletes` argument controls how DELETE rows are emitted and what the planner requires from the input. The matrix below shows each combination with `PARTITION BY` (set semantics) and without (row semantics).
+
+##### `produces_full_deletes => true` (default)
+
+The planner requires fully-populated DELETE rows on the input. For upsert sources that emit key-only deletes, a `ChangelogNormalize` operator is inserted upstream to materialize the full pre-image from state. For sources that already emit a full pre-image (e.g. retract), the flag is a no-op. The function then passes the input row through unchanged on DELETE.
+
+**Row semantics** (no `PARTITION BY`):
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
+-- Output: +I[op:'DELETE', id:5, name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source)
+
+-- Retract source: -D[id:5, name:'Alice'] (full pre-image).
+-- No ChangelogNormalize inserted; the input row is passed through unchanged.
+-- Output: +I[op:'DELETE', id:5, name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source)
+```
+
+**Set semantics** (`PARTITION BY`):
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
+-- Output: +I[id:5, op:'DELETE', name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source PARTITION BY id)
+
+-- Retract source: -D[id:5, name:'Alice'] (full pre-image).
+-- No ChangelogNormalize inserted; the input row is passed through unchanged.
+-- Output: +I[id:5, op:'DELETE', name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source PARTITION BY id)
+```
+
+##### `produces_full_deletes => false`
+
+The planner skips `ChangelogNormalize` and the function emits partial DELETE rows. This avoids the stateful normalization operator for upsert sources (e.g. Kafka compacted topics) where the full pre-image is not needed downstream. Requires an upsert key (row semantics) or `PARTITION BY` (set semantics); otherwise the call is rejected with a validation error.
Review Comment:
```suggestion
The planner skips `ChangelogNormalize` and the function emits partial DELETE rows. This avoids the stateful normalization operator for upsert sources (e.g. Kafka compacted topics) where the full pre-image is not needed downstream. Requires an upsert key to be present for the input table (row semantics) or `PARTITION BY` (set semantics); otherwise the call is rejected with a validation error.
```
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -397,6 +399,76 @@ SELECT * FROM TO_CHANGELOG(
-- UPDATE_BEFORE is dropped (not in the mapping)
```
+#### Delete handling
+
+The `produces_full_deletes` argument controls how DELETE rows are emitted and what the planner requires from the input. The matrix below shows each combination with `PARTITION BY` (set semantics) and without (row semantics).
+
+##### `produces_full_deletes => true` (default)
+
+The planner requires fully-populated DELETE rows on the input. For upsert sources that emit key-only deletes, a `ChangelogNormalize` operator is inserted upstream to materialize the full pre-image from state. For sources that already emit a full pre-image (e.g. retract), the flag is a no-op. The function then passes the input row through unchanged on DELETE.
+
+**Row semantics** (no `PARTITION BY`):
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
+-- Output: +I[op:'DELETE', id:5, name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source)
+
+-- Retract source: -D[id:5, name:'Alice'] (full pre-image).
+-- No ChangelogNormalize inserted; the input row is passed through unchanged.
+-- Output: +I[op:'DELETE', id:5, name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source)
+```
+
+**Set semantics** (`PARTITION BY`):
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
+-- Output: +I[id:5, op:'DELETE', name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source PARTITION BY id)
+
+-- Retract source: -D[id:5, name:'Alice'] (full pre-image).
+-- No ChangelogNormalize inserted; the input row is passed through unchanged.
+-- Output: +I[id:5, op:'DELETE', name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source PARTITION BY id)
+```
+
+##### `produces_full_deletes => false`
+
+The planner skips `ChangelogNormalize` and the function emits partial DELETE rows. This avoids the stateful normalization operator for upsert sources (e.g. Kafka compacted topics) where the full pre-image is not needed downstream. Requires an upsert key (row semantics) or `PARTITION BY` (set semantics); otherwise the call is rejected with a validation error.
+
+**Row semantics** (no `PARTITION BY`): the function preserves the planner-derived upsert key columns on DELETE rows and nulls the rest. The upsert key is typically a declared `PRIMARY KEY`.
Review Comment:
```suggestion
**Row semantics** (no `PARTITION BY`): the function preserves the planner-derived upsert key columns on DELETE rows and nulls the rest. The upsert key is typically a declared `PRIMARY KEY` when directly reading from source or the key provided in a GROUP BY <key>.
```
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -397,6 +399,76 @@ SELECT * FROM TO_CHANGELOG(
-- UPDATE_BEFORE is dropped (not in the mapping)
```
+#### Delete handling
+
+The `produces_full_deletes` argument controls how DELETE rows are emitted and what the planner requires from the input. The matrix below shows each combination with `PARTITION BY` (set semantics) and without (row semantics).
+
+##### `produces_full_deletes => true` (default)
+
+The planner requires fully-populated DELETE rows on the input. For upsert sources that emit key-only deletes, a `ChangelogNormalize` operator is inserted upstream to materialize the full pre-image from state. For sources that already emit a full pre-image (e.g. retract), the flag is a no-op. The function then passes the input row through unchanged on DELETE.
+
+**Row semantics** (no `PARTITION BY`):
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
+-- Output: +I[op:'DELETE', id:5, name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source)
+
+-- Retract source: -D[id:5, name:'Alice'] (full pre-image).
+-- No ChangelogNormalize inserted; the input row is passed through unchanged.
+-- Output: +I[op:'DELETE', id:5, name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source)
+```
+
+**Set semantics** (`PARTITION BY`):
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
+-- Output: +I[id:5, op:'DELETE', name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source PARTITION BY id)
+
+-- Retract source: -D[id:5, name:'Alice'] (full pre-image).
+-- No ChangelogNormalize inserted; the input row is passed through unchanged.
+-- Output: +I[id:5, op:'DELETE', name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source PARTITION BY id)
+```
+
+##### `produces_full_deletes => false`
+
+The planner skips `ChangelogNormalize` and the function emits partial DELETE rows. This avoids the stateful normalization operator for upsert sources (e.g. Kafka compacted topics) where the full pre-image is not needed downstream. Requires an upsert key (row semantics) or `PARTITION BY` (set semantics); otherwise the call is rejected with a validation error.
+
+**Row semantics** (no `PARTITION BY`): the function preserves the planner-derived upsert key columns on DELETE rows and nulls the rest. The upsert key is typically a declared `PRIMARY KEY`.
+
+```sql
+-- Upsert source with PRIMARY KEY (id): -D[id:5] (key-only).
+-- Output: +I[op:'DELETE', id:5, name:null]
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source, produces_full_deletes => false)
+
+-- Retract source with PRIMARY KEY (id): -D[id:5, name:'Alice'] (full pre-image).
+-- Output: +I[op:'DELETE', id:5, name:null]
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source, produces_full_deletes => false)
+```
+
+**Set semantics** (`PARTITION BY`): the function preserves the partition key and nulls every non-partition-key column on DELETE rows. This matches the shape expected by upsert sinks and Kafka compacted topics.
Review Comment:
```suggestion
**Set semantics** (`PARTITION BY`): the function preserves the partition key and nulls every non-partition-key column on DELETE rows. The key used as the partition-key column should be the unique key that will be used as the record identifier. This matches the shape expected by upsert sinks and Kafka compacted topics.
```
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -397,6 +399,76 @@ SELECT * FROM TO_CHANGELOG(
-- UPDATE_BEFORE is dropped (not in the mapping)
```
+#### Delete handling
Review Comment:
Nice documentation!
```suggestion
#### Full vs partial deletes
```
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -296,17 +296,19 @@ This is useful when you need to materialize changelog events into a downstream s
SELECT * FROM TO_CHANGELOG(
input => TABLE source_table [PARTITION BY key_col],
[op => DESCRIPTOR(op_column_name),]
- [op_mapping => MAP['INSERT', 'I', 'DELETE', 'D', ...]]
+ [op_mapping => MAP['INSERT', 'I', 'DELETE', 'D', ...],]
+ [produces_full_deletes => BOOLEAN]
)
```
### Parameters
-| Parameter | Required | Description |
-|:-------------|:---------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| `input` | Yes | The input table. With `PARTITION BY`, rows with the same key are co-located and run in the same operator instance. Without `PARTITION BY`, each row is processed independently. Accepts insert-only, retract, and upsert tables. For upsert tables, the provided `PARTITION BY` key should match or be a subset of the upsert key of the subquery. |
-| `op` | No | A `DESCRIPTOR` with a single column name for the operation code column. Defaults to `op`. |
-| `op_mapping` | No | A `MAP<STRING, STRING>` mapping change operation names to custom output codes. Keys can contain comma-separated names to map multiple operations to the same code (e.g., `'INSERT, UPDATE_AFTER'`). When provided, only mapped operations are forwarded - unmapped events are dropped. Each change operation may appear at most once across all entries. |
+| Parameter | Required | Description |
+|:------------------------|:---------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| `input` | Yes | The input table. With `PARTITION BY`, rows with the same key are co-located and run in the same operator instance. Without `PARTITION BY`, each row is processed independently. Accepts insert-only, retract, and upsert tables. For upsert tables, the provided `PARTITION BY` key should match or be a subset of the upsert key of the subquery. |
+| `op` | No | A `DESCRIPTOR` with a single column name for the operation code column. Defaults to `op`. |
+| `op_mapping` | No | A `MAP<STRING, STRING>` mapping change operation names to custom output codes. Keys can contain comma-separated names to map multiple operations to the same code (e.g., `'INSERT, UPDATE_AFTER'`). When provided, only mapped operations are forwarded - unmapped events are dropped. Each change operation may appear at most once across all entries. |
+| `produces_full_deletes` | No | A `BOOLEAN` literal that controls how DELETE rows are emitted. When `true` (default), the function requires fully-populated DELETE rows from the input. The planner inserts a `ChangelogNormalize` operator for upsert sources that emit key-only deletes, so downstream sees the full pre-image on DELETE. When `false`, the function instead emits partial DELETE rows: in row semantics it preserves the planner-derived upsert key columns of the input and nulls the rest; in set semantics (`PARTITION BY`) it preserves the partition key and nulls the rest. Requires that the input declares an upsert key or that the call uses `PARTITION BY`; otherwise the function has no identifying columns to preserve and the call is rejected. |
Review Comment:
Let's have here a short description with the information that the user needs to use it. Detailed information is in the section below
```suggestion
| `produces_full_deletes` | No | A `BOOLEAN` literal that controls how DELETE rows are emitted. When `true` (default), DELETE rows carry all columns, the full image. When `false`, only the identifying key columns are preserved and the rest are nulled. See [Delete handling](#delete-handling) for more details. |
```
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/Table.java:
##########
@@ -1459,9 +1459,19 @@ default TableResult executeInsert(
* descriptor("deleted").asArgument("op"),
* map("INSERT, UPDATE_AFTER", "false", "DELETE", "true").asArgument("op_mapping")
* );
+ *
+ * // Opt out of full-delete semantics. The default (true) requires fully-populated DELETE
+ * // rows and inserts a ChangelogNormalize for upsert sources. When false, the function
+ * // emits partial DELETE rows: row semantics preserves the planner-derived upsert key
+ * // columns and nulls the rest; set semantics preserves the partition key. Requires an
+ * // upsert key or PARTITION BY; otherwise the call is rejected.
Review Comment:
```suggestion
*
* // Opt out of full-delete semantics. When `true` (default), DELETE rows carry the full pre-image.
* // When `false`, only the identifying key columns are preserved and the rest are nulled.
* // See [Delete handling](#delete-handling) for more details.
```
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/TableSemantics.java:
##########
@@ -128,6 +128,28 @@ public interface TableSemantics {
*/
Optional<ChangelogMode> changelogMode();
+ /**
+ * Upsert key columns derived from the passed table's metadata.
+ *
+ * <p>Returns 0-based column indices that uniquely identify a row for upsert semantics. This is
+ * distinct from {@link #partitionByColumns()}: partition keys describe distribution and
+ * co-location, upsert keys describe row identity. Useful for functions that need to emit
+ * key-only deletes, match UPDATE_BEFORE / UPDATE_AFTER pairs, or route CDC events without
+ * forcing the caller to repeat the key via {@code PARTITION BY}.
+ *
+ * <p>Returns an empty array when no upsert key is derivable (e.g., a pure append-only source)
+ * or when the planner has not yet computed metadata (during type inference).
+ *
+ * <p>If the planner derives multiple candidate upsert keys for the same input (e.g., a table
+ * with several unique constraints), only one is returned. The planner today picks the candidate
Review Comment:
```suggestion
* with several primary key constraints), only one is returned. The planner today picks the candidate
```
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/TableSemantics.java:
##########
@@ -128,6 +128,28 @@ public interface TableSemantics {
*/
Optional<ChangelogMode> changelogMode();
+ /**
+ * Upsert key columns derived from the passed table's metadata.
+ *
+ * <p>Returns 0-based column indices that uniquely identify a row for upsert semantics. This is
+ * distinct from {@link #partitionByColumns()}: partition keys describe distribution and
+ * co-location, upsert keys describe row identity. Useful for functions that need to emit
+ * key-only deletes, match UPDATE_BEFORE / UPDATE_AFTER pairs, or route CDC events without
+ * forcing the caller to repeat the key via {@code PARTITION BY}.
+ *
+ * <p>Returns an empty array when no upsert key is derivable (e.g., a pure append-only source)
+ * or when the planner has not yet computed metadata (during type inference).
+ *
+ * <p>If the planner derives multiple candidate upsert keys for the same input (e.g., a table
+ * with several unique constraints), only one is returned. The planner today picks the candidate
+ * with the smallest number of columns, but ties between equal-cardinality keys are resolved by
+ * an implementation detail and may change across releases. Callers must not rely on which
+ * candidate is returned when more than one exists.
Review Comment:
I don't think we can allow that? If we change the key that is returned between versions, this can generate huge bugs in pipelines after migrations. Imagine you store in state key1 -> val1 and after a migration you get a deletion for key2 -> val2 (which was previously k1), then we corrupt results and state forever. I think we have to settle for a specific way of picking the upsert key and document it. E.g. Shortest and first indexes
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/ToChangelogTypeStrategy.java:
##########
@@ -187,12 +198,63 @@ private static Optional<List<DataType>> validateOpMappingKeys(
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);
+ @SuppressWarnings("rawtypes")
+ private static Optional<List<DataType>> validateProducesFullDeletes(
+ final CallContext callContext, final boolean throwOnFailure) {
+ final boolean isExplicit = !callContext.isArgumentNull(ARG_PRODUCES_FULL_DELETES);
+ if (!isExplicit) {
+ return Optional.empty();
+ }
+ if (!callContext.isArgumentLiteral(ARG_PRODUCES_FULL_DELETES)) {
+ return callContext.fail(
+ throwOnFailure,
+ "The 'produces_full_deletes' argument must be a constant BOOLEAN literal.");
+ }
+ final boolean producesFullDeletes =
+ callContext.getArgumentValue(ARG_PRODUCES_FULL_DELETES, Boolean.class).orElse(true);
+ if (!producesFullDeletes) {
+ return Optional.empty();
+ }
+ // The check against the input changelog mode lives in the function constructor since
+ // TableSemantics#changelogMode() returns empty here at type-inference time. The mapping
+ // check below only needs the literal op_mapping argument, so it lives here. Only runs
+ // when the user explicitly set produces_full_deletes=true; the default true is not
+ // validated since it is a safe no-op for any input.
+ final Optional<Map> opMapping = callContext.getArgumentValue(ARG_OP_MAPPING, Map.class);
+ if (opMapping.isPresent() && !mapsDelete((Map<String, String>) opMapping.get())) {
+ return callContext.fail(
+ throwOnFailure,
+ "Invalid 'produces_full_deletes' for TO_CHANGELOG: the active 'op_mapping' "
+ + "does not map DELETE rows, so no DELETE rows are emitted. Remove "
+ + "the 'produces_full_deletes' argument or add a DELETE entry to "
+ + "'op_mapping'.");
+ }
+ return Optional.empty();
+ }
+
+ /**
+ * Returns {@code true} when at least one {@code op_mapping} key references {@code DELETE}. Keys
+ * may be comma-separated (e.g., {@code "INSERT, DELETE"}) per the user-facing contract.
+ */
+ private static boolean mapsDelete(final Map<String, String> opMapping) {
+ for (final String key : opMapping.keySet()) {
+ for (final String rawName : key.split(",")) {
+ if (DELETE.equals(rawName.trim())) {
Review Comment:
We are case-sensitive, right? Should we add this information to the error message of opMapping https://github.com/apache/flink/pull/28235/changes#r3310307549
##########
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/inference/strategies/ToChangelogInputTypeStrategyTest.java:
##########
@@ -0,0 +1,142 @@
+/*
+ * 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.table.api.DataTypes;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.inference.InputTypeStrategiesTestBase;
+import org.apache.flink.table.types.inference.utils.TableSemanticsMock;
+import org.apache.flink.types.ColumnList;
+
+import java.util.Map;
+import java.util.stream.Stream;
+
+import static org.apache.flink.table.types.inference.strategies.SpecificInputTypeStrategies.TO_CHANGELOG_INPUT_TYPE_STRATEGY;
+
+/** Tests for {@link ToChangelogTypeStrategy#INPUT_TYPE_STRATEGY}. */
+class ToChangelogInputTypeStrategyTest extends InputTypeStrategiesTestBase {
+
+ private static final DataType TABLE_TYPE =
+ DataTypes.ROW(
+ DataTypes.FIELD("name", DataTypes.STRING()),
+ DataTypes.FIELD("score", DataTypes.BIGINT()));
+
+ private static final DataType DESCRIPTOR_TYPE = DataTypes.DESCRIPTOR();
+
+ private static final DataType MAP_TYPE = DataTypes.MAP(DataTypes.STRING(), DataTypes.STRING());
+
+ private static final DataType BOOLEAN_TYPE = DataTypes.BOOLEAN();
+
+ @Override
+ protected Stream<TestSpec> testData() {
+ return Stream.of(
+ // Valid: produces_full_deletes=true with default op_mapping (includes DELETE)
+ TestSpec.forStrategy(
+ "Valid produces_full_deletes=true with default mapping",
+ TO_CHANGELOG_INPUT_TYPE_STRATEGY)
+ .calledWithArgumentTypes(
+ TABLE_TYPE, DESCRIPTOR_TYPE, MAP_TYPE, BOOLEAN_TYPE)
+ .calledWithTableSemanticsAt(0, new TableSemanticsMock(TABLE_TYPE))
+ .calledWithLiteralAt(1, ColumnList.of("op"))
+ .calledWithLiteralAt(2, null)
+ .calledWithLiteralAt(3, true)
Review Comment:
Can you use the constants you created for all the indexes in these tests?
```suggestion
.calledWithLiteralAt(ARG_OP, ColumnList.of("op"))
```
##########
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/inference/strategies/ToChangelogInputTypeStrategyTest.java:
##########
@@ -0,0 +1,142 @@
+/*
+ * 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.table.api.DataTypes;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.inference.InputTypeStrategiesTestBase;
+import org.apache.flink.table.types.inference.utils.TableSemanticsMock;
+import org.apache.flink.types.ColumnList;
+
+import java.util.Map;
+import java.util.stream.Stream;
+
+import static org.apache.flink.table.types.inference.strategies.SpecificInputTypeStrategies.TO_CHANGELOG_INPUT_TYPE_STRATEGY;
+
+/** Tests for {@link ToChangelogTypeStrategy#INPUT_TYPE_STRATEGY}. */
+class ToChangelogInputTypeStrategyTest extends InputTypeStrategiesTestBase {
+
+ private static final DataType TABLE_TYPE =
+ DataTypes.ROW(
+ DataTypes.FIELD("name", DataTypes.STRING()),
+ DataTypes.FIELD("score", DataTypes.BIGINT()));
+
+ private static final DataType DESCRIPTOR_TYPE = DataTypes.DESCRIPTOR();
+
+ private static final DataType MAP_TYPE = DataTypes.MAP(DataTypes.STRING(), DataTypes.STRING());
+
+ private static final DataType BOOLEAN_TYPE = DataTypes.BOOLEAN();
+
+ @Override
+ protected Stream<TestSpec> testData() {
+ return Stream.of(
+ // Valid: produces_full_deletes=true with default op_mapping (includes DELETE)
+ TestSpec.forStrategy(
+ "Valid produces_full_deletes=true with default mapping",
+ TO_CHANGELOG_INPUT_TYPE_STRATEGY)
+ .calledWithArgumentTypes(
+ TABLE_TYPE, DESCRIPTOR_TYPE, MAP_TYPE, BOOLEAN_TYPE)
+ .calledWithTableSemanticsAt(0, new TableSemanticsMock(TABLE_TYPE))
+ .calledWithLiteralAt(1, ColumnList.of("op"))
+ .calledWithLiteralAt(2, null)
+ .calledWithLiteralAt(3, true)
+ .expectArgumentTypes(TABLE_TYPE, DESCRIPTOR_TYPE, MAP_TYPE, BOOLEAN_TYPE),
+
+ // Valid: produces_full_deletes=true with op_mapping that includes DELETE
+ TestSpec.forStrategy(
+ "Valid produces_full_deletes=true with explicit DELETE mapping",
+ TO_CHANGELOG_INPUT_TYPE_STRATEGY)
+ .calledWithArgumentTypes(
+ TABLE_TYPE, DESCRIPTOR_TYPE, MAP_TYPE, BOOLEAN_TYPE)
+ .calledWithTableSemanticsAt(0, new TableSemanticsMock(TABLE_TYPE))
+ .calledWithLiteralAt(1, ColumnList.of("op"))
+ .calledWithLiteralAt(2, Map.of("INSERT", "I", "DELETE", "D"))
+ .calledWithLiteralAt(3, true)
+ .expectArgumentTypes(TABLE_TYPE, DESCRIPTOR_TYPE, MAP_TYPE, BOOLEAN_TYPE),
+
+ // Valid: produces_full_deletes=true with comma-separated DELETE key
+ TestSpec.forStrategy(
+ "Valid produces_full_deletes=true with comma-separated DELETE",
+ TO_CHANGELOG_INPUT_TYPE_STRATEGY)
+ .calledWithArgumentTypes(
+ TABLE_TYPE, DESCRIPTOR_TYPE, MAP_TYPE, BOOLEAN_TYPE)
+ .calledWithTableSemanticsAt(0, new TableSemanticsMock(TABLE_TYPE))
+ .calledWithLiteralAt(1, ColumnList.of("op"))
+ .calledWithLiteralAt(2, Map.of("INSERT, DELETE", "X"))
+ .calledWithLiteralAt(3, true)
+ .expectArgumentTypes(TABLE_TYPE, DESCRIPTOR_TYPE, MAP_TYPE, BOOLEAN_TYPE),
+
+ // Valid: produces_full_deletes=false with op_mapping that omits DELETE
+ TestSpec.forStrategy(
+ "Valid produces_full_deletes=false with no DELETE in mapping",
+ TO_CHANGELOG_INPUT_TYPE_STRATEGY)
+ .calledWithArgumentTypes(
+ TABLE_TYPE, DESCRIPTOR_TYPE, MAP_TYPE, BOOLEAN_TYPE)
+ .calledWithTableSemanticsAt(0, new TableSemanticsMock(TABLE_TYPE))
+ .calledWithLiteralAt(1, ColumnList.of("op"))
+ .calledWithLiteralAt(2, Map.of("INSERT, UPDATE_AFTER", "X"))
+ .calledWithLiteralAt(3, false)
+ .expectArgumentTypes(TABLE_TYPE, DESCRIPTOR_TYPE, MAP_TYPE, BOOLEAN_TYPE),
+
+ // Error: produces_full_deletes=true with op_mapping that strips DELETE
+ TestSpec.forStrategy(
+ "produces_full_deletes=true rejected when op_mapping omits DELETE",
+ TO_CHANGELOG_INPUT_TYPE_STRATEGY)
+ .calledWithArgumentTypes(
+ TABLE_TYPE, DESCRIPTOR_TYPE, MAP_TYPE, BOOLEAN_TYPE)
+ .calledWithTableSemanticsAt(0, new TableSemanticsMock(TABLE_TYPE))
+ .calledWithLiteralAt(1, ColumnList.of("op"))
+ .calledWithLiteralAt(2, Map.of("INSERT, UPDATE_AFTER", "X"))
+ .calledWithLiteralAt(3, true)
+ .expectErrorMessage(
+ "Invalid 'produces_full_deletes' for TO_CHANGELOG: the active "
+ + "'op_mapping' does not map DELETE rows"),
+
+ // Error: multi-column descriptor
Review Comment:
```suggestion
// Error: multi-column descriptor for `op`
```
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/ToChangelogTestPrograms.java:
##########
@@ -598,4 +599,220 @@ public class ToChangelogTestPrograms {
ValidationException.class,
"Duplicate change operation: 'DELETE'")
.build();
+
+ public static final TableTestProgram PRODUCES_FULL_DELETES_ON_APPEND_ONLY_INPUT =
+ TableTestProgram.of(
+ "to-changelog-produces-full-deletes-on-append-only-input",
+ "fails when produces_full_deletes=true on an input that never emits DELETE rows")
+ .setupTableSource(SIMPLE_SOURCE)
+ .runFailingSql(
+ "SELECT * FROM TO_CHANGELOG("
+ + "input => TABLE t, "
+ + "produces_full_deletes => true)",
+ ValidationException.class,
+ "the input table only produces [INSERT] and never emits DELETE rows")
+ .build();
+
+ // --------------------------------------------------------------------------------------------
+ // Row semantics x delete handling matrix
+ // --------------------------------------------------------------------------------------------
+
+ public static final TableTestProgram ROW_SEM_PARTIAL_DELETES =
Review Comment:
Let's rename the tests so it matches the naming style we have
...
RETRACT_PRODUCES_PARTIAL_DELETES
UPSERT_PRODUCES_FULL_DELETES
UPSERT_PRODUCES_PARTIAL_DELETES
RETRACT_PARTITION_BY_PRODUCES_PARTIAL_DELETES
RETRACT_PARTITION_BY_PRODUCES_FULL_DELETES
UPSERT_PARTITION_BY_PRODUCES_FULL_DELETES
...
This makes it easier for us to navigate tests
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/ToChangelogTestPrograms.java:
##########
@@ -598,4 +599,220 @@ public class ToChangelogTestPrograms {
ValidationException.class,
"Duplicate change operation: 'DELETE'")
.build();
+
+ public static final TableTestProgram PRODUCES_FULL_DELETES_ON_APPEND_ONLY_INPUT =
Review Comment:
Move this to error validation tests section and rename so it matches other tests
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/PartitionedTable.java:
##########
@@ -204,9 +204,18 @@ public interface PartitionedTable {
* descriptor("deleted").asArgument("op"),
* map("INSERT, UPDATE_AFTER", "false", "DELETE", "true").asArgument("op_mapping")
* );
+ *
+ * // Opt out of full-delete semantics. The default (true) requires fully-populated DELETE
+ * // rows and inserts a ChangelogNormalize for upsert sources. When false, the function
+ * // preserves the partition key on DELETE rows and nulls the rest, which avoids the
+ * // stateful normalization operator upstream.
+ * Table result = table
+ * .partitionBy($("id"))
+ * .toChangelog(lit(false).asArgument("produces_full_deletes"));
Review Comment:
Let's keep the api usage simple with only the info the user needs. More details can be found in the documentation
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/TableSemantics.java:
##########
@@ -128,6 +128,28 @@ public interface TableSemantics {
*/
Optional<ChangelogMode> changelogMode();
+ /**
+ * Upsert key columns derived from the passed table's metadata.
+ *
+ * <p>Returns 0-based column indices that uniquely identify a row for upsert semantics. This is
+ * distinct from {@link #partitionByColumns()}: partition keys describe distribution and
+ * co-location, upsert keys describe row identity. Useful for functions that need to emit
+ * key-only deletes, match UPDATE_BEFORE / UPDATE_AFTER pairs, or route CDC events without
+ * forcing the caller to repeat the key via {@code PARTITION BY}.
+ *
+ * <p>Returns an empty array when no upsert key is derivable (e.g., a pure append-only source)
+ * or when the planner has not yet computed metadata (during type inference).
+ *
+ * <p>If the planner derives multiple candidate upsert keys for the same input (e.g., a table
+ * with several unique constraints), only one is returned. The planner today picks the candidate
+ * with the smallest number of columns, but ties between equal-cardinality keys are resolved by
+ * an implementation detail and may change across releases. Callers must not rely on which
+ * candidate is returned when more than one exists.
Review Comment:
This would also be one of the reasons to pass down all upsert keys so that users decide which one they want to use
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/TableSemantics.java:
##########
@@ -128,6 +128,28 @@ public interface TableSemantics {
*/
Optional<ChangelogMode> changelogMode();
+ /**
+ * Upsert key columns derived from the passed table's metadata.
+ *
+ * <p>Returns 0-based column indices that uniquely identify a row for upsert semantics. This is
+ * distinct from {@link #partitionByColumns()}: partition keys describe distribution and
+ * co-location, upsert keys describe row identity. Useful for functions that need to emit
+ * key-only deletes, match UPDATE_BEFORE / UPDATE_AFTER pairs, or route CDC events without
+ * forcing the caller to repeat the key via {@code PARTITION BY}.
+ *
+ * <p>Returns an empty array when no upsert key is derivable (e.g., a pure append-only source)
+ * or when the planner has not yet computed metadata (during type inference).
Review Comment:
append-only sources can actually have a primary and an upsert key
```suggestion
* <p>Returns an empty array when no upsert key is derivable
* or when the planner has not yet computed metadata (during type inference).
```
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/ToChangelogTypeStrategy.java:
##########
@@ -187,12 +198,63 @@ private static Optional<List<DataType>> validateOpMappingKeys(
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);
+ @SuppressWarnings("rawtypes")
+ private static Optional<List<DataType>> validateProducesFullDeletes(
+ final CallContext callContext, final boolean throwOnFailure) {
+ final boolean isExplicit = !callContext.isArgumentNull(ARG_PRODUCES_FULL_DELETES);
+ if (!isExplicit) {
+ return Optional.empty();
+ }
+ if (!callContext.isArgumentLiteral(ARG_PRODUCES_FULL_DELETES)) {
+ return callContext.fail(
+ throwOnFailure,
+ "The 'produces_full_deletes' argument must be a constant BOOLEAN literal.");
+ }
+ final boolean producesFullDeletes =
+ callContext.getArgumentValue(ARG_PRODUCES_FULL_DELETES, Boolean.class).orElse(true);
+ if (!producesFullDeletes) {
+ return Optional.empty();
+ }
+ // The check against the input changelog mode lives in the function constructor since
+ // TableSemantics#changelogMode() returns empty here at type-inference time. The mapping
+ // check below only needs the literal op_mapping argument, so it lives here. Only runs
+ // when the user explicitly set produces_full_deletes=true; the default true is not
+ // validated since it is a safe no-op for any input.
+ final Optional<Map> opMapping = callContext.getArgumentValue(ARG_OP_MAPPING, Map.class);
+ if (opMapping.isPresent() && !mapsDelete((Map<String, String>) opMapping.get())) {
+ return callContext.fail(
+ throwOnFailure,
+ "Invalid 'produces_full_deletes' for TO_CHANGELOG: the active 'op_mapping' "
Review Comment:
nice
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/TableSemantics.java:
##########
@@ -128,6 +128,28 @@ public interface TableSemantics {
*/
Optional<ChangelogMode> changelogMode();
+ /**
+ * Upsert key columns derived from the passed table's metadata.
+ *
+ * <p>Returns 0-based column indices that uniquely identify a row for upsert semantics. This is
+ * distinct from {@link #partitionByColumns()}: partition keys describe distribution and
+ * co-location, upsert keys describe row identity. Useful for functions that need to emit
+ * key-only deletes, match UPDATE_BEFORE / UPDATE_AFTER pairs, or route CDC events without
+ * forcing the caller to repeat the key via {@code PARTITION BY}.
Review Comment:
```suggestion
* <p>Returns 0-based column indices that uniquely identify a row for upsert semantics. This is
* distinct from {@link #partitionByColumns()}: partition keys describe distribution and
* co-location, upsert keys describe row identity. Useful for functions that need to emit
* key-only deletes, match UPDATE_BEFORE / UPDATE_AFTER pairs, or want to have a unique identifier to interact with state.
```
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -397,6 +399,76 @@ SELECT * FROM TO_CHANGELOG(
-- UPDATE_BEFORE is dropped (not in the mapping)
```
+#### Delete handling
+
+The `produces_full_deletes` argument controls how DELETE rows are emitted and what the planner requires from the input. The matrix below shows each combination with `PARTITION BY` (set semantics) and without (row semantics).
+
+##### `produces_full_deletes => true` (default)
+
+The planner requires fully-populated DELETE rows on the input. For upsert sources that emit key-only deletes, a `ChangelogNormalize` operator is inserted upstream to materialize the full pre-image from state. For sources that already emit a full pre-image (e.g. retract), the flag is a no-op. The function then passes the input row through unchanged on DELETE.
+
+**Row semantics** (no `PARTITION BY`):
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
+-- Output: +I[op:'DELETE', id:5, name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source)
+
+-- Retract source: -D[id:5, name:'Alice'] (full pre-image).
+-- No ChangelogNormalize inserted; the input row is passed through unchanged.
+-- Output: +I[op:'DELETE', id:5, name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source)
+```
+
+**Set semantics** (`PARTITION BY`):
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
+-- Output: +I[id:5, op:'DELETE', name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source PARTITION BY id)
+
+-- Retract source: -D[id:5, name:'Alice'] (full pre-image).
+-- No ChangelogNormalize inserted; the input row is passed through unchanged.
+-- Output: +I[id:5, op:'DELETE', name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source PARTITION BY id)
+```
+
+##### `produces_full_deletes => false`
+
+The planner skips `ChangelogNormalize` and the function emits partial DELETE rows. This avoids the stateful normalization operator for upsert sources (e.g. Kafka compacted topics) where the full pre-image is not needed downstream. Requires an upsert key (row semantics) or `PARTITION BY` (set semantics); otherwise the call is rejected with a validation error.
Review Comment:
I think we don't have a good explanation of the upsert key in the docs. It'd be good to have it and then link it in the places where we mention it for the users
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/ToChangelogTypeStrategy.java:
##########
Review Comment:
```suggestion
"Invalid target mapping for argument 'op_mapping'. "
+ "Unknown change operation: '%s'. Operations are case-sensitive. Valid values are: %s.",
```
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/ToChangelogTestPrograms.java:
##########
@@ -598,4 +599,220 @@ public class ToChangelogTestPrograms {
ValidationException.class,
"Duplicate change operation: 'DELETE'")
.build();
+
+ public static final TableTestProgram PRODUCES_FULL_DELETES_ON_APPEND_ONLY_INPUT =
+ TableTestProgram.of(
+ "to-changelog-produces-full-deletes-on-append-only-input",
+ "fails when produces_full_deletes=true on an input that never emits DELETE rows")
+ .setupTableSource(SIMPLE_SOURCE)
+ .runFailingSql(
+ "SELECT * FROM TO_CHANGELOG("
+ + "input => TABLE t, "
+ + "produces_full_deletes => true)",
+ ValidationException.class,
+ "the input table only produces [INSERT] and never emits DELETE rows")
+ .build();
+
+ // --------------------------------------------------------------------------------------------
+ // Row semantics x delete handling matrix
+ // --------------------------------------------------------------------------------------------
+
+ public static final TableTestProgram ROW_SEM_PARTIAL_DELETES =
+ TableTestProgram.of(
+ "to-changelog-row-sem-partial-deletes",
+ "row semantics: produces_full_deletes=false skips ChangelogNormalize and a partial DELETE row from the input passes through unchanged")
+ .setupTableSource(
+ SourceTestStep.newBuilder("t")
+ .addSchema(
+ "name STRING PRIMARY KEY NOT ENFORCED", "score BIGINT")
+ .addMode(ChangelogMode.all())
+ .producedValues(
+ Row.ofKind(RowKind.INSERT, "Alice", 10L),
+ Row.ofKind(RowKind.INSERT, "Bob", 20L),
+ Row.ofKind(RowKind.UPDATE_BEFORE, "Alice", 10L),
+ Row.ofKind(RowKind.UPDATE_AFTER, "Alice", 30L),
+ Row.ofKind(RowKind.DELETE, "Bob", null))
+ .build())
+ .setupTableSink(
+ SinkTestStep.newBuilder("sink")
+ .addSchema("op STRING", "name STRING", "score BIGINT")
+ .consumedValues(
+ "+I[INSERT, Alice, 10]",
+ "+I[INSERT, Bob, 20]",
+ "+I[UPDATE_BEFORE, Alice, 10]",
+ "+I[UPDATE_AFTER, Alice, 30]",
+ "+I[DELETE, Bob, null]")
+ .build())
+ .runSql(
+ "INSERT INTO sink SELECT * FROM TO_CHANGELOG("
+ + "input => TABLE t, "
+ + "produces_full_deletes => false)")
+ .build();
+
+ public static final TableTestProgram ROW_SEM_FORCE_FULL_DELETES =
+ TableTestProgram.of(
+ "to-changelog-row-sem-force-full-deletes",
+ "row semantics: produces_full_deletes=true forces ChangelogNormalize to materialize the full DELETE row from an upsert source emitting key-only deletes")
+ .setupTableSource(
+ SourceTestStep.newBuilder("t")
+ .addSchema(
+ "name STRING PRIMARY KEY NOT ENFORCED", "score BIGINT")
+ .addMode(ChangelogMode.upsert())
+ .producedValues(
+ Row.ofKind(RowKind.INSERT, "Alice", 10L),
+ // Key-only delete: ChangelogNormalize fills the row.
+ Row.ofKind(RowKind.DELETE, "Alice", null))
+ .build())
+ .setupTableSink(
+ SinkTestStep.newBuilder("sink")
+ .addSchema("op STRING", "name STRING", "score BIGINT")
+ .consumedValues(
+ "+I[INSERT, Alice, 10]", "+I[DELETE, Alice, 10]")
+ .build())
+ .runSql(
+ "INSERT INTO sink SELECT * FROM TO_CHANGELOG("
+ + "input => TABLE t, "
+ + "produces_full_deletes => true)")
+ .build();
+
+ public static final TableTestProgram ROW_SEM_PARTIAL_DELETES_VIA_UPSERT_KEY =
+ TableTestProgram.of(
+ "to-changelog-row-sem-partial-deletes-via-upsert-key",
+ "row semantics with single-column upsert key + "
+ + "produces_full_deletes=false: DELETE preserves the key "
+ + "column and nulls the rest without requiring PARTITION BY")
+ .setupTableSource(
+ SourceTestStep.newBuilder("t")
+ .addSchema(
+ "name STRING PRIMARY KEY NOT ENFORCED", "score BIGINT")
+ .addMode(ChangelogMode.upsert())
+ .producedValues(
+ Row.ofKind(RowKind.INSERT, "Alice", 10L),
+ Row.ofKind(RowKind.DELETE, "Alice", 10L))
+ .build())
+ .setupTableSink(
+ SinkTestStep.newBuilder("sink")
+ .addSchema("op STRING", "name STRING", "score BIGINT")
+ .consumedValues(
+ "+I[INSERT, Alice, 10]", "+I[DELETE, Alice, null]")
+ .build())
+ .runSql(
+ "INSERT INTO sink SELECT * FROM TO_CHANGELOG("
+ + "input => TABLE t, "
+ + "produces_full_deletes => false)")
+ .build();
+
+ // --------------------------------------------------------------------------------------------
+ // Set semantics x delete handling matrix
+ // --------------------------------------------------------------------------------------------
+
+ public static final TableTestProgram SET_SEM_FORCE_PARTIAL_DELETES =
+ TableTestProgram.of(
+ "to-changelog-set-sem-force-partial-deletes",
+ "set semantics: produces_full_deletes=false nulls non-partition-key columns on DELETE even when the input row is fully populated")
+ .setupTableSource(
+ SourceTestStep.newBuilder("t")
+ .addSchema(
+ "name STRING PRIMARY KEY NOT ENFORCED", "score BIGINT")
+ .addMode(ChangelogMode.all())
+ .producedValues(
+ Row.ofKind(RowKind.INSERT, "Alice", 10L),
+ Row.ofKind(RowKind.INSERT, "Bob", 20L),
+ Row.ofKind(RowKind.UPDATE_AFTER, "Alice", 30L),
+ Row.ofKind(RowKind.DELETE, "Bob", 20L))
+ .build())
+ .setupTableSink(
+ SinkTestStep.newBuilder("sink")
+ .addSchema("name STRING", "op STRING", "score BIGINT")
+ .consumedValues(
+ "+I[Alice, INSERT, 10]",
+ "+I[Bob, INSERT, 20]",
+ "+I[Alice, UPDATE_AFTER, 30]",
+ "+I[Bob, DELETE, null]")
+ .build())
+ .runSql(
+ "INSERT INTO sink SELECT * FROM TO_CHANGELOG("
+ + "input => TABLE t PARTITION BY name,"
+ + "produces_full_deletes => false)")
+ .build();
+
+ public static final TableTestProgram SET_SEM_PARTIAL_DELETES =
+ TableTestProgram.of(
+ "to-changelog-set-sem-partial-deletes",
+ "set semantics: produces_full_deletes=false (default) lets a partial DELETE row from the input pass through with non-partition-key columns null")
Review Comment:
This is wrong, the default is true. Is this test passing?
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3310084922
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/BuiltInFunctionDefinitions.java:
##########
@@ -840,25 +840,35 @@ ANY, and(logical(LogicalTypeRoot.BOOLEAN), LITERAL)
"UPDATE_BEFORE"))))
.withConditionalTrait(
StaticArgumentTrait.REQUIRE_FULL_DELETE,
- TraitCondition.or(
- // op_mapping omitted: default mapping includes
- // DELETE.
- TraitCondition.not(
- TraitCondition.argIsPresent(
- "op_mapping")),
- TraitCondition.argMatches(
- "op_mapping",
- Map.class,
- mapping ->
- opMappingContainsKey(
- (Map<String, String>)
- mapping,
- "DELETE")))),
+ // Require full deletes only when the user explicitly
+ // asks for them via produces_full_deletes=TRUE *and*
+ // the active op_mapping includes DELETE. Otherwise the
+ // planner can skip ChangelogNormalize for upsert
+ // sources that emit key-only deletes.
+ TraitCondition.and(
+ TraitCondition.argIsEqualTo(
+ "produces_full_deletes", Boolean.TRUE),
Review Comment:
Okay! Now the default `produces_full_deletes` is set to `true`
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3318535130
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/ToChangelogTestPrograms.java:
##########
@@ -598,4 +598,192 @@ public class ToChangelogTestPrograms {
ValidationException.class,
"Duplicate change operation: 'DELETE'")
.build();
+
+ public static final TableTestProgram INVALID_PRODUCES_FULL_DELETES_FOR_APPEND_ONLY =
+ TableTestProgram.of(
+ "to-changelog-invalid-produces-full-deletes-for-append-only",
+ "fails when produces_full_deletes=true on an input that never emits DELETE rows")
+ .setupTableSource(SIMPLE_SOURCE)
+ .runFailingSql(
+ "SELECT * FROM TO_CHANGELOG("
+ + "input => TABLE t, "
+ + "produces_full_deletes => true)",
+ ValidationException.class,
+ "the input table only produces [INSERT] and never emits DELETE rows")
+ .build();
+
+ // --------------------------------------------------------------------------------------------
+ // Full vs partial deletes matrix (input kind x PARTITION BY x produces_full_deletes)
+ // --------------------------------------------------------------------------------------------
+
+ public static final TableTestProgram RETRACT_PRODUCES_PARTIAL_DELETES =
+ TableTestProgram.of(
+ "to-changelog-retract-produces-partial-deletes",
+ "retract input in row semantics with produces_full_deletes=false: skips ChangelogNormalize and the partial DELETE row from the input passes through unchanged")
+ .setupTableSource(
+ SourceTestStep.newBuilder("t")
+ .addSchema(
+ "name STRING PRIMARY KEY NOT ENFORCED", "score BIGINT")
Review Comment:
This was a tricky one to solve but now I have pushed the new changes in separate commit.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3320504202
##########
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/inference/strategies/ToChangelogOutputTypeStrategyTest.java:
##########
@@ -0,0 +1,110 @@
+/*
+ * 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.table.api.DataTypes;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.inference.TypeStrategiesTestBase;
+import org.apache.flink.table.types.inference.utils.TableSemanticsMock;
+import org.apache.flink.types.ColumnList;
+
+import java.util.List;
+import java.util.stream.Stream;
+
+import static org.apache.flink.table.types.inference.strategies.SpecificTypeStrategies.TO_CHANGELOG_OUTPUT_TYPE_STRATEGY;
+import static org.apache.flink.table.types.inference.strategies.ToChangelogTypeStrategy.ARG_OP;
+import static org.apache.flink.table.types.inference.strategies.ToChangelogTypeStrategy.ARG_OP_MAPPING;
+import static org.apache.flink.table.types.inference.strategies.ToChangelogTypeStrategy.ARG_PRODUCES_FULL_DELETES;
+import static org.apache.flink.table.types.inference.strategies.ToChangelogTypeStrategy.ARG_TABLE;
+
+/** Tests for {@link ToChangelogTypeStrategy#OUTPUT_TYPE_STRATEGY}. */
+class ToChangelogOutputTypeStrategyTest extends TypeStrategiesTestBase {
+
+ private static final DataType TABLE_TYPE_NOT_NULL_SCORE =
+ DataTypes.ROW(
+ DataTypes.FIELD("name", DataTypes.STRING().notNull()),
+ DataTypes.FIELD("score", DataTypes.BIGINT().notNull()));
+
+ private static final DataType DESCRIPTOR_TYPE = DataTypes.DESCRIPTOR();
+ private static final DataType MAP_TYPE = DataTypes.MAP(DataTypes.STRING(), DataTypes.STRING());
+ private static final DataType BOOLEAN_TYPE = DataTypes.BOOLEAN();
+
+ @Override
+ protected Stream<TestSpec> testData() {
+ return Stream.of(
+ TestSpec.forStrategy(
+ "produces_full_deletes=true preserves NOT NULL on input columns",
Review Comment:
Yeah I tried to keep the tests simple here and only assert the necessary and critical output strategy logic
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3311153580
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -397,6 +399,76 @@ SELECT * FROM TO_CHANGELOG(
-- UPDATE_BEFORE is dropped (not in the mapping)
```
+#### Delete handling
+
+The `produces_full_deletes` argument controls how DELETE rows are emitted and what the planner requires from the input. The matrix below shows each combination with `PARTITION BY` (set semantics) and without (row semantics).
+
+##### `produces_full_deletes => true` (default)
+
+The planner requires fully-populated DELETE rows on the input. For upsert sources that emit key-only deletes, a `ChangelogNormalize` operator is inserted upstream to materialize the full pre-image from state. For sources that already emit a full pre-image (e.g. retract), the flag is a no-op. The function then passes the input row through unchanged on DELETE.
+
+**Row semantics** (no `PARTITION BY`):
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
+-- Output: +I[op:'DELETE', id:5, name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source)
+
+-- Retract source: -D[id:5, name:'Alice'] (full pre-image).
+-- No ChangelogNormalize inserted; the input row is passed through unchanged.
+-- Output: +I[op:'DELETE', id:5, name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source)
+```
+
+**Set semantics** (`PARTITION BY`):
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
+-- Output: +I[id:5, op:'DELETE', name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source PARTITION BY id)
+
+-- Retract source: -D[id:5, name:'Alice'] (full pre-image).
+-- No ChangelogNormalize inserted; the input row is passed through unchanged.
+-- Output: +I[id:5, op:'DELETE', name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source PARTITION BY id)
+```
+
+##### `produces_full_deletes => false`
+
+The planner skips `ChangelogNormalize` and the function emits partial DELETE rows. This avoids the stateful normalization operator for upsert sources (e.g. Kafka compacted topics) where the full pre-image is not needed downstream. Requires an upsert key (row semantics) or `PARTITION BY` (set semantics); otherwise the call is rejected with a validation error.
Review Comment:
Added a section for upsertKey
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -397,6 +399,76 @@ SELECT * FROM TO_CHANGELOG(
-- UPDATE_BEFORE is dropped (not in the mapping)
```
+#### Delete handling
+
+The `produces_full_deletes` argument controls how DELETE rows are emitted and what the planner requires from the input. The matrix below shows each combination with `PARTITION BY` (set semantics) and without (row semantics).
+
+##### `produces_full_deletes => true` (default)
+
+The planner requires fully-populated DELETE rows on the input. For upsert sources that emit key-only deletes, a `ChangelogNormalize` operator is inserted upstream to materialize the full pre-image from state. For sources that already emit a full pre-image (e.g. retract), the flag is a no-op. The function then passes the input row through unchanged on DELETE.
+
+**Row semantics** (no `PARTITION BY`):
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
+-- Output: +I[op:'DELETE', id:5, name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source)
+
+-- Retract source: -D[id:5, name:'Alice'] (full pre-image).
+-- No ChangelogNormalize inserted; the input row is passed through unchanged.
+-- Output: +I[op:'DELETE', id:5, name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source)
+```
+
+**Set semantics** (`PARTITION BY`):
+
+```sql
+-- Upsert source: -D[id:5] (key-only).
+-- ChangelogNormalize materializes the full pre-image from state.
+-- Output: +I[id:5, op:'DELETE', name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE upsert_source PARTITION BY id)
+
+-- Retract source: -D[id:5, name:'Alice'] (full pre-image).
+-- No ChangelogNormalize inserted; the input row is passed through unchanged.
+-- Output: +I[id:5, op:'DELETE', name:'Alice']
+SELECT * FROM TO_CHANGELOG(input => TABLE retract_source PARTITION BY id)
+```
+
+##### `produces_full_deletes => false`
+
+The planner skips `ChangelogNormalize` and the function emits partial DELETE rows. This avoids the stateful normalization operator for upsert sources (e.g. Kafka compacted topics) where the full pre-image is not needed downstream. Requires an upsert key (row semantics) or `PARTITION BY` (set semantics); otherwise the call is rejected with a validation error.
+
+**Row semantics** (no `PARTITION BY`): the function preserves the planner-derived upsert key columns on DELETE rows and nulls the rest. The upsert key is typically a declared `PRIMARY KEY`.
Review Comment:
added
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3311141329
##########
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/inference/strategies/ToChangelogInputTypeStrategyTest.java:
##########
@@ -0,0 +1,142 @@
+/*
+ * 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.table.api.DataTypes;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.inference.InputTypeStrategiesTestBase;
+import org.apache.flink.table.types.inference.utils.TableSemanticsMock;
+import org.apache.flink.types.ColumnList;
+
+import java.util.Map;
+import java.util.stream.Stream;
+
+import static org.apache.flink.table.types.inference.strategies.SpecificInputTypeStrategies.TO_CHANGELOG_INPUT_TYPE_STRATEGY;
+
+/** Tests for {@link ToChangelogTypeStrategy#INPUT_TYPE_STRATEGY}. */
+class ToChangelogInputTypeStrategyTest extends InputTypeStrategiesTestBase {
+
+ private static final DataType TABLE_TYPE =
+ DataTypes.ROW(
+ DataTypes.FIELD("name", DataTypes.STRING()),
+ DataTypes.FIELD("score", DataTypes.BIGINT()));
+
+ private static final DataType DESCRIPTOR_TYPE = DataTypes.DESCRIPTOR();
+
+ private static final DataType MAP_TYPE = DataTypes.MAP(DataTypes.STRING(), DataTypes.STRING());
+
+ private static final DataType BOOLEAN_TYPE = DataTypes.BOOLEAN();
+
+ @Override
+ protected Stream<TestSpec> testData() {
+ return Stream.of(
+ // Valid: produces_full_deletes=true with default op_mapping (includes DELETE)
+ TestSpec.forStrategy(
+ "Valid produces_full_deletes=true with default mapping",
+ TO_CHANGELOG_INPUT_TYPE_STRATEGY)
+ .calledWithArgumentTypes(
+ TABLE_TYPE, DESCRIPTOR_TYPE, MAP_TYPE, BOOLEAN_TYPE)
+ .calledWithTableSemanticsAt(0, new TableSemanticsMock(TABLE_TYPE))
+ .calledWithLiteralAt(1, ColumnList.of("op"))
+ .calledWithLiteralAt(2, null)
+ .calledWithLiteralAt(3, true)
Review Comment:
Done, all replaced with the const
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/ToChangelogTestPrograms.java:
##########
@@ -598,4 +599,220 @@ public class ToChangelogTestPrograms {
ValidationException.class,
"Duplicate change operation: 'DELETE'")
.build();
+
+ public static final TableTestProgram PRODUCES_FULL_DELETES_ON_APPEND_ONLY_INPUT =
Review Comment:
Moved and renamed 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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3311149574
##########
docs/content/docs/sql/reference/queries/changelog.md:
##########
@@ -397,6 +399,76 @@ SELECT * FROM TO_CHANGELOG(
-- UPDATE_BEFORE is dropped (not in the mapping)
```
+#### Delete handling
Review Comment:
Updated the title
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "gustavodemorais (via GitHub)" <gi...@apache.org>.
gustavodemorais commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3312058552
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecProcessTableFunction.java:
##########
@@ -121,6 +123,10 @@ public class StreamExecProcessTableFunction extends ExecNodeBase<RowData>
@JsonProperty(FIELD_NAME_OUTPUT_CHANGELOG_MODE)
private final ChangelogMode outputChangelogMode;
+ @JsonProperty(value = FIELD_NAME_INPUT_UPSERT_KEYS, defaultValue = "[]")
+ @JsonInclude(JsonInclude.Include.NON_DEFAULT)
Review Comment:
For omit-when-empty + backwards compat, use:
```
@JsonProperty(FIELD_NAME_INPUT_UPSERT_KEYS)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
```
and also
```
private final List<int[]> inputUpsertKeys;
and in the @JsonCreator, null-coalesce: this.inputUpsertKeys = inputUpsertKeys != null ? inputUpsertKeys : Collections.emptyList();.
```
NON_EMPTY omits both null and empty lists from JSON. The null-coalesce handles old plans (missing field → null → empty). Drop defaultValue = "[]", Jackson treats it as docs only.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3317902412
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/ToChangelogTypeStrategy.java:
##########
@@ -46,39 +42,30 @@
@Internal
public final class ToChangelogTypeStrategy {
- private static final String DEFAULT_OP_COLUMN_NAME = "op";
+ // Positional argument indexes for TO_CHANGELOG. Must match the order of StaticArguments
+ // registered in BuiltInFunctionDefinitions#TO_CHANGELOG; changing one without the other
+ // silently breaks argument resolution.
+ public static final int ARG_TABLE = 0;
Review Comment:
I would rather keep the name as-is. All the argument are by convention like `ARG_<argName>` (`op -> ARG_OP`, `op_mapping -> ARG_OP_MAPPING`, `table -> ARG_TABLE`)
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "gustavodemorais (via GitHub)" <gi...@apache.org>.
gustavodemorais merged PR #28235:
URL: https://github.com/apache/flink/pull/28235
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "gustavodemorais (via GitHub)" <gi...@apache.org>.
gustavodemorais commented on code in PR #28235:
URL: https://github.com/apache/flink/pull/28235#discussion_r3318673764
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/ToChangelogTestPrograms.java:
##########
@@ -598,4 +598,192 @@ public class ToChangelogTestPrograms {
ValidationException.class,
"Duplicate change operation: 'DELETE'")
.build();
+
+ public static final TableTestProgram INVALID_PRODUCES_FULL_DELETES_FOR_APPEND_ONLY =
+ TableTestProgram.of(
+ "to-changelog-invalid-produces-full-deletes-for-append-only",
+ "fails when produces_full_deletes=true on an input that never emits DELETE rows")
+ .setupTableSource(SIMPLE_SOURCE)
+ .runFailingSql(
+ "SELECT * FROM TO_CHANGELOG("
+ + "input => TABLE t, "
+ + "produces_full_deletes => true)",
+ ValidationException.class,
+ "the input table only produces [INSERT] and never emits DELETE rows")
+ .build();
+
+ // --------------------------------------------------------------------------------------------
+ // Full vs partial deletes matrix (input kind x PARTITION BY x produces_full_deletes)
+ // --------------------------------------------------------------------------------------------
+
+ public static final TableTestProgram RETRACT_PRODUCES_PARTIAL_DELETES =
+ TableTestProgram.of(
+ "to-changelog-retract-produces-partial-deletes",
+ "retract input in row semantics with produces_full_deletes=false: skips ChangelogNormalize and the partial DELETE row from the input passes through unchanged")
+ .setupTableSource(
+ SourceTestStep.newBuilder("t")
+ .addSchema(
+ "name STRING PRIMARY KEY NOT ENFORCED", "score BIGINT")
Review Comment:
You added it to [ToChangelogOutputTypeStrategyTest.ja](https://github.com/apache/flink/pull/28235/files/e85c2644b018845fb1cd19431ee5da8f1594b5bc#diff-140d309e243999637609c3963eb949f27423d9bd678bb4617ec59e52e3c2f250) instead of TestPrograms, right?
I think that should be enough. One detail, see https://github.com/apache/flink/pull/28235#discussion_r3318657761
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-39636][table] Add produces_full_deletes parameter in TO_CHANGELOG [flink]
Posted by "flinkbot (via GitHub)" <gi...@apache.org>.
flinkbot commented on PR #28235:
URL: https://github.com/apache/flink/pull/28235#issuecomment-4520046388
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "2d669479a11dc4ba5b687237369d1945c647bf9e",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "2d669479a11dc4ba5b687237369d1945c647bf9e",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 2d669479a11dc4ba5b687237369d1945c647bf9e UNKNOWN
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run azure` re-run the last Azure build
</details>
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org