Saturday, April 18, 2009

SPQueryBuilder - a handy class to build SP queries

Hey there again. As I'm getting bored with writing SPQuery's query all the time and I've got some better things to do in life, I've decided to create a handy class to do that work for me.
It allows you to use object model instead of writing queries in plain strings (like SP devs intent you to do).

String-coded queries tend to become a nightmare when you need to filter list using like 10 columns as a horde of xml nodes and attributes jumps on you from the corner. And of course you always tend forget about that closing tag here and there. Not to mention that readability of such code is below water line.

So instead you can now use SPQueryBuilder like that:

string queryString = new SPQueryBuilder()
                    .Eq(columnName1, columnValue1)
                    .Eq(columnName2, columnValue2)
                    .ToQuery();
SPQuery query = new SPQuery(){Query = queryString };
Console.WriteLine(queryString);

By default all expressions are joined by <And> tag, so code above will produce following output:
<Where><And>
<Eq><FieldRef Name=':ColumnName1'/><Value Type='Text'>:ColumnValue1</Value></Eq>
<Eq><FieldRef Name=':ColumnName2'/><Value Type='Text'>:ColumnValue2</Value></Eq>
</And></Where>

Note that you can join any number of expressions this way, say if you expressions ten times, all ten expressions will be joined.

To build <Or> tag you use .Or method of SPQueryBuilder (what a surprise!).
string queryString = new SPQueryBuilder()
.Or(Expressions.Eq(columnName1, columnValue1), Expressions.Eq(columnName2, columnValue2, column2Type))
.ToQuery();
SPQuery query = new SPQuery(){Query = queryString };
Console.WriteLine(queryString);

This call will produce the following output:
<Where><Or>
<Eq><FieldRef Name=':ColumnName1'/><Value Type='Text'>:ColumnValue1</Value></Eq>
<Eq><FieldRef Name=':ColumnName2'/><Value Type=':ColumnValueType2'>:ColumnValue2</Value></Eq>
</Or></Where>

Also note that default Value type is Text, is you want another type, use SPFieldType class.

So far those features are implemented:
  • Building expressions in chain calls style
  • Full support for Or and And expressions. You can build nested expressions of any complexity. Both Or and And expressions allow you to pass any number of expressions to as arguments. So you can check say 5 expressions in one Or call - Or(expr1, expr2, expr3, ...) and have them all  gathered under one big Or tag.
  • Eq expression (support for text and boolean fields so far, I'll include more field types soon, though it is very easy to extend types being supported, so you might as well add them on your own).
  • IsNull expression
  • IsNotNull expression

You can download code with tests here.

No comments:

Post a Comment