[alibaba/druid]SQLSelectQueryBlock 设置括号无效,导致执行union sql 报错

2025-11-11 609 views
0
    公司可视化项目需要根据数据源动态拼接SQL,拼接预览 Union SQL 时 setBracket 无效,导致执行报错,请问下要怎么设置(MySqlSelectQueryBlock 的有效)
    //DbType dbType = DbType.of("presto");
    //DbType dbType = DbType.of("oracle");
    //DbType dbType = DbType.of("sqlserver");
    DbType dbType = DbType.of("mysql");

    List<SQLSelectQueryBlock> queryBlocks = Lists.newArrayList();
    for (int i = 0; i < 2; i++) {
        String sql = "SELECT column1, column2  from table1 LIMIT 100";
        List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);
        SQLSelectStatement sqlSelectStatement = (SQLSelectStatement) stmtList.get(0);
        SQLSelectQueryBlock queryBlock = (SQLSelectQueryBlock) sqlSelectStatement.getSelect().getQuery();
        queryBlock.setBracket(true);
        queryBlocks.add(queryBlock);
    }

    SQLUnionQuery sqlUnionQuery = new SQLUnionQuery();
    sqlUnionQuery.setOperator(SQLUnionOperator.UNION_ALL);

    sqlUnionQuery.setLeft(queryBlocks.get(0));
    for (SQLSelectQueryBlock queryBlock : queryBlocks) {
        SQLSelectQuery right = sqlUnionQuery.getRight();
        if (right == null) {
            sqlUnionQuery.setRight(queryBlock);
        } else {
            SQLUnionQuery newUnion = new SQLUnionQuery();
            newUnion.setLeft(sqlUnionQuery);
            newUnion.setOperator(SQLUnionOperator.UNION_ALL);
            newUnion.setRight(queryBlock);
            sqlUnionQuery = newUnion;
        }
    }

    String sql = SQLUtils.toSQLString(sqlUnionQuery, dbType);
    System.out.println(sql);

    if (sql.startsWith("(")) {
        System.out.println("success");
    } else {
        System.err.println("error");
    }

回答

1

druid什么版本?

7

版本是1.2.4

7

同样遇到问题。 MySqlSelectQueryBlock 在打印的时候,括号会打印。