Copilot commented on code in PR #13480:
URL: https://github.com/apache/seatunnel/pull/13480#discussion_r4712526198


##########
seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/OrderedBufferedBatchStatementExecutor.java:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.jdbc.internal.executor;
+
+import org.apache.seatunnel.api.table.type.RowKind;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.common.exception.CommonErrorCodeDeprecated;
+import 
org.apache.seatunnel.connectors.seatunnel.jdbc.exception.JdbcConnectorException;
+
+import lombok.NonNull;
+import lombok.RequiredArgsConstructor;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.function.Function;
+
+/**
+ * Applies every change of a batch in arrival order, used by {@code 
update_condition_sql}. Unlike
+ * {@link BufferReducedBatchStatementExecutor}, a key is not reduced to its 
last change.
+ *
+ * <p>The pending upsert batch is executed before a key repeats, because 
PostgreSQL fails a
+ * statement that changes the same row twice, such as a batch rewritten by the 
driver.
+ */
+@RequiredArgsConstructor
+public class OrderedBufferedBatchStatementExecutor
+        implements JdbcBatchStatementExecutor<SeaTunnelRow> {
+    @NonNull private final JdbcBatchStatementExecutor<SeaTunnelRow> 
upsertExecutor;
+    @NonNull private final JdbcBatchStatementExecutor<SeaTunnelRow> 
deleteExecutor;
+    @NonNull private final Function<SeaTunnelRow, SeaTunnelRow> keyExtractor;
+    @NonNull private final Function<SeaTunnelRow, SeaTunnelRow> valueTransform;
+
+    /** Kept until a flush succeeds, so a retry replays every change. */
+    @NonNull private final List<SeaTunnelRow> buffer = new ArrayList<>();
+
+    private boolean flushFailed;
+
+    @Override
+    public void prepareStatements(Connection connection) throws SQLException {
+        upsertExecutor.prepareStatements(connection);
+        deleteExecutor.prepareStatements(connection);
+    }
+
+    @Override
+    public void addToBatch(SeaTunnelRow record) throws SQLException {
+        if (RowKind.UPDATE_BEFORE.equals(record.getRowKind())) {
+            return;
+        }
+        // Fail on an unsupported row kind when it arrives, not when the batch 
is flushed.
+        isUpsert(record.getRowKind());
+        buffer.add(record);
+    }
+
+    @Override
+    public void executeBatch() throws SQLException {
+        try {
+            // Drop statements left by a failed attempt, as the whole buffer 
is replayed.
+            upsertExecutor.clearBatch();
+            deleteExecutor.clearBatch();
+
+            Set<SeaTunnelRow> keysInUpsertBatch = new HashSet<>();
+            Boolean pendingUpsert = null;
+            for (SeaTunnelRow record : buffer) {
+                boolean upsert = isUpsert(record.getRowKind());
+                if (pendingUpsert != null && pendingUpsert != upsert) {
+                    executePending(pendingUpsert);
+                    keysInUpsertBatch.clear();
+                }
+                SeaTunnelRow key = keyExtractor.apply(record);
+                if (upsert) {
+                    // A key with a NULL field never conflicts, so it cannot 
repeat a row.
+                    if (!hasNullField(key) && !keysInUpsertBatch.add(key)) {

Review Comment:
   On PostgreSQL 15+, a unique constraint with `NULLS NOT DISTINCT` allows 
NULL-containing keys to conflict, but this shortcut excludes them from repeat 
detection. Repeated nullable keys can therefore reach one rewritten INSERT and 
fail because it affects the same row twice. Track repeated keys even when they 
contain NULL, and update the NULL-key regression test to expect a batch 
boundary.



##########
seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/psql/PostgresDialect.java:
##########
@@ -208,6 +211,58 @@ public Optional<String> getUpsertStatement(
         return Optional.of(upsertSQL);
     }
 
+    /**
+     * Builds the upsert statement for {@code update_condition_sql}. The 
condition is added to the
+     * update branch only, so a new key is always inserted. {@code EXCLUDED} 
is the incoming row and
+     * {@value #UPDATE_CONDITION_TARGET_ALIAS} the stored one.
+     */
+    public String getConditionalUpsertStatement(
+            String database,
+            String tableName,
+            String[] fieldNames,
+            String[] pkNames,
+            UpdateCondition condition) {
+        String columns =
+                Arrays.stream(fieldNames)
+                        .map(this::quoteIdentifier)
+                        .collect(Collectors.joining(", "));
+        String placeholders =
+                Arrays.stream(fieldNames)
+                        .map(fieldName -> ":" + fieldName)
+                        .collect(Collectors.joining(", "));
+        String uniqueColumns =
+                
Arrays.stream(pkNames).map(this::quoteIdentifier).collect(Collectors.joining(", 
"));
+        final Set<String> pkNamesSet = new HashSet<>(Arrays.asList(pkNames));
+        String updateClause =
+                Arrays.stream(fieldNames)
+                        .filter(fieldName -> !pkNamesSet.contains(fieldName))
+                        .map(
+                                fieldName ->
+                                        quoteIdentifier(fieldName)
+                                                + "=EXCLUDED."
+                                                + quoteIdentifier(fieldName))
+                        .collect(Collectors.joining(", "));
+        // When every written column is a key column there is nothing to 
update.
+        String conflictAction =
+                updateClause.isEmpty()
+                        ? "DO NOTHING"
+                        : String.format(
+                                "DO UPDATE SET %s WHERE (%s)",
+                                updateClause,
+                                condition.toSql(
+                                        this::quoteIdentifier,

Review Comment:
   The parser accepts quoted column names containing dots or escaped quotes, 
but `PostgresDialect.quoteIdentifier` splits dots and does not escape embedded 
quotes. Accepted references such as `target."a.b"` and `:"say""hi"` therefore 
produce invalid SQL; the generated INSERT, conflict-key and update column lists 
have the same issue. Use literal column-name quoting consistently throughout 
the conditional statement, and test these names with the actual dialect.



##########
seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/OrderedBufferedBatchStatementExecutor.java:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.jdbc.internal.executor;
+
+import org.apache.seatunnel.api.table.type.RowKind;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.common.exception.CommonErrorCodeDeprecated;
+import 
org.apache.seatunnel.connectors.seatunnel.jdbc.exception.JdbcConnectorException;
+
+import lombok.NonNull;
+import lombok.RequiredArgsConstructor;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.function.Function;
+
+/**
+ * Applies every change of a batch in arrival order, used by {@code 
update_condition_sql}. Unlike
+ * {@link BufferReducedBatchStatementExecutor}, a key is not reduced to its 
last change.
+ *
+ * <p>The pending upsert batch is executed before a key repeats, because 
PostgreSQL fails a
+ * statement that changes the same row twice, such as a batch rewritten by the 
driver.
+ */
+@RequiredArgsConstructor
+public class OrderedBufferedBatchStatementExecutor
+        implements JdbcBatchStatementExecutor<SeaTunnelRow> {
+    @NonNull private final JdbcBatchStatementExecutor<SeaTunnelRow> 
upsertExecutor;
+    @NonNull private final JdbcBatchStatementExecutor<SeaTunnelRow> 
deleteExecutor;
+    @NonNull private final Function<SeaTunnelRow, SeaTunnelRow> keyExtractor;
+    @NonNull private final Function<SeaTunnelRow, SeaTunnelRow> valueTransform;
+
+    /** Kept until a flush succeeds, so a retry replays every change. */
+    @NonNull private final List<SeaTunnelRow> buffer = new ArrayList<>();
+
+    private boolean flushFailed;
+
+    @Override
+    public void prepareStatements(Connection connection) throws SQLException {
+        upsertExecutor.prepareStatements(connection);
+        deleteExecutor.prepareStatements(connection);
+    }
+
+    @Override
+    public void addToBatch(SeaTunnelRow record) throws SQLException {
+        if (RowKind.UPDATE_BEFORE.equals(record.getRowKind())) {
+            return;
+        }
+        // Fail on an unsupported row kind when it arrives, not when the batch 
is flushed.
+        isUpsert(record.getRowKind());
+        buffer.add(record);
+    }
+
+    @Override
+    public void executeBatch() throws SQLException {
+        try {
+            // Drop statements left by a failed attempt, as the whole buffer 
is replayed.
+            upsertExecutor.clearBatch();
+            deleteExecutor.clearBatch();
+
+            Set<SeaTunnelRow> keysInUpsertBatch = new HashSet<>();
+            Boolean pendingUpsert = null;
+            for (SeaTunnelRow record : buffer) {
+                boolean upsert = isUpsert(record.getRowKind());
+                if (pendingUpsert != null && pendingUpsert != upsert) {
+                    executePending(pendingUpsert);
+                    keysInUpsertBatch.clear();
+                }
+                SeaTunnelRow key = keyExtractor.apply(record);
+                if (upsert) {
+                    // A key with a NULL field never conflicts, so it cannot 
repeat a row.
+                    if (!hasNullField(key) && !keysInUpsertBatch.add(key)) {

Review Comment:
   The duplicate check uses Java equality rather than PostgreSQL conflict-key 
equality: numeric keys `1.0` and `1.00`, or `CHAR(10)` keys `"a"` and `"a "`, 
can be distinct set entries but identify the same database row. With 
`reWriteBatchedInserts=true`, those upserts can reach one rewritten statement 
and fail because it affects the same row twice. Normalize keys using 
target-type semantics where safe, and use single-row execution when database 
key equality cannot be determined reliably.



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