8

I have just started to explore JSqlparser. According to my understanding, I have modified the TablesNamesFinder to extract columns and tables and its working fine but a very small problem.

@Override
public void visit(Column col) {
    Column c = col;
    String cname = c.getFullyQualifiedName();
    Table t = c.getTable();
    System.out.println(t.getName());
}

This wont print table, for most of the cases it prints null and for very few cases it prints alias of the table but not the table. Is there anything I am forgetting?

Rest of the visits

@Override
public void visit(SelectExpressionItem exp){
    exp.getExpression().accept(this);  
}        

@Override
public void visit(Table tableName) {
   // System.out.println(tableName.getFullyQualifiedName()); 
}

@Override
public void visit(Select select) {
    select.getSelectBody().accept(this);
}
SkyWalker
  • 28,384
  • 14
  • 74
  • 132
Waleed
  • 1,097
  • 18
  • 45

1 Answers1

7

First of all your sourcecode is correct. You have to keep in mind:

JSqlParser is only a parser. So if you do something like

select col1 from table1

The parser generated object Column does not know its tablename. This is only the case if you write it fully qualified:

select table1.col1 from table1

Similar behaviour occurs with aliases. JSqlParser does not expand alias definitions.

Why? If you look at this example, which is a correct SQL:

select col1 from table1, table2

it becomes clear, that calculating the table the column belongs to needs the database schema itself.

wumpz
  • 8,257
  • 3
  • 30
  • 25
  • and for aggregate functions like sum(col1 * col2), I can catch these in Functions visit, is there a better way? Can I have more info about what names of the parts you have given to query. Like: Select (col1,col2,col3,) here col1,col2,col3 are select body. Can I have wiki? – Waleed May 23 '16 at 08:58
  • I am not sure, what you mean? Do you mean context? Like which column within which construct (e.g. which function)? The context is derivable from the parse tree. Using the visitor like you did is ok. – wumpz May 23 '16 at 19:05