Search in sources :

Example 81 with SQLNonTransientException

use of java.sql.SQLNonTransientException in project jaybird by FirebirdSQL.

the class V11Statement method prepare.

@Override
public void prepare(final String statementText) throws SQLException {
    try {
        synchronized (getSynchronizationObject()) {
            checkTransactionActive(getTransaction());
            final StatementState currentState = getState();
            if (!isPrepareAllowed(currentState)) {
                throw new SQLNonTransientException(String.format("Current statement state (%s) does not allow call to prepare", currentState));
            }
            resetAll();
            int expectedResponseCount = 0;
            try {
                if (currentState == StatementState.NEW) {
                    sendAllocate();
                    expectedResponseCount++;
                } else {
                    checkStatementValid();
                }
                sendPrepare(statementText);
                expectedResponseCount++;
                getXdrOut().flush();
            } catch (IOException ex) {
                switchState(StatementState.ERROR);
                throw new FbExceptionBuilder().exception(ISCConstants.isc_net_write_err).cause(ex).toSQLException();
            }
            try {
                final FbWireDatabase db = getDatabase();
                try {
                    if (currentState == StatementState.NEW) {
                        expectedResponseCount--;
                        processAllocateResponse(db.readGenericResponse(getStatementWarningCallback()));
                    }
                    expectedResponseCount--;
                    processPrepareResponse(db.readGenericResponse(getStatementWarningCallback()));
                } finally {
                    db.consumePackets(expectedResponseCount, getStatementWarningCallback());
                }
            } catch (IOException ex) {
                switchState(StatementState.ERROR);
                throw new FbExceptionBuilder().exception(ISCConstants.isc_net_read_err).cause(ex).toSQLException();
            }
        }
    } catch (SQLException e) {
        exceptionListenerDispatcher.errorOccurred(e);
        throw e;
    }
}
Also used : StatementState(org.firebirdsql.gds.ng.StatementState) SQLNonTransientException(java.sql.SQLNonTransientException) SQLException(java.sql.SQLException) FbExceptionBuilder(org.firebirdsql.gds.ng.FbExceptionBuilder) IOException(java.io.IOException) FbWireDatabase(org.firebirdsql.gds.ng.wire.FbWireDatabase)

Example 82 with SQLNonTransientException

use of java.sql.SQLNonTransientException in project jaybird by FirebirdSQL.

the class AbstractFbStatement method validateParameters.

/**
 * Validates if the number of parameters matches the expected number and types, and if all values have been set.
 *
 * @param parameters
 *         Parameter values to validate
 * @throws SQLException
 *         When the number or type of parameters does not match {@link #getParameterDescriptor()}, or when a parameter has not been set.
 */
protected void validateParameters(final RowValue parameters) throws SQLException {
    final RowDescriptor parameterDescriptor = getParameterDescriptor();
    final int expectedSize = parameterDescriptor != null ? parameterDescriptor.getCount() : 0;
    final int actualSize = parameters.getCount();
    // TODO Externalize sqlstates
    if (actualSize != expectedSize) {
        // TODO use HY021 (inconsistent descriptor information) instead?
        throw new SQLNonTransientException(String.format("Invalid number of parameters, expected %d, got %d", expectedSize, actualSize), // invalid descriptor count
        "07008");
    }
    for (int fieldIndex = 0; fieldIndex < actualSize; fieldIndex++) {
        FieldValue fieldValue = parameters.getFieldValue(fieldIndex);
        if (fieldValue == null || !fieldValue.isInitialized()) {
            // TODO use HY000 (dynamic parameter value needed) instead?
            throw new SQLTransientException(String.format("Parameter with index %d was not set", fieldIndex + 1), // undefined DATA value
            "0700C");
        }
    }
}
Also used : SQLNonTransientException(java.sql.SQLNonTransientException) SQLTransientException(java.sql.SQLTransientException) FieldValue(org.firebirdsql.gds.ng.fields.FieldValue) RowDescriptor(org.firebirdsql.gds.ng.fields.RowDescriptor)

Example 83 with SQLNonTransientException

use of java.sql.SQLNonTransientException in project Mycat_plus by coderczp.

the class RouterUtil method ruleByJoinValueCalculate.

/**
 * @return dataNodeIndex -&gt; [partitionKeysValueTuple+]
 */
public static Set<String> ruleByJoinValueCalculate(RouteResultset rrs, TableConfig tc, Set<ColumnRoutePair> colRoutePairSet) throws SQLNonTransientException {
    String joinValue = "";
    if (colRoutePairSet.size() > 1) {
        LOGGER.warn("joinKey can't have multi Value");
    } else {
        Iterator<ColumnRoutePair> it = colRoutePairSet.iterator();
        ColumnRoutePair joinCol = it.next();
        joinValue = joinCol.colValue;
    }
    Set<String> retNodeSet = new LinkedHashSet<String>();
    Set<String> nodeSet;
    if (tc.isSecondLevel() && tc.getParentTC().getPartitionColumn().equals(tc.getParentKey())) {
        // using
        // parent
        // rule to
        // find
        // datanode
        nodeSet = ruleCalculate(tc.getParentTC(), colRoutePairSet, rrs.getDataNodeSlotMap());
        if (nodeSet.isEmpty()) {
            throw new SQLNonTransientException("parent key can't find  valid datanode ,expect 1 but found: " + nodeSet.size());
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("found partion node (using parent partion rule directly) for child table to insert  " + nodeSet + " sql :" + rrs.getStatement());
        }
        retNodeSet.addAll(nodeSet);
        // }
        return retNodeSet;
    } else {
        retNodeSet.addAll(tc.getParentTC().getDataNodes());
    }
    return retNodeSet;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) SQLNonTransientException(java.sql.SQLNonTransientException) ColumnRoutePair(io.mycat.sqlengine.mpp.ColumnRoutePair)

Example 84 with SQLNonTransientException

use of java.sql.SQLNonTransientException in project Mycat_plus by coderczp.

the class RouterUtil method tryRouteForOneTable.

/**
 * 单表路由
 */
public static RouteResultset tryRouteForOneTable(SchemaConfig schema, DruidShardingParseInfo ctx, RouteCalculateUnit routeUnit, String tableName, RouteResultset rrs, boolean isSelect, LayerCachePool cachePool) throws SQLNonTransientException {
    if (isNoSharding(schema, tableName)) {
        return routeToSingleNode(rrs, schema.getDataNode(), ctx.getSql());
    }
    TableConfig tc = schema.getTables().get(tableName);
    if (tc == null) {
        String msg = "can't find table define in schema " + tableName + " schema:" + schema.getName();
        LOGGER.warn(msg);
        throw new SQLNonTransientException(msg);
    }
    if (tc.isDistTable()) {
        return routeToDistTableNode(tableName, schema, rrs, ctx.getSql(), routeUnit.getTablesAndConditions(), cachePool, isSelect);
    }
    if (tc.isGlobalTable()) {
        // 全局表
        if (isSelect) {
            // global select ,not cache route result
            rrs.setCacheAble(false);
            return routeToSingleNode(rrs, getAliveRandomDataNode(tc), /*getRandomDataNode(tc)*/
            ctx.getSql());
        } else {
            // insert into 全局表的记录
            return routeToMultiNode(false, rrs, tc.getDataNodes(), ctx.getSql(), true);
        }
    } else {
        // 单表或者分库表
        if (!checkRuleRequired(schema, ctx, routeUnit, tc)) {
            throw new IllegalArgumentException("route rule for table " + tc.getName() + " is required: " + ctx.getSql());
        }
        if (tc.getPartitionColumn() == null && !tc.isSecondLevel()) {
            // return RouterUtil.routeToSingleNode(rrs, tc.getDataNodes().get(0),ctx.getSql());
            return routeToMultiNode(rrs.isCacheAble(), rrs, tc.getDataNodes(), ctx.getSql());
        } else {
            // 每个表对应的路由映射
            Map<String, Set<String>> tablesRouteMap = new HashMap<String, Set<String>>();
            if (routeUnit.getTablesAndConditions() != null && routeUnit.getTablesAndConditions().size() > 0) {
                RouterUtil.findRouteWithcConditionsForTables(schema, rrs, routeUnit.getTablesAndConditions(), tablesRouteMap, ctx.getSql(), cachePool, isSelect);
                if (rrs.isFinishedRoute()) {
                    return rrs;
                }
            }
            if (tablesRouteMap.get(tableName) == null) {
                return routeToMultiNode(rrs.isCacheAble(), rrs, tc.getDataNodes(), ctx.getSql());
            } else {
                return routeToMultiNode(rrs.isCacheAble(), rrs, tablesRouteMap.get(tableName), ctx.getSql());
            }
        }
    }
}
Also used : SQLNonTransientException(java.sql.SQLNonTransientException) Set(java.util.Set) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) HashMap(java.util.HashMap) TableConfig(io.mycat.config.model.TableConfig)

Example 85 with SQLNonTransientException

use of java.sql.SQLNonTransientException in project Mycat_plus by coderczp.

the class RouterUtil method routeToDistTableNode.

private static RouteResultset routeToDistTableNode(String tableName, SchemaConfig schema, RouteResultset rrs, String orgSql, Map<String, Map<String, Set<ColumnRoutePair>>> tablesAndConditions, LayerCachePool cachePool, boolean isSelect) throws SQLNonTransientException {
    TableConfig tableConfig = schema.getTables().get(tableName);
    if (tableConfig == null) {
        String msg = "can't find table define in schema " + tableName + " schema:" + schema.getName();
        LOGGER.warn(msg);
        throw new SQLNonTransientException(msg);
    }
    if (tableConfig.isGlobalTable()) {
        String msg = "can't suport district table  " + tableName + " schema:" + schema.getName() + " for global table ";
        LOGGER.warn(msg);
        throw new SQLNonTransientException(msg);
    }
    String partionCol = tableConfig.getPartitionColumn();
    // String primaryKey = tableConfig.getPrimaryKey();
    boolean isLoadData = false;
    Set<String> tablesRouteSet = new HashSet<String>();
    List<String> dataNodes = tableConfig.getDataNodes();
    if (dataNodes.size() > 1) {
        String msg = "can't suport district table  " + tableName + " schema:" + schema.getName() + " for mutiple dataNode " + dataNodes;
        LOGGER.warn(msg);
        throw new SQLNonTransientException(msg);
    }
    String dataNode = dataNodes.get(0);
    // 主键查找缓存暂时不实现
    if (tablesAndConditions.isEmpty()) {
        List<String> subTables = tableConfig.getDistTables();
        tablesRouteSet.addAll(subTables);
    }
    for (Map.Entry<String, Map<String, Set<ColumnRoutePair>>> entry : tablesAndConditions.entrySet()) {
        boolean isFoundPartitionValue = partionCol != null && entry.getValue().get(partionCol) != null;
        Map<String, Set<ColumnRoutePair>> columnsMap = entry.getValue();
        Set<ColumnRoutePair> partitionValue = columnsMap.get(partionCol);
        if (partitionValue == null || partitionValue.size() == 0) {
            tablesRouteSet.addAll(tableConfig.getDistTables());
        } else {
            for (ColumnRoutePair pair : partitionValue) {
                AbstractPartitionAlgorithm algorithm = tableConfig.getRule().getRuleAlgorithm();
                if (pair.colValue != null) {
                    Integer tableIndex = algorithm.calculate(pair.colValue);
                    if (tableIndex == null) {
                        String msg = "can't find any valid datanode :" + tableConfig.getName() + " -> " + tableConfig.getPartitionColumn() + " -> " + pair.colValue;
                        LOGGER.warn(msg);
                        throw new SQLNonTransientException(msg);
                    }
                    String subTable = tableConfig.getDistTables().get(tableIndex);
                    if (subTable != null) {
                        tablesRouteSet.add(subTable);
                        if (algorithm instanceof SlotFunction) {
                            rrs.getDataNodeSlotMap().put(subTable, ((SlotFunction) algorithm).slotValue());
                        }
                    }
                }
                if (pair.rangeValue != null) {
                    Integer[] tableIndexs = algorithm.calculateRange(pair.rangeValue.beginValue.toString(), pair.rangeValue.endValue.toString());
                    for (Integer idx : tableIndexs) {
                        String subTable = tableConfig.getDistTables().get(idx);
                        if (subTable != null) {
                            tablesRouteSet.add(subTable);
                            if (algorithm instanceof SlotFunction) {
                                rrs.getDataNodeSlotMap().put(subTable, ((SlotFunction) algorithm).slotValue());
                            }
                        }
                    }
                }
            }
        }
    }
    Object[] subTables = tablesRouteSet.toArray();
    RouteResultsetNode[] nodes = new RouteResultsetNode[subTables.length];
    Map<String, Integer> dataNodeSlotMap = rrs.getDataNodeSlotMap();
    for (int i = 0; i < nodes.length; i++) {
        String table = String.valueOf(subTables[i]);
        String changeSql = orgSql;
        // rrs.getStatement()
        nodes[i] = new RouteResultsetNode(dataNode, rrs.getSqlType(), changeSql);
        nodes[i].setSubTableName(table);
        nodes[i].setSource(rrs);
        if (rrs.getDataNodeSlotMap().containsKey(dataNode)) {
            nodes[i].setSlot(rrs.getDataNodeSlotMap().get(dataNode));
        }
        if (rrs.getCanRunInReadDB() != null) {
            nodes[i].setCanRunInReadDB(rrs.getCanRunInReadDB());
        }
        if (dataNodeSlotMap.containsKey(table)) {
            nodes[i].setSlot(dataNodeSlotMap.get(table));
        }
        if (rrs.getRunOnSlave() != null) {
            nodes[0].setRunOnSlave(rrs.getRunOnSlave());
        }
    }
    rrs.setNodes(nodes);
    rrs.setSubTables(tablesRouteSet);
    rrs.setFinishedRoute(true);
    return rrs;
}
Also used : AbstractPartitionAlgorithm(io.mycat.route.function.AbstractPartitionAlgorithm) Set(java.util.Set) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) ColumnRoutePair(io.mycat.sqlengine.mpp.ColumnRoutePair) SlotFunction(io.mycat.route.function.SlotFunction) SQLNonTransientException(java.sql.SQLNonTransientException) RouteResultsetNode(io.mycat.route.RouteResultsetNode) TableConfig(io.mycat.config.model.TableConfig) Map(java.util.Map) HashMap(java.util.HashMap) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Aggregations

SQLNonTransientException (java.sql.SQLNonTransientException)125 TableConfig (io.mycat.config.model.TableConfig)26 SQLException (java.sql.SQLException)23 Test (org.testng.annotations.Test)19 BaseTest (util.BaseTest)19 RouteResultset (io.mycat.route.RouteResultset)17 TableConfig (com.actiontech.dble.config.model.TableConfig)15 HashMap (java.util.HashMap)14 MySqlStatementParser (com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser)13 RouteResultsetNode (io.mycat.route.RouteResultsetNode)13 HashSet (java.util.HashSet)13 SQLExpr (com.alibaba.druid.sql.ast.SQLExpr)12 ColumnRoutePair (io.mycat.sqlengine.mpp.ColumnRoutePair)12 LinkedHashSet (java.util.LinkedHashSet)12 SchemaConfig (com.actiontech.dble.config.model.SchemaConfig)11 SQLStatement (com.alibaba.druid.sql.ast.SQLStatement)11 SchemaInfo (com.actiontech.dble.server.util.SchemaUtil.SchemaInfo)10 Map (java.util.Map)10 SlotFunction (io.mycat.route.function.SlotFunction)9 SQLExprTableSource (com.alibaba.druid.sql.ast.statement.SQLExprTableSource)8