0

I use below code to get selected columns. But in the column item, why the table.getName() is alias name t1 or t2 and table.getAlias() is null?

Is any sample code to get the table name(Spark_Test_1, Spark_Test_2) and the alias table name(t1,t2) in the same time?

String sql  = "SELECT t1.AsOfD,t1.ValidD,t1.urn,t1.Money FROM Spark_Test_1 as t1 join  Spark_Test_2 as t2 on ( t1.AsOfD = t2.AsOfD)";

        Statement statement = CCJSqlParserUtil.parse(sqlStr);
        Select selectStatement = (Select) statement;
        for (int i = 0; i < size; i++) {
            Expression expression = ((SelectExpressionItem) selectitems.get(i))
                    .getExpression();
            //System.out.println("Expression:" + expression);
            if(expression instanceof  Column){
                Column col = (Column) expression;
                Table table = col.getTable();
                logger.info(table.getFullyQualifiedName());
                logger.info(table.getAlias());
                logger.info(table.getName());

            }
        }
simafengyun
  • 423
  • 1
  • 9
  • 19

1 Answers1

0

This is not an issue but normal JSqlParser behaviour. JSqlParser gives you a structured way to look at your SQL but does no semantic processing. It is a parser.

Therefore for a column the tablename is in your example indeed the alias. JSqlParser does not resolve this alias to the real table name. You have to process the from items to get the tablenames its aliases and map it to your columns.

IMHO you should follow the path of TableNamesFinder to build a visitor that extracts your columns and additional gets your tables including name and alias. You have to be careful to use only the tables that are valid within your columns context, e.g.

select data.a from (select a from mydata) as data 

Here data is an alias for a subsql and not for a table.

wumpz
  • 8,257
  • 3
  • 30
  • 25