Search in sources :

Example 1 with MycatDataContext

use of io.mycat.MycatDataContext in project Mycat2 by MyCATApache.

the class PlanImpl method explain.

public List<String> explain(MycatDataContext dataContext, DrdsSqlWithParams drdsSql, boolean code) {
    ArrayList<String> list = new ArrayList<>();
    ExplainWriter explainWriter = new ExplainWriter();
    switch(this.type) {
        case PHYSICAL:
            Optional<ExplainDetail> singleViewOptional = ColocatedPlanner.executeQuery(dataContext, this, drdsSql);
            if (singleViewOptional.isPresent()) {
                ExplainDetail explainDetail = singleViewOptional.get();
                list.add("ColocatedPushDown:");
                list.add(explainDetail.toString());
            }
            list.add("\n");
            list.add("Plan:");
            String s = dumpPlan();
            list.addAll(Arrays.asList(s.split("\n")));
            List<SpecificSql> map = specificSql(drdsSql, dataContext);
            for (SpecificSql specificSql : map) {
                list.addAll(Arrays.asList(specificSql.toString().split("\n")));
            }
            if (code) {
                list.add("Code:");
                list.addAll(Arrays.asList(getCodeExecuterContext().getCodeContext().getCode().split("\n")));
            }
            break;
        case UPDATE:
            {
                Collection<VertxExecuter.EachSQL> eachSQLS = VertxUpdateExecuter.explainUpdate(drdsSql, dataContext);
                for (VertxExecuter.EachSQL eachSQL : eachSQLS) {
                    list.add(eachSQL.toString());
                }
                break;
            }
        case INSERT:
            {
                Iterable<VertxExecuter.EachSQL> eachSQLS = (VertxExecuter.explainInsert((SQLInsertStatement) drdsSql.getParameterizedStatement(), drdsSql.getParams()));
                for (VertxExecuter.EachSQL eachSQL : eachSQLS) {
                    list.add(eachSQL.toString());
                }
                break;
            }
        default:
            throw new IllegalStateException("Unexpected value: " + this.type);
    }
    for (String s1 : explainWriter.getText().split("\n")) {
        list.add(s1);
    }
    return list.stream().filter(i -> !i.isEmpty()).collect(Collectors.toList());
}
Also used : VertxExecuter(io.mycat.vertx.VertxExecuter) java.util(java.util) MycatRowMetaData(io.mycat.beans.mycat.MycatRowMetaData) RelShuttleImpl(org.apache.calcite.rel.RelShuttleImpl) CalciteRowMetaData(io.mycat.calcite.resultset.CalciteRowMetaData) SqlNode(org.apache.calcite.sql.SqlNode) ExplainWriter(io.mycat.calcite.ExplainWriter) MycatTransientSQLTableScan(io.mycat.calcite.table.MycatTransientSQLTableScan) DrdsSqlWithParams(io.mycat.DrdsSqlWithParams) MycatRel(io.mycat.calcite.MycatRel) ImmutableMultimap(com.google.common.collect.ImmutableMultimap) ExplainDetail(io.mycat.ExplainDetail) MycatView(io.mycat.calcite.logical.MycatView) VertxUpdateExecuter(io.mycat.vertx.VertxUpdateExecuter) SQLInsertStatement(com.alibaba.druid.sql.ast.statement.SQLInsertStatement) MycatCalciteSupport(io.mycat.calcite.MycatCalciteSupport) RelNode(org.apache.calcite.rel.RelNode) Collectors(java.util.stream.Collectors) MycatSQLTableLookup(io.mycat.calcite.physical.MycatSQLTableLookup) MycatUpdateRel(io.mycat.calcite.physical.MycatUpdateRel) MycatInsertRel(io.mycat.calcite.physical.MycatInsertRel) AsyncMycatDataContextImpl(io.mycat.AsyncMycatDataContextImpl) RelDataTypeField(org.apache.calcite.rel.type.RelDataTypeField) CodeExecuterContext(io.mycat.calcite.CodeExecuterContext) MycatDataContext(io.mycat.MycatDataContext) SqlString(org.apache.calcite.sql.util.SqlString) Util(org.apache.calcite.util.Util) NotNull(org.jetbrains.annotations.NotNull) ColocatedPlanner(io.mycat.calcite.plan.ColocatedPlanner) VertxExecuter(io.mycat.vertx.VertxExecuter) SqlString(org.apache.calcite.sql.util.SqlString) ExplainWriter(io.mycat.calcite.ExplainWriter) ExplainDetail(io.mycat.ExplainDetail)

Example 2 with MycatDataContext

use of io.mycat.MycatDataContext in project Mycat2 by MyCATApache.

the class ProxyReceiverImpl method execute.

@Override
public Future<Void> execute(ExplainDetail detail) {
    MycatDataContext dataContext = session.getDataContext();
    if (count == 0 && !binary && !dataContext.isInTransaction() && (detail.getExecuteType() == ExecuteType.QUERY || detail.getExecuteType() == ExecuteType.QUERY_MASTER) && detail.getTargets().size() == 1 && MySQLServerCapabilityFlags.isDeprecateEOF(dataContext.getServerCapabilities()) == NewMycatConnectionConfig.CLIENT_DEPRECATE_EOF) {
        String targetName = dataContext.resolveDatasourceTargetName(detail.getTargets().get(0));
        MySQLManager mySQLManager = MetaClusterCurrent.wrapper(MySQLManager.class);
        Future<NewMycatConnection> connection = mySQLManager.getConnection(targetName);
        return connection.flatMap(connection1 -> {
            Observable<Buffer> bufferObservable = connection1.prepareQuery(detail.getSql(), detail.getParams(), session.getServerStatusValue());
            bufferObservable = bufferObservable.doOnComplete(() -> connection1.close());
            bufferObservable = bufferObservable;
            return swapBuffer(bufferObservable);
        });
    }
    return super.execute(detail);
}
Also used : Buffer(io.vertx.core.buffer.Buffer) MySQLManager(cn.mycat.vertx.xa.MySQLManager) NewMycatConnection(io.mycat.newquery.NewMycatConnection) MycatDataContext(io.mycat.MycatDataContext)

Example 3 with MycatDataContext

use of io.mycat.MycatDataContext in project Mycat2 by MyCATApache.

the class CommandResolver method handle.

public static void handle(MycatSession mycat, MySQLPacket curPacket, CommandDispatcher commandHandler) {
    MycatMonitor.onCommandStart(mycat);
    Future<Void> endFuture = null;
    try {
        boolean isEmptyPayload = curPacket.readFinished();
        if (isEmptyPayload) {
            MycatMonitor.onLoadDataLocalInFileEmptyPacketStart(mycat);
            endFuture = commandHandler.handleContentOfFilenameEmptyOk(mycat);
            mycat.resetCurrentProxyPayload();
            MycatMonitor.onLoadDataLocalInFileEmptyPacketEnd(mycat);
            return;
        } else if (mycat.shouldHandleContentOfFilename()) {
            MycatMonitor.onLoadDataLocalInFileContextStart(mycat);
            endFuture = commandHandler.handleContentOfFilename(curPacket.readEOFStringBytes(), mycat);
            mycat.resetCurrentProxyPayload();
            MycatMonitor.onLoadDataLocalInFileContextEnd(mycat);
            return;
        }
        byte head = curPacket.getByte(curPacket.packetReadStartIndex());
        switch(head) {
            case MySQLCommandType.COM_SLEEP:
                {
                    MycatMonitor.onSleepCommandStart(mycat);
                    curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleSleep(mycat);
                    MycatMonitor.onSleepCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_QUIT:
                {
                    MycatMonitor.onQuitCommandStart(mycat);
                    curPacket.readByte();
                    endFuture = commandHandler.handleQuit(mycat);
                    MycatMonitor.onQuitCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_QUERY:
                {
                    MycatMonitor.onQueryCommandStart(mycat);
                    curPacket.readByte();
                    byte[] bytes = curPacket.readEOFStringBytes();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleQuery(bytes, mycat);
                    break;
                }
            case MySQLCommandType.COM_INIT_DB:
                {
                    MycatMonitor.onInitDbCommandStart(mycat);
                    curPacket.readByte();
                    String schema = curPacket.readEOFString();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleInitDb(schema, mycat);
                    MycatMonitor.onInitDbCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_PING:
                {
                    MycatMonitor.onPingCommandStart(mycat);
                    curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handlePing(mycat);
                    MycatMonitor.onPingCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_FIELD_LIST:
                {
                    MycatMonitor.onFieldListCommandStart(mycat);
                    curPacket.readByte();
                    String table = curPacket.readNULString();
                    String field = curPacket.readEOFString();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleFieldList(table, field, mycat);
                    MycatMonitor.onFieldListCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_SET_OPTION:
                {
                    MycatMonitor.onSetOptionCommandStart(mycat);
                    curPacket.readByte();
                    boolean option = curPacket.readFixInt(2) == 1;
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleSetOption(option, mycat);
                    MycatMonitor.onSetOptionCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_STMT_PREPARE:
                {
                    MycatMonitor.onPrepareCommandStart(mycat);
                    curPacket.readByte();
                    byte[] bytes = curPacket.readEOFStringBytes();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handlePrepareStatement(bytes, mycat);
                    MycatMonitor.onPrepareCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_STMT_SEND_LONG_DATA:
                {
                    MycatMonitor.onSendLongDataCommandStart(mycat);
                    curPacket.readByte();
                    long statementId = curPacket.readFixInt(4);
                    int paramId = (int) curPacket.readFixInt(2);
                    byte[] data = curPacket.readEOFStringBytes();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handlePrepareStatementLongdata(statementId, paramId, data, mycat);
                    MycatMonitor.onSendLongDataCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_STMT_EXECUTE:
                {
                    MycatMonitor.onExecuteCommandStart(mycat);
                    MycatDataContext dataContext = mycat.getDataContext();
                    dataContext.getPrepareInfo();
                    try {
                        byte[] rawPayload = curPacket.getEOFStringBytes(curPacket.packetReadStartIndex());
                        curPacket.readByte();
                        long statementId = curPacket.readFixInt(4);
                        byte flags = curPacket.readByte();
                        long iteration = curPacket.readFixInt(4);
                        assert iteration == 1;
                        int numParams = commandHandler.getNumParamsByStatementId(statementId, mycat);
                        byte[] nullMap = null;
                        if (numParams > 0) {
                            nullMap = curPacket.readBytes((numParams + 7) / 8);
                        }
                        int[] params = null;
                        BindValue[] values = null;
                        boolean newParameterBoundFlag = !curPacket.readFinished() && curPacket.readByte() == 1;
                        if (newParameterBoundFlag) {
                            params = new int[numParams];
                            for (int i = 0; i < numParams; i++) {
                                params[i] = (int) curPacket.readFixInt(2);
                            }
                            values = new BindValue[numParams];
                            for (int i = 0; i < numParams; i++) {
                                BindValue bv = new BindValue();
                                bv.type = params[i];
                                if ((nullMap[i / 8] & (1 << (i & 7))) != 0) {
                                    bv.isNull = true;
                                } else {
                                    byte[] longData = commandHandler.getLongData(statementId, i, mycat);
                                    if (longData == null) {
                                        ServerConfig serverConfig = MetaClusterCurrent.wrapper(ServerConfig.class);
                                        BindValueUtil.read(curPacket, bv, StandardCharsets.UTF_8, !serverConfig.isPstmtStringVal());
                                        bv.isLongData = false;
                                    } else {
                                        bv.value = longData;
                                        bv.isLongData = true;
                                    }
                                }
                                values[i] = bv;
                            }
                            commandHandler.saveBindValue(statementId, values, mycat);
                        } else {
                            values = commandHandler.getLastBindValue(statementId, mycat);
                        }
                        mycat.resetCurrentProxyPayload();
                        endFuture = commandHandler.handlePrepareStatementExecute(statementId, flags, params, values, mycat);
                        break;
                    } finally {
                        MycatMonitor.onExecuteCommandEnd(mycat);
                    }
                }
            case MySQLCommandType.COM_STMT_CLOSE:
                {
                    MycatMonitor.onCloseCommandStart(mycat);
                    curPacket.readByte();
                    long statementId = curPacket.readFixInt(4);
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handlePrepareStatementClose(statementId, mycat);
                    endFuture = endFuture.onComplete(event -> mycat.onHandlerFinishedClear());
                    MycatMonitor.onCloseCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_STMT_FETCH:
                {
                    MycatMonitor.onFetchCommandStart(mycat);
                    curPacket.readByte();
                    long statementId = curPacket.readFixInt(4);
                    long row = curPacket.readFixInt(4);
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handlePrepareStatementFetch(statementId, row, mycat);
                    MycatMonitor.onFetchCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_STMT_RESET:
                {
                    MycatMonitor.onResetCommandStart(mycat);
                    curPacket.readByte();
                    long statementId = curPacket.readFixInt(4);
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handlePrepareStatementReset(statementId, mycat);
                    MycatMonitor.onResetCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_CREATE_DB:
                {
                    MycatMonitor.onCreateDbCommandStart(mycat);
                    curPacket.readByte();
                    String schema = curPacket.readEOFString();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleCreateDb(schema, mycat);
                    MycatMonitor.onCreateDbCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_DROP_DB:
                {
                    MycatMonitor.onDropDbCommandStart(mycat);
                    curPacket.readByte();
                    String schema = curPacket.readEOFString();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleDropDb(schema, mycat);
                    MycatMonitor.onDropDbCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_REFRESH:
                {
                    MycatMonitor.onRefreshCommandStart(mycat);
                    curPacket.readByte();
                    byte subCommand = curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleRefresh(subCommand, mycat);
                    MycatMonitor.onRefreshCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_SHUTDOWN:
                {
                    MycatMonitor.onShutdownCommandStart(mycat);
                    curPacket.readByte();
                    try {
                        if (!curPacket.readFinished()) {
                            byte shutdownType = curPacket.readByte();
                            mycat.resetCurrentProxyPayload();
                            endFuture = commandHandler.handleShutdown(shutdownType, mycat);
                        } else {
                            mycat.resetCurrentProxyPayload();
                            endFuture = commandHandler.handleShutdown(0, mycat);
                        }
                    } finally {
                        MycatMonitor.onShutdownCommandEnd(mycat);
                    }
                    break;
                }
            case MySQLCommandType.COM_STATISTICS:
                {
                    MycatMonitor.onStatisticsCommandStart(mycat);
                    curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleStatistics(mycat);
                    MycatMonitor.onStatisticsCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_PROCESS_INFO:
                {
                    MycatMonitor.onProcessInfoCommandStart(mycat);
                    curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleProcessInfo(mycat);
                    MycatMonitor.onProcessInfoCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_CONNECT:
                {
                    MycatMonitor.onConnectCommandStart(mycat);
                    curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleConnect(mycat);
                    MycatMonitor.onConnectCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_PROCESS_KILL:
                {
                    MycatMonitor.onProcessKillCommandStart(mycat);
                    curPacket.readByte();
                    long connectionId = curPacket.readFixInt(4);
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleProcessKill(connectionId, mycat);
                    MycatMonitor.onProcessKillCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_DEBUG:
                {
                    MycatMonitor.onDebugCommandStart(mycat);
                    curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleDebug(mycat);
                    MycatMonitor.onDebugCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_TIME:
                {
                    MycatMonitor.onTimeCommandStart(mycat);
                    curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleTime(mycat);
                    MycatMonitor.onTimeCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_DELAYED_INSERT:
                {
                    MycatMonitor.onDelayedInsertCommandStart(mycat);
                    curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleDelayedInsert(mycat);
                    MycatMonitor.onDelayedInsertCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_CHANGE_USER:
                {
                    MycatMonitor.onChangeUserCommandStart(mycat);
                    curPacket.readByte();
                    try {
                        String userName = curPacket.readNULString();
                        String authResponse = null;
                        String schemaName = null;
                        Integer characterSet = null;
                        String authPluginName = null;
                        HashMap<String, String> clientConnectAttrs = new HashMap<>();
                        int capabilities = mycat.getCapabilities();
                        if (MySQLServerCapabilityFlags.isCanDo41Anthentication(capabilities)) {
                            byte len = curPacket.readByte();
                            authResponse = curPacket.readFixString(len);
                        } else {
                            authResponse = curPacket.readNULString();
                        }
                        schemaName = curPacket.readNULString();
                        if (!curPacket.readFinished()) {
                            characterSet = (int) curPacket.readFixInt(2);
                            if (MySQLServerCapabilityFlags.isPluginAuth(capabilities)) {
                                authPluginName = curPacket.readNULString();
                            }
                            if (MySQLServerCapabilityFlags.isConnectAttrs(capabilities)) {
                                long kvAllLength = curPacket.readLenencInt();
                                if (kvAllLength != 0) {
                                    clientConnectAttrs = new HashMap<>();
                                }
                                int count = 0;
                                while (count < kvAllLength) {
                                    String k = curPacket.readLenencString();
                                    String v = curPacket.readLenencString();
                                    count += k.length();
                                    count += v.length();
                                    count += calcLenencLength(k.length());
                                    count += calcLenencLength(v.length());
                                    clientConnectAttrs.put(k, v);
                                }
                            }
                        }
                        mycat.resetCurrentProxyPayload();
                        endFuture = commandHandler.handleChangeUser(userName, authResponse, schemaName, characterSet, authPluginName, clientConnectAttrs, mycat);
                    } finally {
                        MycatMonitor.onChangeUserCommandEnd(mycat);
                    }
                    break;
                }
            case MySQLCommandType.COM_RESET_CONNECTION:
                {
                    MycatMonitor.onResetConnectionCommandStart(mycat);
                    curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleResetConnection(mycat);
                    MycatMonitor.onResetConnectionCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_DAEMON:
                {
                    MycatMonitor.onDaemonCommandStart(mycat);
                    curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleDaemon(mycat);
                    MycatMonitor.onDaemonCommandEnd(mycat);
                    break;
                }
            default:
                {
                    assert false;
                }
        }
    } finally {
        Objects.requireNonNull(endFuture).onComplete(event -> {
            Future<Void> future = Future.succeededFuture();
            if (event.failed()) {
                mycat.setLastMessage(event.cause());
                future = mycat.writeErrorEndPacketBySyncInProcessError();
            }
            future.onComplete(event1 -> {
                MycatMonitor.onCommandEnd(mycat);
            });
        });
    }
}
Also used : ServerConfig(io.mycat.config.ServerConfig) HashMap(java.util.HashMap) MycatDataContext(io.mycat.MycatDataContext) BindValue(io.mycat.BindValue)

Aggregations

MycatDataContext (io.mycat.MycatDataContext)3 MySQLManager (cn.mycat.vertx.xa.MySQLManager)1 SQLInsertStatement (com.alibaba.druid.sql.ast.statement.SQLInsertStatement)1 ImmutableMultimap (com.google.common.collect.ImmutableMultimap)1 AsyncMycatDataContextImpl (io.mycat.AsyncMycatDataContextImpl)1 BindValue (io.mycat.BindValue)1 DrdsSqlWithParams (io.mycat.DrdsSqlWithParams)1 ExplainDetail (io.mycat.ExplainDetail)1 MycatRowMetaData (io.mycat.beans.mycat.MycatRowMetaData)1 CodeExecuterContext (io.mycat.calcite.CodeExecuterContext)1 ExplainWriter (io.mycat.calcite.ExplainWriter)1 MycatCalciteSupport (io.mycat.calcite.MycatCalciteSupport)1 MycatRel (io.mycat.calcite.MycatRel)1 MycatView (io.mycat.calcite.logical.MycatView)1 MycatInsertRel (io.mycat.calcite.physical.MycatInsertRel)1 MycatSQLTableLookup (io.mycat.calcite.physical.MycatSQLTableLookup)1 MycatUpdateRel (io.mycat.calcite.physical.MycatUpdateRel)1 ColocatedPlanner (io.mycat.calcite.plan.ColocatedPlanner)1 CalciteRowMetaData (io.mycat.calcite.resultset.CalciteRowMetaData)1 MycatTransientSQLTableScan (io.mycat.calcite.table.MycatTransientSQLTableScan)1