Java Code Examples for com.alibaba.fastsql.sql.SQLUtils#normalize()

The following examples show how to use com.alibaba.fastsql.sql.SQLUtils#normalize() . 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: MycatDBSharedServerImpl.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
public MycatSQLPrepareObject query(String sql, SQLStatement sqlStatement, MycatDBContext dbContext) {
    boolean ddl = sqlStatement instanceof SQLSelectStatement || sqlStatement instanceof MySqlInsertStatement
            || sqlStatement instanceof MySqlUpdateStatement || sqlStatement instanceof MySqlDeleteStatement;
    if (ddl) {
        return prepare(sql, null, sqlStatement, dbContext);
    }
    if (sqlStatement instanceof SQLCommitStatement) return commit(sql, dbContext);
    if (sqlStatement instanceof SQLRollbackStatement) return (rollback(sql, dbContext));
    if (sqlStatement instanceof SQLSetStatement) {
        return setStatement(sql, (SQLSetStatement) sqlStatement, dbContext);
    }
    if (sqlStatement instanceof SQLUseStatement) {
        String normalize = SQLUtils.normalize(((SQLUseStatement) sqlStatement).getDatabase().getSimpleName());
        return use(sql, normalize, dbContext);
    }
    if (sqlStatement instanceof MySqlExplainStatement) {
        return explain(sql, (MySqlExplainStatement) sqlStatement, dbContext);
    }
    return null;
}
 
Example 2
Source File: MycatCalciteMySqlNodeVisitor.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
public boolean visit(SQLSelectItem x) {
    SQLExpr expr = x.getExpr();

    if (expr instanceof SQLIdentifierExpr) {
        visit((SQLIdentifierExpr) expr);
    } else if (expr instanceof SQLPropertyExpr) {
        visit((SQLPropertyExpr) expr);
    } else if (expr instanceof SQLAggregateExpr) {
        visit((SQLAggregateExpr) expr);
    } else {
        expr.accept(this);
    } // select a + (select count(1) from b) as mm from c;
    // select a + (select COUNT(1) from b) as 'a + (select count(1) as
    // 'count(1)' from b)' from c;
    String alias = x.getAlias();
    if (alias != null && alias.length() > 0) {
        String alias2 = x.getAlias2();
        sqlNode = new SqlBasicCall(SqlStdOperatorTable.AS,
                new SqlNode[] { sqlNode, new SqlIdentifier(SQLUtils.normalize(alias2, DbType.mysql), SqlParserPos.ZERO) },
                SqlParserPos.ZERO);
    }

    return false;
}
 
Example 3
Source File: MycatCalciteMySqlNodeVisitor.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
SqlIdentifier buildIdentifier(SQLPropertyExpr x) {
    String name = SQLUtils.normalize(x.getName());
    if ("*".equals(name)) {
        name = "";
    }

    SQLExpr owner = x.getOwner();

    List<String> names;
    if (owner instanceof SQLIdentifierExpr) {
        names = Arrays.asList(((SQLIdentifierExpr) owner).normalizedName(), name);
    } else if (owner instanceof SQLPropertyExpr) {
        names = new ArrayList<String>();
        buildIdentifier((SQLPropertyExpr) owner, names);
        names.add(name);
    } else {
        throw new FastsqlException("not support : " + owner);
    }

    return new SqlIdentifier(names, SqlParserPos.ZERO);
}
 
Example 4
Source File: RexTranslator.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void endVisit(SQLPropertyExpr x) {
    String columnName = x.getName();
    if (x.getOwner() == null) {
        result = relBuilder.field(columnName);
        return;
    }
    if (x.getOwner() instanceof SQLIdentifierExpr) {
        result = relBuilder.field(((SQLIdentifierExpr) x.getOwner()).normalizedName(), columnName);
        return;
    }
    if (x.getOwner() instanceof SQLPropertyExpr) {
        SQLPropertyExpr owner = (SQLPropertyExpr) x.getOwner();
        if (owner.getOwner() instanceof SQLIdentifierExpr) {
            String databaseName = SQLUtils.normalize(((SQLIdentifierExpr) owner.getOwner()).getName());
            String tableName = SQLUtils.normalize(owner.getName());
            result = relBuilder.field(databaseName, tableName, columnName);
            return;
        }
    }
    if (x.getOwner() instanceof SQLVariantRefExpr) {
        result = relBuilder.placeHolder(x.normalizedName());
        return;
    }
    //SQLVariantRefExpr
}
 
Example 5
Source File: ShowStatementRewriter.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
public static String rewriteShowTables(String defaultSchema, SQLShowTablesStatement ast) {
    SQLExpr where = ast.getWhere();
    SQLName from = ast.getFrom();
    SQLExpr like = ast.getLike();
    boolean full = ast.isFull();
    String schema = SQLUtils.normalize(from == null ? defaultSchema : from.getSimpleName());
    if (schema == null) {
        throw new MycatException(1046, "No database selected");
    }
    String schemaCondition = " TABLE_SCHEMA = '" + schema + "' ";
    String whereCondition = " " + (where == null ? "true" : where.toString()) + " ";
    String likeCondition = like == null ? " true " : " TABLE_NAME like " + " " + like.toString() + " ";
    String fullCondition = !full ? " true " : " TABLE_TYPE  = 'BASE TABLE' ";

    String sql = MessageFormat.format("select TABLE_NAME as {0} from information_schema.`TABLES` where {1} ",
            "`" + "Tables_in_" + schema + "`", String.join(" and ", schemaCondition, whereCondition, likeCondition, fullCondition)
    );
    LOGGER.info(ast + "->" + sql);
    return sql;
}
 
Example 6
Source File: MycatCalciteMySqlNodeVisitor.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean visit(SQLSubqueryTableSource x) {
    sqlNode = convertToSqlNode(x.getSelect());

    final String alias = x.getAlias();
    if (alias != null) {
        SqlIdentifier aliasIdentifier = new SqlIdentifier(alias, SqlParserPos.ZERO);

        List<SQLName> columns = x.getColumns();

        SqlNode[] operands;
        if (columns.size() == 0) {
            operands = new SqlNode[] { sqlNode, aliasIdentifier };
        } else {
            operands = new SqlNode[columns.size() + 2];
            operands[0] = sqlNode;
            operands[1] = aliasIdentifier;
            for (int i = 0; i < columns.size(); i++) {
                SQLName column = columns.get(i);
                operands[i + 2] = new SqlIdentifier(
                        SQLUtils.normalize(column.getSimpleName()), SqlParserPos.ZERO);
            }
        }
        sqlNode = new SqlBasicCall(SqlStdOperatorTable.AS, operands, SqlParserPos.ZERO);
    }

    return false;
}
 
Example 7
Source File: MycatCalciteMySqlNodeVisitor.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
void buildIdentifier(SQLPropertyExpr x, List<String> names) {
    String name = SQLUtils.normalize(x.getName());

    SQLExpr owner = x.getOwner();
    if (owner instanceof SQLIdentifierExpr) {
        names.add(((SQLIdentifierExpr) owner).normalizedName());
    } else if (owner instanceof SQLPropertyExpr) {
        buildIdentifier((SQLPropertyExpr) owner, names);
    } else {
        throw new FastsqlException("not support : " + owner);
    }

    names.add(name);
}
 
Example 8
Source File: SqlToExprTranslator.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private QueryPlan convertExprTable(SQLExprTableSource from) {
    if (from.getSchema() == null)
        from.setSchema(rexBuilder.getDefaultSchema());//from.getExpr()类型必为SQLPropertyExpr
    String schemaName = SQLUtils.normalize(from.getSchema());
    String tableName = SQLUtils.normalize(from.getTableName());
    return rexBuilder.scan(schemaName,tableName).build();
}
 
Example 9
Source File: SwitchHeatbeatCommand.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void handle(MycatRequest request, MycatDataContext context, Response response) {
    try {
        String value = SQLUtils.normalize(request.getText().split("=")[1].trim());
        if (Boolean.parseBoolean(value)) {
            ReplicaSelectorRuntime.INSTANCE.restartHeatbeat();
        }else {
            ReplicaSelectorRuntime.INSTANCE.stopHeartBeat();
        }
        response.sendOk();
    } catch (Throwable e) {
        response.sendError(e);
    }
}
 
Example 10
Source File: SelectSQLHandler.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public static String normalize(String sql) {
    if (sql == null) {
        return null;
    }
    if ("''".equals(sql)) {
        return "";
    }
    return SQLUtils.normalize(sql, DbType.mysql);
}
 
Example 11
Source File: ShowCreateTableSQLHandler.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected ExecuteCode onExecute(SQLRequest<SQLShowCreateTableStatement> request, MycatDataContext dataContext, Response response) {
    SQLShowCreateTableStatement ast = request.getAst();

    SQLName nameExpr = ast.getName();
    if (nameExpr == null) {
        response.sendError(new MycatException("table name is null"));
        return ExecuteCode.PERFORMED;
    }
    String schemaName = dataContext.getDefaultSchema();
    String tableName;
    if (nameExpr instanceof SQLIdentifierExpr) {
        tableName = ((SQLIdentifierExpr) nameExpr).normalizedName();
    }else if (nameExpr instanceof SQLPropertyExpr){
        schemaName =
                ((SQLIdentifierExpr)((SQLPropertyExpr) nameExpr).getOwner()).normalizedName();
        tableName = SQLUtils.normalize(((SQLPropertyExpr) nameExpr).getName());
    }else {
        response.proxyShow(ast);
        return ExecuteCode.PERFORMED;
    }
    TableHandler table = MetadataManager.INSTANCE.getTable(schemaName, tableName);
    if (table == null){
        response.proxyShow(ast);
        return ExecuteCode.PERFORMED;
    }
    String createTableSQL = table.getCreateTableSQL();

    ResultSetBuilder resultSetBuilder = ResultSetBuilder.create();
    resultSetBuilder.addColumnInfo("Table", JDBCType.VARCHAR);
    resultSetBuilder.addColumnInfo("Create Table", JDBCType.VARCHAR);
    resultSetBuilder.addObjectRowPayload(Arrays.asList(table.getTableName(),createTableSQL));
    response.sendResultSet(()->resultSetBuilder.build(),()->{throw  new UnsupportedOperationException();});
    return ExecuteCode.PERFORMED;
}
 
Example 12
Source File: AnalyzeHanlder.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected ExecuteCode onExecute(SQLRequest<MySqlAnalyzeStatement> request, MycatDataContext dataContext, Response response) {
    MySqlAnalyzeStatement ast = request.getAst();
    List<SQLExprTableSource> tableSources = Optional.ofNullable(ast.getTableSources()).orElse(Collections.emptyList());
    if (tableSources.isEmpty()) {
        response.sendError(new MycatException("need tables"));
        return ExecuteCode.PERFORMED;
    } else {
        ResultSetBuilder resultSetBuilder = ResultSetBuilder.create();
        resultSetBuilder.addColumnInfo("Table", JDBCType.VARCHAR);
        resultSetBuilder.addColumnInfo("Op", JDBCType.VARCHAR);
        resultSetBuilder.addColumnInfo("Msg_type", JDBCType.VARCHAR);
        resultSetBuilder.addColumnInfo("Msg_Text", JDBCType.VARCHAR);

        for (SQLExprTableSource tableSource : tableSources) {
            String schemaName = SQLUtils.normalize(tableSource.getSchema());
            String tableName = SQLUtils.normalize(tableSource.getTableName());
            resultSetBuilder.addObjectRowPayload(Arrays.asList(
                    schemaName+"."+tableName,
                    "analyze",
                    "status",
                    "OK"
            ));
            TableHandler tableHandler = MetadataManager.INSTANCE.getTable(schemaName, tableName);
            if (tableHandler == null) {
                response.sendError(new MycatException(tableSource + "不存在"));
                return ExecuteCode.PERFORMED;
            }
            StatisticCenter.INSTANCE.computeTableRowCount(tableHandler);
        }
        response.sendResultSet(()->resultSetBuilder.build(),()->{throw new UnsupportedOperationException();});
        return ExecuteCode.PERFORMED;
    }


}
 
Example 13
Source File: MycatCalciteMySqlNodeVisitor.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
SqlIdentifier buildIdentifier(SQLIdentifierExpr x) {
    return new SqlIdentifier(SQLUtils.normalize(x.getName()), SqlParserPos.ZERO);
}
 
Example 14
Source File: CloseJdbcDatasourceCommand.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void handle(MycatRequest request, MycatDataContext context, Response response) {
    String s = SQLUtils.normalize(request.getText().split("=")[1].trim());
   throw new UnsupportedOperationException();//todo

}
 
Example 15
Source File: UpdateSQLHandler.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
public static void updateHandler(SQLStatement sql, MycatDataContext dataContext, SQLExprTableSource tableSource, Response receiver) {
    MycatDBClientMediator mycatDBClientMediator = MycatDBs.createClient(dataContext);
    String schemaName = Optional.ofNullable(tableSource.getSchema() == null ? dataContext.getDefaultSchema() : tableSource.getSchema())
            .map(i-> SQLUtils.normalize(i)).orElse(null);
    String tableName = SQLUtils.normalize(tableSource.getTableName());
    SchemaHandler schemaHandler;
    Optional<Map<String, SchemaHandler>> handlerMapOptional = Optional.ofNullable(mycatDBClientMediator)
            .map(i -> i.config())
            .map(i -> i.getSchemaMap());
    Optional<String> targetNameOptional = Optional.ofNullable(RootHelper.INSTANCE)
            .map(i -> i.getConfigProvider())
            .map(i -> i.currentConfig())
            .map(i -> i.getMetadata())
            .map(i -> i.getPrototype())
            .map(i -> i.getTargetName());
    if (!handlerMapOptional.isPresent()) {
        if (targetNameOptional.isPresent()) {
            receiver.proxyUpdate(targetNameOptional.get(), Objects.toString(sql));
            return;
        } else {
            receiver.sendError(new MycatException("Unable to route:" + sql));
            return;
        }
    } else {
        Map<String, SchemaHandler> handlerMap = handlerMapOptional.get();
        schemaHandler = Optional.ofNullable(handlerMap.get(schemaName))
                .orElseGet(() -> {
                    if (mycatDBClientMediator.getSchema() == null) {
                        throw new MycatException("unknown schema:"+schemaName);//可能schemaName有值,但是值名不是配置的名字
                    }
                    return handlerMap.get(mycatDBClientMediator.getSchema());
                });
        if (schemaHandler == null) {
            receiver.sendError(new MycatException("Unable to route:" + sql));
            return;
        }
    }
    String defaultTargetName = schemaHandler.defaultTargetName();
    Map<String, TableHandler> tableMap = schemaHandler.logicTables();
    TableHandler tableHandler = tableMap.get(tableName);
    ///////////////////////////////common///////////////////////////////
    if (tableHandler == null) {
        receiver.proxyUpdate(defaultTargetName, sql.toString());
        return;
    }
    String string = sql.toString();
    if (sql instanceof MySqlInsertStatement) {
        switch (tableHandler.getType()) {
            case SHARDING:
                receiver.multiInsert(string, tableHandler.insertHandler().apply(new ParseContext(sql.toString())));
                break;
            case GLOBAL:
                receiver.multiGlobalInsert(string, tableHandler.insertHandler().apply(new ParseContext(sql.toString())));
                break;
        }

    } else if (sql instanceof com.alibaba.fastsql.sql.dialect.mysql.ast.statement.MySqlDeleteStatement) {
        switch (tableHandler.getType()) {
            case SHARDING:
                receiver.multiUpdate(string, tableHandler.deleteHandler().apply(new ParseContext(sql.toString())));
                break;
            case GLOBAL:
                receiver.multiGlobalUpdate(string, tableHandler.deleteHandler().apply(new ParseContext(sql.toString())));
                break;
        }

    } else if (sql instanceof com.alibaba.fastsql.sql.dialect.mysql.ast.statement.MySqlUpdateStatement) {
        switch (tableHandler.getType()) {
            case SHARDING:
                receiver.multiUpdate(string, tableHandler.updateHandler().apply(new ParseContext(sql.toString())));
                break;
            case GLOBAL:
                receiver.multiGlobalUpdate(string, tableHandler.deleteHandler().apply(new ParseContext(sql.toString())));
                break;
        }
    } else {
        throw new UnsupportedOperationException("unsupported statement:" + sql);
    }

}