Is this the correct parseTree for a SQL join statement?

Viewed 37

I have written the following pared-down example to verify that the parse tree for the SQL FROM clause is correct. Particularly, that doing something like tbl1 JOIN tbl2 JOIN tbl3 JOIN ... is done correctly. Here is the grammar I currently have:

grammar Associativity1;
root: (select ';')* EOF;

select
    : 'SELECT' expr (',' expr)*
       ('FROM' tblExpr)?
    ;

expr
    : '(' expr ')'
    | subSelect
    | expr '=' expr
    | Atom
    ;

tblExpr
    : subSelect
    | tblExpr 'JOIN' tblExpr 'ON' expr
    | Atom
    ;

subSelect:
    '(' select ')'
    ;

Atom: [a-zA-Z]+ | [0-9]+;
WHITESPACE: [ \t\r\n] -> skip;

And the parse tree from the following statement (using the AAA's so easier to recognize from the parseTree:

SELECT 1
FROM (SELECT AAAAAAAAAA) 
JOIN (SELECT BBBBBBBBBB) ON (1=2) 
JOIN (SELECT CCCCCCCCCC) ON (2=3) 
JOIN (SELECT DDDDDDDDDD) ON (4=3);

enter image description here

If I am interpreting it correctly it is evaluating it as (feel like I'm writing lisp...):

# First join AAA to BBB.
# Join that result to CCC
# Join that result to DDD
JOIN(
  JOIN(
    JOIN(
      TblExpr(AAA), 
      TblExpr(BBB)),
     TblExpr(CCC)),
   TblExpr(DDD)
)
1 Answers

Yes, you interpretation is an accurate understanding of the parse tree.

Since SQL is a declarative language, I don't suppose there's any guarantee that the sql engine would actually execute the joins in that order, though it should guarantee the same result.

Related