Skip to content

Commit df814c2

Browse files
committed
Use 'SELECT 1' expression as a ping request to an underlying database.
The current implementation lacks of timeout support because it would require at least Statement.setQueryTimeout() and Statement.cancel(). This will be implemented in the scope of #155. Closes: #75
1 parent 8b72cf2 commit df814c2

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

@@ -382,9 +383,40 @@ public SQLXML createSQLXML() throws SQLException {
382383
throw new SQLFeatureNotSupportedException();
383384
}
384385

386+
/**
387+
* {@inheritDoc}
388+
*
389+
* @param timeout temporally ignored param
390+
*
391+
* @return connection activity status
392+
*/
385393
@Override
386394
public boolean isValid(int timeout) throws SQLException {
387-
return true;
395+
if (timeout < 0) {
396+
throw new SQLNonTransientException(
397+
"Timeout cannot be negative",
398+
SQLStates.INVALID_PARAMETER_VALUE.getSqlState()
399+
);
400+
}
401+
if (isClosed()) {
402+
return false;
403+
}
404+
return checkConnection(timeout);
405+
}
406+
407+
private boolean checkConnection(int timeout) {
408+
ResultSet resultSet = null;
409+
try (Statement pingStatement = createStatement()) {
410+
// todo: before use timeout we need to provide query timeout per statement
411+
412+
resultSet = pingStatement.executeQuery(PING_QUERY);
413+
boolean isValid = resultSet.next() && resultSet.getInt(1) == 1;
414+
resultSet.close();
415+
416+
return isValid;
417+
} catch (SQLException e) {
418+
return false;
419+
}
388420
}
389421

390422
@Override

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

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

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

0 commit comments

Comments
 (0)