Analyzing table relations of a Query object

One of my ISV Buddies asked me how he could write code to analyze the table relations between the data sources of a Query object.

Here is the job I wrote for him as an example. I thought it might could be of general interest.

 static void QueryLinks(Args _args) 
{     
    Query query = new Query(queryStr(VendTransOpen));
    
    void getLinks(QueryBuildDatasource _qbds)     
    {         
        QueryBuildDataSource childDataSource;            
        QueryBuildLink       queryBuildLink;        
        Counter              links;         
        int                  i;         
        ;
        
        if (_qbds.enabled())         
        {             
            setPrefix (tableId2Name(_qbds.table()));
            if (_qbds.level() > 1)             
            {                 
                while (links < _qbds.linkCount())                 
                {                     
                    links++;
                    queryBuildLink = _qbds.link(links);  
                    info (strFmt("%1.%2 --> %3.%4", tableId2Name(queryBuildLink.relatedTable()),
                                                    fieldId2Name(queryBuildLink.relatedTable(),       
                                                    queryBuildLink.relatedField()),
                                                    tableId2Name(queryBuildLink.table()),
                                                    fieldId2Name(queryBuildLink.table(), 
                                                    queryBuildLink.field())));                 
                }             
            }
            for (i = 1; i <= _qbds.childDataSourceCount(); i++)             
            {
                childDataSource = _qbds.childDataSourceNo(i);                 
                getLinks(childDataSource);             
            }         
        }     
    }      
    ;
    setPrefix(strFmt("Query: '%1'", query.name()));     getLinks(query.dataSourceNo(1));
}

This posting is provided "AS IS" with no warranties, and confers no rights.
Use of included script samples are subject to the terms specified at https://www.microsoft.com/info/cpyright.htm