/
CopyTest.java
446 lines (391 loc) · 12.8 KB
/
CopyTest.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
/*
* Copyright (c) 2008, PostgreSQL Global Development Group
* See the LICENSE file in the project root for more information.
*/
package org.postgresql.test.jdbc2;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.postgresql.PGConnection;
import org.postgresql.copy.CopyIn;
import org.postgresql.copy.CopyManager;
import org.postgresql.copy.CopyOut;
import org.postgresql.copy.PGCopyOutputStream;
import org.postgresql.core.ServerVersion;
import org.postgresql.test.TestUtil;
import org.postgresql.util.PSQLState;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* @author kato@iki.fi
*/
public class CopyTest {
private Connection con;
private CopyManager copyAPI;
private String copyParams;
// 0's required to match DB output for numeric(5,2)
private String[] origData =
{"First Row\t1\t1.10\n",
"Second Row\t2\t-22.20\n",
"\\N\t\\N\t\\N\n",
"\t4\t444.40\n"};
private int dataRows = origData.length;
private byte[] getData(String[] origData) {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(buf);
for (String anOrigData : origData) {
ps.print(anOrigData);
}
return buf.toByteArray();
}
@Before
public void setUp() throws Exception {
con = TestUtil.openDB();
TestUtil.createTable(con, "copytest", "stringvalue text, intvalue int, numvalue numeric(5,2)");
copyAPI = ((PGConnection) con).getCopyAPI();
if (TestUtil.haveMinimumServerVersion(con, ServerVersion.v9_0)) {
copyParams = "(FORMAT CSV, HEADER false)";
} else {
copyParams = "CSV";
}
}
@After
public void tearDown() throws Exception {
TestUtil.closeDB(con);
// one of the tests will render the existing connection broken,
// so we need to drop the table on a fresh one.
con = TestUtil.openDB();
try {
TestUtil.dropTable(con, "copytest");
} finally {
con.close();
}
}
private int getCount() throws SQLException {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT count(*) FROM copytest");
rs.next();
int result = rs.getInt(1);
rs.close();
return result;
}
@Test
public void testCopyInByRow() throws SQLException {
String sql = "COPY copytest FROM STDIN";
CopyIn cp = copyAPI.copyIn(sql);
for (String anOrigData : origData) {
byte[] buf = anOrigData.getBytes();
cp.writeToCopy(buf, 0, buf.length);
}
long count1 = cp.endCopy();
long count2 = cp.getHandledRowCount();
assertEquals(dataRows, count1);
assertEquals(dataRows, count2);
try {
cp.cancelCopy();
} catch (SQLException se) { // should fail with obsolete operation
if (!PSQLState.OBJECT_NOT_IN_STATE.getState().equals(se.getSQLState())) {
fail("should have thrown object not in state exception.");
}
}
int rowCount = getCount();
assertEquals(dataRows, rowCount);
}
@Test
public void testCopyInAsOutputStream() throws SQLException, IOException {
String sql = "COPY copytest FROM STDIN";
OutputStream os = new PGCopyOutputStream((PGConnection) con, sql, 1000);
for (String anOrigData : origData) {
byte[] buf = anOrigData.getBytes();
os.write(buf);
}
os.close();
int rowCount = getCount();
assertEquals(dataRows, rowCount);
}
@Test
public void testCopyInFromInputStream() throws SQLException, IOException {
String sql = "COPY copytest FROM STDIN";
copyAPI.copyIn(sql, new ByteArrayInputStream(getData(origData)), 3);
int rowCount = getCount();
assertEquals(dataRows, rowCount);
}
@Test
public void testCopyInFromStreamFail() throws SQLException {
String sql = "COPY copytest FROM STDIN";
try {
copyAPI.copyIn(sql, new InputStream() {
public int read() {
throw new RuntimeException("COPYTEST");
}
}, 3);
} catch (Exception e) {
if (!e.toString().contains("COPYTEST")) {
fail("should have failed trying to read from our bogus stream.");
}
}
int rowCount = getCount();
assertEquals(0, rowCount);
}
@Test
public void testCopyInFromReader() throws SQLException, IOException {
String sql = "COPY copytest FROM STDIN";
copyAPI.copyIn(sql, new StringReader(new String(getData(origData))), 3);
int rowCount = getCount();
assertEquals(dataRows, rowCount);
}
@Test
public void testSkipping() {
String sql = "COPY copytest FROM STDIN";
String at = "init";
int rowCount = -1;
int skip = 0;
int skipChar = 1;
try {
while (skipChar > 0) {
at = "buffering";
InputStream ins = new ByteArrayInputStream(getData(origData));
at = "skipping";
ins.skip(skip++);
skipChar = ins.read();
at = "copying";
copyAPI.copyIn(sql, ins, 3);
at = "using connection after writing copy";
rowCount = getCount();
}
} catch (Exception e) {
if (!(skipChar == '\t')) {
// error expected when field separator consumed
fail("testSkipping at " + at + " round " + skip + ": " + e.toString());
}
}
assertEquals(dataRows * (skip - 1), rowCount);
}
@Test
public void testCopyOutByRow() throws SQLException, IOException {
testCopyInByRow(); // ensure we have some data.
String sql = "COPY copytest TO STDOUT";
CopyOut cp = copyAPI.copyOut(sql);
int count = 0;
byte[] buf;
while ((buf = cp.readFromCopy()) != null) {
count++;
}
assertEquals(false, cp.isActive());
assertEquals(dataRows, count);
long rowCount = cp.getHandledRowCount();
assertEquals(dataRows, rowCount);
assertEquals(dataRows, getCount());
}
@Test
public void testCopyOut() throws SQLException, IOException {
testCopyInByRow(); // ensure we have some data.
String sql = "COPY copytest TO STDOUT";
ByteArrayOutputStream copydata = new ByteArrayOutputStream();
copyAPI.copyOut(sql, copydata);
assertEquals(dataRows, getCount());
// deep comparison of data written and read
byte[] copybytes = copydata.toByteArray();
assertNotNull(copybytes);
for (int i = 0, l = 0; i < origData.length; i++) {
byte[] origBytes = origData[i].getBytes();
assertTrue("Copy is shorter than original", copybytes.length >= l + origBytes.length);
for (int j = 0; j < origBytes.length; j++, l++) {
assertEquals("content changed at byte#" + j + ": " + origBytes[j] + copybytes[l],
origBytes[j], copybytes[l]);
}
}
}
@Test
public void testNonCopyOut() throws SQLException, IOException {
String sql = "SELECT 1";
try {
copyAPI.copyOut(sql, new ByteArrayOutputStream());
fail("Can't use a non-copy query.");
} catch (SQLException sqle) {
}
// Ensure connection still works.
assertEquals(0, getCount());
}
@Test
public void testNonCopyIn() throws SQLException, IOException {
String sql = "SELECT 1";
try {
copyAPI.copyIn(sql, new ByteArrayInputStream(new byte[0]));
fail("Can't use a non-copy query.");
} catch (SQLException sqle) {
}
// Ensure connection still works.
assertEquals(0, getCount());
}
@Test
public void testStatementCopyIn() throws SQLException {
Statement stmt = con.createStatement();
try {
stmt.execute("COPY copytest FROM STDIN");
fail("Should have failed because copy doesn't work from a Statement.");
} catch (SQLException sqle) {
}
stmt.close();
assertEquals(0, getCount());
}
@Test
public void testStatementCopyOut() throws SQLException {
testCopyInByRow(); // ensure we have some data.
Statement stmt = con.createStatement();
try {
stmt.execute("COPY copytest TO STDOUT");
fail("Should have failed because copy doesn't work from a Statement.");
} catch (SQLException sqle) {
}
stmt.close();
assertEquals(dataRows, getCount());
}
@Test
public void testCopyQuery() throws SQLException, IOException {
testCopyInByRow(); // ensure we have some data.
long count = copyAPI.copyOut("COPY (SELECT generate_series(1,1000)) TO STDOUT",
new ByteArrayOutputStream());
assertEquals(1000, count);
}
@Test
public void testCopyRollback() throws SQLException {
con.setAutoCommit(false);
testCopyInByRow();
con.rollback();
assertEquals(0, getCount());
}
@Test
public void testChangeDateStyle() throws SQLException {
try {
con.setAutoCommit(false);
con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
CopyManager manager = con.unwrap(PGConnection.class).getCopyAPI();
Statement stmt = con.createStatement();
stmt.execute("SET DateStyle = 'ISO, DMY'");
// I expect an SQLException
String sql = "COPY copytest FROM STDIN with xxx " + copyParams;
CopyIn cp = manager.copyIn(sql);
for (String anOrigData : origData) {
byte[] buf = anOrigData.getBytes();
cp.writeToCopy(buf, 0, buf.length);
}
long count1 = cp.endCopy();
long count2 = cp.getHandledRowCount();
con.commit();
} catch (SQLException ex) {
// the with xxx is a syntax error which shoud return a state of 42601
// if this fails the 'S' command is not being handled in the copy manager query handler
assertEquals("42601", ex.getSQLState());
con.rollback();
}
}
@Test
public void testLockReleaseOnCancelFailure() throws SQLException, InterruptedException {
if (!TestUtil.haveMinimumServerVersion(con, ServerVersion.v8_4)) {
// pg_backend_pid() requires PostgreSQL 8.4+
return;
}
// This is a fairly complex test because it is testing a
// deadlock that only occurs when the connection to postgres
// is broken during a copy operation. We'll start a copy
// operation, use pg_terminate_backend to rudely break it,
// and then cancel. The test passes if a subsequent operation
// on the Connection object fails to deadlock.
con.setAutoCommit(false);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select pg_backend_pid()");
rs.next();
int pid = rs.getInt(1);
rs.close();
stmt.close();
CopyManager manager = con.unwrap(PGConnection.class).getCopyAPI();
CopyIn copyIn = manager.copyIn("COPY copytest FROM STDIN with " + copyParams);
try {
killConnection(pid);
byte[] bunchOfNulls = ",,\n".getBytes();
while (true) {
copyIn.writeToCopy(bunchOfNulls, 0, bunchOfNulls.length);
}
} catch (SQLException e) {
acceptIOCause(e);
} finally {
if (copyIn.isActive()) {
try {
copyIn.cancelCopy();
fail("cancelCopy should have thrown an exception");
} catch (SQLException e) {
acceptIOCause(e);
}
}
}
// Now we'll execute rollback on another thread so that if the
// deadlock _does_ occur the testcase doesn't just hange forever.
Rollback rollback = new Rollback(con);
rollback.start();
rollback.join(1000);
if (rollback.isAlive()) {
fail("rollback did not terminate");
}
SQLException rollbackException = rollback.exception();
if (rollbackException == null) {
fail("rollback should have thrown an exception");
}
acceptIOCause(rollbackException);
}
private static class Rollback extends Thread {
private final Connection con;
private SQLException rollbackException;
Rollback(Connection con) {
setName("Asynchronous rollback");
setDaemon(true);
this.con = con;
}
@Override
public void run() {
try {
con.rollback();
} catch (SQLException e) {
rollbackException = e;
}
}
public SQLException exception() {
return rollbackException;
}
}
private void killConnection(int pid) throws SQLException {
Connection killerCon;
try {
killerCon = TestUtil.openPrivilegedDB();
} catch (Exception e) {
fail("Unable to open secondary connection to terminate copy");
return; // persuade Java killerCon will not be used uninitialized
}
try {
PreparedStatement stmt = killerCon.prepareStatement("select pg_terminate_backend(?)");
stmt.setInt(1, pid);
stmt.execute();
} finally {
killerCon.close();
}
}
private void acceptIOCause(SQLException e) throws SQLException {
if (!(e.getCause() instanceof IOException)) {
throw e;
}
}
}