-
Notifications
You must be signed in to change notification settings - Fork 53
/
SomethingDaoTest.java
382 lines (353 loc) · 18 KB
/
SomethingDaoTest.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package io.github.jklingsporn.vertx.jooq.generate.rx.reactive.regular;
import generated.rx.reactive.regular.Tables;
import generated.rx.reactive.regular.enums.Someenum;
import generated.rx.reactive.regular.tables.daos.SomethingDao;
import generated.rx.reactive.regular.tables.pojos.Something;
import generated.rx.reactive.regular.tables.records.SomethingRecord;
import io.github.jklingsporn.vertx.jooq.generate.PostgresConfigurationProvider;
import io.github.jklingsporn.vertx.jooq.generate.ReactiveDatabaseClientProvider;
import io.github.jklingsporn.vertx.jooq.generate.rx.RXTestBase;
import io.github.jklingsporn.vertx.jooq.rx.reactivepg.ReactiveRXGenericQueryExecutor;
import io.github.jklingsporn.vertx.jooq.rx.reactivepg.ReactiveRXQueryExecutor;
import io.reactivex.Completable;
import io.reactivex.Maybe;
import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.internal.functions.Functions;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.pgclient.PgException;
import org.jooq.Condition;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
/**
* Created by jensklingsporn on 02.11.16.
*/
public class SomethingDaoTest extends RXTestBase<Something, Integer, Long, SomethingDao> {
public SomethingDaoTest() {
super(Tables.SOMETHING.SOMEHUGENUMBER, new SomethingDao(PostgresConfigurationProvider.getInstance().createDAOConfiguration(), ReactiveDatabaseClientProvider.getInstance().rxGetClient()));
}
@BeforeClass
public static void beforeClass() throws Exception {
PostgresConfigurationProvider.getInstance().setupDatabase();
}
@Override
protected Something create() {
return createWithId().setSomeid(null);
}
@Override
protected Something createWithId() {
Random random = new Random();
Something something = new Something();
something.setSomeid(random.nextInt());
something.setSomedouble(random.nextDouble());
something.setSomeregularnumber(random.nextInt());
something.setSomehugenumber(random.nextLong());
something.setSomejsonarray(new JsonArray().add(1).add(2).add(3));
something.setSomejsonobject(new JsonObject().put("key", "value"));
something.setSomesmallnumber((short) random.nextInt(Short.MAX_VALUE));
something.setSomeenum(Someenum.values()[random.nextInt(Someenum.values().length)]);
something.setSomestring("my_string");
something.setSometimestamp(LocalDateTime.now());
something.setSometime(LocalTime.now());
something.setSomedate(LocalDate.now());
something.setSometimestampwithtz(OffsetDateTime.now());
something.setSomedecimal(new BigDecimal("1.23E3"));
return something;
}
@Override
protected Something setId(Something pojo, Integer id) {
return pojo.setSomeid(id);
}
@Override
protected Something setSomeO(Something pojo, Long someO) {
return pojo.setSomehugenumber(someO);
}
@Override
protected Integer getId(Something pojo) {
return pojo.getSomeid();
}
@Override
protected Long createSomeO() {
return new Random().nextLong();
}
@Override
protected Condition eqPrimaryKey(Integer id) {
return Tables.SOMETHING.SOMEID.eq(id);
}
@Override
protected void assertDuplicateKeyException(Throwable x) {
assertException(PgException.class, x, pgException -> Assert.assertEquals("23505", pgException.getCode()));
}
//for now the tests have to be located in this class as transactions are only supported by the reactive driver
@Test
public void manualTransactionProcessingShouldSucceed() {
try{
Something pojo = createWithId();
CountDownLatch completionLatch = new CountDownLatch(1);
dao.queryExecutor().beginTransaction()
.flatMap(
transactionQE -> transactionQE.execute(
dslContext -> dslContext.insertInto(dao.getTable()).set(dslContext.newRecord(dao.getTable(), pojo))
).doOnSuccess(
inserted -> Assert.assertEquals(1, inserted.intValue())
).flatMap(
v -> transactionQE.findOne(
dslContext -> dslContext.selectFrom(dao.getTable()).where(eqPrimaryKey(pojo.getSomeid()))
)
).doOnSuccess(this::optionalAssertNotNull)
.flatMap(v -> dao.findOneById(pojo.getSomeid()))
.doOnSuccess(this::optionalAssertNull) //not known outside of transaction
.flatMapCompletable(v -> transactionQE.commit())
.andThen(dao.findOneById(pojo.getSomeid())) //now known because we committed the transaction
.doOnSuccess(this::optionalAssertNotNull)
.flatMap(v -> dao.deleteById(pojo.getSomeid()))
.doOnSuccess(deleted -> Assert.assertEquals(1, deleted.intValue())))
.subscribe(countdownLatchHandler(completionLatch));
await(completionLatch);
}catch (Throwable e){
Assert.fail(e.getMessage());
}
}
@Test
public void commitAndRollbackShouldSucceed(){
CountDownLatch latch = new CountDownLatch(1);
Single<ReactiveRXQueryExecutor<SomethingRecord, Something, Integer>> transaction = dao.queryExecutor()
.beginTransaction();
transaction
.flatMapCompletable(ReactiveRXGenericQueryExecutor::rollback)
.toSingleDefault(transaction)
.subscribe(countdownLatchHandler(latch));
await(latch);
}
@Test
public void beginTransactionCanNotBeCalledInTransaction(){
CountDownLatch latch = new CountDownLatch(1);
dao.queryExecutor()
.beginTransaction()
.flatMap(ReactiveRXQueryExecutor::beginTransaction)
.subscribe(res-> Assert.fail("should not succeed"), ex-> latch.countDown());
await(latch);
}
@Test
public void commitTransactionCanNotBeCalledOutsideTransaction(){
CountDownLatch latch = new CountDownLatch(1);
dao
.queryExecutor()
.commit()
.subscribe(()->Assert.fail("should not succeed"), ex-> latch.countDown())
;
await(latch);
}
@Test
public void rollbackTransactionCanNotBeCalledOutsideTransaction(){
CountDownLatch latch = new CountDownLatch(1);
dao
.queryExecutor()
.rollback()
.subscribe(()->Assert.fail("should not succeed"), ex-> latch.countDown())
;
await(latch);
}
@Test
public void illegalQueriesShouldRollbackTransaction() throws InterruptedException {
Something pojo = createWithId();
CountDownLatch completionLatch = new CountDownLatch(1);
dao.queryExecutor().beginTransaction()
.flatMapCompletable(
transactionQE -> transactionQE.execute(
dslContext -> dslContext.insertInto(dao.getTable()).set(dslContext.newRecord(dao.getTable(), pojo))
).doOnSuccess(
inserted -> Assert.assertEquals(1, inserted.intValue())
).flatMap(
//insert again to trigger an exception
v -> transactionQE.execute(
dslContext -> dslContext.insertInto(dao.getTable()).set(dslContext.newRecord(dao.getTable(), pojo))
)
.doOnSuccess(qe -> Assert.fail("Should not succeed"))
.onErrorResumeNext(x -> Single.just(0)) //we know it failed, just recover from the exception
).flatMap(v -> dao.findOneById(pojo.getSomeid()))
.doOnSuccess(this::optionalAssertNull) //not known because transaction was rolled back
.flatMapCompletable(v -> transactionQE.commit()) //should throw error because the transaction was already rolled back
.doOnComplete(() -> Assert.fail("Should not succeed"))
.onErrorResumeNext(x -> {
Assert.assertTrue("Wrong exception. Got: " + x.getMessage(), x.getMessage().contains("Rollback"));
return Completable.complete();
})
)
.toSingleDefault(0)
.subscribe(countdownLatchHandler(completionLatch));
await(completionLatch);
}
@Test
public void rollbackShouldNotExecuteTransactionalQueries() throws InterruptedException {
Something pojo = createWithId();
CountDownLatch completionLatch = new CountDownLatch(1);
dao.queryExecutor().beginTransaction()
.flatMap(transactionQE -> transactionQE.execute(dslContext -> dslContext.insertInto(dao.getTable()).set(dslContext.newRecord(dao.getTable(), pojo)))
.doOnSuccess(inserted -> Assert.assertEquals(1, inserted.intValue()))
.flatMapCompletable(v -> transactionQE.rollback())
.andThen(dao.findOneById(pojo.getSomeid()))
.doOnSuccess(this::optionalAssertNull))
.subscribe(countdownLatchHandler(completionLatch))
;
await(completionLatch);
}
@Test
public void convenientTransactionShouldSucceed() throws InterruptedException {
Something pojo = createWithId();
CountDownLatch completionLatch = new CountDownLatch(1);
dao.queryExecutor().transaction(
transactionQE -> transactionQE.execute(
dslContext -> dslContext.insertInto(dao.getTable()).set(dslContext.newRecord(dao.getTable(), pojo))
).doOnSuccess(
inserted -> Assert.assertEquals(1, inserted.intValue())
).flatMap(
v -> transactionQE.findOneRow(
dslContext -> dslContext.selectFrom(dao.getTable()).where(eqPrimaryKey(pojo.getSomeid()))
)
).doOnSuccess(this::optionalAssertNotNull)
.flatMap(v -> dao.findOneById(pojo.getSomeid()))
.doOnSuccess(this::optionalAssertNull) //not known outside of transaction
.toMaybe()
) //implicitly commit the transaction
.flatMapSingle(v -> dao.findOneById(pojo.getSomeid())) //now known because we committed the transaction
.doOnSuccess(this::optionalAssertNotNull)
.flatMap(v -> dao.deleteById(pojo.getSomeid()))
.doOnSuccess(deleted -> Assert.assertEquals(1, deleted.intValue()))
.subscribe(countdownLatchHandler(completionLatch));
await(completionLatch);
}
@Test
public void rollbackTransactionsShouldReturnConnectionToPool(){
Something pojo = createWithId();
//we try to create one more connection than available in the pool to ensure that connections are properly returned on rollback
//additionally we count down on completion
CountDownLatch completionLatch = new CountDownLatch(ReactiveDatabaseClientProvider.POOL_SIZE+2);
dao.insert(pojo)
.doOnSuccess(inserted -> Assert.assertEquals(1, inserted.intValue()))
.flatMapObservable(v->{
/*
* Try to insert the same object inside a transaction. Prior to the fix for
* https://github.com/jklingsporn/vertx-jooq/issues/197 this test should not succeed
* and the connection pool will exhaust
*/
return Observable
.range(1,ReactiveDatabaseClientProvider.POOL_SIZE+1)
.flatMapMaybe(i -> dao.queryExecutor().transaction(
transactionQE -> transactionQE
.execute(dslContext -> dslContext.insertInto(dao.getTable()).set(dslContext.newRecord(dao.getTable(), pojo))).toMaybe()
).doOnSuccess(res -> Assert.fail("Should not succeed"))
.onErrorResumeNext(x -> {
completionLatch.countDown();
Assert.assertTrue("Wrong exception. Got: " + x.getMessage(), x.getMessage().toLowerCase().contains("duplicate"));
return Maybe.empty();
})
);
})
.subscribe(
i -> {
Assert.fail("shouldn't emit item");
},
x-> {
x.printStackTrace();
Assert.fail(x.getMessage());
},
()->{
completionLatch.countDown();
}
)
;
await(completionLatch);
}
@Test
public void queryFlowableRowShouldSucceed(){
Something pojo1 = createWithId();
Something pojo2 = createWithId();
/*
* Latch has to count down 6 times
* - one for each processed item (2)
* - when the items have been deleted (1)
* - upon successful processing (1)
* - when transaction has ben committed (1)
* - when connection has been closed (1)
*/
CountDownLatch completionLatch = new CountDownLatch(6);
dao
.insert(Arrays.asList(pojo1,pojo2))
.map(res -> dao.queryExecutor()
.queryFlowableRow(
dslContext -> dslContext.selectFrom(generated.rx3.reactive.regular.Tables.SOMETHING),
2,
r -> completionLatch.countDown(), //tx commit
r -> completionLatch.countDown() // connection closed
)
.subscribe(
//on next
row -> {
//conveniently map it to a pojo
Something mapped = dao.queryExecutor().pojoMapper().apply(row.getDelegate());
Assert.assertNotNull(mapped);
completionLatch.countDown();
},
//on error
Functions.ON_ERROR_MISSING,
//on complete (action - does not block)
() -> dao.deleteByIds(Arrays.asList(pojo1.getSomeid(),pojo2.getSomeid()))
.subscribe(i->completionLatch.countDown())
)
)
.subscribe(countdownLatchHandler(completionLatch));
await(completionLatch);
}
@Test
public void queryFlowableShouldSucceed(){
Something pojo1 = createWithId();
Something pojo2 = createWithId();
/*
* Latch has to count down 6 times
* - one for each processed item (2)
* - when the items have been deleted (1)
* - upon successful processing (1)
* - when transaction has ben committed (1)
* - when connection has been closed (1)
*/
CountDownLatch completionLatch = new CountDownLatch(6);
List<Something> pojos = Arrays.asList(pojo1, pojo2);
dao
.insert(pojos)
.map(res -> dao.queryExecutor()
.queryFlowable(
dslContext -> dslContext.selectFrom(generated.rx.reactive.regular.Tables.SOMETHING),
2,
r -> completionLatch.countDown(), //tx commit
r -> completionLatch.countDown() // connection closed
)
.subscribe(
//on next
pojo -> {
Assert.assertNotNull(pojo);
Assert.assertTrue(pojos.stream().anyMatch(p -> p.getSomeid().equals(pojo.getSomeid())));
completionLatch.countDown();
},
//on error
Functions.ON_ERROR_MISSING,
//on complete (action - does not block)
() -> dao.deleteByIds(Arrays.asList(pojo1.getSomeid(),pojo2.getSomeid()))
.subscribe(i->completionLatch.countDown())
)
)
.subscribe(countdownLatchHandler(completionLatch));
await(completionLatch);
}
}