Skip to content

Commit

Permalink
Merge pull request #100 from qrollin/feature/fix_merge_into
Browse files Browse the repository at this point in the history
fix empty "WHEN MATCHED THEN UPDATE SET" clause on "MERGE INTO"
  • Loading branch information
osalvador authored Sep 20, 2022
2 parents 6c62099 + f747059 commit 151a80e
Showing 1 changed file with 18 additions and 12 deletions.
30 changes: 18 additions & 12 deletions src/main/java/org/replicadb/manager/SQLServerManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.stream.Collectors;

public class SQLServerManager extends SqlManager {

Expand Down Expand Up @@ -165,19 +166,24 @@ protected void mergeStagingTable () throws SQLException {
sql.append("src.").append(pks[i]).append("= trg.").append(pks[i]);
}

sql.append(" ) WHEN MATCHED THEN UPDATE SET ");
LOG.trace("allColls: {} \n pks: {}", allColls, pks);
// Set all columns for UPDATE SET statement
for (String colName : allColls.split("\\s*,\\s*")) {
LOG.trace("colName: {}", colName);
boolean contains = Arrays.asList(pks).contains(colName);
boolean containsQuoted = Arrays.asList(pks).contains("\"" + colName + "\"");
if (!contains && !containsQuoted)
sql.append(" trg.").append(colName).append(" = src.").append(colName).append(" ,");
sql.append(" ) ");
LOG.trace("allColls: {} \n pks: {}", allColls, pks);

// Set all columns for UPDATE SET statement
String allColSelect = Arrays.stream(allColls.split("\\s*,\\s*"))
.filter(colName -> {
boolean contains = Arrays.asList(pks).contains(colName);
boolean containsQuoted = Arrays.asList(pks).contains("\"" + colName + "\"");
return !contains && !containsQuoted;
}).map(colName -> {
LOG.debug("colName: {}", colName);
return String.format("trg.%s = src.%s", colName, colName);
}).collect(Collectors.joining(", "));

if (allColSelect.length() > 0) {
sql.append(" WHEN MATCHED THEN UPDATE SET ");
sql.append(allColSelect);
}
// Delete the last comma
sql.setLength(sql.length() - 1);


sql.append(" WHEN NOT MATCHED THEN INSERT ( ").append(allColls).
append(" ) VALUES (");
Expand Down

0 comments on commit 151a80e

Please sign in to comment.