Skip to content

Commit e9272e8

Browse files
committed
Support Connection.isValid method
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
1 parent 06755d5 commit e9272e8

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

Diff for: src/main/java/org/tarantool/jdbc/SQLConnection.java

+33-1
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
public class SQLConnection implements Connection {
4545

4646
private static final int UNSET_HOLDABILITY = 0;
47+
private static final String PING_QUERY = "SELECT 1";
4748

4849
private final TarantoolConnection connection;
4950

@@ -374,9 +375,40 @@ public SQLXML createSQLXML() throws SQLException {
374375
throw new SQLFeatureNotSupportedException();
375376
}
376377

378+
/**
379+
* {@inheritDoc}
380+
*
381+
* @param timeout temporally ignored param
382+
*
383+
* @return connection activity status
384+
*/
377385
@Override
378386
public boolean isValid(int timeout) throws SQLException {
379-
return true;
387+
if (timeout < 0) {
388+
throw new SQLNonTransientException(
389+
"Timeout cannot be negative",
390+
SQLStates.INVALID_PARAMETER_VALUE.getSqlState()
391+
);
392+
}
393+
if (isClosed()) {
394+
return false;
395+
}
396+
return checkConnection(timeout);
397+
}
398+
399+
private boolean checkConnection(int timeout) {
400+
ResultSet resultSet = null;
401+
try (Statement pingStatement = createStatement()) {
402+
// todo: before use timeout we need to provide query timeout per statement
403+
404+
resultSet = pingStatement.executeQuery(PING_QUERY);
405+
boolean isValid = resultSet.next() && resultSet.getInt(1) == 1;
406+
resultSet.close();
407+
408+
return isValid;
409+
} catch (SQLException e) {
410+
return false;
411+
}
380412
}
381413

382414
@Override

Diff for: src/test/java/org/tarantool/jdbc/JdbcConnectionIT.java

+9
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,15 @@ public void execute() throws Throwable {
113113
assertEquals(5, i);
114114
}
115115

116+
@Test
117+
void testIsValidCheck() throws SQLException {
118+
assertTrue(conn.isValid(2000));
119+
assertThrows(SQLException.class, () -> conn.isValid(-1000));
120+
121+
conn.close();
122+
assertFalse(conn.isValid(2000));
123+
}
124+
116125
@Test
117126
public void testConnectionUnwrap() throws SQLException {
118127
assertEquals(conn, conn.unwrap(SQLConnection.class));

0 commit comments

Comments
 (0)