Apache Calcite to Find Selected Columns in an SQL String

拟墨画扇 提交于 2020-03-23 12:11:37

问题


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.


回答1:


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.




回答2:


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());
}


来源:https://stackoverflow.com/questions/44508240/apache-calcite-to-find-selected-columns-in-an-sql-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!