Attempt to fix duplicate key issue in UpdateWebPermissionsPatch

Affects issues:
- #3543
This commit is contained in:
Aurora Lahtela 2024-03-30 09:48:19 +02:00
parent 95a20b54a3
commit 49269d3aab
2 changed files with 30 additions and 1 deletions

View File

@ -30,6 +30,7 @@ import java.util.Optional;
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) {
@ -77,7 +78,7 @@ public class DBOpException extends IllegalStateException implements ExceptionWit
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
@ -165,4 +166,9 @@ public class DBOpException extends IllegalStateException implements ExceptionWit
&& getCause() != null
&& getCause().getMessage().contains("user_id");
}
public boolean isDuplicateKeyViolation() {
return context != null
&& context.getRelated().contains(DBOpException.CONSTRAINT_VIOLATION);
}
}

View File

@ -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;
@ -55,6 +56,18 @@ public class UpdateWebPermissionsPatch extends Patch {
@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 {
@ -65,4 +78,14 @@ public class UpdateWebPermissionsPatch extends Patch {
}
});
}
private void retry(DBOpException failed) {
try {
if (hasBeenApplied()) return;
storeMissing();
} catch (DBOpException anotherFail) {
anotherFail.addSuppressed(failed);
throw anotherFail;
}
}
}