com.alibaba.fastsql.sql.SQLUtils Java Examples

The following examples show how to use com.alibaba.fastsql.sql.SQLUtils. 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
@Override
public Iterator<RowBaseIterator> executeSqls(String sql, MycatDBContext dbContext) {
    List<SQLStatement> statements = SQLUtils.parseStatements(sql, DbType.mysql);
    List<MycatSQLPrepareObject> collect = new ArrayList<>();
    for (SQLStatement statement : statements) {
        MycatSQLPrepareObject query = prepare(sql, null, statement, dbContext);
        collect.add(query);
    }
    Iterator<MycatSQLPrepareObject> iterator = collect.iterator();
    return new Iterator<RowBaseIterator>() {
        @Override
        public boolean hasNext() {
            return iterator.hasNext();
        }

        @Override
        public RowBaseIterator next() {
            return iterator.next().plan(Collections.emptyList()).run();
        }
    };
}
 
Example #2
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 #3
Source File: MycatDBSharedServerImpl.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
@NotNull
private MycatSQLPrepareObject getMycatPrepareObject(
        MycatDBContext uponDBContext,
        String templateSql,
        Long id,
        SQLStatement sqlStatement,
        int variantRefCount,
        Function<ParseContext, Iterator<TextUpdateInfo>> accept) {
    return new MycatDelegateSQLPrepareObject(id, uponDBContext, templateSql, new MycatTextUpdatePrepareObject(id, variantRefCount, (prepareObject, params) -> {
        StringBuilder out = new StringBuilder();
        SQLASTOutputVisitor visitor = SQLUtils.createOutputVisitor(out, DbType.mysql);
        visitor.setInputParameters(params);
        sqlStatement.accept(visitor);
        String sql = out.toString();
        ParseContext parseContext = new ParseContext();
        parseContext.setSql(sql);
        return accept.apply(parseContext);
    }, uponDBContext));

}
 
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: 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 #6
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 #7
Source File: MysqlTableReplacer.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean visit(SQLExprTableSource x) {
    String schemaName = x.getSchema();
    String tableName = x.getTableName();
    if (schemaName != null) {
        schemaName = SQLUtils.forcedNormalize(schemaName, DbType.mysql);
    }
    if (tableName != null) {
        tableName = SQLUtils.forcedNormalize(tableName, DbType.mysql);
    }
    if (schemaName == null) {
        schemaName = this.schemaName;
    }
    Objects.requireNonNull(tableName);
    SchemaInfo mappingTable = getMappingTable(schemaName, tableName);
    if (mappingTable!=null){
        x.setExpr(new SQLPropertyExpr(mappingTable.getTargetSchema(), mappingTable.getTargetTable()));
    }
    return super.visit(x);
}
 
Example #8
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 #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: ValuesPlanTest.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void test4(){
    MyRelBuilder builder = new MyRelBuilder();
    SqlToExprTranslator sqlToExprTranslator = new SqlToExprTranslator(builder);
    SQLSelectStatement sqlSelectStatement = (SQLSelectStatement)SQLUtils.parseSingleMysqlStatement("select 1");
    SQLSelectQuery query = sqlSelectStatement.getSelect().getQuery();
    QueryPlan queryPlan1 = sqlToExprTranslator.convertQueryRecursive(query);
    Scanner scan = queryPlan1.scan(dataContext, 0);
    RowType type = queryPlan1.getType();
    String collect = scan.stream().map(i -> i.toString()).collect(Collectors.joining());
}
 
Example #11
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 #12
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 #13
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 #14
Source File: ShowTablesSQLHandler.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
    protected ExecuteCode onExecute(SQLRequest<SQLShowTablesStatement> request, MycatDataContext dataContext, Response response) {
        SQLShowTablesStatement ast = request.getAst();
        if (ast.getDatabase() == null && dataContext.getDefaultSchema() != null) {
            ast.setDatabase(new SQLIdentifierExpr(dataContext.getDefaultSchema()));
        }
        SQLName database = ast.getDatabase();
        if (database == null){
            response.sendError(new MycatException("NO DATABASES SELECTED"));
            return ExecuteCode.PERFORMED;
        }
        Optional<SchemaHandler> schemaHandler = Optional.ofNullable(MetadataManager.INSTANCE.getSchemaMap()).map(i -> i.get(SQLUtils.normalize(ast.getDatabase().toString())));
        String targetName = schemaHandler.map(i -> i.defaultTargetName()).map(name -> ReplicaSelectorRuntime.INSTANCE.getDatasourceNameByReplicaName(name, true, null)).orElse(null);
        if (targetName != null) {
            response.proxySelect(targetName, ast.toString());
        } else {
            response.proxyShow(ast);
        }
//        DDLManager.INSTANCE.updateTables();
//        String sql = ShowStatementRewriter.rewriteShowTables(dataContext.getDefaultSchema(), request.getAst());
//        LOGGER.info(sql);
//        //show 语句变成select 语句
//
//        try (RowBaseIterator query = MycatDBs.createClient(dataContext).query(sql)) {
//            //schema上默认的targetName;
//            try {
//                SQLShowTablesStatement showTablesStatement = request.getAst();
//                SQLName from = showTablesStatement.getFrom();
//                String schema = SQLUtils.normalize(from == null ? dataContext.getDefaultSchema() : from.getSimpleName());
//                if (WithDefaultTargetInfo(response, sql, query, schema)) return ExecuteCode.PERFORMED;
//            } catch (Exception e) {
//                LOGGER.error("", e);
//            }
//            response.sendResultSet(()->query, null);
//            return ExecuteCode.PERFORMED;
//        }
//        response.proxyShow(ast);
        return ExecuteCode.PERFORMED;
    }
 
Example #15
Source File: PreProcesssorTest.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private String process(String defaultSchema, String sql) {
    SQLStatement sqlStatement = SQLUtils.parseSingleMysqlStatement(sql);
    Scope scope = new Scope(defaultSchema);

    sqlStatement.accept(scope);
    scope.build();
    PreProcesssor preProcesssor = new PreProcesssor(defaultSchema);
    sqlStatement.accept(preProcesssor);
    return sqlStatement.toString();
}
 
Example #16
Source File: TableCollector.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public static Map<String, Collection<String>> collect(String defaultSchema, String sql) {
    Map<String, Collection<String>> collectionMap = new HashMap<>();
    try {
        SQLStatement sqlStatement = SQLUtils.parseSingleMysqlStatement(sql);
        sqlStatement.accept(new MySqlASTVisitorAdapter() {
            @Override
            public boolean visit(SQLExprTableSource x) {
                String schema = x.getSchema();
                String tableName = x.getTableName();
                if (schema == null) {
                    schema = defaultSchema;
                }
                if (schema == null) {
                    throw new UnsupportedOperationException("please use schema");
                }
                schema = SQLUtils.normalize(schema);
                tableName = SQLUtils.normalize(tableName);
                Collection<String> strings = collectionMap.computeIfAbsent(schema, s -> new HashSet<>());
                strings.add(tableName);
                return super.visit(x);
            }
        });
    } catch (Throwable ignored) {

    }
    return collectionMap;
}
 
Example #17
Source File: SqlParser.java    From canal with Apache License 2.0 5 votes vote down vote up
/**
 * 解析sql
 *
 * @param sql sql
 * @return 视图对象
 */
public static SchemaItem parse(String sql) {
    try {
        SQLStatementParser parser = new MySqlStatementParser(sql);
        SQLSelectStatement statement = (SQLSelectStatement) parser.parseStatement();
        MySqlSelectQueryBlock sqlSelectQueryBlock = (MySqlSelectQueryBlock) statement.getSelect().getQuery();

        SchemaItem schemaItem = new SchemaItem();
        schemaItem.setSql(SQLUtils.toMySqlString(sqlSelectQueryBlock));
        SQLTableSource sqlTableSource = sqlSelectQueryBlock.getFrom();
        List<TableItem> tableItems = new ArrayList<>();
        SqlParser.visitSelectTable(schemaItem, sqlTableSource, tableItems, null);
        tableItems.forEach(tableItem -> schemaItem.getAliasTableItems().put(tableItem.getAlias(), tableItem));

        List<FieldItem> fieldItems = collectSelectQueryFields(sqlSelectQueryBlock);
        fieldItems.forEach(fieldItem -> schemaItem.getSelectFields().put(fieldItem.getFieldName(), fieldItem));

        schemaItem.init();

        if (schemaItem.getAliasTableItems().isEmpty() || schemaItem.getSelectFields().isEmpty()) {
            throw new ParserException("Parse sql error");
        }
        return schemaItem;
    } catch (Exception e) {
        throw new ParserException();
    }
}
 
Example #18
Source File: SqlParser.java    From canal with Apache License 2.0 5 votes vote down vote up
public static String parse4SQLSelectItem(MySqlSelectQueryBlock sqlSelectQueryBlock) {
    List<SQLSelectItem> selectItems = sqlSelectQueryBlock.getSelectList();
    StringBuilder subSql = new StringBuilder();
    int i = 0;
    for (SQLSelectItem sqlSelectItem : selectItems) {
        if (i != 0) {
            subSql.append(",");
        } else {
            i++;
        }
        subSql.append(SQLUtils.toMySqlString(sqlSelectItem));
    }
    return subSql.toString();
}
 
Example #19
Source File: SqlParser.java    From canal with Apache License 2.0 5 votes vote down vote up
public static String parse4WhereItem(MySqlSelectQueryBlock sqlSelectQueryBlock) {
    SQLExpr sqlExpr = sqlSelectQueryBlock.getWhere();
    if (sqlExpr != null) {
        return SQLUtils.toMySqlString(sqlExpr);
    }
    return null;
}
 
Example #20
Source File: SqlParser.java    From canal with Apache License 2.0 5 votes vote down vote up
public static String parse4GroupBy(MySqlSelectQueryBlock sqlSelectQueryBlock) {
    SQLSelectGroupByClause expr = sqlSelectQueryBlock.getGroupBy();
    if (expr != null) {
        return SQLUtils.toMySqlString(expr);
    }
    return null;
}
 
Example #21
Source File: SqlParser.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
/**
 * 解析sql
 *
 * @param sql sql
 * @return 视图对象
 */
public static SchemaItem parse(String sql) {
    try {
        SQLStatementParser parser = new MySqlStatementParser(sql);
        SQLSelectStatement statement = (SQLSelectStatement) parser.parseStatement();
        MySqlSelectQueryBlock sqlSelectQueryBlock = (MySqlSelectQueryBlock) statement.getSelect().getQuery();

        SchemaItem schemaItem = new SchemaItem();
        schemaItem.setSql(SQLUtils.toMySqlString(sqlSelectQueryBlock));
        SQLTableSource sqlTableSource = sqlSelectQueryBlock.getFrom();
        List<TableItem> tableItems = new ArrayList<>();
        SqlParser.visitSelectTable(schemaItem, sqlTableSource, tableItems, null);
        tableItems.forEach(tableItem -> schemaItem.getAliasTableItems().put(tableItem.getAlias(), tableItem));

        List<FieldItem> fieldItems = collectSelectQueryFields(sqlSelectQueryBlock);
        fieldItems.forEach(fieldItem -> schemaItem.getSelectFields().put(fieldItem.getFieldName(), fieldItem));

        schemaItem.init();

        if (schemaItem.getAliasTableItems().isEmpty() || schemaItem.getSelectFields().isEmpty()) {
            throw new ParserException("Parse sql error");
        }
        return schemaItem;
    } catch (Exception e) {
        throw new ParserException();
    }
}
 
Example #22
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 #23
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 #24
Source File: ContextExecuter.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean visit(SQLMethodInvokeExpr x) {
    List<SQLExpr> arguments = x.getArguments();
    String methodName = x.getMethodName();
    SQLObject parent = x.getParent();
    if (parent instanceof SQLReplaceable) {
        Map<String, MySQLFunction> functions = context.functions();
        if (functions != null) {
            MySQLFunction mySQLFunction = functions.get(methodName);
            if (mySQLFunction != null) {
                String[] strings = arguments.stream().map(i -> SQLUtils.normalize(Objects.toString(i))).toArray(i -> new String[i]);
                Object res = mySQLFunction.eval(context, strings);
                SQLExpr sqlExpr;
                if (res instanceof SQLValuableExpr){
                    sqlExpr =(SQLValuableExpr) res;
                }else {
                    sqlExpr = SQLExprUtils.fromJavaObject(res);
                }
                sqlExpr.setParent(parent);
                ((SQLReplaceable) parent).replace(x, sqlExpr);

                try {
                    if (parent instanceof SQLSelectItem) {
                        ((SQLSelectItem) parent).setAlias(x.toString());
                    }
                } catch (Throwable ignored) {

                }
            }
        }
    }
    return super.visit(x);
}
 
Example #25
Source File: GlobalTable.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Function<ParseContext, Iterator<TextUpdateInfo>> deleteHandler() {
    return new Function<ParseContext, Iterator<TextUpdateInfo>>() {
        @Override
        public Iterator<TextUpdateInfo> apply(ParseContext parseContext) {
            SQLStatement sqlStatement = SQLUtils.parseSingleMysqlStatement(parseContext.getSql());
            MySqlDeleteStatement sqlStatement1 = (MySqlDeleteStatement) sqlStatement;
            SQLExprTableSource tableSource = (SQLExprTableSource)sqlStatement1.getTableSource();
            return updateHandler(tableSource, sqlStatement1);
        }
    };
}
 
Example #26
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 #27
Source File: GlobalTable.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Function<ParseContext, Iterator<TextUpdateInfo>> updateHandler() {
    return new Function<ParseContext, Iterator<TextUpdateInfo>>() {
        @Override
        public Iterator<TextUpdateInfo> apply(ParseContext s) {
            SQLStatement sqlStatement = SQLUtils.parseSingleMysqlStatement(s.getSql());
            MySqlUpdateStatement sqlStatement1 = (MySqlUpdateStatement) sqlStatement;
            SQLExprTableSource tableSource = (SQLExprTableSource)sqlStatement1.getTableSource();
            return updateHandler(tableSource, sqlStatement1);
        }
    };
}
 
Example #28
Source File: HBTQueryConvertor.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private RelDataType tryGetRelDataTypeByParse(String targetName, String sql) {
    try {
        RelDataType relDataType;
        MycatCalcitePlanner planner = MycatCalciteSupport.INSTANCE.createPlanner(context);
        SQLStatement sqlStatement = SQLUtils.parseSingleMysqlStatement(sql);
        SqlNode parse = planner.parse(MycatSqlUtil.getCalciteSQL(sqlStatement));
        parse = parse.accept(new SqlShuttle() {
            @Override
            public SqlNode visit(SqlIdentifier id) {
                if (id.names.size() == 2) {
                    String schema = id.names.get(0);
                    String table = id.names.get(1);
                    MycatLogicTable logicTable = context.getLogicTable(targetName, schema, table);
                    if (logicTable!=null) {
                        TableHandler table1 = logicTable.getTable();
                        return new SqlIdentifier(Arrays.asList(table1.getSchemaName(), table1.getTableName()), SqlParserPos.ZERO);
                    }
                }
                return super.visit(id);
            }
        });
        parse = planner.validate(parse);
        relDataType = planner.convert(parse).getRowType();
        return relDataType;
    } catch (Throwable e) {
        log.warn("", e);
    }
    return null;
}
 
Example #29
Source File: GlobalTable.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Function<ParseContext, Iterator<TextUpdateInfo>> insertHandler() {
    return new Function<ParseContext, Iterator<TextUpdateInfo>>() {
        @Override
        public Iterator<TextUpdateInfo> apply(ParseContext s) {
            SQLStatement sqlStatement = SQLUtils.parseSingleMysqlStatement(s.getSql());
            MySqlInsertStatement sqlStatement1 = (MySqlInsertStatement) sqlStatement;
            SQLExprTableSource tableSource = sqlStatement1.getTableSource();
            return updateHandler(tableSource, sqlStatement1);
        }
    };
}
 
Example #30
Source File: MycatDBSharedServerImpl.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
private PrepareObject prepare(String sql, Long id, MycatDBContext dbContext) {
    SQLStatement sqlStatement = SQLUtils.parseSingleMysqlStatement(sql);//不支持多语句的预处理
    return prepare(sql, id, sqlStatement, dbContext);
}