Skip to content
Permalink
Browse files

Fix exception on PGCopyOutputStream.close() after endCopy() (#1574) (#…

…1575)

* Fix: check if active before close() (#1574)

* Fix: NPEs on flush() and isActive() if copy has ended

* Tests for close(), flush(), isActive()
  • Loading branch information
virtual-machinist authored and davecramer committed Nov 12, 2019
1 parent 9b8a3ff commit 539a09258f6009581785474fe5f15a46992ade6f
@@ -101,17 +101,20 @@ public void close() throws IOException {
return;
}

try {
endCopy();
} catch (SQLException se) {
IOException ioe = new IOException("Ending write to copy failed.");
ioe.initCause(se);
throw ioe;
if (op.isActive()) {
try {
endCopy();
} catch (SQLException se) {
IOException ioe = new IOException("Ending write to copy failed.");
ioe.initCause(se);
throw ioe;
}
}
op = null;
}

public void flush() throws IOException {
checkClosed();
try {
op.writeToCopy(copyBuffer, 0, at);
at = 0;
@@ -154,7 +157,7 @@ public int getFieldCount() {
}

public boolean isActive() {
return op.isActive();
return op != null && op.isActive();
}

public void flushCopy() throws SQLException {
@@ -6,6 +6,7 @@
package org.postgresql.test.jdbc2;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@@ -134,6 +135,47 @@ public void testCopyInAsOutputStream() throws SQLException, IOException {
assertEquals(dataRows, rowCount);
}

@Test
public void testCopyInAsOutputStreamClosesAfterEndCopy() throws SQLException, IOException {
String sql = "COPY copytest FROM STDIN";
PGCopyOutputStream os = new PGCopyOutputStream((PGConnection) con, sql, 1000);
try {
for (String anOrigData : origData) {
byte[] buf = anOrigData.getBytes();
os.write(buf);
}
os.endCopy();
} finally {
os.close();
}
assertFalse(os.isActive());
int rowCount = getCount();
assertEquals(dataRows, rowCount);
}

@Test
public void testCopyInAsOutputStreamFailsOnFlushAfterEndCopy() throws SQLException, IOException {
String sql = "COPY copytest FROM STDIN";
PGCopyOutputStream os = new PGCopyOutputStream((PGConnection) con, sql, 1000);
try {
for (String anOrigData : origData) {
byte[] buf = anOrigData.getBytes();
os.write(buf);
}
os.endCopy();
} finally {
os.close();
}
try {
os.flush();
fail("should have failed flushing an inactive copy stream.");
} catch (IOException e) {
if (!e.toString().contains("This copy stream is closed.")) {
fail("has failed not due to checkClosed(): " + e);
}
}
}

@Test
public void testCopyInFromInputStream() throws SQLException, IOException {
String sql = "COPY copytest FROM STDIN";

0 comments on commit 539a092

Please sign in to comment.
You can’t perform that action at this time.