使用druid解析SQL时,SQLIdentifierExpr的getSourceColumn无法正确获取表名字符串的位置

pkln4tw6  于 2022-10-22  发布在  Druid
关注(0)|答案(3)|浏览(174)

您好,在使用druid解析SQL时,如果是单表查询的SQL,SQLIdentifierExpr的getSourceColumn无法正确获取表名的pos位置,返回的是0。(已设置KeepSourceLocation参数)
如果是多表查询的SQL,第一张表的getSourceColumn返回0 ,但是其余表的getSourceColumn能够正确返回pos位置。
请问是需要有其他的配置,还是我哪里的用法不对呢?

ercv8c1e

ercv8c1e1#

请提供重现问题的testcase

lfapxunr

lfapxunr2#

您好,测试的代码如下:

public void test1(){
    DbType dbType = JdbcConstants.MYSQL;
    String sql = "select test1.id, test2.id from test1,test2 where test1.id=test2.id";
    String formatsql = SQLUtils.format(sql, dbType, Arrays.asList(new SQLParserFeature[]{
            SQLParserFeature.KeepSourceLocation}));
    System.out.println("SQL:\n" +  formatsql);

    List<SQLStatement> stmtList = SQLUtils.parseStatements(formatsql, dbType,
            SQLParserFeature.KeepSourceLocation);
    SQLSelectStatement stmt1 = (SQLSelectStatement)stmtList.get(0);
    SQLSelectQueryBlock sqlSelectQueryBlock = (SQLSelectQueryBlock) stmt1.getSelect().getQuery();

    // 获取表
    SQLJoinTableSource table = (SQLJoinTableSource)sqlSelectQueryBlock.getFrom();  //test1 test2
    SQLExprTableSource left = (SQLExprTableSource)table.getLeft();  //test1
    SQLExprTableSource right = (SQLExprTableSource)table.getRight(); //test2
    SQLIdentifierExpr leftIdentifer = (SQLIdentifierExpr) left.getExpr();
    SQLIdentifierExpr rightIdentifer = (SQLIdentifierExpr) right.getExpr();
    System.out.println("test1 in from pos:" + leftIdentifer.getSourceLine() + " " + leftIdentifer.getSourceColumn());
    System.out.println("test2 in from pos:" + rightIdentifer.getSourceLine() + " " + rightIdentifer.getSourceColumn());

    // 获取where条件
    SQLBinaryOpExpr where = (SQLBinaryOpExpr) sqlSelectQueryBlock.getWhere();   //test1.id=test2.id
    SQLPropertyExpr leftCond = (SQLPropertyExpr) where.getLeft();  //test1.id
    SQLPropertyExpr rightCond = (SQLPropertyExpr) where.getRight();  //test2.id
    SQLIdentifierExpr leftCondIdentifer = (SQLIdentifierExpr) leftCond.getOwner();
    SQLIdentifierExpr rightCondIdentifer = (SQLIdentifierExpr) rightCond.getOwner();
    System.out.println("test1 in where pos:" + leftCondIdentifer.getSourceLine() + " " + leftCondIdentifer.getSourceColumn());
    System.out.println("test2 in where pos:" + rightCondIdentifer.getSourceLine() + " " + rightCondIdentifer.getSourceColumn());
}

输出结果为:
SQL:
SELECT test1.id, test2.id
FROM test1, test2
WHERE test1.id = test2.id
test1 in from pos:2 0
test2 in from pos:2 12
test1 in where pos:0 0
test2 in where pos:3 17

从结果上面看,test2的pos都是对的,但是test1的pos不对,很奇怪,麻烦帮忙看看是我哪里用的不对?
使用的版本为1.21

cgfeq70w

cgfeq70w3#

您好,请帮忙看下这个问题

相关问题