how to get the tablenames/functions from postgresql query using java

52 views Asked by At

1 ) Let say the Query is,

Select * from Users;

I need "Users" from above query. Also It could be more than one table name.

2 ) Let say the Query is,

  • Select 1 from pg_sleep(1);

  • Select current_user;

I need "pg_sleep", "*current_user" from above query. Also It could be more than one function.

I tried with net.sf.jsqlparser, However I could get tablenames only using this package. Unable to get functions list.

Is there anyway to get these functions/tablenames ?

1

There are 1 answers

0
Buğra Kömürcü On

You used the net.sf.jsqlparser library in the Java programming language to extract the table names and contents from the relevant queries, and you were able to successfully extract the table names. However, you are having trouble getting capacity. Below you can find an example code to solve this situation

    import net.sf.jsqlparser.parser.CCJSqlParserUtil;
    import net.sf.jsqlparser.statement.Statement;
    import net.sf.jsqlparser.statement.select.Select;
    import net.sf.jsqlparser.statement.select.SelectItem;
    import net.sf.jsqlparser.statement.select.SelectVisitorAdapter;
    import net.sf.jsqlparser.statement.select.SelectVisitor;
    
    public class QueryParser {
    
        public static void main(String[] args) {
            parseQuery("Select * from Users;");
            parseQuery("Select 1 from pg_sleep(1); Select current_user;");
        }
    
        public static void parseQuery(String sql) {
            try {
                Statement statement = CCJSqlParserUtil.parse(sql);
    
                if (statement instanceof Select) {
                    Select select = (Select) statement;
                    SelectVisitor selectVisitor = new SelectItemVisitor();
                    select.getSelectBody().accept(selectVisitor);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        static class SelectItemVisitor extends SelectVisitorAdapter {
            @Override
            public void visit(SelectItem selectItem) {
                String itemName = selectItem.toString();
                System.out.println(itemName);
            }
        }
    }