]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/storage/keyValue/KeyValueStore.java
90c932afa1679e26db3e386e3e28c5bc7ad1831b
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / storage / keyValue / KeyValueStore.java
1 package org.asamk.signal.manager.storage.keyValue;
2
3 import org.asamk.signal.manager.storage.Database;
4 import org.asamk.signal.manager.storage.Utils;
5 import org.slf4j.Logger;
6 import org.slf4j.LoggerFactory;
7
8 import java.sql.Connection;
9 import java.sql.PreparedStatement;
10 import java.sql.ResultSet;
11 import java.sql.SQLException;
12 import java.sql.Types;
13
14 public class KeyValueStore {
15
16 private static final String TABLE_KEY_VALUE = "key_value";
17 private final static Logger logger = LoggerFactory.getLogger(KeyValueStore.class);
18
19 private final Database database;
20
21 public static void createSql(Connection connection) throws SQLException {
22 // When modifying the CREATE statement here, also add a migration in AccountDatabase.java
23 try (final var statement = connection.createStatement()) {
24 statement.executeUpdate("""
25 CREATE TABLE key_value (
26 _id INTEGER PRIMARY KEY,
27 key TEXT UNIQUE NOT NULL,
28 value ANY
29 ) STRICT;
30 """);
31 }
32 }
33
34 public KeyValueStore(final Database database) {
35 this.database = database;
36 }
37
38 public <T> T getEntry(KeyValueEntry<T> key) {
39 final var sql = (
40 """
41 SELECT key, value
42 FROM %s p
43 WHERE p.key = ?
44 """
45 ).formatted(TABLE_KEY_VALUE);
46 try (final var connection = database.getConnection()) {
47 try (final var statement = connection.prepareStatement(sql)) {
48 statement.setString(1, key.key());
49
50 final var result = Utils.executeQueryForOptional(statement,
51 resultSet -> readValueFromResultSet(key, resultSet)).orElse(null);
52
53 if (result == null) {
54 return key.defaultValue();
55 }
56 return result;
57 }
58 } catch (SQLException e) {
59 throw new RuntimeException("Failed read from pre_key store", e);
60 }
61 }
62
63 public <T> void storeEntry(KeyValueEntry<T> key, T value) {
64 final var sql = (
65 """
66 INSERT INTO %s (key, value)
67 VALUES (?1, ?2)
68 ON CONFLICT (key) DO UPDATE SET value=excluded.value
69 """
70 ).formatted(TABLE_KEY_VALUE);
71 try (final var connection = database.getConnection()) {
72 try (final var statement = connection.prepareStatement(sql)) {
73 statement.setString(1, key.key());
74 setParameterValue(statement, 2, key.clazz(), value);
75 statement.executeUpdate();
76 }
77 } catch (SQLException e) {
78 throw new RuntimeException("Failed update key_value store", e);
79 }
80 }
81
82 private static <T> T readValueFromResultSet(
83 final KeyValueEntry<T> key, final ResultSet resultSet
84 ) throws SQLException {
85 Object value;
86 final var clazz = key.clazz();
87 if (clazz == int.class || clazz == Integer.class) {
88 value = resultSet.getInt("value");
89 } else if (clazz == long.class || clazz == Long.class) {
90 value = resultSet.getLong("value");
91 } else if (clazz == boolean.class || clazz == Boolean.class) {
92 value = resultSet.getBoolean("value");
93 } else if (clazz == byte[].class || clazz == Byte[].class) {
94 value = resultSet.getBytes("value");
95 } else if (clazz == String.class) {
96 value = resultSet.getString("value");
97 } else if (Enum.class.isAssignableFrom(clazz)) {
98 final var name = resultSet.getString("value");
99 if (name == null) {
100 value = null;
101 } else {
102 try {
103 value = Enum.valueOf((Class<Enum>) key.clazz(), name);
104 } catch (IllegalArgumentException e) {
105 logger.debug("Read invalid enum value from store, ignoring: {} for {}", name, key.clazz());
106 value = null;
107 }
108 }
109 } else {
110 throw new AssertionError("Invalid key type " + clazz.getSimpleName());
111 }
112 if (resultSet.wasNull()) {
113 return null;
114 }
115 return (T) value;
116 }
117
118 private static <T> void setParameterValue(
119 final PreparedStatement statement, final int parameterIndex, final Class<T> clazz, final T value
120 ) throws SQLException {
121 if (clazz == int.class || clazz == Integer.class) {
122 if (value == null) {
123 statement.setNull(parameterIndex, Types.INTEGER);
124 } else {
125 statement.setInt(parameterIndex, (int) value);
126 }
127 } else if (clazz == long.class || clazz == Long.class) {
128 if (value == null) {
129 statement.setNull(parameterIndex, Types.INTEGER);
130 } else {
131 statement.setLong(parameterIndex, (long) value);
132 }
133 } else if (clazz == boolean.class || clazz == Boolean.class) {
134 if (value == null) {
135 statement.setNull(parameterIndex, Types.BOOLEAN);
136 } else {
137 statement.setBoolean(parameterIndex, (boolean) value);
138 }
139 } else if (clazz == byte[].class || clazz == Byte[].class) {
140 if (value == null) {
141 statement.setNull(parameterIndex, Types.BLOB);
142 } else {
143 statement.setBytes(parameterIndex, (byte[]) value);
144 }
145 } else if (clazz == String.class) {
146 if (value == null) {
147 statement.setNull(parameterIndex, Types.VARCHAR);
148 } else {
149 statement.setString(parameterIndex, (String) value);
150 }
151 } else if (Enum.class.isAssignableFrom(clazz)) {
152 if (value == null) {
153 statement.setNull(parameterIndex, Types.VARCHAR);
154 } else {
155 statement.setString(parameterIndex, ((Enum<?>) value).name());
156 }
157 } else {
158 throw new AssertionError("Invalid key type " + clazz.getSimpleName());
159 }
160 }
161 }