Refactor KeyValueStore

This commit is contained in:
AsamK 2023-11-12 14:19:10 +01:00
parent 26cef99cdf
commit fbcc1cfb50

View file

@ -36,6 +36,22 @@ public class KeyValueStore {
}
public <T> T getEntry(KeyValueEntry<T> key) {
try (final var connection = database.getConnection()) {
return getEntry(connection, key);
} catch (SQLException e) {
throw new RuntimeException("Failed read from pre_key store", e);
}
}
public <T> void storeEntry(KeyValueEntry<T> key, T value) {
try (final var connection = database.getConnection()) {
storeEntry(connection, key, value);
} catch (SQLException e) {
throw new RuntimeException("Failed update key_value store", e);
}
}
private <T> T getEntry(final Connection connection, final KeyValueEntry<T> key) throws SQLException {
final var sql = (
"""
SELECT key, value
@ -43,7 +59,6 @@ public class KeyValueStore {
WHERE p.key = ?
"""
).formatted(TABLE_KEY_VALUE);
try (final var connection = database.getConnection()) {
try (final var statement = connection.prepareStatement(sql)) {
statement.setString(1, key.key());
@ -55,12 +70,11 @@ public class KeyValueStore {
}
return result;
}
} catch (SQLException e) {
throw new RuntimeException("Failed read from pre_key store", e);
}
}
public <T> void storeEntry(KeyValueEntry<T> key, T value) {
private <T> void storeEntry(
final Connection connection, final KeyValueEntry<T> key, final T value
) throws SQLException {
final var sql = (
"""
INSERT INTO %s (key, value)
@ -68,15 +82,11 @@ public class KeyValueStore {
ON CONFLICT (key) DO UPDATE SET value=excluded.value
"""
).formatted(TABLE_KEY_VALUE);
try (final var connection = database.getConnection()) {
try (final var statement = connection.prepareStatement(sql)) {
statement.setString(1, key.key());
setParameterValue(statement, 2, key.clazz(), value);
statement.executeUpdate();
}
} catch (SQLException e) {
throw new RuntimeException("Failed update key_value store", e);
}
}
@SuppressWarnings("unchecked")