[CockroachDB] 대용량 delete 처리 팁 (using jdbc code)
jdbc를 통해서 특정 테이블의 데이터를 삭제할 때 발생될 수 있는 에러를 해결할 수 있는 방법입니다.
첫번째. delete large amount error ~~
특정 rows 이상을 한번에 삭제하는 경우에 발생 합니다.
ex) delete from t_orders where order_dt >= '20190101';
이경우는 limit 절을 이용해 삭제할 대상을 split하면서 삭제하면 해결이 됩니다.
ex)
con.setAutoCommit(false);
Statement stmt = con.createStatement();
int nDeleteRows;
do {
// 1만건씩 삭제하는 경우
nDeleteRows = (stmt.executeUpdate("delete from t_orders where order_dt >= '20190101' limit 10000");
con.commit();
} while(nDeleteRows > 0);
stmt.close();
두번째 에러는 Batch Insert 처럼 처리하는 데이터가 많으면 발생하는
org.postgresql.util.PSQLException: ERROR: restart transaction:
TransactionRetryWithProtoRefreshError:
TransactionAbortedError(ABORT_REASON_TIMESTAMP_CACHE_REJECTED_POSSIBLE_REPLAY):
CockroachDB에 DML를 수행하는 경우는 에러가 발생시 3번정도 재시도하는 로직을 넣어 두는 것이 필 수 입니다.
첫번째 처리하는 부분이 doDelete()라는 함수로 구현이 되어 있다면 아래와 같이 재시도 하는 로직을 넣어주며 됩니다.
private static final String RETRY_SQL_STATE = "40001";
for (int i=1; i <=3; i++) {
try {
doDelete();
break;
} catch(SQLException e) {
if (RETRY_SQL_STATE.equals(e.getSQLState())) {
if ( i == 3) {
throw e;
} else {
continue;
}
}
throw e;
}
} // end for