querybuilder icon indicating copy to clipboard operation
querybuilder copied to clipboard

CteFinder currently does not support set operations

Open mindcrash opened this issue 2 years ago • 0 comments

When the right hand side of Union(), Intersect() or Except() contains Common Table Expressions these are not written because CteFinder currently has no support for traversing AbstractCombine nodes.

As I need this functionality right now, I patched the findInternal function in CteFinder as follows:

private List<AbstractFrom> findInternal(Query queryToSearch)
{
    var cteList = queryToSearch.GetComponents<AbstractFrom>("cte", engineCode);

    // Traverse the right hand side of Union, Intersect and Except operators, if any
    var combineClauses = queryToSearch.GetComponents<AbstractCombine>("combine", engineCode);

    foreach (var combineClause in combineClauses)
    {
        if (combineClause is Combine combine)
        {
            // Add common table expression nodes, if any
            cteList.AddRange(combine.Query.GetComponents<AbstractFrom>("cte", engineCode));
        }
    }
    
    var resultList = new List<AbstractFrom>();

    foreach (var cte in cteList)
    {
        if (namesOfPreviousCtes.Contains(cte.Alias))
            continue;

        namesOfPreviousCtes.Add(cte.Alias);
        resultList.Add(cte);

        if (cte is QueryFromClause queryFromClause)
        {
            resultList.InsertRange(0, findInternal(queryFromClause.Query));
        }
    }

    return resultList;
}

mindcrash avatar Nov 01 '21 12:11 mindcrash