Last active
October 7, 2019 19:00
-
-
Save karussell/45da5c90ac00a4cb658bad150f9b559e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public int removeAllOlderThan(int batchSize, DateTime date) { | |
try (Connection c = dc.getConnection()) { | |
PreparedStatement s1 = c.prepareStatement(String.format("SELECT %s FROM %s WHERE created_at < ?", | |
KEY, dc.getTableName(tableName))); | |
s1.setLong(1, date.getMillis()); | |
ResultSet rs = s1.executeQuery(); | |
List<String> list = new ArrayList<>(batchSize); | |
PreparedStatement s2 = null; | |
int executeUpdateCount = 0; | |
while (true) { | |
list.clear(); | |
for (int i = 0; i < batchSize; i++) { | |
if (!rs.next()) | |
break; | |
list.add(rs.getString(1)); | |
} | |
if (list.isEmpty()) | |
return executeUpdateCount; | |
if (s2 == null || list.size() < batchSize) | |
s2 = c.prepareStatement(String.format("DELETE FROM %s WHERE %s IN (%s)", | |
dc.getTableName(tableName), KEY, buildParams(Math.min(list.size(), batchSize)))); | |
for (int i = 0; i < list.size(); i++) { | |
s2.setString(i + 1, list.get(i)); | |
} | |
executeUpdateCount += s2.executeUpdate(); | |
} | |
} catch (SQLException ex2) { | |
throw new IllegalStateException(ex2); | |
} | |
} | |
static String buildParams(int params) { | |
if (params == 0) | |
throw new IllegalArgumentException("0 or negative param count not expected"); | |
StringBuilder query = new StringBuilder(); | |
int currentCount = 0; | |
for (; currentCount < params; currentCount++) { | |
if (currentCount > 0) | |
query.append(','); | |
query.append('?'); | |
} | |
return query.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment