sql-metadata icon indicating copy to clipboard operation
sql-metadata copied to clipboard

Aliases with "Union"

Open usbo opened this issue 2 years ago • 1 comments

SQL:

select a.A as M
from tab1 a
union all
select b.B as M
from tab2 b
parser = Parser(SQL)
print(parser.columns_dict, parser.columns_aliases)

Result:

{"M": "tab1.A"}

Expected:

{"M": ["tab1.A", "tab2.B"]}

usbo avatar May 29 '23 20:05 usbo

ditto...to solve this I had to hack together something that does this:

  • breaks up query into each query type ("WITH" queries, subqueries and the main select query)
  • for each query, if "UNION" in query split on union type ("UNION" or "UNION ALL")
  • parse those select statements individually and merge them into a single 'union_column_aliases_dict'
  • update the original columns_aliases attribute with this 'union_column_aliases_dict'

definitely not 'Pythonic' and wish it could be handled automatically by this library but SQLToken.is_potential_column_alias stops any 'updates' from happening if the parser sees the same alias twice in the query

trevdoz avatar Jul 28 '23 17:07 trevdoz