Skip to content

Commit

Permalink
Attempt to fix duplicate key issue in UpdateWebPermissionsPatch
Browse files Browse the repository at this point in the history
Affects issues:
- #3543
  • Loading branch information
AuroraLS3 committed Mar 30, 2024
1 parent 95a20b5 commit 49269d3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
public class DBOpException extends IllegalStateException implements ExceptionWithContext {

public static final String CONSTRAINT_VIOLATION = "Constraint Violation";
public static final String DUPLICATE_KEY = "Duplicate key";
private final ErrorContext context;

public DBOpException(String message) {
Expand Down Expand Up @@ -77,7 +78,7 @@ public static DBOpException forCause(String sql, SQLException e) {
case 1022:
case 23001:
case 23505:
context.related("Duplicate key")
context.related(DUPLICATE_KEY)
.whatToDo("Report this, duplicate key exists in SQL.");
break;
// Constraint violation
Expand Down Expand Up @@ -165,4 +166,9 @@ public boolean isUserIdConstraintViolation() {
&& getCause() != null
&& getCause().getMessage().contains("user_id");
}

public boolean isDuplicateKeyViolation() {
return context != null
&& context.getRelated().contains(DBOpException.CONSTRAINT_VIOLATION);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.djrapitops.plan.storage.database.transactions.patches;

import com.djrapitops.plan.delivery.domain.auth.WebPermission;
import com.djrapitops.plan.exceptions.database.DBOpException;
import com.djrapitops.plan.storage.database.queries.objects.WebUserQueries;
import com.djrapitops.plan.storage.database.sql.tables.webuser.WebPermissionTable;
import com.djrapitops.plan.storage.database.transactions.ExecBatchStatement;
Expand Down Expand Up @@ -55,6 +56,18 @@ public boolean hasBeenApplied() {

@Override
protected void applyPatch() {
try {
storeMissing();
} catch (DBOpException failed) {
if (failed.isDuplicateKeyViolation()) {
retry(failed);
} else {
throw failed;
}
}
}

private void storeMissing() {
execute(new ExecBatchStatement(WebPermissionTable.INSERT_STATEMENT) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
Expand All @@ -65,4 +78,14 @@ public void prepare(PreparedStatement statement) throws SQLException {
}
});
}

private void retry(DBOpException failed) {
try {
if (hasBeenApplied()) return;
storeMissing();
} catch (DBOpException anotherFail) {
anotherFail.addSuppressed(failed);
throw anotherFail;
}
}
}

0 comments on commit 49269d3

Please sign in to comment.