2

I have a use case where I want to know the columns which have been selected in an SQL string.For instance, if the SQL is like this:
SELECT name, age*5 as intelligence FROM bla WHERE bla=bla
Then, after parsing the above String, I just want the output to be: name, intelligence.
Firstly, is it possible through Calcite?
Any other option is also welcome.

PS: I want to know this before actually running the query on database.

Michael Mior
  • 28,107
  • 9
  • 89
  • 113
Saurabh
  • 139
  • 2
  • 9

2 Answers2

7

This is definitely doable with Calcite. You'll want to start by creating an instance of SqlParser and parsing the query:

SqlParser parser = SqlParser.create(query)
SqlNode parsed = parser.parseQuery()

From there, you'll probably have the most success implementing the SqlVisitor interface. You'll want to first find a SqlSelect instance and then visit each expression being selected by calling visit on each element of getSelectList.

From there, how you proceed will depend on the complexity of expressions you want to support. However, it's probably sufficient to recursively visit all SqlCall nodes and their operands and then collect any SqlIdentifier values that you see.

Michael Mior
  • 28,107
  • 9
  • 89
  • 113
  • Can you just parse part of the sql expression? e.g. parsing `SUM(amount)/Count(id)` . I can make dummy sql but it'd be nice just to be able to parse a valid sql expression made out of sql functions. – nir Jan 18 '18 at 18:10
  • 2
    You should be able to use the `parseExpression` method of `SqlParser` for cases like this. – Michael Mior Jan 19 '18 at 14:51
0

It can be as simple as:

SqlParser parser = SqlParser.create(yourQuery);
SqlSelect selectNode = (SqlSelect) parser.parseQuery();
SqlNodeList list = selectNode.getList();

for (int i = 0; i < list.size(); i++) {
    System.out.println("Column " + (i + 1) + ": " + list.get(i).toString());
}
Dilip Raj Baral
  • 3,060
  • 6
  • 34
  • 62