Search in sources :

Example 1 with MycatRouterConfigOps

use of io.mycat.config.MycatRouterConfigOps in project Mycat2 by MyCATApache.

the class CreateViewSQLHandler method onExecute.

@Override
protected Future<Void> onExecute(SQLRequest<SQLCreateViewStatement> request, MycatDataContext dataContext, Response response) {
    LockService lockService = MetaClusterCurrent.wrapper(LockService.class);
    SQLCreateViewStatement ast = request.getAst();
    resolveSQLExprTableSource(ast.getTableSource(), dataContext);
    return lockService.lock(DDL_LOCK, new Supplier<Future<Void>>() {

        @Override
        public Future<Void> get() {
            String schemaName = Optional.ofNullable(ast.getSchema()).orElse(dataContext.getDefaultSchema());
            schemaName = SQLUtils.normalize(schemaName);
            String viewName = SQLUtils.normalize(ast.getName().getSimpleName());
            SQLSelect subQuery = ast.getSubQuery();
            SQLSelectStatement sqlSelectStatement = new SQLSelectStatement();
            sqlSelectStatement.setSelect(subQuery);
            List<String> aliasList = Optional.ofNullable(ast.getColumns()).orElse(Collections.emptyList()).stream().map(i -> SQLUtils.normalize(i.toString())).collect(Collectors.toList());
            HackRouter hackRouter = new HackRouter(sqlSelectStatement, dataContext);
            boolean distSql = !hackRouter.analyse();
            try (MycatRouterConfigOps ops = ConfigUpdater.getOps()) {
                if (!distSql) {
                    Pair<String, String> plan = hackRouter.getPlan();
                    JdbcConnectionManager jdbcConnectionManager = MetaClusterCurrent.wrapper(JdbcConnectionManager.class);
                    try (DefaultConnection connection = jdbcConnectionManager.getConnection(plan.getKey())) {
                        Connection rawConnection = connection.getRawConnection();
                        Statement statement = rawConnection.createStatement();
                        statement.setMaxRows(0);
                        MycatRowMetaData metaData = connection.executeQuery(plan.getValue()).getMetaData();
                        if (!aliasList.isEmpty()) {
                            metaData = RenameMycatRowMetaData.of(metaData, aliasList);
                        }
                        String createTableSql = PrototypeService.generateSql(schemaName, viewName, metaData.metaData());
                        ops.putNormalTable(schemaName, viewName, (MySqlCreateTableStatement) SQLUtils.parseSingleMysqlStatement(createTableSql));
                        statement.close();
                        try {
                            SQLSelectStatement phySQLSelectStatement = (SQLSelectStatement) SQLUtils.parseSingleMysqlStatement(plan.getValue());
                            ast.setSubQuery(phySQLSelectStatement.getSelect());
                            // 建立物理视图
                            JdbcUtils.execute(rawConnection, ast.toString());
                        } catch (Throwable throwable) {
                            LOGGER.error("build phy view fail", throwable);
                        }
                    }
                } else {
                    ops.addView(schemaName, viewName, ast.toString());
                }
                ops.commit();
                return response.sendOk();
            } catch (Throwable throwable) {
                return Future.failedFuture(throwable);
            }
        }
    });
}
Also used : SQLSelect(com.alibaba.druid.sql.ast.statement.SQLSelect) SQLCreateViewStatement(com.alibaba.druid.sql.ast.statement.SQLCreateViewStatement) MySqlCreateTableStatement(com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlCreateTableStatement) Statement(java.sql.Statement) SQLSelectStatement(com.alibaba.druid.sql.ast.statement.SQLSelectStatement) Connection(java.sql.Connection) DefaultConnection(io.mycat.datasource.jdbc.datasource.DefaultConnection) MycatRouterConfigOps(io.mycat.config.MycatRouterConfigOps) HackRouter(io.mycat.prototypeserver.mysql.HackRouter) DefaultConnection(io.mycat.datasource.jdbc.datasource.DefaultConnection) SQLCreateViewStatement(com.alibaba.druid.sql.ast.statement.SQLCreateViewStatement) Future(io.vertx.core.Future) SQLSelectStatement(com.alibaba.druid.sql.ast.statement.SQLSelectStatement) List(java.util.List) JdbcConnectionManager(io.mycat.datasource.jdbc.datasource.JdbcConnectionManager) MySqlCreateTableStatement(com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlCreateTableStatement) Pair(io.mycat.util.Pair) MycatRowMetaData(io.mycat.beans.mycat.MycatRowMetaData) RenameMycatRowMetaData(io.mycat.beans.mycat.RenameMycatRowMetaData)

Example 2 with MycatRouterConfigOps

use of io.mycat.config.MycatRouterConfigOps in project Mycat2 by MyCATApache.

the class CreateTableSQLHandler method createTable.

public synchronized void createTable(Map hint, String schemaName, String tableName, MySqlCreateTableStatement createTableSql) throws Exception {
    if (createTableSql == null && hint != null) {
        Object sql = hint.get("createTableSql");
        if (sql instanceof MySqlCreateTableStatement) {
            createTableSql = (MySqlCreateTableStatement) sql;
        } else {
            createTableSql = (MySqlCreateTableStatement) SQLUtils.parseSingleMysqlStatement(Objects.toString(sql));
        }
    }
    Objects.requireNonNull(createTableSql);
    try (MycatRouterConfigOps ops = ConfigUpdater.getOps()) {
        if (schemaName == null || tableName == null) {
            MySqlCreateTableStatement ast = (MySqlCreateTableStatement) createTableSql;
            schemaName = SQLUtils.normalize(ast.getSchema());
            tableName = SQLUtils.normalize(ast.getTableName());
        }
        if (hint == null || (hint != null && hint.isEmpty())) {
            if (createTableSql.isBroadCast()) {
                ops.putGlobalTable(schemaName, tableName, createTableSql);
            } else if (createTableSql.getDbPartitionBy() == null && createTableSql.getTablePartitionBy() == null) {
                ops.putNormalTable(schemaName, tableName, createTableSql);
            } else {
                MetadataManager metadataManager = MetaClusterCurrent.wrapper(MetadataManager.class);
                int defaultStoreNodeNum = metadataManager.getDefaultStoreNodeNum();
                if (defaultStoreNodeNum == 0) {
                    ops.getOriginal().getClusters().stream().filter(i -> "prototype".equals(i.getName())).findFirst().ifPresent(clusterConfig -> {
                        ClusterConfig config = JsonUtil.from(JsonUtil.toJson(clusterConfig), ClusterConfig.class);
                        ops.putReplica(config);
                    });
                }
                ops.putHashTable(schemaName, tableName, createTableSql, getAutoHashProperties(createTableSql));
            }
        } else {
            Map<String, Object> infos = hint;
            switch(Objects.requireNonNull(infos.get("type")).toString()) {
                case "normal":
                    {
                        String targetName = (String) infos.get("targetName");
                        ops.putNormalTable(schemaName, tableName, createTableSql, targetName);
                        break;
                    }
                case "global":
                    {
                        ops.putGlobalTable(schemaName, tableName, createTableSql);
                        break;
                    }
                case "range":
                    {
                        ops.putRangeTable(schemaName, tableName, createTableSql, infos);
                        break;
                    }
                case "hash":
                    {
                        ops.putHashTable(schemaName, tableName, createTableSql, infos);
                        break;
                    }
            }
        }
        ops.commit();
        MetadataManager metadataManager = MetaClusterCurrent.wrapper(MetadataManager.class);
        TableHandler table = metadataManager.getTable(schemaName, tableName);
        if (table == null) {
            throw new MycatException("create table fail:" + schemaName + "." + tableName);
        }
    }
}
Also used : ClusterConfig(io.mycat.config.ClusterConfig) SQLUtils(com.alibaba.druid.sql.SQLUtils) Logger(org.slf4j.Logger) io.mycat(io.mycat) SQLRequest(io.mycat.sqlhandler.SQLRequest) MySqlCreateTableStatement(com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlCreateTableStatement) Vertx(io.vertx.core.Vertx) LoggerFactory(org.slf4j.LoggerFactory) AbstractSQLHandler(io.mycat.sqlhandler.AbstractSQLHandler) MycatRouterConfigOps.getAutoHashProperties(io.mycat.config.MycatRouterConfigOps.getAutoHashProperties) ConfigUpdater(io.mycat.sqlhandler.ConfigUpdater) Future(io.vertx.core.Future) Objects(java.util.Objects) Lock(io.vertx.core.shareddata.Lock) MycatRouterConfigOps(io.mycat.config.MycatRouterConfigOps) Map(java.util.Map) Optional(java.util.Optional) JsonUtil(io.mycat.util.JsonUtil) MycatRouterConfigOps(io.mycat.config.MycatRouterConfigOps) MySqlCreateTableStatement(com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlCreateTableStatement) ClusterConfig(io.mycat.config.ClusterConfig)

Example 3 with MycatRouterConfigOps

use of io.mycat.config.MycatRouterConfigOps in project Mycat2 by MyCATApache.

the class DropViewSQLHandler method onExecute.

@Override
protected Future<Void> onExecute(SQLRequest<SQLDropViewStatement> request, MycatDataContext dataContext, Response response) {
    LockService lockService = MetaClusterCurrent.wrapper(LockService.class);
    SQLDropViewStatement ast = request.getAst();
    SQLExprTableSource sqlExprTableSource = ast.getTableSources().get(0);
    resolveSQLExprTableSource(sqlExprTableSource, dataContext);
    return lockService.lock(DDL_LOCK, new Supplier<Future<Void>>() {

        @Override
        public Future<Void> get() {
            String schemaName = Optional.ofNullable(sqlExprTableSource.getSchema()).orElse(dataContext.getDefaultSchema());
            schemaName = SQLUtils.normalize(schemaName);
            String viewName = SQLUtils.normalize(sqlExprTableSource.getTableName());
            try (MycatRouterConfigOps ops = ConfigUpdater.getOps()) {
                ops.removeView(schemaName, viewName);
                ops.commit();
                return response.sendOk();
            } catch (Throwable throwable) {
                return Future.failedFuture(throwable);
            }
        }
    });
}
Also used : LockService(io.mycat.LockService) SQLDropViewStatement(com.alibaba.druid.sql.ast.statement.SQLDropViewStatement) Future(io.vertx.core.Future) SQLExprTableSource(com.alibaba.druid.sql.ast.statement.SQLExprTableSource) MycatRouterConfigOps(io.mycat.config.MycatRouterConfigOps)

Example 4 with MycatRouterConfigOps

use of io.mycat.config.MycatRouterConfigOps in project Mycat2 by MyCATApache.

the class SQLCreateProcedureHandler method onExecute.

@Override
@SneakyThrows
protected Future<Void> onExecute(SQLRequest<SQLCreateProcedureStatement> request, MycatDataContext dataContext, Response response) {
    SQLCreateProcedureStatement ast = request.getAst();
    if (ast.getName() instanceof SQLIdentifierExpr) {
        String defaultSchema = dataContext.getDefaultSchema();
        if (defaultSchema != null) {
            ast.setName(new SQLPropertyExpr(defaultSchema, ((SQLIdentifierExpr) ast.getName()).getName()));
        }
    }
    if (!(ast.getName() instanceof SQLPropertyExpr)) {
        throw new IllegalArgumentException("unknown schema:");
    }
    SQLPropertyExpr pNameExpr = (SQLPropertyExpr) ast.getName();
    String schemaName = SQLUtils.normalize(pNameExpr.getOwnerName().toLowerCase());
    String pName = SQLUtils.normalize(pNameExpr.getName().toLowerCase());
    List<SQLParameter> sqlParameters = Optional.ofNullable(ast.getParameters()).orElse(Collections.emptyList());
    Map<SQLParameter.ParameterType, List<SQLParameter>> parameterTypeListMap = sqlParameters.stream().collect(Collectors.groupingBy(k -> k.getParamType()));
    SQLBlockStatement block = (SQLBlockStatement) ast.getBlock();
    if (dataContext.getDefaultSchema() != null) {
        block.accept(new MySqlASTVisitorAdapter() {

            @Override
            public void endVisit(SQLExprTableSource x) {
                resolveSQLExprTableSource(x, dataContext);
            }
        });
    }
    Map<String, Collection<String>> collect = TableCollector.collect(dataContext.getDefaultSchema(), block);
    int resultSetCount = getResultSetCount(block);
    List<TableHandler> tableHandlers = getTableHandlers(block);
    MetadataManager metadataManager = MetaClusterCurrent.wrapper(MetadataManager.class);
    NormalProcedureConfig normalProcedureConfig = new NormalProcedureConfig();
    normalProcedureConfig.setCreateProcedureSQL(ast.toString());
    NormalBackEndProcedureInfoConfig normalBackEndProcedureInfoConfig = new NormalBackEndProcedureInfoConfig();
    normalBackEndProcedureInfoConfig.setProcedureName(pName);
    normalBackEndProcedureInfoConfig.setSchemaName(schemaName);
    normalBackEndProcedureInfoConfig.setTargetName(MetadataManager.getPrototype());
    normalProcedureConfig.setLocality(normalBackEndProcedureInfoConfig);
    try (MycatRouterConfigOps ops = ConfigUpdater.getOps()) {
        ops.addProcedure(schemaName, pName, normalProcedureConfig);
        ops.commit();
    }
    JdbcConnectionManager jdbcConnectionManager = MetaClusterCurrent.wrapper(JdbcConnectionManager.class);
    try (DefaultConnection connection = jdbcConnectionManager.getConnection(MetadataManager.getPrototype())) {
        connection.executeUpdate(ast.toString(), false);
    }
    return response.sendOk();
}
Also used : java.util(java.util) SQLUtils(com.alibaba.druid.sql.SQLUtils) SQLIdentifierExpr(com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr) io.mycat(io.mycat) SneakyThrows(lombok.SneakyThrows) SQLRequest(io.mycat.sqlhandler.SQLRequest) NormalBackEndProcedureInfoConfig(io.mycat.config.NormalBackEndProcedureInfoConfig) AbstractSQLHandler(io.mycat.sqlhandler.AbstractSQLHandler) SQLBlockStatement(com.alibaba.druid.sql.ast.statement.SQLBlockStatement) SQLCreateProcedureStatement(com.alibaba.druid.sql.ast.statement.SQLCreateProcedureStatement) DefaultConnection(io.mycat.datasource.jdbc.datasource.DefaultConnection) ConfigUpdater(io.mycat.sqlhandler.ConfigUpdater) Future(io.vertx.core.Future) Collectors(java.util.stream.Collectors) SQLPropertyExpr(com.alibaba.druid.sql.ast.expr.SQLPropertyExpr) MySqlASTVisitorAdapter(com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitorAdapter) MycatRouterConfigOps(io.mycat.config.MycatRouterConfigOps) JdbcConnectionManager(io.mycat.datasource.jdbc.datasource.JdbcConnectionManager) SQLParameter(com.alibaba.druid.sql.ast.SQLParameter) SQLStatement(com.alibaba.druid.sql.ast.SQLStatement) SQLSelectStatement(com.alibaba.druid.sql.ast.statement.SQLSelectStatement) NormalProcedureConfig(io.mycat.config.NormalProcedureConfig) NotNull(org.jetbrains.annotations.NotNull) SQLExprTableSource(com.alibaba.druid.sql.ast.statement.SQLExprTableSource) MySqlASTVisitorAdapter(com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitorAdapter) NormalBackEndProcedureInfoConfig(io.mycat.config.NormalBackEndProcedureInfoConfig) SQLPropertyExpr(com.alibaba.druid.sql.ast.expr.SQLPropertyExpr) MycatRouterConfigOps(io.mycat.config.MycatRouterConfigOps) SQLCreateProcedureStatement(com.alibaba.druid.sql.ast.statement.SQLCreateProcedureStatement) SQLBlockStatement(com.alibaba.druid.sql.ast.statement.SQLBlockStatement) NormalProcedureConfig(io.mycat.config.NormalProcedureConfig) SQLParameter(com.alibaba.druid.sql.ast.SQLParameter) SQLIdentifierExpr(com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr) DefaultConnection(io.mycat.datasource.jdbc.datasource.DefaultConnection) SQLExprTableSource(com.alibaba.druid.sql.ast.statement.SQLExprTableSource) JdbcConnectionManager(io.mycat.datasource.jdbc.datasource.JdbcConnectionManager) SneakyThrows(lombok.SneakyThrows)

Example 5 with MycatRouterConfigOps

use of io.mycat.config.MycatRouterConfigOps in project Mycat2 by MyCATApache.

the class SQLDropProcedureHandler method onExecute.

@Override
@SneakyThrows
protected Future<Void> onExecute(SQLRequest<SQLDropProcedureStatement> request, MycatDataContext dataContext, Response response) {
    SQLDropProcedureStatement ast = request.getAst();
    if (ast.getName() instanceof SQLIdentifierExpr) {
        String defaultSchema = dataContext.getDefaultSchema();
        if (defaultSchema != null) {
            ast.setName(new SQLPropertyExpr(defaultSchema, ((SQLIdentifierExpr) ast.getName()).getName()));
        }
    }
    if (!(ast.getName() instanceof SQLPropertyExpr)) {
        throw new IllegalArgumentException("unknown schema:");
    }
    SQLPropertyExpr pNameExpr = (SQLPropertyExpr) ast.getName();
    String schemaName = SQLUtils.normalize(pNameExpr.getOwnerName().toLowerCase());
    String pName = SQLUtils.normalize(pNameExpr.getName().toLowerCase());
    try (MycatRouterConfigOps ops = ConfigUpdater.getOps()) {
        ops.removeProcedure(schemaName, pName);
        ops.commit();
    }
    JdbcConnectionManager jdbcConnectionManager = MetaClusterCurrent.wrapper(JdbcConnectionManager.class);
    try (DefaultConnection connection = jdbcConnectionManager.getConnection(MetadataManager.getPrototype())) {
        connection.executeUpdate(ast.toString(), false);
    }
    return response.sendOk();
}
Also used : SQLDropProcedureStatement(com.alibaba.druid.sql.ast.statement.SQLDropProcedureStatement) DefaultConnection(io.mycat.datasource.jdbc.datasource.DefaultConnection) SQLIdentifierExpr(com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr) SQLPropertyExpr(com.alibaba.druid.sql.ast.expr.SQLPropertyExpr) MycatRouterConfigOps(io.mycat.config.MycatRouterConfigOps) JdbcConnectionManager(io.mycat.datasource.jdbc.datasource.JdbcConnectionManager) SneakyThrows(lombok.SneakyThrows)

Aggregations

MycatRouterConfigOps (io.mycat.config.MycatRouterConfigOps)5 Future (io.vertx.core.Future)4 DefaultConnection (io.mycat.datasource.jdbc.datasource.DefaultConnection)3 JdbcConnectionManager (io.mycat.datasource.jdbc.datasource.JdbcConnectionManager)3 SQLUtils (com.alibaba.druid.sql.SQLUtils)2 SQLIdentifierExpr (com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr)2 SQLPropertyExpr (com.alibaba.druid.sql.ast.expr.SQLPropertyExpr)2 SQLExprTableSource (com.alibaba.druid.sql.ast.statement.SQLExprTableSource)2 SQLSelectStatement (com.alibaba.druid.sql.ast.statement.SQLSelectStatement)2 MySqlCreateTableStatement (com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlCreateTableStatement)2 io.mycat (io.mycat)2 AbstractSQLHandler (io.mycat.sqlhandler.AbstractSQLHandler)2 ConfigUpdater (io.mycat.sqlhandler.ConfigUpdater)2 SQLRequest (io.mycat.sqlhandler.SQLRequest)2 SneakyThrows (lombok.SneakyThrows)2 SQLParameter (com.alibaba.druid.sql.ast.SQLParameter)1 SQLStatement (com.alibaba.druid.sql.ast.SQLStatement)1 SQLBlockStatement (com.alibaba.druid.sql.ast.statement.SQLBlockStatement)1 SQLCreateProcedureStatement (com.alibaba.druid.sql.ast.statement.SQLCreateProcedureStatement)1 SQLCreateViewStatement (com.alibaba.druid.sql.ast.statement.SQLCreateViewStatement)1