java.sql.SQLNonTransientException Java Examples

The following examples show how to use java.sql.SQLNonTransientException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DruidLockTableParser.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
private void handleSingleViewLock(Map<String, Set<String>> dataNodeToLocks, PlanNode viewQuery, String alias, MySqlLockTableStatement.LockType lockType, String schemaName) throws SQLNonTransientException {
    Map<String, Set<String>> tableMap = new HashMap<>();
    findTableInPlanNode(tableMap, viewQuery, schemaName);
    for (Map.Entry<String, Set<String>> entry : tableMap.entrySet()) {
        SchemaConfig schemaConfig = DbleServer.getInstance().getConfig().getSchemas().get(entry.getKey());
        for (String table : entry.getValue()) {
            TableConfig tableConfig = schemaConfig.getTables().get(table);
            if (tableConfig != null) {
                handleConfigTable(dataNodeToLocks, tableConfig, alias == null ? null : "view_" + alias + "_" + table, lockType);
            } else if (ProxyMeta.getInstance().getTmManager().getSyncTableMeta(schemaConfig.getName(), table) != null) {
                handleNoshardTable(dataNodeToLocks, table, schemaConfig.getDataNode(), alias == null ? null : "view_" + alias + "_" + table, lockType);
            } else {
                String msg = "Table '" + schemaConfig.getName() + "." + table + "' doesn't exist";
                LOGGER.info(msg);
                throw new SQLNonTransientException(msg);
            }
        }
    }
    return;
}
 
Example #2
Source File: AbstractFbStatement.java    From jaybird with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public SqlCountHolder getSqlCounts() throws SQLException {
    try {
        checkStatementValid();
        if (getState() == StatementState.CURSOR_OPEN && !isAllRowsFetched()) {
            // We disallow fetching count when we haven't fetched all rows yet.
            // TODO SQLState
            throw new SQLNonTransientException("Cursor still open, fetch all rows or close cursor before fetching SQL counts");
        }
    } catch (SQLException e) {
        exceptionListenerDispatcher.errorOccurred(e);
        throw e;
    }
    final SqlCountProcessor countProcessor = createSqlCountProcessor();
    // NOTE: implementation of SqlCountProcessor assumes the specified size is sufficient (actual requirement is 49 bytes max) and does not handle truncation
    final SqlCountHolder sqlCounts = getSqlInfo(countProcessor.getRecordCountInfoItems(), 64, countProcessor);
    statementListenerDispatcher.sqlCounts(this, sqlCounts);
    return sqlCounts;
}
 
Example #3
Source File: SQLNonTransientExceptionTests.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Validate that the ordering of the returned Exceptions is correct
 * using traditional while loop
 */
@Test
public void test12() {
    SQLNonTransientException ex = new SQLNonTransientException("Exception 1", t1);
    SQLNonTransientException ex1 = new SQLNonTransientException("Exception 2");
    SQLNonTransientException ex2 = new SQLNonTransientException("Exception 3", t2);
    ex.setNextException(ex1);
    ex.setNextException(ex2);
    int num = 0;
    SQLException sqe = ex;
    while (sqe != null) {
        assertTrue(msgs[num++].equals(sqe.getMessage()));
        Throwable c = sqe.getCause();
        while (c != null) {
            assertTrue(msgs[num++].equals(c.getMessage()));
            c = c.getCause();
        }
        sqe = sqe.getNextException();
    }
}
 
Example #4
Source File: RouterUtil.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
private static boolean findRouterWithConditionsForTable(
        RouteResultset rrs, Map<Pair<String, String>, Set<String>> tablesRouteMap,
        Pair<String, String> table, TableConfig tableConfig,
        Map<String, ColumnRoute> columnsMap) throws SQLNonTransientException {
    String joinKey = tableConfig.getJoinKey();
    String partitionCol = tableConfig.getPartitionColumn();
    boolean isFoundPartitionValue = partitionCol != null && columnsMap.get(partitionCol) != null;

    // where filter contains partition column
    if (isFoundPartitionValue) {
        ColumnRoute partitionValue = columnsMap.get(partitionCol);
        Set<String> dataNodeSet = ruleCalculate(rrs, tableConfig, partitionValue, rrs.isComplexSQL());
        if (dataNodeSet.size() > 0) {
            tablesRouteMap.computeIfAbsent(table, k -> new HashSet<>());
            tablesRouteMap.get(table).addAll(dataNodeSet);
        }
    } else if (joinKey != null && columnsMap.get(joinKey) != null) {
        routerForJoinTable(rrs, tableConfig, columnsMap, joinKey);
        return true;
    } else {
        //no partition column,router to all nodes
        tablesRouteMap.computeIfAbsent(table, k -> new HashSet<>());
        tablesRouteMap.get(table).addAll(tableConfig.getDataNodes());
    }
    return false;
}
 
Example #5
Source File: AbstractFbStatement.java    From jaybird with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Checks if this statement is not in {@link StatementState#CLOSED}, {@link StatementState#CLOSING},
 * {@link StatementState#NEW} or {@link StatementState#ERROR}, and throws an <code>SQLException</code> if it is.
 *
 * @throws SQLException
 *         When this statement is closed or in error state.
 */
protected final void checkStatementValid() throws SQLException {
    switch (getState()) {
    case NEW:
        // TODO Externalize sqlstate
        // TODO See if there is a firebird error code matching this (isc_cursor_not_open is not exactly the same)
        throw new SQLNonTransientException("Statement not yet allocated", "24000");
    case CLOSING:
    case CLOSED:
        // TODO Externalize sqlstate
        // TODO See if there is a firebird error code matching this (isc_cursor_not_open is not exactly the same)
        throw new SQLNonTransientException("Statement closed", "24000");
    case ERROR:
        // TODO SQLState?
        // TODO See if there is a firebird error code matching this
        throw new SQLNonTransientException("Statement is in error state and needs to be closed");
    default:
        // Valid state, continue
        break;
    }
}
 
Example #6
Source File: RouterUtil.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
/**
 * findRouterForMultiSchemaTables
 */
private static void findRouterForMultiSchemaTables(
        Map<Pair<String, String>, SchemaConfig> schemaMap, RouteResultset rrs,
        Map<Pair<String, String>, Map<String, ColumnRoute>> tablesAndConditions,
        Map<Pair<String, String>, Set<String>> tablesRouteMap) throws SQLNonTransientException {

    //router for shard-ing tables
    for (Map.Entry<Pair<String, String>, Map<String, ColumnRoute>> entry : tablesAndConditions.entrySet()) {
        Pair<String, String> table = entry.getKey();
        String tableName = table.getValue();
        SchemaConfig schema = schemaMap.get(table);
        TableConfig tableConfig = schema.getTables().get(tableName);
        if (tableConfig != null && !tableConfig.isGlobalTable() && schema.getTables().get(tableName).getDataNodes().size() != 1) {
            //shard-ing table,childTable or others
            if (findRouterWithConditionsForTable(rrs, tablesRouteMap, table, tableConfig, entry.getValue()))
                return;
        }
    }
}
 
Example #7
Source File: TestJnaBlob.java    From jaybird with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Test double open is not allowed.
 */
@Test
public void testOutputBlobDoubleOpen() throws Exception {
    expectedException.expect(SQLNonTransientException.class);
    expectedException.expect(allOf(
            errorCodeEquals(ISCConstants.isc_segstr_no_op),
            fbMessageStartsWith(ISCConstants.isc_segstr_no_op)
    ));

    try (JnaDatabase db = createDatabaseConnection()) {
        final FbTransaction transaction = getTransaction(db);
        try {
            final FbBlob blob = db.createBlobForOutput(transaction, null);
            blob.open();
            blob.open();
        } finally {
            transaction.commit();
        }
    }
}
 
Example #8
Source File: RouterUtil.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
private static boolean tryRouteNoShardingTablesToOneNode(Set<String> tmpResultNodes, Set<Pair<String, String>> tablesSet, Pair<String, String> table, String schemaName, String tableName, SchemaConfig schema) throws SQLNonTransientException {
    //may view
    if (ProxyMeta.getInstance().getTmManager().getSyncView(schemaName, tableName) != null) {
        return true;
    }
    if (schema.getDataNode() == null) {
        String msg = " Table '" + schemaName + "." + tableName + "' doesn't exist";
        LOGGER.info(msg);
        throw new SQLNonTransientException(msg);
    } else {
        tmpResultNodes.add(schema.getDataNode());
        tablesSet.remove(table);
        if (tmpResultNodes.size() != 1) {
            return true;
        }
    }
    return false;
}
 
Example #9
Source File: DefaultDruidParser.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
@Override
public SchemaConfig visitorParse(SchemaConfig schemaConfig, RouteResultset rrs, SQLStatement stmt, ServerSchemaStatVisitor visitor, ServerConnection sc, boolean isExplain)
        throws SQLException {
    stmt.accept(visitor);
    if (visitor.getNotSupportMsg() != null) {
        throw new SQLNonTransientException(visitor.getNotSupportMsg());
    }
    String schemaName = null;
    if (schemaConfig != null) {
        schemaName = schemaConfig.getName();
    }
    Map<String, String> tableAliasMap = getTableAliasMap(schemaName, visitor.getAliasMap());
    ctx.setRouteCalculateUnits(ConditionUtil.buildRouteCalculateUnits(visitor.getAllWhereUnit(), tableAliasMap, schemaName));

    return schemaConfig;
}
 
Example #10
Source File: RouterUtil.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
/**
 * no shard-ing table dataNode
 *
 * @param schemaConfig the SchemaConfig info
 * @param tableName    the TableName
 * @return dataNode DataNode of no-sharding table
 */
public static String isNoSharding(SchemaConfig schemaConfig, String tableName) throws SQLNonTransientException {
    if (schemaConfig == null || ProxyMeta.getInstance().getTmManager().getSyncView(schemaConfig.getName(), tableName) instanceof QueryNode) {
        return null;
    }
    if (schemaConfig.isNoSharding()) { //schema without table
        return schemaConfig.getDataNode();
    }
    TableConfig tbConfig = schemaConfig.getTables().get(tableName);
    if (tbConfig == null && schemaConfig.getDataNode() != null) {
        return schemaConfig.getDataNode();
    }
    if (tbConfig != null && tbConfig.isNoSharding()) {
        return tbConfig.getDataNodes().get(0);
    }
    return null;
}
 
Example #11
Source File: InsertHandler.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(DumpFileContext context, SQLStatement sqlStatement) throws InterruptedException {
    MySqlInsertStatement insert = (MySqlInsertStatement) sqlStatement;
    SQLInsertStatement.ValuesClause valueClause;

    valuesHandler.preProcess(context);
    for (int i = 0; i < insert.getValuesList().size(); i++) {
        valueClause = insert.getValuesList().get(i);
        try {
            processIncrementColumn(context, valueClause.getValues());
            valuesHandler.process(context, valueClause.getValues(), i == 0);
        } catch (SQLNonTransientException e) {
            context.addError(e.getMessage());
        }
    }
    valuesHandler.postProcess(context);
}
 
Example #12
Source File: DruidMysqlHavingTest.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testHaving() throws SQLNonTransientException {
	String sql = "select avg(offer_id) avgofferid, member_id from offer_detail group by member_id having avgofferid > 100";
	SchemaConfig schema = schemaMap.get("cndb");
       RouteResultset rrs = routeStrategy.route(new SystemConfig(), schema, -1, sql, null,
               null, cachePool);
       Assert.assertEquals(3, rrs.getSqlMerge().getHavingColsName().length);

	sql = "select avg(offer_id) avgofferid, member_id from offer_detail group by member_id having avg(offer_id) > 100";
       rrs = routeStrategy.route(new SystemConfig(), schema, -1, sql, null,
               null, cachePool);
       Assert.assertEquals(3, rrs.getSqlMerge().getHavingColsName().length);

       sql = "select count(offer_id) countofferid, member_id from offer_detail group by member_id having countofferid > 100";
       rrs = routeStrategy.route(new SystemConfig(), schema, -1, sql, null,
               null, cachePool);
       Assert.assertEquals(3, rrs.getSqlMerge().getHavingColsName().length);

       sql = "select count(offer_id) countofferid, member_id from offer_detail group by member_id having count(offer_id) > 100";
       rrs = routeStrategy.route(new SystemConfig(), schema, -1, sql, null,
               null, cachePool);
       Assert.assertEquals(3, rrs.getSqlMerge().getHavingColsName().length);

}
 
Example #13
Source File: SQLNonTransientExceptionTests.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Serialize a SQLNonTransientException and make sure you can read it back properly
 */
@Test
public void test10() throws Exception {
    SQLNonTransientException e =
            new SQLNonTransientException(reason, state, errorCode, t);
    SQLNonTransientException ex1 =
            createSerializedException(e);
    assertTrue(reason.equals(ex1.getMessage())
            && ex1.getSQLState().equals(state)
            && cause.equals(ex1.getCause().toString())
            && ex1.getErrorCode() == errorCode);
}
 
Example #14
Source File: PutHiveQL.java    From nifi with Apache License 2.0 5 votes vote down vote up
@OnScheduled
public void constructProcess() {
    exceptionHandler = new ExceptionHandler<>();
    exceptionHandler.mapException(e -> {
        if (e instanceof SQLNonTransientException) {
            return ErrorTypes.InvalidInput;
        } else if (e instanceof SQLException) {
            // Use the SQLException's vendor code for guidance -- see Hive's ErrorMsg class for details on error codes
            int errorCode = ((SQLException) e).getErrorCode();
            getLogger().debug("Error occurred during Hive operation, Hive returned error code {}", new Object[]{errorCode});
            if (errorCode >= 10000 && errorCode < 20000) {
                return ErrorTypes.InvalidInput;
            } else if (errorCode >= 20000 && errorCode < 30000) {
                return ErrorTypes.InvalidInput;
            } else if (errorCode >= 30000 && errorCode < 40000) {
                return ErrorTypes.TemporalInputFailure;
            } else if (errorCode >= 40000 && errorCode < 50000) {
                // These are unknown errors (to include some parse errors), but rather than generating an UnknownFailure which causes
                // a ProcessException, we'll route to failure via an InvalidInput error type.
                return ErrorTypes.InvalidInput;
            } else {
                // Default unknown errors to TemporalFailure (as they were implemented originally), so they can be routed to failure
                // or rolled back depending on the user's setting of Rollback On Failure.
                return ErrorTypes.TemporalFailure;
            }
        } else {
            return ErrorTypes.UnknownFailure;
        }
    });
    exceptionHandler.adjustError(RollbackOnFailure.createAdjustError(getLogger()));

    process = new Put<>();
    process.setLogger(getLogger());
    process.initConnection(initConnection);
    process.fetchFlowFiles(fetchFlowFiles);
    process.putFlowFile(putFlowFile);
    process.adjustRoute(RollbackOnFailure.createAdjustRoute(REL_FAILURE, REL_RETRY));
}
 
Example #15
Source File: SQLExceptionSubclassTranslator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected DataAccessException doTranslate(String task, String sql, SQLException ex) {
	if (ex instanceof SQLTransientException) {
		if (ex instanceof SQLTransientConnectionException) {
			return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLTransactionRollbackException) {
			return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLTimeoutException) {
			return new QueryTimeoutException(buildMessage(task, sql, ex), ex);
		}
	}
	else if (ex instanceof SQLNonTransientException) {
		if (ex instanceof SQLNonTransientConnectionException) {
			return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLDataException) {
			return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLIntegrityConstraintViolationException) {
			return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLInvalidAuthorizationSpecException) {
			return new PermissionDeniedDataAccessException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLSyntaxErrorException) {
			return new BadSqlGrammarException(task, sql, ex);
		}
		else if (ex instanceof SQLFeatureNotSupportedException) {
			return new InvalidDataAccessApiUsageException(buildMessage(task, sql, ex), ex);
		}
	}
	else if (ex instanceof SQLRecoverableException) {
		return new RecoverableDataAccessException(buildMessage(task, sql, ex), ex);
	}

	// Fallback to Spring's own SQL state translation...
	return null;
}
 
Example #16
Source File: AbstractWithTimeZoneField.java    From jaybird with GNU Lesser General Public License v2.1 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> T getObject(Class<T> type) throws SQLException {
    if (type == null) {
        throw new SQLNonTransientException("getObject called with type null");
    }
    switch (type.getName()) {
    case OFFSET_TIME_CLASS_NAME:
        return (T) getOffsetTime();
    case OFFSET_DATE_TIME_CLASS_NAME:
        return (T) getOffsetDateTime();
    }
    return super.getObject(type);
}
 
Example #17
Source File: TestV10OutputBlobMock.java    From jaybird with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Test if calling {@link org.firebirdsql.gds.ng.wire.version10.V10OutputBlob#seek(int, org.firebirdsql.gds.ng.FbBlob.SeekMode)}
 * throws a {@link java.sql.SQLNonTransientException} with error {@link org.firebirdsql.gds.ISCConstants#isc_segstr_no_read}.
 */
@Test
public final void testSeek() throws Exception {
    expectedException.expect(SQLNonTransientException.class);
    expectedException.expect(allOf(
            errorCodeEquals(ISCConstants.isc_segstr_no_read),
            fbMessageStartsWith(ISCConstants.isc_segstr_no_read)
    ));

    V10OutputBlob blob = new V10OutputBlob(db, transaction, null);

    blob.seek(0, FbBlob.SeekMode.ABSOLUTE);
}
 
Example #18
Source File: SQLNonTransientExceptionTests.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create SQLNonTransientException with message, and Throwable
 */
@Test
public void test7() {
    SQLNonTransientException ex = new SQLNonTransientException(reason, t);
    assertTrue(ex.getMessage().equals(reason)
            && ex.getSQLState() == null
            && cause.equals(ex.getCause().toString())
            && ex.getErrorCode() == 0);
}
 
Example #19
Source File: SQLNonTransientExceptionTests.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create SQLNonTransientException with message, SQLState, and error code
 */
@Test
public void test4() {;
    SQLNonTransientException ex =
            new SQLNonTransientException(reason, state, errorCode);
    assertTrue(ex.getMessage().equals(reason)
            && ex.getSQLState().equals(state)
            && ex.getCause() == null
            && ex.getErrorCode() == errorCode);
}
 
Example #20
Source File: ManagedPreparedStatement.java    From cassandra-jdbc-wrapper with Apache License 2.0 5 votes vote down vote up
@Override
public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {
	try {
	    String targetString = CharStreams.toString(reader);
	    reader.close();
	    
	    setString(parameterIndex, targetString);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		throw new SQLNonTransientException(e);
	}
	
}
 
Example #21
Source File: DruidUpdateParser.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
private static boolean columnInExpr(SQLExpr sqlExpr, String colName) throws SQLNonTransientException {
    String column;
    if (sqlExpr instanceof SQLIdentifierExpr) {
        column = StringUtil.removeBackQuote(((SQLIdentifierExpr) sqlExpr).getName()).toUpperCase();
    } else if (sqlExpr instanceof SQLPropertyExpr) {
        column = StringUtil.removeBackQuote(((SQLPropertyExpr) sqlExpr).getName()).toUpperCase();
    } else {
        throw new SQLNonTransientException("Unhandled SQL AST node type encountered: " + sqlExpr.getClass());
    }

    return column.equals(colName.toUpperCase());
}
 
Example #22
Source File: SQLNonTransientExceptionTests.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create SQLNonTransientException with message, and Throwable
 */
@Test
public void test7() {
    SQLNonTransientException ex = new SQLNonTransientException(reason, t);
    assertTrue(ex.getMessage().equals(reason)
            && ex.getSQLState() == null
            && cause.equals(ex.getCause().toString())
            && ex.getErrorCode() == 0);
}
 
Example #23
Source File: MysqlDropViewHandler.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void okResponse(byte[] data, BackendConnection conn) {
    boolean executeResponse = conn.syncAndExecute();
    if (!executeResponse) {
        return;
    }

    if (viewNum.decrementAndGet() == 0) {
        if (vm != null) {
            try {
                vm.addMeta(true);
            } catch (SQLNonTransientException e) {
                ErrorPacket errPkg = new ErrorPacket();
                errPkg.setPacketId(++packetId);
                errPkg.setMessage(StringUtil.encode(e.getMessage(), session.getSource().getCharset().getResults()));
                backConnectionErr(errPkg, conn, conn.syncAndExecute());
                return;
            }
        }

        // return ok
        OkPacket ok = new OkPacket();
        ok.read(data);
        ok.setPacketId(++packetId); // OK_PACKET
        ok.setServerStatus(session.getSource().isAutocommit() ? 2 : 1);
        session.setBackendResponseEndTime((MySQLConnection) conn);
        session.releaseConnectionIfSafe(conn, false);
        session.setResponseTime(true);
        session.multiStatementPacket(ok, packetId);
        boolean multiStatementFlag = session.getIsMultiStatement().get();
        ok.write(session.getSource());
        session.multiStatementNextSql(multiStatementFlag);
    }
}
 
Example #24
Source File: AbstractStatementTest.java    From jaybird with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void test_GetExplainedExecutionPlan_noStatementPrepared() throws Exception {
    allocateStatement();
    expectedException.expect(SQLNonTransientException.class);
    expectedException.expectMessage("Statement not yet allocated");

    statement.getExplainedExecutionPlan();
}
 
Example #25
Source File: InsertHandler.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
private void processIncrementColumn(DumpFileContext context, List<SQLExpr> values) throws SQLNonTransientException {
    int incrementIndex = context.getIncrementColumnIndex();
    if (incrementIndex == -1) {
        return;
    }

    String tableKey = StringUtil.getFullName(context.getSchema(), context.getTable());
    long val = SequenceManager.getHandler().nextId(tableKey);
    SQLExpr value = values.get(incrementIndex);
    if (!StringUtil.isEmpty(SQLUtils.toMySqlString(value)) && !context.isNeedSkipError()) {
        context.addError("For table using global sequence, dble has set increment column values for you.");
        context.setNeedSkipError(true);
    }
    values.set(incrementIndex, new SQLIntegerExpr(val));
}
 
Example #26
Source File: TestV10OutputBlobMock.java    From jaybird with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Test if calling {@link org.firebirdsql.gds.ng.wire.version10.V10OutputBlob#getSegment(int)} throws
 * a {@link java.sql.SQLNonTransientException} with error {@link org.firebirdsql.gds.ISCConstants#isc_segstr_no_read}.
 */
@Test
public final void testGetSegment() throws Exception {
    expectedException.expect(SQLNonTransientException.class);
    expectedException.expect(allOf(
            errorCodeEquals(ISCConstants.isc_segstr_no_read),
            fbMessageStartsWith(ISCConstants.isc_segstr_no_read)
    ));

    V10OutputBlob blob = new V10OutputBlob(db, transaction, null);

    blob.getSegment(1);
}
 
Example #27
Source File: AbstractStatementTest.java    From jaybird with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void test_GetExecutionPlan_noStatementPrepared() throws Exception {
    allocateStatement();
    expectedException.expect(SQLNonTransientException.class);
    expectedException.expectMessage("Statement not yet allocated");

    statement.getExecutionPlan();
}
 
Example #28
Source File: PutHive_1_1QL.java    From nifi with Apache License 2.0 5 votes vote down vote up
@OnScheduled
public void constructProcess() {
    exceptionHandler = new ExceptionHandler<>();
    exceptionHandler.mapException(e -> {
        if (e instanceof SQLNonTransientException) {
            return ErrorTypes.InvalidInput;
        } else if (e instanceof SQLException) {
            // Use the SQLException's vendor code for guidance -- see Hive's ErrorMsg class for details on error codes
            int errorCode = ((SQLException) e).getErrorCode();
            getLogger().debug("Error occurred during Hive operation, Hive returned error code {}", new Object[]{errorCode});
            if (errorCode >= 10000 && errorCode < 20000) {
                return ErrorTypes.InvalidInput;
            } else if (errorCode >= 20000 && errorCode < 30000) {
                return ErrorTypes.InvalidInput;
            } else if (errorCode >= 30000 && errorCode < 40000) {
                return ErrorTypes.TemporalInputFailure;
            } else if (errorCode >= 40000 && errorCode < 50000) {
                // These are unknown errors (to include some parse errors), but rather than generating an UnknownFailure which causes
                // a ProcessException, we'll route to failure via an InvalidInput error type.
                return ErrorTypes.InvalidInput;
            } else {
                // Default unknown errors to TemporalFailure (as they were implemented originally), so they can be routed to failure
                // or rolled back depending on the user's setting of Rollback On Failure.
                return ErrorTypes.TemporalFailure;
            }
        } else {
            return ErrorTypes.UnknownFailure;
        }
    });
    exceptionHandler.adjustError(RollbackOnFailure.createAdjustError(getLogger()));

    process = new Put<>();
    process.setLogger(getLogger());
    process.initConnection(initConnection);
    process.fetchFlowFiles(fetchFlowFiles);
    process.putFlowFile(putFlowFile);
    process.adjustRoute(RollbackOnFailure.createAdjustRoute(REL_FAILURE, REL_RETRY));
}
 
Example #29
Source File: SQLNonTransientExceptionTests.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create SQLNonTransientException with message, SQLState, errorCode, and Throwable
 */
@Test
public void test5() {
    SQLNonTransientException ex =
            new SQLNonTransientException(reason, state, errorCode, t);
    assertTrue(ex.getMessage().equals(reason)
            && ex.getSQLState().equals(state)
            && cause.equals(ex.getCause().toString())
            && ex.getErrorCode() == errorCode);
}
 
Example #30
Source File: SQLNonTransientExceptionTests.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Serialize a SQLNonTransientException and make sure you can read it back properly
 */
@Test
public void test10() throws Exception {
    SQLNonTransientException e =
            new SQLNonTransientException(reason, state, errorCode, t);
    SQLNonTransientException ex1 =
            createSerializedException(e);
    assertTrue(reason.equals(ex1.getMessage())
            && ex1.getSQLState().equals(state)
            && cause.equals(ex1.getCause().toString())
            && ex1.getErrorCode() == errorCode);
}