Skip to content

Commit

Permalink
Support Connection.isValid method
Browse files Browse the repository at this point in the history
Add ping request to the DB using 'SELECT 1' expression. Timeout requires
the implementation of at least Statement.setQueryTimeout and
Statement.cancel.

Closes: #75
Depends on: #155
  • Loading branch information
nicktorwald committed Apr 9, 2019
1 parent 06755d5 commit e9272e8
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
34 changes: 33 additions & 1 deletion src/main/java/org/tarantool/jdbc/SQLConnection.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
public class SQLConnection implements Connection {

private static final int UNSET_HOLDABILITY = 0;
private static final String PING_QUERY = "SELECT 1";

private final TarantoolConnection connection;

Expand Down Expand Up @@ -374,9 +375,40 @@ public SQLXML createSQLXML() throws SQLException {
throw new SQLFeatureNotSupportedException();
}

/**
* {@inheritDoc}
*
* @param timeout temporally ignored param
*
* @return connection activity status
*/
@Override
public boolean isValid(int timeout) throws SQLException {
return true;
if (timeout < 0) {
throw new SQLNonTransientException(
"Timeout cannot be negative",
SQLStates.INVALID_PARAMETER_VALUE.getSqlState()
);
}
if (isClosed()) {
return false;
}
return checkConnection(timeout);
}

private boolean checkConnection(int timeout) {
ResultSet resultSet = null;
try (Statement pingStatement = createStatement()) {
// todo: before use timeout we need to provide query timeout per statement

resultSet = pingStatement.executeQuery(PING_QUERY);
boolean isValid = resultSet.next() && resultSet.getInt(1) == 1;
resultSet.close();

return isValid;
} catch (SQLException e) {
return false;
}
}

@Override
Expand Down
9 changes: 9 additions & 0 deletions src/test/java/org/tarantool/jdbc/JdbcConnectionIT.java
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,15 @@ public void execute() throws Throwable {
assertEquals(5, i);
}

@Test
void testIsValidCheck() throws SQLException {
assertTrue(conn.isValid(2000));
assertThrows(SQLException.class, () -> conn.isValid(-1000));

conn.close();
assertFalse(conn.isValid(2000));
}

@Test
public void testConnectionUnwrap() throws SQLException {
assertEquals(conn, conn.unwrap(SQLConnection.class));
Expand Down

0 comments on commit e9272e8

Please sign in to comment.