-
Notifications
You must be signed in to change notification settings - Fork 612
/
QueriesJdbcJoinTest.java
307 lines (269 loc) · 13.5 KB
/
QueriesJdbcJoinTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
package org.infinispan.persistence.sql;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletionException;
import java.util.stream.Stream;
import org.infinispan.Cache;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.test.ExceptionRunnable;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.manager.EmbeddedCacheManagerStartupException;
import org.infinispan.persistence.jdbc.common.UnitTestDatabaseManager;
import org.infinispan.persistence.jdbc.common.configuration.ConnectionFactoryConfiguration;
import org.infinispan.persistence.jdbc.common.configuration.ConnectionFactoryConfigurationBuilder;
import org.infinispan.persistence.jdbc.common.connectionfactory.ConnectionFactory;
import org.infinispan.persistence.sql.configuration.QueriesJdbcConfigurationBuilder;
import org.infinispan.persistence.sql.configuration.QueriesJdbcStoreConfigurationBuilder;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.data.Address;
import org.infinispan.test.data.Person;
import org.infinispan.test.data.Sex;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "persistence.sql.QueriesJdbcJoinTest")
public class QueriesJdbcJoinTest extends AbstractInfinispanTest {
private static final String TABLE1_NAME = "Person";
private static final String TABLE2_NAME = "Address";
private ConnectionFactory FACTORY;
@AfterMethod(alwaysRun = true)
public void afterClass() {
if (FACTORY != null) {
FACTORY.stop();
}
}
enum TestType {
TOO_MANY_COLUMNS {
@Override
void runTest(ExceptionRunnable runnable) {
Exceptions.expectException(".*Additional value columns.*found that were not part of the schema.*", runnable,
EmbeddedCacheManagerStartupException.class, CacheConfigurationException.class,
CompletionException.class, CacheConfigurationException.class);
}
@Override
void modifyConfiguration(QueriesJdbcStoreConfigurationBuilder builder, boolean idJoin) {
super.modifyConfiguration(builder, idJoin);
QueriesJdbcConfigurationBuilder queryBuilder = builder.queries();
if (idJoin) {
queryBuilder
// Note these return * which will include the joined columns as well
.select("SELECT * FROM " + TABLE1_NAME + " t1 JOIN " + TABLE2_NAME + " t2 ON t1.address = t2.id WHERE t1.name = :name")
.selectAll("SELECT * FROM " + TABLE1_NAME + " t1 JOIN " + TABLE2_NAME + " t2 ON t1.address = t2.id");
} else {
queryBuilder
// Note these return * which will include the joined columns as well
.select("SELECT * FROM " + TABLE1_NAME + " t1 JOIN " + TABLE2_NAME + " t2 WHERE t1.name = :name AND t2.name = :name")
.selectAll("SELECT * FROM " + TABLE1_NAME + " t1 JOIN " + TABLE2_NAME + " t2 WHERE t1.name = t2.name");
}
}
},
NOT_EMBEDDED_KEY {
@Override
void runTest(ExceptionRunnable runnable) {
Exceptions.expectException(".*was found in the value schema .* but embedded key was not true", runnable,
EmbeddedCacheManagerStartupException.class, CacheConfigurationException.class,
CompletionException.class, CacheConfigurationException.class);
}
@Override
void modifyConfiguration(QueriesJdbcStoreConfigurationBuilder builder, boolean idJoin) {
super.modifyConfiguration(builder, idJoin);
builder.schema().embeddedKey(false);
}
},
PASS;
void runTest(ExceptionRunnable runnable) throws Exception {
runnable.run();
}
void modifyConfiguration(QueriesJdbcStoreConfigurationBuilder builder, boolean idJoin) {
QueriesJdbcConfigurationBuilder queryBuilder = builder.queries();
queryBuilder.size("SELECT COUNT(*) FROM " + TABLE1_NAME);
builder.schema().embeddedKey(true);
if (idJoin) {
builder.queries()
.select("SELECT t1.name, t1.picture, t1.sex, t1.birthdate, t1.accepted_tos, t2.street, t2.city, t2.zip FROM " + TABLE1_NAME + " t1 JOIN " + TABLE2_NAME + " t2 ON t1.address = t2.id WHERE t1.name = :name")
.selectAll("SELECT t1.name, t1.picture, t1.sex, t1.birthdate, t1.accepted_tos, t2.street, t2.city, t2.zip FROM " + TABLE1_NAME + " t1 JOIN " + TABLE2_NAME + " t2 ON t1.address = t2.id");
} else {
builder.queries()
.select("SELECT t1.name, t1.picture, t1.sex, t1.birthdate, t1.accepted_tos, t2.street, t2.city, t2.zip FROM " + TABLE1_NAME + " t1 JOIN " + TABLE2_NAME + " t2 WHERE t1.name = :name AND t2.name = :name")
.selectAll("SELECT t1.name, t1.picture, t1.sex, t1.birthdate, t1.accepted_tos, t2.street, t2.city, t2.zip FROM " + TABLE1_NAME + " t1 JOIN " + TABLE2_NAME + " t2 WHERE t1.name = t2.name");
}
}
}
protected EmbeddedCacheManager createCacheManager(TestType type, boolean idJoin) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.encoding().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE);
QueriesJdbcStoreConfigurationBuilder queriesBuilder = builder.persistence()
.addStore(QueriesJdbcStoreConfigurationBuilder.class)
.ignoreModifications(true);
queriesBuilder.keyColumns("name");
queriesBuilder.schema()
.messageName("Person")
.packageName("org.infinispan.test.core");
UnitTestDatabaseManager.configureUniqueConnectionFactory(queriesBuilder);
createTables(queriesBuilder.getConnectionFactory(), idJoin);
type.modifyConfiguration(queriesBuilder, idJoin);
return TestCacheManagerFactory.createCacheManager(TestDataSCI.INSTANCE, builder);
}
private void createTables(ConnectionFactoryConfigurationBuilder<ConnectionFactoryConfiguration> builder, boolean idJoin) {
ConnectionFactoryConfiguration config = builder.create();
FACTORY = ConnectionFactory.getConnectionFactory(config.connectionFactoryClass());
FACTORY.start(config, getClass().getClassLoader());
Connection connection = null;
try {
connection = FACTORY.getConnection();
try (Statement stmt = connection.createStatement()) {
String tableCreation = "CREATE TABLE " + TABLE1_NAME + " (" +
"name VARCHAR(255) NOT NULL, " +
(idJoin ? "address INT, " : "") +
"picture VARBINARY(255), " +
"sex VARCHAR(255), " +
"birthdate TIMESTAMP, " +
"accepted_tos boolean, " +
"notused VARCHAR(255), " +
"PRIMARY KEY (NAME))";
stmt.execute(tableCreation);
tableCreation = "create TABLE " + TABLE2_NAME + " (" +
(idJoin ? "id INT NOT NULL, " : "name VARCHAR(255) NOT NULL, ") +
"street VARCHAR(255), " +
"city VARCHAR(255), " +
"zip INT, " +
"PRIMARY KEY (" + (idJoin ? "id" : "name") + "))";
stmt.execute(tableCreation);
}
} catch (SQLException t) {
throw new AssertionError(t);
} finally {
FACTORY.releaseConnection(connection);
}
}
public void testUpsertMultipleValues() {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.encoding().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE);
QueriesJdbcStoreConfigurationBuilder queriesBuilder = builder.persistence()
.addStore(QueriesJdbcStoreConfigurationBuilder.class);
queriesBuilder.keyColumns("name");
queriesBuilder.schema()
.messageName("Person")
.packageName("org.infinispan.test.core");
UnitTestDatabaseManager.configureUniqueConnectionFactory(queriesBuilder);
createTables(queriesBuilder.getConnectionFactory(), false);
TestType.PASS.modifyConfiguration(queriesBuilder, false);
queriesBuilder.queries()
.delete("DELETE FROM " + TABLE1_NAME + " t1 WHERE t1.name = :name; DELETE FROM " + TABLE2_NAME + " t2 where t2.name = :name")
.deleteAll("DELETE FROM " + TABLE1_NAME + "; DELETE FROM " + TABLE2_NAME)
.upsert(insertTable1Statement(false, true) +
"; " + insertTable2Statement(false, true));
EmbeddedCacheManager embeddedCacheManager = TestCacheManagerFactory.createCacheManager(TestDataSCI.INSTANCE, builder);
Cache<String, Person> cache = embeddedCacheManager.getCache();
String name = "Mircea Markus";
Person person = samplePerson(name);
cache.put(name, person);
assertEquals(person, cache.get(name));
cache.remove(name);
assertNull(cache.get(name));
}
@DataProvider(name = "testTypes")
public static Object[][] testTypes() {
return Stream.of(TestType.values())
.flatMap(t -> Stream.of(new Object[]{t, true}, new Object[]{t, false}))
.toArray(Object[][]::new);
}
@Test(dataProvider = "testTypes")
public void testIdJoinTypes(TestType type, boolean idJoin) throws Exception {
type.runTest(() -> {
EmbeddedCacheManager cacheManager = createCacheManager(type, idJoin);
Cache<String, Person> cache = cacheManager.getCache();
Connection connection = FACTORY.getConnection();
try {
String name = "Manik Surtani";
Person person = samplePerson(name);
insertData(connection, Collections.singleton(person), idJoin);
assertEquals(person, cache.get(name));
} finally {
FACTORY.releaseConnection(connection);
}
});
}
private Person samplePerson(String name) {
Address address = new Address();
address.setCity("London");
address.setStreet("Cool Street");
address.setZip(1321);
Person person = new Person(name, address);
person.setPicture(new byte[]{0x1, 0x12});
person.setSex(Sex.MALE);
person.setBirthDate(new java.util.Date(1629495308));
person.setAcceptedToS(true);
return person;
}
private String insertTable1Statement(boolean idJoin, boolean namedParams) {
return "INSERT INTO " + TABLE1_NAME +
" (name, " + (idJoin ? "address, " : "") + " picture, sex, birthdate, accepted_tos) " +
(namedParams ? "VALUES (:name" + (idJoin ? ", :address" : "") + ", :picture, :sex, :birthdate, :accepted_tos)" :
"VALUES (?, ?, ?, ?, ?" + (idJoin ? ", ?)" : ")"));
}
private String insertTable2Statement(boolean idJoin, boolean namedParams) {
return "INSERT INTO " + TABLE2_NAME +
"(" + (idJoin ? "id" : "name") + ", street, city, zip) " +
(namedParams ? "VALUES (" + (idJoin ? ":id" : ":name") + ", :street, :city, :zip)" :
"VALUES (?, ?, ?, ?)");
}
private void insertData(Connection connection, Set<Person> peopleToCreate, boolean idJoin) throws SQLException {
String insertStatement = insertTable1Statement(idJoin, false);
int addressCount = 0;
Map<Address, Integer> addressIntegerMap = idJoin ? new HashMap<>() : null;
try (PreparedStatement ps = connection.prepareStatement(insertStatement)) {
for (Person person : peopleToCreate) {
int offset = 1;
ps.setString(offset++, person.getName());
if (addressIntegerMap != null) {
Address address = person.getAddress();
Integer addressNumber = addressIntegerMap.get(address);
if (addressNumber == null) {
addressNumber = addressCount++;
addressIntegerMap.put(address, addressNumber);
}
ps.setInt(offset++, addressNumber);
}
ps.setBytes(offset++, person.getPicture());
ps.setString(offset++, person.getSex().toString());
ps.setTimestamp(offset++, new Timestamp(person.getBirthDate().getTime()));
ps.setBoolean(offset, person.isAcceptedToS());
ps.addBatch();
}
ps.executeBatch();
}
insertStatement = insertTable2Statement(idJoin, false);
try (PreparedStatement ps = connection.prepareStatement(insertStatement)) {
for (Person person : peopleToCreate) {
Address address = person.getAddress();
if (addressIntegerMap != null) {
Integer id = addressIntegerMap.get(address);
assert id != null;
ps.setInt(1, id);
} else {
ps.setString(1, person.getName());
}
ps.setString(2, address.getStreet());
ps.setString(3, address.getCity());
ps.setInt(4, address.getZip());
ps.addBatch();
}
ps.executeBatch();
}
}
}