Skip to content

Commit

Permalink
fix: NPE as a result of calling executeQuery twice on a statement fix…
Browse files Browse the repository at this point in the history
…es issue #684 (#1610)
  • Loading branch information
davecramer committed Nov 18, 2019
1 parent 8abf316 commit 00fa448
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 9 deletions.
22 changes: 16 additions & 6 deletions pgjdbc/src/main/java/org/postgresql/jdbc/PgResultSet.java
Expand Up @@ -1852,17 +1852,27 @@ public boolean next() throws SQLException {

public void close() throws SQLException {
try {
// release resources held (memory for tuples)
rows = null;
if (cursor != null) {
cursor.close();
cursor = null;
}
closeInternally();
} finally {
((PgStatement) statement).checkCompletion();
}
}

/*
used by PgStatement.closeForNextExecution to avoid
closing the firstUnclosedResult twice.
checkCompletion above modifies firstUnclosedResult
fixes issue #684
*/
protected void closeInternally() throws SQLException {
// release resources held (memory for tuples)
rows = null;
if (cursor != null) {
cursor.close();
cursor = null;
}
}

public boolean wasNull() throws SQLException {
checkClosed();
return wasNullFlag;
Expand Down
6 changes: 3 additions & 3 deletions pgjdbc/src/main/java/org/postgresql/jdbc/PgStatement.java
Expand Up @@ -125,7 +125,7 @@ public class PgStatement implements Statement, BaseStatement {
/**
* The first unclosed result.
*/
protected ResultWrapper firstUnclosedResult = null;
protected volatile ResultWrapper firstUnclosedResult = null;

/**
* Results returned by a statement that wants generated keys.
Expand Down Expand Up @@ -327,9 +327,9 @@ protected void closeForNextExecution() throws SQLException {
// Close any existing resultsets associated with this statement.
synchronized (this) {
while (firstUnclosedResult != null) {
ResultSet rs = firstUnclosedResult.getResultSet();
PgResultSet rs = (PgResultSet)firstUnclosedResult.getResultSet();
if (rs != null) {
rs.close();
rs.closeInternally();
}
firstUnclosedResult = firstUnclosedResult.getNext();
}
Expand Down
Expand Up @@ -15,6 +15,7 @@
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
Expand Down Expand Up @@ -89,4 +90,12 @@ public void testNoResultSet() throws SQLException {
stmt.executeUpdate(TestUtil.insertSQL("table1", "1"));
assertFalse(stmt.isClosed());
}

@Test
public void testExecuteTwice() throws SQLException {
PreparedStatement s = conn.prepareStatement("SELECT 1");
s.closeOnCompletion();
s.executeQuery();
s.executeQuery();
}
}

0 comments on commit 00fa448

Please sign in to comment.