leonardBang commented on code in PR #4638:
URL: https://github.com/apache/flink-cdc/pull/4638#discussion_r4783057026


##########
flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-postgres/src/main/java/org/apache/flink/cdc/connectors/postgres/source/PostgresEventDeserializer.java:
##########
@@ -79,23 +97,205 @@ public PostgresEventDeserializer(
             List<PostgreSQLReadableMetadata> readableMetadataList,
             boolean includeDatabaseInTableId,
             String databaseName) {
+        this(changelogMode, readableMetadataList, includeDatabaseInTableId, 
databaseName, false);
+    }
+
+    public PostgresEventDeserializer(
+            DebeziumChangelogMode changelogMode,
+            List<PostgreSQLReadableMetadata> readableMetadataList,
+            boolean includeDatabaseInTableId,
+            String databaseName,
+            boolean deleteNonKeyNullAsDefault) {
         super(new PostgresSchemaDataTypeInference(), changelogMode);
         this.readableMetadataList = readableMetadataList;
         this.includeDatabaseInTableId = includeDatabaseInTableId;
         this.databaseName = databaseName;
+        this.deleteNonKeyNullAsDefault = deleteNonKeyNullAsDefault;
+    }
+
+    public DebeziumChangelogMode getChangelogMode() {
+        return changelogMode;
+    }
+
+    public void setDeleteBeforeColumns(
+            io.debezium.relational.TableId tableId, Set<String> columns) {
+        deleteBeforeColumns.put(tableId, new HashSet<>(columns));
     }
 
     @Override
-    protected RecordData extractBeforeDataRecord(Struct value, Schema 
valueSchema)
-            throws Exception {
-        Struct beforeValue = fieldStruct(value, Envelope.FieldName.BEFORE);
-        Preconditions.checkNotNull(
-                beforeValue,
-                "Before data is null for UPDATE/DELETE event. "
-                        + "This usually happens when the source table is not 
configured with "
-                        + "REPLICA IDENTITY FULL. Schema name: "
-                        + valueSchema.name());
-        return super.extractBeforeDataRecord(value, valueSchema);
+    public List<DataChangeEvent> deserializeDataChangeRecord(SourceRecord 
record) throws Exception {
+        Envelope.Operation operation = Envelope.operationFor(record);
+        TableId tableId = getTableId(record);
+        Struct value = (Struct) record.value();
+        if (changelogMode == DebeziumChangelogMode.UPSERT
+                && operation == Envelope.Operation.DELETE) {
+            return Collections.singletonList(
+                    DataChangeEvent.deleteEvent(
+                            tableId, extractDeleteRecord(record, tableId), 
getMetadata(record)));
+        }
+        if (changelogMode == DebeziumChangelogMode.ALL
+                && (operation == Envelope.Operation.UPDATE
+                        || operation == Envelope.Operation.DELETE)) {
+            Struct before = fieldStruct(value, Envelope.FieldName.BEFORE);
+            if (before == null) {
+                throw missingBefore(tableId, operation, "the before image is 
missing");
+            }
+            for (Field field : before.schema().fields()) {
+                if (!field.schema().isOptional()
+                        && before.getWithoutDefault(field.name()) == null) {
+                    throw missingBefore(
+                            tableId,
+                            operation,
+                            "the before image is missing required column '" + 
field.name() + "'");
+                }
+            }
+        }
+        List<DataChangeEvent> events = 
super.deserializeDataChangeRecord(record);
+        if (changelogMode == DebeziumChangelogMode.UPSERT
+                && operation == Envelope.Operation.UPDATE) {
+            DataChangeEvent event = events.get(0);
+            return Collections.singletonList(
+                    DataChangeEvent.replaceEvent(tableId, event.after(), 
event.meta()));
+        }
+        return events;
+    }
+
+    private IllegalStateException missingBefore(
+            TableId tableId, Envelope.Operation operation, String reason) {
+        return new IllegalStateException(
+                String.format(
+                        "Cannot deserialize %s event for PostgreSQL table 
'%s': %s, but changelog-mode='all' requires complete before images. This can 
happen when REPLICA IDENTITY is not FULL. %s",
+                        operation,
+                        tableId,
+                        reason,
+                        PostgresSchemaUtils.replicaIdentityHint(
+                                PostgresSchemaUtils.toDbzTableId(tableId))));
+    }
+
+    private RecordData extractDeleteRecord(SourceRecord record, TableId 
tableId) throws Exception {
+        CreateTableEvent createTableEvent =
+                getCreateTableEventCache()
+                        .get(
+                                new io.debezium.relational.TableId(
+                                        null, tableId.getSchemaName(), 
tableId.getTableName()));
+        if (createTableEvent == null || 
createTableEvent.getSchema().primaryKeys().isEmpty()) {
+            throw new IllegalStateException(
+                    "Cannot deserialize DELETE event for PostgreSQL table '"
+                            + tableId
+                            + "': a table schema with a primary key is 
required by changelog-mode='upsert'.");
+        }
+        org.apache.flink.cdc.common.schema.Schema schema = 
createTableEvent.getSchema();
+        Set<String> beforeColumns =
+                deleteBeforeColumns.get(
+                        new io.debezium.relational.TableId(
+                                null, tableId.getSchemaName(), 
tableId.getTableName()));
+        if (beforeColumns == null) {
+            throw new IllegalStateException(
+                    "Cannot deserialize DELETE event for PostgreSQL table '"
+                            + tableId
+                            + "': replica identity metadata has not been 
initialized.");
+        }
+        Struct key = record.key() instanceof Struct ? (Struct) record.key() : 
null;
+        Struct before = fieldStruct((Struct) record.value(), 
Envelope.FieldName.BEFORE);
+        Object[] fields = new Object[schema.getColumnCount()];
+        for (String primaryKey : schema.primaryKeys()) {
+            Struct keySource = key;
+            if (keySource == null
+                    || keySource.schema().field(primaryKey) == null

Review Comment:
   Would it make sense to use Debezium's field-name mapping when reading the 
key and before-image Structs here? With `debezium.sanitize.field.names: true`, 
a PostgreSQL column such as `"tenant-id"` is exposed as `tenant_id` in the 
Struct, while the cached CDC schema still uses `tenant-id`. Looking it up by 
the original name therefore reports a missing primary key even with `REPLICA 
IDENTITY FULL`. The non-key lookups below have the same issue: an available old 
value can be treated as missing, causing a NOT NULL error or replacement with a 
placeholder.
   
   I reproduced both cases with PostgreSQL 14/pgoutput by reading the snapshot 
and then deleting a row. The same tables and settings pass in `all` mode and 
fail in `upsert` mode. Could we apply the same field-name mapping as Debezium 
and add regression coverage for both primary-key and non-key columns?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to