Using Facebook presto-parser

I am trying to use presto-parser. What I need to know is how to analyze and extract the query body our of a created Statement:

SqlParser SQL_PARSER = new SqlParser();
Statement statement = SQL_PARSER.createStatement(query);

There doesn’t seem any way to get that from the Statement getters/setters. I debugged the Statement object and I can see from the debug view the values I need to get.


enter image description here

I need to get the select,from,where,groupBy,orderBy and limit values that were extracted out by the SqlParser.


From the sql string, you can get a Query (which extends Statement) by casting down the Statement. Query.getQueryBody returns a QueryBody which you can cast to a QuerySpecification(which extends QueryBody). From the QuerySpecification, you can now get what you’re looking for. Here’s a simple example:

public class PrestoParserTest {
    public static void main(String[] args) {
        SqlParser parser = new SqlParser();
        String sql = "select * from xyz where x=y group by x order by y limit 10";
        Query query = (Query)parser.createStatement(sql);
        QuerySpecification body = (QuerySpecification)query.getQueryBody();
        Select select = body.getSelect();
        System.out.println("Columns = " + select.getSelectItems());
        System.out.println("From = " + body.getFrom().get());
        Optional<Expression> where = body.getWhere();
        System.out.println("Where = " + where.get());
        System.out.println("Group by = " + body.getGroupBy());
        System.out.println("Order by = " + body.getOrderBy());
        System.out.println("Limit = " + body.getLimit().get());


Running this returns:

Columns = [*]
From = Table{xyz}
Where = ("x" = "y")
Group by = ["x"]
Order by = [SortItem{sortKey="y", ordering=ASCENDING, nullOrdering=UNDEFINED}]
Limit = 10

Leave a Reply

Your email address will not be published. Required fields are marked *