google / zetasql

ZetaSQL - Analyzer Framework for SQL
Apache License 2.0
2.32k stars 219 forks source link

Get SQL source from ResolvedNodes after Analyzer#analyzeStatement #63

Closed estebgonza closed 3 years ago

estebgonza commented 3 years ago

Hi everyone,

Thanks a lot for the ZetaSQL supporting.

I'm looking to get the SQL source for each aggregate function in my query. For a given query SELECT SUM(col1) FROM mytable I want be able to get SUM(col1) in string.

So, at date I'm playing with the Analyzer#analyzeStatement. I get a ResolvedStatement and I visit with my own ResolvedNodes.Visitor

@Override
public void visit(ResolvedNodes.ResolvedAggregateFunctionCall node) {
    // Here I get my SUM node which contains my arguments nodes
    super.visit(node);
}

And after I'm little bit lost. I don't understand which way I can use in order to get the SQL source from this resolved node, or build back the SQL just for this node.

Thanks by advance for your help. Have a good day, Esteban

matthewcbrown commented 3 years ago

I think you probably want

String fnSql = Analyzer.buildExpression(node, catalog);
estebgonza commented 3 years ago

Perfect ! Thanks a lot ! It's looks like the way I want 🎉

By the way, this method Analyzer#buildExpression on a node who like this: SUM(col1 + 1) returns SUM(a_1 + (NUMERIC "1"))

I understand for the (NUMERIC "1") and its works when I execute in BigQuery.

But about a_1 instead col1 I misunderstand. Just my column name replaced. Do you understand why it's works like that ?

Thanks a lot again

serebro commented 3 years ago

Hi @estebgonza

I think addExpressionColumn will help you. Example: https://github.com/google/zetasql/blob/697da738be2af3b6b9492c73c55616d8b9fed0b6/javatests/com/google/zetasql/AnalyzerTest.java#L155-L159

estebgonza commented 3 years ago

Thanks a lot guys for your answers. Perfect.

meghabedi commented 1 year ago

@estebgonza Can you please show me your code? I'm trying to do more or less same thing.