Search code examples
prestosql-parser

Generate SQL statement using Facebook Presto SQL Parser


I am struggling to generate the SQL statement using the Presto Parser. Here are the usecase details-

  1. Parse existing SQL statement which is generated using external frontend ui (nodejs app).
  2. Append new columns and where clause conditions.
  3. Regenerate SQL Statement. These SQL will be executed on Hive/Spark.

So far I had a success on step 1 & 2 using the Facebook Presto parser and not able to figure out how to generate SQL back?

Shall I use some other library to generate SQL? any suggestions here would be appreciated.


Solution

  • You can use the SqlFormatter class (https://github.com/prestosql/presto/blob/master/presto-parser/src/main/java/io/prestosql/sql/SqlFormatter.java) to convert from a parsed syntax tree back to SQL text:

    SqlParser parser = new SqlParser();
    Statement statement = parser.createStatement("SELECT * FROM t WHERE v = 0", new ParsingOptions());
    String formatted = SqlFormatter.formatSql(statement);
    

    Keep in mind that these are not public APIs in Presto and are subject to change.