Building WHERE Clauses for Query Strings

So I had need to create a way of building queries programmatically -- in this case, specifically for OData.  This proved to be somewhat tricky as the ways in which filters could be applied can get pretty complex.

Take for example the following:

A > B OR A < C

Chaining filters together like this (direct one-to-one) is extremely trivial!  Now let's look at a different example:

(A > B) OR (A <  C AND A = D)

It's immediately clear that there are two groups here.  In the first group is a fairly simple clause, A > B.  In the second group are two filters ANDed together: A < C and A = D.  Abstractly, we can see that there can be one to many groups chained together with some logical operator which themselves contain one to many filters.  Not too bad! 

Now let's look at a final example:

(A > B) OR (A < C AND A = D AND (D < E OR F <=  G))

By introducing an inner group, we can show above the simplest case expressing the largest complexity we're going to allow. The group D < E OR F <= G can be seen as belonging to the group on the left-hand side (A < C AND A = D).

Let's start with a way of organizing our filters by implementing some FilterGroup.  Here are our requirements:

  • A filter group must contain a logical operator (AND/OR) with the option of NONE for the first group within a chain
  • A filter group must contain a Filter.  This filter is the start of the filter chain within each group
  • A way of adding a filter to the group (AND/OR)
  • A way of chaining another group to the group (AND/OR)
There are some additional requirements here which were solved for after the initial coding and have been included:
  • The ability to tell whether filters have been added to the group
  • The ability to translate the query into some arbitrary language using dependency injection (initially, our requirement was for Odata, but what if we want to later translate to SQL?)

With this in mind, the following FilterGroup class was created.  Let's take a look!

/// <summary>
/// A group which can contain one or more filters (ex: (A < B AND B > C)) and can itself be chained with 
/// zero to many groups (ex: GROUPA OR GROUPB OR GROUPC).  Each filter within the group can contain subgroups,
/// allowing more complex constructs (ex: (A < B AND (B > C AND D < E))
/// </summary>
public class FilterGroup
{        
    /// <summary>
    /// Logical operator, if applicable (and, or).  If there is no preceding group,
    /// this would be none
    /// </summary>
    internal LogicalOperator LogicalOperator = LogicalOperator.None;

    /// <summary>
    /// Next filter group in the chain
    /// </summary>
    internal FilterGroup Next;

    /// <summary>
    /// The first filter within a group.  Additional filters may be chained
    /// </summary>
    internal Filter _filter;

    /// <summary>
    /// Translator determining to which language the filter group should be translated
    /// </summary>
    private readonly IQueryTranslator _translator;

    /// <summary>
    /// The last filter that has been added to the group
    /// </summary>
    public Filter LastFilter { get; internal set; }

    /// <summary>
    /// Determines whether the group contains filters
    /// </summary>
    public bool HasFilters { get { return LastFilter != null; } }

    internal FilterGroup(IQueryTranslator translator) 
    { 
        _translator = translator;
    }

    /// <summary>
    /// Adds the filter to the group.  If a filter has already been added to the group, it will be replaced.
    /// (Ex: ColA < 10)
    /// </summary>
    /// <param name="name">Value name</param>
    /// <param name="comparisonOperator">Comparison operator (greater than, less than, etc)</param>
    /// <param name="value">Value</param>
    /// <param name="function">Function, if applicable (ToUpper, Length, etc)</param>
    /// <param name="not">True if the filter should be notted</param>
    /// <returns>Filter that has been added</returns>
    public Filter AddFilter(string name, ComparisonOperator comparisonOperator, object value, ComparisonFunction function = ComparisonFunction.None, bool not = false)
    {
        _filter = new ComparisonFilter(this, name, comparisonOperator, value, function, _translator, not);
        LastFilter = _filter;
        return _filter;
    }

    /// <summary>
    /// Adds the filter to the group for performing a value function (in, starts with, etc).  If a filter has already been added to the group, it will be replaced.
    /// (Ex: ColA startswith 'x')
    /// </summary>
    /// <param name="name">Value name</param>
    /// <param name="function">Function, if applicable (in, starts with, etc)</param>
    /// <param name="value">Value</param>
    /// <param name="not">True if the filter should be notted</param>
    /// <returns>Filter that has been added</returns>
    public Filter AddFilter(string name, ValueFunction function, object value, bool not = false)
    {
        _filter = new FunctionFilter(this, name, function, value, _translator, not);
        LastFilter = _filter;
        return _filter;
    }

    /// <summary>
    /// Creates a new filter group and ANDs it with the current group
    /// </summary>
    /// <returns>New filter group</returns>
    public FilterGroup AndGroup()
    {
        var newGroup = new FilterGroup(_translator)
        {
            LogicalOperator = LogicalOperator.And
        };
        Next = newGroup;
        return Next;
    }

    /// <summary>
    /// Creates a new filter group and OR it with the current group
    /// </summary>
    /// <returns>New filter group</returns>
    public FilterGroup OrGroup()
    {
        var newGroup = new FilterGroup(_translator)
        {
            LogicalOperator = LogicalOperator.Or
        };
        Next = newGroup;
        return Next;
    }

    public override string ToString() => _translator.Translate(this);
}

It looks like all of our requirements have been met! 

Notice that every FilterGroup must be given some translator when constructed. This translator is then passed to each group to ensure they're all translated to the same language. When calling .ToString() on a filter group, we depend on the translator to somehow convert our group (and all filters and groups referencing it) to the specified language. Consider this an exercise for the future!

Comments

Popular posts from this blog

ExcelDNA: Parameter Limit for Excel Functions Using a Variable Parameter Array (params and ParamArray)

A Concrete Filter for Simple Comparisons

Building a Filter class for WHERE clauses