Search in sources :

Example 41 with SQLTimeoutException

use of java.sql.SQLTimeoutException in project drill by axbaretto.

the class PreparedStatementTest method testClientTriggeredQueryTimeout.

/**
 * Test setting timeout for a query that actually times out
 */
@Test
public void testClientTriggeredQueryTimeout() throws Exception {
    // Setting to a very low value (3sec)
    int timeoutDuration = 3;
    int rowsCounted = 0;
    try (PreparedStatement stmt = connection.prepareStatement(SYS_RANDOM_SQL)) {
        stmt.setQueryTimeout(timeoutDuration);
        logger.info("Set a timeout of {} seconds", stmt.getQueryTimeout());
        ResultSet rs = stmt.executeQuery();
        // Fetch each row and pause (simulate a slow client)
        try {
            while (rs.next()) {
                rs.getString(1);
                rowsCounted++;
                // Pause briefly (a second beyond the timeout) before attempting to fetch rows
                try {
                    Thread.sleep(TimeUnit.SECONDS.toMillis(timeoutDuration + 1));
                } catch (InterruptedException e) {
                /*DoNothing*/
                }
                logger.info("Paused for {} seconds", (timeoutDuration + 1));
            }
        } catch (SQLTimeoutException sqlEx) {
            logger.info("Counted " + rowsCounted + " rows before hitting timeout");
            // Successfully return
            return;
        }
    }
    // Throw an exception to indicate that we shouldn't have reached this point
    throw new Exception("Failed to trigger timeout of " + timeoutDuration + " sec");
}
Also used : ResultSet(java.sql.ResultSet) SQLTimeoutException(java.sql.SQLTimeoutException) PreparedStatement(java.sql.PreparedStatement) SQLFeatureNotSupportedException(java.sql.SQLFeatureNotSupportedException) SQLTimeoutException(java.sql.SQLTimeoutException) SQLException(java.sql.SQLException) Test(org.junit.Test) JdbcTest(org.apache.drill.categories.JdbcTest)

Example 42 with SQLTimeoutException

use of java.sql.SQLTimeoutException in project drill by axbaretto.

the class DrillJdbc41Factory method newServerPreparedStatement.

private DrillJdbc41PreparedStatement newServerPreparedStatement(DrillConnectionImpl connection, StatementHandle h, Meta.Signature signature, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
    String sql = signature.sql;
    try {
        DrillRpcFuture<CreatePreparedStatementResp> respFuture = connection.getClient().createPreparedStatement(signature.sql);
        CreatePreparedStatementResp resp;
        try {
            resp = respFuture.get();
        } catch (InterruptedException e) {
            // Preserve evidence that the interruption occurred so that code higher up
            // on the call stack can learn of the interruption and respond to it if it
            // wants to.
            Thread.currentThread().interrupt();
            throw new SQLException("Interrupted", e);
        }
        final RequestStatus status = resp.getStatus();
        if (status != RequestStatus.OK) {
            final String errMsgFromServer = resp.getError() != null ? resp.getError().getMessage() : "";
            if (status == RequestStatus.TIMEOUT) {
                logger.error("Request timed out to create prepare statement: {}", errMsgFromServer);
                throw new SQLTimeoutException("Failed to create prepared statement: " + errMsgFromServer);
            }
            if (status == RequestStatus.FAILED) {
                logger.error("Failed to create prepared statement: {}", errMsgFromServer);
                throw new SQLException("Failed to create prepared statement: " + errMsgFromServer);
            }
            logger.error("Failed to create prepared statement. Unknown status: {}, Error: {}", status, errMsgFromServer);
            throw new SQLException(String.format("Failed to create prepared statement. Unknown status: %s, Error: %s", status, errMsgFromServer));
        }
        return new DrillJdbc41PreparedStatement(connection, h, signature, resp.getPreparedStatement(), resultSetType, resultSetConcurrency, resultSetHoldability);
    } catch (SQLException e) {
        throw e;
    } catch (RuntimeException e) {
        throw Helper.INSTANCE.createException("Error while preparing statement [" + sql + "]", e);
    } catch (Exception e) {
        throw Helper.INSTANCE.createException("Error while preparing statement [" + sql + "]", e);
    }
}
Also used : SQLException(java.sql.SQLException) SQLTimeoutException(java.sql.SQLTimeoutException) CreatePreparedStatementResp(org.apache.drill.exec.proto.UserProtos.CreatePreparedStatementResp) SQLTimeoutException(java.sql.SQLTimeoutException) SQLException(java.sql.SQLException) RequestStatus(org.apache.drill.exec.proto.UserProtos.RequestStatus)

Example 43 with SQLTimeoutException

use of java.sql.SQLTimeoutException in project mssql-jdbc by Microsoft.

the class TVPWithSqlVariantTest method testNull.

/**
 * Test with null value
 *
 * @throws SQLException
 * @throws SQLTimeoutException
 */
// TODO We need to check this later. Right now sending null with TVP is not supported
@Test
public void testNull() throws SQLException {
    tvp = new SQLServerDataTable();
    tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT);
    try {
        tvp.addRow((Date) null);
    } catch (Exception e) {
        assertTrue(e.getMessage().startsWith("Use of TVPs containing null sql_variant columns is not supported."));
    }
    pstmt = (SQLServerPreparedStatement) connection.prepareStatement("INSERT INTO " + destTable + " select * from ? ;");
    pstmt.setStructured(1, tvpName, tvp);
    pstmt.execute();
    if (null != pstmt) {
        pstmt.close();
    }
    rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable);
    while (rs.next()) {
        System.out.println(rs.getString(1));
    }
}
Also used : SQLServerDataTable(com.microsoft.sqlserver.jdbc.SQLServerDataTable) SQLTimeoutException(java.sql.SQLTimeoutException) SQLException(java.sql.SQLException) AbstractTest(com.microsoft.sqlserver.testframework.AbstractTest) Test(org.junit.jupiter.api.Test)

Example 44 with SQLTimeoutException

use of java.sql.SQLTimeoutException in project cerberus-source by cerberustesting.

the class SQLService method queryDatabase.

@Override
public List<String> queryDatabase(String connectionName, String sql, int limit, int defaultTimeOut) throws CerberusEventException {
    List<String> list = null;
    boolean throwEx = false;
    int maxSecurityFetch = 100;
    int nbFetch = 0;
    MessageEvent msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_SQL_GENERIC);
    msg.setDescription(msg.getDescription().replace("%JDBC%", "jdbc/" + connectionName));
    try (Connection connection = this.databaseSpring.connect(connectionName);
        PreparedStatement preStat = connection.prepareStatement(sql)) {
        preStat.setQueryTimeout(defaultTimeOut);
        if (limit > 0 && limit < maxSecurityFetch) {
            preStat.setMaxRows(limit);
        } else {
            preStat.setMaxRows(maxSecurityFetch);
        }
        /*
             ORACLE      => * WHERE ROWNUM <= limit *
             DB2         => * FETCH FIRST limit ROWS ONLY
             MYSQL       => * LIMIT 0, limit
             SQL SERVER  => SELECT TOP limit *
             SYBASE      => SET ROWCOUNT limit *
             if (limit > 0) {
             sql.concat(Util.DbLimit(databaseType, limit));
             }
             */
        try {
            LOG.info("Sending to external Database (queryDatabase) : '" + connectionName + "' SQL '" + sql + "'");
            ResultSet resultSet = preStat.executeQuery();
            list = new ArrayList<String>();
            try {
                while ((resultSet.next()) && (nbFetch < maxSecurityFetch)) {
                    list.add(resultSet.getString(1));
                    nbFetch++;
                }
            } catch (SQLException exception) {
                LOG.warn("Unable to execute query : " + exception.toString());
            } finally {
                resultSet.close();
            }
        } catch (SQLTimeoutException exception) {
            msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_SQL_TIMEOUT);
            msg.setDescription(msg.getDescription().replace("%SQL%", sql));
            msg.setDescription(msg.getDescription().replace("%TIMEOUT%", String.valueOf(defaultTimeOut)));
            msg.setDescription(msg.getDescription().replace("%EX%", exception.toString()));
        } catch (SQLException exception) {
            LOG.warn(exception.toString());
            msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_SQL_ERROR);
            msg.setDescription(msg.getDescription().replace("%SQL%", sql));
            msg.setDescription(msg.getDescription().replace("%EX%", exception.toString()));
            throwEx = true;
        } finally {
            preStat.close();
        }
    } catch (SQLException exception) {
        LOG.warn(exception.toString());
        msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_SQL_ERROR);
        msg.setDescription(msg.getDescription().replace("%SQL%", sql));
        msg.setDescription(msg.getDescription().replace("%EX%", exception.toString()));
        throwEx = true;
    } catch (NullPointerException exception) {
        // TODO check where exception occur
        LOG.warn(exception.toString());
        msg = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_SQL_CANNOTACCESSJDBC);
        msg.setDescription(msg.getDescription().replace("%JDBC%", "jdbc/" + connectionName));
        msg.setDescription(msg.getDescription().replace("%EX%", exception.toString()));
        throwEx = true;
    }
    if (throwEx) {
        throw new CerberusEventException(msg);
    }
    return list;
}
Also used : SQLException(java.sql.SQLException) MessageEvent(org.cerberus.engine.entity.MessageEvent) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) CerberusEventException(org.cerberus.exception.CerberusEventException) ResultSet(java.sql.ResultSet) SQLTimeoutException(java.sql.SQLTimeoutException)

Example 45 with SQLTimeoutException

use of java.sql.SQLTimeoutException in project drill by apache.

the class DrillJdbc41Factory method newServerPreparedStatement.

private DrillJdbc41PreparedStatement newServerPreparedStatement(DrillConnectionImpl connection, StatementHandle h, Meta.Signature signature, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
    String sql = signature.sql;
    try {
        DrillRpcFuture<CreatePreparedStatementResp> respFuture = connection.getClient().createPreparedStatement(signature.sql);
        CreatePreparedStatementResp resp;
        try {
            resp = respFuture.get();
        } catch (InterruptedException e) {
            // Preserve evidence that the interruption occurred so that code higher up
            // on the call stack can learn of the interruption and respond to it if it
            // wants to.
            Thread.currentThread().interrupt();
            throw new SQLException("Interrupted", e);
        }
        final RequestStatus status = resp.getStatus();
        if (status != RequestStatus.OK) {
            final String errMsgFromServer = resp.getError() != null ? resp.getError().getMessage() : "";
            if (status == RequestStatus.TIMEOUT) {
                logger.error("Request timed out to create prepare statement: {}", errMsgFromServer);
                throw new SQLTimeoutException("Failed to create prepared statement: " + errMsgFromServer);
            }
            if (status == RequestStatus.FAILED) {
                logger.error("Failed to create prepared statement: {}", errMsgFromServer);
                throw new SQLException("Failed to create prepared statement: " + errMsgFromServer);
            }
            logger.error("Failed to create prepared statement. Unknown status: {}, Error: {}", status, errMsgFromServer);
            throw new SQLException(String.format("Failed to create prepared statement. Unknown status: %s, Error: %s", status, errMsgFromServer));
        }
        return new DrillJdbc41PreparedStatement(connection, h, signature, resp.getPreparedStatement(), resultSetType, resultSetConcurrency, resultSetHoldability);
    } catch (SQLException e) {
        throw e;
    } catch (Exception e) {
        throw Helper.INSTANCE.createException("Error while preparing statement [" + sql + "]", e);
    }
}
Also used : SQLException(java.sql.SQLException) SQLTimeoutException(java.sql.SQLTimeoutException) CreatePreparedStatementResp(org.apache.drill.exec.proto.UserProtos.CreatePreparedStatementResp) SQLTimeoutException(java.sql.SQLTimeoutException) SQLException(java.sql.SQLException) RequestStatus(org.apache.drill.exec.proto.UserProtos.RequestStatus)

Aggregations

SQLTimeoutException (java.sql.SQLTimeoutException)53 SQLException (java.sql.SQLException)36 ResultSet (java.sql.ResultSet)20 Statement (java.sql.Statement)17 Test (org.testng.annotations.Test)15 Test (org.junit.Test)14 BaseTest (util.BaseTest)14 Connection (java.sql.Connection)12 PreparedStatement (java.sql.PreparedStatement)10 JdbcTest (org.apache.drill.categories.JdbcTest)8 SQLFeatureNotSupportedException (java.sql.SQLFeatureNotSupportedException)7 ArrayList (java.util.ArrayList)7 HadoopException (org.apache.ranger.plugin.client.HadoopException)6 ScreenCreator (org.apache.drill.exec.physical.impl.ScreenCreator)4 MessageEvent (org.cerberus.engine.entity.MessageEvent)4 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)3 Ignore (org.junit.Ignore)3 IOException (java.io.IOException)2 BatchUpdateException (java.sql.BatchUpdateException)2 CallableStatement (java.sql.CallableStatement)2