/
JdbcAbortedTransactionTest.java
373 lines (348 loc) · 14.7 KB
/
JdbcAbortedTransactionTest.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
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.jdbc;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.ErrorCode;
import com.google.cloud.spanner.MockSpannerServiceImpl;
import com.google.cloud.spanner.MockSpannerServiceImpl.StatementResult;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.admin.database.v1.MockDatabaseAdminImpl;
import com.google.cloud.spanner.admin.instance.v1.MockInstanceAdminImpl;
import com.google.cloud.spanner.jdbc.JdbcSqlExceptionFactory.JdbcAbortedDueToConcurrentModificationException;
import com.google.cloud.spanner.jdbc.JdbcSqlExceptionFactory.JdbcAbortedException;
import com.google.protobuf.ListValue;
import com.google.protobuf.Value;
import com.google.spanner.v1.ResultSetMetadata;
import com.google.spanner.v1.StructType;
import com.google.spanner.v1.StructType.Field;
import com.google.spanner.v1.Type;
import com.google.spanner.v1.TypeCode;
import io.grpc.Server;
import io.grpc.Status;
import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class JdbcAbortedTransactionTest {
private static final class TransactionRetryCounter implements TransactionRetryListener {
private int retriesFinished;
@Override
public void retryStarting(Timestamp transactionStarted, long transactionId, int retryAttempt) {}
@Override
public void retryFinished(
Timestamp transactionStarted, long transactionId, int retryAttempt, RetryResult result) {
retriesFinished++;
}
}
private static final Statement SELECT1 = Statement.of("SELECT 1 AS COL1");
private static final ResultSetMetadata SELECT1_METADATA =
ResultSetMetadata.newBuilder()
.setRowType(
StructType.newBuilder()
.addFields(
Field.newBuilder()
.setName("COL1")
.setType(Type.newBuilder().setCode(TypeCode.INT64).build())
.build())
.build())
.build();
private static final com.google.spanner.v1.ResultSet SELECT1_RESULTSET =
com.google.spanner.v1.ResultSet.newBuilder()
.addRows(
ListValue.newBuilder()
.addValues(Value.newBuilder().setStringValue("1").build())
.build())
.setMetadata(SELECT1_METADATA)
.build();
private static final Statement SELECT_RANDOM = Statement.of("SELECT * FROM RANDOM");
private static final Statement UPDATE_STATEMENT =
Statement.of("UPDATE FOO SET BAR=1 WHERE BAZ=2");
private static final int UPDATE_COUNT = 1;
private static MockSpannerServiceImpl mockSpanner;
private static MockInstanceAdminImpl mockInstanceAdmin;
private static MockDatabaseAdminImpl mockDatabaseAdmin;
private static Server server;
private static InetSocketAddress address;
@Parameter(0)
public boolean retryAbortsInternally;
@Parameters(name = "retryAbortsInternally = {0}")
public static Collection<Object[]> data() {
List<Object[]> params = new ArrayList<>();
params.add(new Object[] {Boolean.TRUE});
params.add(new Object[] {Boolean.FALSE});
return params;
}
@BeforeClass
public static void startStaticServer() throws IOException {
mockSpanner = new MockSpannerServiceImpl();
mockSpanner.setAbortProbability(0.0D); // We don't want any unpredictable aborted transactions.
mockSpanner.putStatementResult(StatementResult.query(SELECT1, SELECT1_RESULTSET));
mockSpanner.putStatementResult(StatementResult.update(UPDATE_STATEMENT, UPDATE_COUNT));
mockInstanceAdmin = new MockInstanceAdminImpl();
mockDatabaseAdmin = new MockDatabaseAdminImpl();
address = new InetSocketAddress("localhost", 0);
server =
NettyServerBuilder.forAddress(address)
.addService(mockSpanner)
.addService(mockInstanceAdmin)
.addService(mockDatabaseAdmin)
.build()
.start();
}
@AfterClass
public static void stopServer() throws Exception {
SpannerPool.closeSpannerPool();
server.shutdown();
server.awaitTermination();
}
private String createUrl() {
return String.format(
"jdbc:cloudspanner://localhost:%d/projects/%s/instances/%s/databases/%s?usePlainText=true;retryAbortsInternally=%s",
server.getPort(), "proj", "inst", "db", Boolean.toString(retryAbortsInternally));
}
private Connection createConnection() throws SQLException {
Connection connection = DriverManager.getConnection(createUrl());
CloudSpannerJdbcConnection cs = connection.unwrap(CloudSpannerJdbcConnection.class);
cs.addTransactionRetryListener(new TransactionRetryCounter());
return connection;
}
private int getRetryCount(Connection connection) throws SQLException {
return ((TransactionRetryCounter)
connection
.unwrap(CloudSpannerJdbcConnection.class)
.getTransactionRetryListeners()
.next())
.retriesFinished;
}
@Test
public void testAutocommitUpdateAborted() throws SQLException {
// Updates in autocommit are always automatically retried.
// These retries are not picked up by the transaction retry listener, as that is only done for
// actual JDBC transactions that are retried.
try (java.sql.Connection connection = createConnection()) {
mockSpanner.abortNextStatement();
int updateCount = connection.createStatement().executeUpdate(UPDATE_STATEMENT.getSql());
assertThat(updateCount).isEqualTo(UPDATE_COUNT);
}
}
@Test
public void testTransactionalUpdateAborted() throws SQLException {
// Updates in transactional mode are automatically retried by default, but this can be switched
// off.
try (java.sql.Connection connection = createConnection()) {
connection.setAutoCommit(false);
mockSpanner.abortNextStatement();
int updateCount = connection.createStatement().executeUpdate(UPDATE_STATEMENT.getSql());
if (!retryAbortsInternally) {
fail("missing expected exception");
}
assertThat(updateCount).isEqualTo(UPDATE_COUNT);
assertThat(getRetryCount(connection)).isEqualTo(1);
} catch (JdbcAbortedException e) {
assertThat(retryAbortsInternally).isFalse();
}
}
@Test
public void testAutocommitBatchUpdateAborted() throws SQLException {
try (java.sql.Connection connection = createConnection()) {
mockSpanner.abortNextStatement();
try (java.sql.Statement statement = connection.createStatement()) {
statement.addBatch(UPDATE_STATEMENT.getSql());
statement.addBatch(UPDATE_STATEMENT.getSql());
int[] updateCounts = statement.executeBatch();
assertThat(updateCounts).asList().containsExactly(UPDATE_COUNT, UPDATE_COUNT);
}
}
}
@Test
public void testTransactionalBatchUpdateAborted() throws SQLException {
try (java.sql.Connection connection = createConnection()) {
connection.setAutoCommit(false);
mockSpanner.abortNextStatement();
try (java.sql.Statement statement = connection.createStatement()) {
statement.addBatch(UPDATE_STATEMENT.getSql());
statement.addBatch(UPDATE_STATEMENT.getSql());
int[] updateCounts = statement.executeBatch();
if (!retryAbortsInternally) {
fail("missing expected exception");
}
assertThat(updateCounts).asList().containsExactly(UPDATE_COUNT, UPDATE_COUNT);
assertThat(getRetryCount(connection)).isEqualTo(1);
} catch (JdbcAbortedException e) {
assertThat(retryAbortsInternally).isFalse();
}
}
}
@Test
public void testAutocommitSelectAborted() throws SQLException {
// Selects in autocommit are executed using a singleUse read-only transaction and cannot abort.
try (java.sql.Connection connection = createConnection()) {
mockSpanner.abortNextStatement();
try (ResultSet rs = connection.createStatement().executeQuery(SELECT1.getSql())) {
while (rs.next()) {
assertThat(rs.getLong(1)).isEqualTo(1L);
}
}
}
}
@Test
public void testTransactionalSelectAborted() throws SQLException {
try (java.sql.Connection connection = createConnection()) {
connection.setAutoCommit(false);
mockSpanner.abortNextStatement();
try (ResultSet rs = connection.createStatement().executeQuery(SELECT1.getSql())) {
while (rs.next()) {
if (!retryAbortsInternally) {
fail("missing expected exception");
}
assertThat(rs.getLong(1)).isEqualTo(1L);
}
}
assertThat(getRetryCount(connection)).isEqualTo(1);
} catch (JdbcAbortedException e) {
assertThat(retryAbortsInternally).isFalse();
}
}
@Test
public void testTransactionalUpdateWithConcurrentModificationsAborted() throws SQLException {
// As the transaction does a random select, the retry will always see different data than the
// original attempt.
try (java.sql.Connection connection = createConnection()) {
connection.setAutoCommit(false);
// Set a random answer.
mockSpanner.putStatementResult(
StatementResult.query(SELECT_RANDOM, new RandomResultSetGenerator(25).generate()));
try (ResultSet rs = connection.createStatement().executeQuery(SELECT_RANDOM.getSql())) {
while (rs.next()) {}
}
// Set a new random answer that will be returned during the retry.
mockSpanner.putStatementResult(
StatementResult.query(SELECT_RANDOM, new RandomResultSetGenerator(25).generate()));
// Abort all transactions (including the current one).
mockSpanner.abortNextStatement();
// This will abort and start an internal retry.
connection.createStatement().executeUpdate(UPDATE_STATEMENT.getSql());
fail("missing expected aborted exception");
} catch (JdbcAbortedDueToConcurrentModificationException e) {
assertThat(retryAbortsInternally).isTrue();
} catch (JdbcAbortedException e) {
assertThat(retryAbortsInternally).isFalse();
}
}
@Test
public void testTransactionalUpdateWithErrorOnOriginalAndRetry() throws SQLException {
final String sql = "UPDATE SOMETHING SET OTHER=1";
mockSpanner.putStatementResult(
StatementResult.exception(
Statement.of(sql),
Status.INVALID_ARGUMENT.withDescription("test").asRuntimeException()));
try (java.sql.Connection connection = createConnection()) {
connection.setAutoCommit(false);
try (ResultSet rs = connection.createStatement().executeQuery(SELECT1.getSql())) {
while (rs.next()) {
assertThat(rs.getLong(1)).isEqualTo(1L);
}
}
try {
connection.createStatement().executeUpdate(sql);
fail("missing 'test' exception");
} catch (SQLException e) {
// ignore
}
mockSpanner.abortNextStatement();
connection.commit();
if (!retryAbortsInternally) {
fail("missing expected exception");
}
} catch (JdbcAbortedException e) {
assertThat(retryAbortsInternally).isFalse();
}
}
@Test
public void testTransactionalUpdateWithErrorOnRetryAndNotOnOriginal() throws SQLException {
final String sql = "UPDATE SOMETHING SET OTHER=1";
try (java.sql.Connection connection = createConnection()) {
connection.setAutoCommit(false);
// Set a normal response to the update statement.
mockSpanner.putStatementResult(StatementResult.update(Statement.of(sql), 1L));
connection.createStatement().executeUpdate(sql);
// Set an error as response for the same update statement that will be used during the retry.
// This will cause the retry to fail.
mockSpanner.putStatementResult(
StatementResult.exception(
Statement.of(sql),
Status.INVALID_ARGUMENT.withDescription("test").asRuntimeException()));
mockSpanner.abortNextStatement();
connection.commit();
fail("missing expected aborted exception");
} catch (JdbcAbortedDueToConcurrentModificationException e) {
assertThat(retryAbortsInternally).isTrue();
assertThat(e.getDatabaseErrorDuringRetry().getErrorCode())
.isEqualTo(ErrorCode.INVALID_ARGUMENT);
assertThat(e.getDatabaseErrorDuringRetry().getMessage()).endsWith("test");
} catch (JdbcAbortedException e) {
assertThat(retryAbortsInternally).isFalse();
}
}
@Test
public void testTransactionalUpdateWithErrorOnOriginalAndNotOnRetry() throws SQLException {
final String sql = "UPDATE SOMETHING SET OTHER=1";
mockSpanner.putStatementResult(
StatementResult.exception(
Statement.of(sql),
Status.INVALID_ARGUMENT.withDescription("test").asRuntimeException()));
try (java.sql.Connection connection = createConnection()) {
connection.setAutoCommit(false);
try (ResultSet rs = connection.createStatement().executeQuery(SELECT1.getSql())) {
while (rs.next()) {
assertThat(rs.getLong(1)).isEqualTo(1L);
}
}
try {
connection.createStatement().executeUpdate(sql);
fail("missing 'test' exception");
} catch (SQLException e) {
// ignore
}
// Set the update statement to return a result next time (i.e. during retry).
mockSpanner.putStatementResult(StatementResult.update(Statement.of(sql), 1L));
mockSpanner.abortNextStatement();
connection.commit();
fail("missing expected aborted exception");
} catch (JdbcAbortedDueToConcurrentModificationException e) {
assertThat(retryAbortsInternally).isTrue();
assertThat(e.getDatabaseErrorDuringRetry()).isNull();
} catch (JdbcAbortedException e) {
assertThat(retryAbortsInternally).isFalse();
}
}
}