-
Notifications
You must be signed in to change notification settings - Fork 113
/
ITDMLTest.java
383 lines (343 loc) · 13.4 KB
/
ITDMLTest.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
383
/*
* Copyright 2017 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.it;
import static com.google.cloud.spanner.testing.EmulatorSpannerHelper.isUsingEmulator;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.cloud.spanner.AbortedException;
import com.google.cloud.spanner.Database;
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.Dialect;
import com.google.cloud.spanner.ErrorCode;
import com.google.cloud.spanner.IntegrationTestEnv;
import com.google.cloud.spanner.Key;
import com.google.cloud.spanner.KeyRange;
import com.google.cloud.spanner.KeySet;
import com.google.cloud.spanner.Mutation;
import com.google.cloud.spanner.ParallelIntegrationTest;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.SpannerException;
import com.google.cloud.spanner.SpannerExceptionFactory;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.TimestampBound;
import com.google.cloud.spanner.TransactionRunner;
import com.google.cloud.spanner.TransactionRunner.TransactionCallable;
import com.google.cloud.spanner.connection.ConnectionOptions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
/** Integration tests for DML. */
@Category(ParallelIntegrationTest.class)
@RunWith(Parameterized.class)
public final class ITDMLTest {
@ClassRule public static IntegrationTestEnv env = new IntegrationTestEnv();
private static DatabaseClient googleStandardSQLClient;
private static DatabaseClient postgreSQLClient;
/** Sequence for assigning unique keys to test cases. */
private static int seq;
/** Id prefix per test case. */
private static int id;
private static final String INSERT_DML =
"INSERT INTO T (k, v) VALUES ('%d-boo1', 1), ('%d-boo2', 2), ('%d-boo3', 3), ('%d-boo4', 4);";
private static final String UPDATE_DML = "UPDATE T SET V = 100 WHERE K LIKE '%d-boo%%';";
private static final String DELETE_DML = "DELETE FROM T WHERE K like '%d-boo%%';";
private static final long DML_COUNT = 4;
private static boolean throwAbortOnce = false;
@BeforeClass
public static void setUpDatabase() {
Database googleStandardSQLDatabase =
env.getTestHelper()
.createTestDatabase(
"CREATE TABLE T ("
+ " K STRING(MAX) NOT NULL,"
+ " V INT64,"
+ ") PRIMARY KEY (K)");
googleStandardSQLClient = env.getTestHelper().getDatabaseClient(googleStandardSQLDatabase);
if (!isUsingEmulator()) {
Database postgreSQLDatabase =
env.getTestHelper()
.createTestDatabase(
Dialect.POSTGRESQL,
Arrays.asList(
"CREATE TABLE T (" + " K VARCHAR PRIMARY KEY," + " V BIGINT" + ")"));
postgreSQLClient = env.getTestHelper().getDatabaseClient(postgreSQLDatabase);
}
}
@AfterClass
public static void teardown() {
ConnectionOptions.closeSpanner();
}
@Before
public void increaseTestIdAndDeleteTestData() {
if (dialect.dialect == Dialect.GOOGLE_STANDARD_SQL) {
googleStandardSQLClient.writeAtLeastOnce(
Collections.singletonList(Mutation.delete("T", KeySet.all())));
} else {
postgreSQLClient.writeAtLeastOnce(
Collections.singletonList(Mutation.delete("T", KeySet.all())));
}
id++;
}
@Parameterized.Parameters(name = "Dialect = {0}")
public static List<DialectTestParameter> data() {
List<DialectTestParameter> params = new ArrayList<>();
params.add(new DialectTestParameter(Dialect.GOOGLE_STANDARD_SQL));
// "PG dialect tests are not supported by the emulator"
if (!isUsingEmulator()) {
params.add(new DialectTestParameter(Dialect.POSTGRESQL));
}
return params;
}
@Parameterized.Parameter(0)
public DialectTestParameter dialect;
private static String uniqueKey() {
return "k" + seq++;
}
private String insertDml() {
return String.format(INSERT_DML, id, id, id, id);
}
private String updateDml() {
return String.format(UPDATE_DML, id);
}
private String deleteDml() {
return String.format(DELETE_DML, id);
}
private void executeUpdate(long expectedCount, final String... stmts) {
final TransactionCallable<Long> callable =
transaction -> {
long rowCount = 0;
for (String stmt : stmts) {
if (throwAbortOnce) {
throwAbortOnce = false;
throw SpannerExceptionFactory.newSpannerException(ErrorCode.ABORTED, "Abort in test");
}
rowCount += transaction.executeUpdate(Statement.of(stmt));
}
return rowCount;
};
TransactionRunner runner = getClient(dialect.dialect).readWriteTransaction();
Long rowCount = runner.run(callable);
assertThat(rowCount).isEqualTo(expectedCount);
}
private DatabaseClient getClient(Dialect dialect) {
if (dialect == Dialect.POSTGRESQL) {
return postgreSQLClient;
}
return googleStandardSQLClient;
}
@Test
public void abortOnceShouldSucceedAfterRetry() {
try {
throwAbortOnce = true;
executeUpdate(DML_COUNT, insertDml());
assertThat(throwAbortOnce).isFalse();
} catch (AbortedException e) {
fail("Abort Exception not caught and retried");
}
}
@Test
public void partitionedDML() {
executeUpdate(DML_COUNT, insertDml());
assertThat(
getClient(dialect.dialect)
.singleUse(TimestampBound.strong())
.readRow("T", Key.of(String.format("%d-boo1", id)), Collections.singletonList("V"))
.getLong(0))
.isEqualTo(1);
long rowCount = getClient(dialect.dialect).executePartitionedUpdate(Statement.of(updateDml()));
// Note: With PDML there is a possibility of network replay or partial update to occur, causing
// this assert to fail. We should remove this assert if it is a recurring failure in IT tests.
assertThat(rowCount).isEqualTo(DML_COUNT);
assertThat(
getClient(dialect.dialect)
.singleUse(TimestampBound.strong())
.readRow("T", Key.of(String.format("%d-boo1", id)), Collections.singletonList("V"))
.getLong(0))
.isEqualTo(100);
rowCount = getClient(dialect.dialect).executePartitionedUpdate(Statement.of(deleteDml()));
assertThat(rowCount).isEqualTo(DML_COUNT);
assertThat(
getClient(dialect.dialect)
.singleUse(TimestampBound.strong())
.readRow("T", Key.of(String.format("%d-boo1", id)), Collections.singletonList("V")))
.isNull();
}
@Test
public void standardDML() {
executeUpdate(DML_COUNT, insertDml());
assertThat(
getClient(dialect.dialect)
.singleUse(TimestampBound.strong())
.readRow("T", Key.of(String.format("%d-boo1", id)), Collections.singletonList("V"))
.getLong(0))
.isEqualTo(1);
executeUpdate(DML_COUNT, updateDml());
assertThat(
getClient(dialect.dialect)
.singleUse(TimestampBound.strong())
.readRow("T", Key.of(String.format("%d-boo1", id)), Collections.singletonList("V"))
.getLong(0))
.isEqualTo(100);
executeUpdate(DML_COUNT, deleteDml());
assertThat(
getClient(dialect.dialect)
.singleUse(TimestampBound.strong())
.readRow("T", Key.of(String.format("%d-boo1", id)), Collections.singletonList("V")))
.isNull();
}
@Test
public void standardDMLWithError() {
try {
executeUpdate(0, "SELECT * FROM T;");
fail("Expected illegal argument exception");
} catch (SpannerException e) {
assertThat(e.getErrorCode()).isEqualTo(ErrorCode.UNKNOWN);
assertThat(e.getMessage())
.contains("DML response missing stats possibly due to non-DML statement as input");
assertThat(e.getCause()).isInstanceOf(IllegalArgumentException.class);
}
}
@Test
public void standardDMLWithDuplicates() {
executeUpdate(DML_COUNT, insertDml());
executeUpdate(
4,
String.format("UPDATE T SET v = 200 WHERE k = '%d-boo1';", id),
String.format("UPDATE T SET v = 300 WHERE k = '%d-boo1';", id),
String.format("UPDATE T SET v = 400 WHERE k = '%d-boo1';", id),
String.format("UPDATE T SET v = 500 WHERE k = '%d-boo1';", id));
assertThat(
getClient(dialect.dialect)
.singleUse(TimestampBound.strong())
.readRow("T", Key.of(String.format("%d-boo1", id)), Collections.singletonList("V"))
.getLong(0))
.isEqualTo(500);
executeUpdate(DML_COUNT, deleteDml(), deleteDml());
}
@Test
public void standardDMLReadYourWrites() {
executeUpdate(DML_COUNT, insertDml());
final TransactionCallable<Void> callable =
transaction -> {
long rowCount =
transaction.executeUpdate(
Statement.of(String.format("UPDATE T SET v = v * 2 WHERE k = '%d-boo2';", id)));
assertThat(rowCount).isEqualTo(1);
assertThat(
transaction
.readRow(
"T", Key.of(String.format("%d-boo2", id)), Collections.singletonList("v"))
.getLong(0))
.isEqualTo(2 * 2);
return null;
};
TransactionRunner runner = getClient(dialect.dialect).readWriteTransaction();
runner.run(callable);
executeUpdate(DML_COUNT, deleteDml());
}
@Test
public void standardDMLRollback() {
class UserException extends Exception {
UserException(String message) {
super(message);
}
}
final TransactionCallable<Void> callable =
transaction -> {
long rowCount = transaction.executeUpdate(Statement.of(insertDml()));
assertThat(rowCount).isEqualTo(DML_COUNT);
throw new UserException("failing to commit");
};
try {
TransactionRunner runner = getClient(dialect.dialect).readWriteTransaction();
runner.run(callable);
fail("Expected user exception");
} catch (SpannerException e) {
assertThat(e.getErrorCode()).isEqualTo(ErrorCode.UNKNOWN);
assertThat(e.getMessage()).contains("failing to commit");
assertThat(e.getCause()).isInstanceOf(UserException.class);
}
ResultSet resultSet =
getClient(dialect.dialect)
.singleUse(TimestampBound.strong())
.read(
"T",
KeySet.range(KeyRange.prefix(Key.of(String.format("%d-boo", id)))),
Collections.singletonList("K"));
assertThat(resultSet.next()).isFalse();
}
@Test
public void standardDMLAndMutations() {
final String key1 = uniqueKey();
final String key2 = uniqueKey();
final TransactionCallable<Void> callable =
transaction -> {
// DML
long rowCount =
transaction.executeUpdate(
Statement.of("INSERT INTO T (k, v) VALUES ('" + key1 + "', 1)"));
assertThat(rowCount).isEqualTo(1);
// Mutations
transaction.buffer(
Mutation.newInsertOrUpdateBuilder("T").set("K").to(key2).set("V").to(2).build());
return null;
};
TransactionRunner runner = getClient(dialect.dialect).readWriteTransaction();
runner.run(callable);
KeySet.Builder keys = KeySet.newBuilder();
keys.addKey(Key.of(key1)).addKey(Key.of(key2));
ResultSet resultSet =
getClient(dialect.dialect)
.singleUse(TimestampBound.strong())
.read("T", keys.build(), Collections.singletonList("K"));
int rowCount = 0;
while (resultSet.next()) {
rowCount++;
}
assertThat(rowCount).isEqualTo(2);
}
private void executeQuery(long expectedCount, final String... stmts) {
final TransactionCallable<Long> callable =
transaction -> {
long rowCount = 0;
for (final String stmt : stmts) {
ResultSet resultSet = transaction.executeQuery(Statement.of(stmt));
assertThat(resultSet.next()).isFalse();
assertThat(resultSet.getStats()).isNotNull();
rowCount += resultSet.getStats().getRowCountExact();
}
return rowCount;
};
TransactionRunner runner = getClient(dialect.dialect).readWriteTransaction();
Long rowCount = runner.run(callable);
assertThat(rowCount).isEqualTo(expectedCount);
}
@Test
public void standardDMLWithExecuteSQL() {
executeQuery(DML_COUNT, insertDml());
// checks for multi-stmts within a txn, therefore also verifying seqNo.
executeQuery(DML_COUNT * 2, updateDml(), deleteDml());
}
}