Search in sources :

Example 1 with TableConfig

use of com.actiontech.dble.config.model.TableConfig in project dble by actiontech.

the class ShowTableDataNode method execute.

public static void execute(ManagerConnection c, String tableInfo) {
    Matcher ma = PATTERN_FOR_TABLE_INFO.matcher(tableInfo);
    if (!ma.matches()) {
        c.writeErrMessage(ErrorCode.ER_UNKNOWN_ERROR, "The Correct Query Format Is:show @@datanodes where schema=? and table =?");
        return;
    }
    String schemaName = ma.group(2);
    String tableName = ma.group(4);
    if (DbleServer.getInstance().getSystemVariables().isLowerCaseTableNames()) {
        schemaName = schemaName.toLowerCase();
        tableName = tableName.toLowerCase();
    }
    SchemaConfig schemaConfig = DbleServer.getInstance().getConfig().getSchemas().get(schemaName);
    List<String> dataNodes;
    if (schemaConfig == null) {
        c.writeErrMessage(ErrorCode.ER_UNKNOWN_ERROR, "the schema [" + schemaName + "] does not exists");
        return;
    } else if (schemaConfig.isNoSharding()) {
        dataNodes = Collections.singletonList(schemaConfig.getDataNode());
    } else {
        TableConfig tableConfig = schemaConfig.getTables().get(tableName);
        if (tableConfig == null) {
            if (schemaConfig.getDataNode() == null) {
                c.writeErrMessage(ErrorCode.ER_UNKNOWN_ERROR, "the table [" + tableName + "] in schema [" + schemaName + "] does not exists");
                return;
            } else {
                dataNodes = Collections.singletonList(schemaConfig.getDataNode());
            }
        } else {
            dataNodes = tableConfig.getDataNodes();
        }
    }
    ByteBuffer buffer = c.allocate();
    // write header
    buffer = HEADER.write(buffer, c, true);
    // write fields
    for (FieldPacket field : FIELDS) {
        buffer = field.write(buffer, c, true);
    }
    // write eof
    buffer = EOF.write(buffer, c, true);
    // write rows
    byte packetId = EOF.getPacketId();
    for (RowDataPacket row : getRows(dataNodes, c.getCharset().getResults())) {
        row.setPacketId(++packetId);
        buffer = row.write(buffer, c, true);
    }
    // write last eof
    EOFPacket lastEof = new EOFPacket();
    lastEof.setPacketId(++packetId);
    buffer = lastEof.write(buffer, c, true);
    // post write
    c.write(buffer);
}
Also used : SchemaConfig(com.actiontech.dble.config.model.SchemaConfig) Matcher(java.util.regex.Matcher) RowDataPacket(com.actiontech.dble.net.mysql.RowDataPacket) EOFPacket(com.actiontech.dble.net.mysql.EOFPacket) TableConfig(com.actiontech.dble.config.model.TableConfig) ByteBuffer(java.nio.ByteBuffer) FieldPacket(com.actiontech.dble.net.mysql.FieldPacket)

Example 2 with TableConfig

use of com.actiontech.dble.config.model.TableConfig in project dble by actiontech.

the class DbleServer method tryRecovery.

private void tryRecovery(CoordinatorLogEntry coordinatorLogEntry, boolean needCommit) {
    StringBuilder xaCmd = new StringBuilder();
    if (needCommit) {
        xaCmd.append("XA COMMIT ");
    } else {
        xaCmd.append("XA ROLLBACK ");
    }
    boolean finished = true;
    for (int j = 0; j < coordinatorLogEntry.getParticipants().length; j++) {
        ParticipantLogEntry participantLogEntry = coordinatorLogEntry.getParticipants()[j];
        // XA commit
        if (participantLogEntry.getTxState() != TxState.TX_COMMIT_FAILED_STATE && participantLogEntry.getTxState() != TxState.TX_COMMITTING_STATE && participantLogEntry.getTxState() != TxState.TX_PREPARE_UNCONNECT_STATE && participantLogEntry.getTxState() != TxState.TX_ROLLBACKING_STATE && participantLogEntry.getTxState() != TxState.TX_ROLLBACK_FAILED_STATE && participantLogEntry.getTxState() != TxState.TX_PREPARED_STATE) {
            continue;
        }
        finished = false;
        outLoop: for (SchemaConfig schema : DbleServer.getInstance().getConfig().getSchemas().values()) {
            for (TableConfig table : schema.getTables().values()) {
                for (String dataNode : table.getDataNodes()) {
                    PhysicalDBNode dn = DbleServer.getInstance().getConfig().getDataNodes().get(dataNode);
                    if (participantLogEntry.compareAddress(dn.getDbPool().getSource().getConfig().getIp(), dn.getDbPool().getSource().getConfig().getPort(), dn.getDatabase())) {
                        OneRawSQLQueryResultHandler resultHandler = new OneRawSQLQueryResultHandler(new String[0], new XARecoverCallback(needCommit, participantLogEntry));
                        xaCmd.append(coordinatorLogEntry.getId().substring(0, coordinatorLogEntry.getId().length() - 1));
                        xaCmd.append(".");
                        xaCmd.append(dn.getDatabase());
                        xaCmd.append("'");
                        SQLJob sqlJob = new SQLJob(xaCmd.toString(), dn.getDatabase(), resultHandler, dn.getDbPool().getSource());
                        sqlJob.run();
                        LOGGER.debug(String.format("[%s] Host:[%s] schema:[%s]", xaCmd, dn.getName(), dn.getDatabase()));
                        // reset xaCmd
                        xaCmd.setLength(0);
                        if (needCommit) {
                            xaCmd.append("XA COMMIT ");
                        } else {
                            xaCmd.append("XA ROLLBACK ");
                        }
                        break outLoop;
                    }
                }
            }
        }
    }
    if (finished) {
        XAStateLog.saveXARecoveryLog(coordinatorLogEntry.getId(), needCommit ? TxState.TX_COMMITTED_STATE : TxState.TX_ROLLBACKED_STATE);
        XAStateLog.writeCheckpoint(coordinatorLogEntry.getId());
    }
}
Also used : PhysicalDBNode(com.actiontech.dble.backend.datasource.PhysicalDBNode) OneRawSQLQueryResultHandler(com.actiontech.dble.sqlengine.OneRawSQLQueryResultHandler) SchemaConfig(com.actiontech.dble.config.model.SchemaConfig) SQLJob(com.actiontech.dble.sqlengine.SQLJob) TableConfig(com.actiontech.dble.config.model.TableConfig)

Example 3 with TableConfig

use of com.actiontech.dble.config.model.TableConfig in project dble by actiontech.

the class ProxyMetaManager method tableStructureCheck.

private void tableStructureCheck(Set<String> selfNode) {
    for (SchemaConfig schema : DbleServer.getInstance().getConfig().getSchemas().values()) {
        if (!checkDbExists(schema.getName())) {
            continue;
        }
        for (TableConfig table : schema.getTables().values()) {
            if (!checkTableExists(schema.getName(), table.getName())) {
                continue;
            }
            AbstractTableMetaHandler handler = new TableMetaCheckHandler(this, schema.getName(), table, selfNode);
            handler.execute();
        }
    }
}
Also used : SchemaConfig(com.actiontech.dble.config.model.SchemaConfig) TableConfig(com.actiontech.dble.config.model.TableConfig)

Example 4 with TableConfig

use of com.actiontech.dble.config.model.TableConfig in project dble by actiontech.

the class DruidInsertParser method parserChildTable.

private void parserChildTable(SchemaInfo schemaInfo, final RouteResultset rrs, MySqlInsertStatement insertStmt, final ServerConnection sc) throws SQLNonTransientException {
    final SchemaConfig schema = schemaInfo.getSchemaConfig();
    String tableName = schemaInfo.getTable();
    final TableConfig tc = schema.getTables().get(tableName);
    if (isMultiInsert(insertStmt)) {
        String msg = "ChildTable multi insert not provided";
        LOGGER.info(msg);
        throw new SQLNonTransientException(msg);
    }
    String joinKey = tc.getJoinKey();
    int joinKeyIndex = getJoinKeyIndex(schemaInfo, insertStmt, joinKey);
    final String joinKeyVal = insertStmt.getValues().getValues().get(joinKeyIndex).toString();
    String realVal = StringUtil.removeApostrophe(joinKeyVal);
    final String sql = RouterUtil.removeSchema(insertStmt.toString(), schemaInfo.getSchema());
    rrs.setStatement(sql);
    // try to route by ER parent partion key
    RouteResultset theRrs = routeByERParentKey(rrs, tc, realVal);
    if (theRrs != null) {
        rrs.setFinishedRoute(true);
    } else {
        rrs.setFinishedExecute(true);
        DbleServer.getInstance().getComplexQueryExecutor().execute(new Runnable() {

            // get child result will be blocked, so use ComplexQueryExecutor
            @Override
            public void run() {
                // route by sql query root parent's data node
                String findRootTBSql = tc.getLocateRTableKeySql().toLowerCase() + joinKeyVal;
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("to find root parent's node sql :" + findRootTBSql);
                }
                FetchStoreNodeOfChildTableHandler fetchHandler = new FetchStoreNodeOfChildTableHandler(findRootTBSql, sc.getSession2());
                String dn = fetchHandler.execute(schema.getName(), tc.getRootParent().getDataNodes());
                if (dn == null) {
                    sc.writeErrMessage(ErrorCode.ER_UNKNOWN_ERROR, "can't find (root) parent sharding node for sql:" + sql);
                    return;
                }
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("found partition node for child table to insert " + dn + " sql :" + sql);
                }
                RouterUtil.routeToSingleNode(rrs, dn);
                sc.getSession2().execute(rrs);
            }
        });
    }
}
Also used : SQLNonTransientException(java.sql.SQLNonTransientException) SchemaConfig(com.actiontech.dble.config.model.SchemaConfig) FetchStoreNodeOfChildTableHandler(com.actiontech.dble.backend.mysql.nio.handler.FetchStoreNodeOfChildTableHandler) TableConfig(com.actiontech.dble.config.model.TableConfig) RouteResultset(com.actiontech.dble.route.RouteResultset)

Example 5 with TableConfig

use of com.actiontech.dble.config.model.TableConfig in project dble by actiontech.

the class DruidInsertParser method parserBatchInsert.

/**
 * insert into .... select .... or insert into table() values (),(),....
 *
 * @param schemaInfo SchemaInfo
 * @param rrs RouteResultset
 * @param partitionColumn partitionColumn
 * @param insertStmt insertStmt
 * @throws SQLNonTransientException if the column size of values is not correct
 */
private void parserBatchInsert(SchemaInfo schemaInfo, RouteResultset rrs, String partitionColumn, MySqlInsertStatement insertStmt) throws SQLNonTransientException {
    // insert into table() values (),(),....
    SchemaConfig schema = schemaInfo.getSchemaConfig();
    String tableName = schemaInfo.getTable();
    // the size of columns
    int columnNum = getTableColumns(schemaInfo, insertStmt.getColumns());
    int shardingColIndex = tryGetShardingColIndex(schemaInfo, insertStmt, partitionColumn);
    List<ValuesClause> valueClauseList = insertStmt.getValuesList();
    Map<Integer, List<ValuesClause>> nodeValuesMap = new HashMap<>();
    TableConfig tableConfig = schema.getTables().get(tableName);
    AbstractPartitionAlgorithm algorithm = tableConfig.getRule().getRuleAlgorithm();
    for (ValuesClause valueClause : valueClauseList) {
        if (valueClause.getValues().size() != columnNum) {
            String msg = "bad insert sql columnSize != valueSize:" + columnNum + " != " + valueClause.getValues().size() + "values:" + valueClause;
            LOGGER.info(msg);
            throw new SQLNonTransientException(msg);
        }
        SQLExpr expr = valueClause.getValues().get(shardingColIndex);
        String shardingValue = shardingValueToSting(expr);
        Integer nodeIndex = algorithm.calculate(shardingValue);
        // null means can't find any valid index
        if (nodeIndex == null) {
            String msg = "can't find any valid datanode :" + tableName + " -> " + partitionColumn + " -> " + shardingValue;
            LOGGER.info(msg);
            throw new SQLNonTransientException(msg);
        }
        if (nodeValuesMap.get(nodeIndex) == null) {
            nodeValuesMap.put(nodeIndex, new ArrayList<ValuesClause>());
        }
        nodeValuesMap.get(nodeIndex).add(valueClause);
    }
    RouteResultsetNode[] nodes = new RouteResultsetNode[nodeValuesMap.size()];
    int count = 0;
    for (Map.Entry<Integer, List<ValuesClause>> node : nodeValuesMap.entrySet()) {
        Integer nodeIndex = node.getKey();
        List<ValuesClause> valuesList = node.getValue();
        insertStmt.setValuesList(valuesList);
        nodes[count] = new RouteResultsetNode(tableConfig.getDataNodes().get(nodeIndex), rrs.getSqlType(), RouterUtil.removeSchema(insertStmt.toString(), schemaInfo.getSchema()));
        count++;
    }
    rrs.setNodes(nodes);
    rrs.setFinishedRoute(true);
}
Also used : AbstractPartitionAlgorithm(com.actiontech.dble.route.function.AbstractPartitionAlgorithm) SchemaConfig(com.actiontech.dble.config.model.SchemaConfig) SQLExpr(com.alibaba.druid.sql.ast.SQLExpr) SQLNonTransientException(java.sql.SQLNonTransientException) RouteResultsetNode(com.actiontech.dble.route.RouteResultsetNode) TableConfig(com.actiontech.dble.config.model.TableConfig) ValuesClause(com.alibaba.druid.sql.ast.statement.SQLInsertStatement.ValuesClause)

Aggregations

TableConfig (com.actiontech.dble.config.model.TableConfig)32 SchemaConfig (com.actiontech.dble.config.model.SchemaConfig)16 SQLNonTransientException (java.sql.SQLNonTransientException)16 SQLException (java.sql.SQLException)7 RouteResultsetNode (com.actiontech.dble.route.RouteResultsetNode)6 SchemaInfo (com.actiontech.dble.server.util.SchemaUtil.SchemaInfo)5 RouteResultset (com.actiontech.dble.route.RouteResultset)4 AbstractPartitionAlgorithm (com.actiontech.dble.route.function.AbstractPartitionAlgorithm)4 SQLExpr (com.alibaba.druid.sql.ast.SQLExpr)4 SQLExprTableSource (com.alibaba.druid.sql.ast.statement.SQLExprTableSource)4 MySqlStatementParser (com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser)4 CacheService (com.actiontech.dble.cache.CacheService)3 ServerConfig (com.actiontech.dble.config.ServerConfig)3 SQLStatementParser (com.alibaba.druid.sql.parser.SQLStatementParser)3 Matcher (java.util.regex.Matcher)3 PhysicalDBNode (com.actiontech.dble.backend.datasource.PhysicalDBNode)2 FetchStoreNodeOfChildTableHandler (com.actiontech.dble.backend.mysql.nio.handler.FetchStoreNodeOfChildTableHandler)2 EOFPacket (com.actiontech.dble.net.mysql.EOFPacket)2 FieldPacket (com.actiontech.dble.net.mysql.FieldPacket)2 RowDataPacket (com.actiontech.dble.net.mysql.RowDataPacket)2