February 18, 2009

SqlBuilder 2.0 – Tutorial

Overview

SqlBuilder is a class designed to make dynamic SQL tasks easier. The top design goals are:

  1. The query should look like SQL, and all SQL queries should be possible.
  2. SqlBuilder is about building SQL, not getting or mapping data, so it should not be bound to any particular data access implementation.

Let’s take a look at the first example:

var query = new SqlBuilder()
   .SELECT("*")
   .FROM("Products")
   .WHERE("Name LIKE {0}", "A%")

What makes SqlBuilder very easy to learn/use is that all methods have the same signature:

SqlBuilder SELECT(string, params object[]);
SqlBuilder FROM(string, params object[]);
SqlBuilder WHERE(string, params object[]);
...

The first parameter is a composite format string, as used on String.Format, and the second parameter is an array of the parameter values you want to use in your command. So, if we call ToString on the first example this is what we get:

SELECT *
FROM products
WHERE name LIKE {0}

Pretty much the same. The parameter placeholder is still there, and the ‘A%’ value is kept in the SqlBuilder.ParameterValues collection. To turn this into a command we need a System.Data.Common.DbProviderFactory instance:

var command = query.ToCommand(SqlClientFactory.Instance);
Console.WriteLine(command.ToTraceString());

The output:

SELECT *
FROM Products
WHERE Name LIKE @p0
-- @p0: Input String (Size = 2) [A%]

The parameter placeholder is now replaced with a parameter name, and the parameter value is included in the command. To understand how this command is created you can read my post about it.

Keeping track of the last clause

SqlBuilder keeps track of the last clause to determine when to use separators like commas (’, ‘), logical operators (’ AND ‘), etc, when building the clause body. This allows you to call the same method more than once:

// SQL.SELECT is just a shortcut to new SqlBuilder().SELECT
var query = SQL
   .SELECT("ID")
   .SELECT("Name")
   .FROM("Products")
   .WHERE("Name LIKE {0}", "A%")
   .WHERE("CategoryID = {0}", 2); 

Console.WriteLine(query);

The output:

SELECT ID, Name
FROM Products
WHERE Name LIKE {0} AND CategoryID = {1}

This is how you can dynamically construct the clause body. The ’separator’ feature is not for all clauses, for example, calling JOIN two times will append JOIN on both calls. Also notice we used a zero index for both parameter placeholders, but the output shows zero and one indexes. The format string must always use method-call-relative placeholders, SqlBuilder takes care of translating those to instance-relative.

Dynamic SQL

So far we’ve only used SqlBuilder to dynamically construct queries that are static, meaning the resulting SQL will always be the same. Let’s look at a real dynamic query example:

void DynamicSql(int? categoryId, int? supplierId) { 

   var query = SQL
      .SELECT("ID, Name")
      .FROM("Products")
      .WHERE_If(categoryId.HasValue, "CategoryID = {0}", categoryId)
      .WHERE_If(supplierId.HasValue, "SupplierID = {0}", supplierId)
      .ORDER_BY("Name DESC"); 

   Console.WriteLine(query);
}

Let’s call this several times with different arguments:

DynamicSql(2, null);
DynamicSql(null, 3);
DynamicSql(2, 3);
DynamicSql(null, null);

The output:

SELECT ID, Name
FROM Products
WHERE CategoryID = {0}
ORDER BY Name DESC 

SELECT ID, Name
FROM Products
WHERE SupplierID = {0}
ORDER BY Name DESC 

SELECT ID, Name
FROM Products
WHERE CategoryID = {0} AND SupplierID = {1}
ORDER BY Name DESC 

SELECT ID, Name
FROM Products
ORDER BY Name DESC

WHERE_If is an extension method that takes an extra boolean parameter which indicates if WHERE should be called or not. Although you can implement the same logic explicitly writing an if statement, the advantage of this method is that you keep the query as a single method-call chain, improving the readability of the code.

Sub-queries

Parameter placeholders are always used for command parameters, except when you pass another SqlBuilder instance, case in which the supplied builder’s text is injected at the placeholder. This is how SqlBuilder support sub-queries:

var query = SQL
   .SELECT("c.CategoryName, t0.TotalProducts")
   .FROM("Categories c")
   .JOIN("({0}) t0 ON c.CategoryID = t0.CategoryID", SQL
      .SELECT("CategoryID, COUNT(*) AS TotalProducts")
      .FROM("Products")
      .GROUP_BY("CategoryID"))
   .ORDER_BY("t0.TotalProducts DESC");

Console.WriteLine(query);

The output:

SELECT c.CategoryName, t0.TotalProducts
FROM Categories c
JOIN (
        SELECT CategoryID, COUNT(*) AS TotalProducts
        FROM Products
        GROUP BY CategoryID) t0 ON c.CategoryID = t0.CategoryID
ORDER BY t0.TotalProducts DESC

If the sub-query contains any parameter values these are copied to the outer query. SqlBuilder doesn’t keep any reference to sub-queries, all instances are completely independent and composability is achieved by copying state from one instance to the other.

Arrays

Not many SQL dialects support array types, but a very common requirement is to use an array of values as the right expression of the IN operator:

int[] ids = { 1, 2, 3 };

var query = SQL
   .SELECT("*")
   .FROM("Products")
   .WHERE("CategoryID IN ({0})", ids);

Console.WriteLine(query);

The output:

SELECT *
FROM Products
WHERE CategoryID IN ({0}, {1}, {2})

Extending an existing query

If there’s a large portion of the query that is static, there’s no need to convert everything to method calls, just pass it to the constructor and extend it from there:

var query = SQL.New(@"
    SELECT ProductID, ProductName
    FROM Products")
   .WHERE("CategoryID = {0}", 1);

Console.WriteLine(query);

The output:

             SELECT ProductID, ProductName
             FROM Products
WHERE CategoryID = {0}

In this case I favored source code readability over SQL readability.

Inserts, Updates, Deletes

There’s really no limit to the kind of statements SqlBuilder can handle:

var insert = SQL
   .INSERT_INTO("Products(ProductName, UnitPrice, CategoryID)")
   .VALUES("Chai", 15.56, 5);

var update = SQL
   .UPDATE("Products")
   .SET("Discontinued", true)
   .WHERE("ProductID = {0}", 1)
   .LIMIT(1);

var delete = SQL
   .DELETE_FROM("Products")
   .WHERE("ProductID = {0}", 1)
   .LIMIT(1);

Console.WriteLine(insert);
Console.WriteLine(update);
Console.WriteLine(delete);

The output:

INSERT INTO Products(ProductName, UnitPrice, CategoryID)
VALUES ({0}, {1}, {2})

UPDATE Products
SET Discontinued = {0}
WHERE ProductID = {1}
LIMIT {2}

DELETE FROM Products
WHERE ProductID = {0}
LIMIT {1}

You can see here some methods that do not take the format string, like SET, VALUES and LIMIT. Since the format of these clauses is well known, all you need to pass in are parameters.

Extensibility

To understand how SqlBuilder can be extended let’s take a look at how some of the built-in clauses are implemented:

public SqlBuilder SELECT(string format, params object[] args) {
   return AppendClause("SELECT", format, args);
}

public SqlBuilder FROM(string format, params object[] args) {
   return AppendClause("FROM", format, args);
}

public SqlBuilder JOIN(string format, params object[] args) {
   return AppendClause(new SqlClauseInfo("JOIN", null), format, args);
}

public SqlBuilder SET(string columnName, TValue value) {
   return AppendClause("SET", columnName + " = {0}", value);
}

As you can see implementing a clause can be as easy as writing one line of code, it all depends on the parameters you define and how much you need to analyze them to produce a format string. Alternatively, you can access the underlying StringBuilder directly to append text, through the Buffer property.

Here’s how the WHERE_If extension method is implemented (right now I don’t have a longer/more complex example, when I do I’ll post it here):

public static SqlBuilder WHERE_If(this SqlBuilder sqlBuilder, bool condition, string format, params object[] args) {
   return (condition) ? sqlBuilder.WHERE(format, args) : sqlBuilder;
}

Mapping to objects with LINQ to SQL

As stated in the design goals, getting and mapping data is beyond the scope of SqlBuilder, so to get data we need a data access component. Since SqlBuilder was inspired by LINQ to SQL’s ExecuteQuery/ExecuteCommand methods, integrating with this ORM is very easy:

public IEnumerable<Product> GetProducts(int? categoryId) {

   var query = SQL
      .SELECT("ProductID, ProductName, UnitPrice")
      .FROM("Products")
      .WHERE_If(categoryId.HasValue, "CategoryID = {0}", categoryId)
      .ORDER_BY("ProductName");

   // instantiate your DataContext
   DataContext context = null;

   return context.ExecuteQuery<Product>(query.ToString(), query.ParameterValues.ToArray());
}

LINQ to SQL parses the query and maps columns to properties based on the column aliases used.

Mapping to objects with DbExtensions

SqlBuilder is part of the DbExtensions library, which includes a basic CRUD API:

public IEnumerable<Product> GetProducts() {

   // Instantiate your DAO
   DataAccessObject dao = null;

   var query = new SqlBuilder { QueryMembers = dao.CreateQueryMembers() }
      .SELECT(typeof(Product), "p")
      .SELECT(typeof(Category), "c")
      .SELECT(typeof(Supplier), "s")
      .FROM("Products p")
      .LEFT_JOIN("Categories c ON p.CategoryID = c.CategoryID")
      .LEFT_JOIN("Suppliers s ON p.SupplierID = s.SupplierID")
      .WHERE("p.ProductID < {0}", 7);

   return dao.Map<Product>(query).ToList();
}

DbExtensions takes a different approach to mapping. First, it defines an extension method SqlBuilder.SELECT(Type, String) that takes the type of a mapped object, which appends the names of the columns based on the mapping, and adds the System.Reflection.MemberInfo instances for each mapped member to the SqlBuilder.QueryMembers collection. This way, the SqlBuilder instance not only contains the query to be executed, but also the members to which the result should map to. With this, DbExtensions is able to take a query and return mapped objects. It also detects that Category and Supplier types are related to Product with a Many-to-one association, and loads the Product.Category and Product.Supplier properties for each returned Product.

Conclusions

SqlBuilder helps your build dynamic SQL in an ADO.NET provider/RDBMS/ORM independent way. Generic query APIs like LINQ work great for simple queries, but it’s statically-typed nature tends to become a disadvantage for complex scenarios, and it’s very difficult to extend. Many ORM products have their own query APIs, but using them means marrying to a particular product and more APIs to learn. Complex queries require complete control of the executing SQL. SqlBuilder gives you that control, freeing you from dealing with low-level objects like DbCommand and DbParameter.

More information

http://www.ohloh.net/p/dbex

kick it on DotNetKicks.com

December 25, 2008

Hello Berkeley DB XML on .NET

UPDATE 2009-05-26: On ASP.NET you might get an ‘Unable to load ikvm-native’ error message. There are several ways to fix this: a) Add the ikvm-native.dll location to the PATH; b) Copy ikvm-native.dll to %windir%\system32; c) Add a ‘ikvm:java.library.path’ appSetting on web.config and set it’s value to the ikvm-native.dll location.

If you’re not familiar with Berkeley DB XML (BDB XML), it is an open source embeddable XML database engine that provides support for XQuery access.

The official BDB XML distribution provides the library in the C++, Java, Perl, Python, PHP, and Tcl languages. Sadly, no .NET version.

I tried to look for a third-party .NET library and found this one from Parthenon Computing:
http://www.parthcomp.com/dbxml_dotnet.html

The problem with this product is that it doesn’t seem up-to-date with .NET 2.0 and the most recent versions of BDB XML. Also it’s free only for non-commercial use.

Since I couldn’t find any other .NET libraries I started to think what I could do with the existing ones, and it occurred to me I could cross-compile the Java version using IKVM.NET. Because I use IKVM all the time with Saxon XSLT/XQuery I trust and have a good opinion of this product.

Running the IKVM compiler is very simple. For this task you have to grab db.jar and dbxml.jar (available from the official BDB XML distribution) and execute this command:

ikvmc -out:dbxml_net.dll db.jar dbxml.jar

And that’s it! You have your .NET API, officially maintained and up-to-date with the latest BDB XML release. The API will have the Java look-and-feel, camelCase for members, no properties, etc. If you can live with that then there’s no problem. Please note that I haven’t tested much this library, but I suspect it shouldn’t have problems, I encourage you to try it and let me know your experience.

Here’s my hello-world program, it queries a container I had previously created using the dbxml command line shell:

using System;
using com.sleepycat.db;
using com.sleepycat.dbxml;

namespace BerkeleyDB_XML1 {
   class Program {

      static void Main() {
         Console.WriteLine("Running {0}...", com.sleepycat.db.Environment.getVersionString());

         XmlManager mgr = new XmlManager();
         XmlContainer cont = mgr.openContainer(@"c:/temp/bdb-hello/hello.dbxml");

         int count = cont.getNumDocuments();

         Console.WriteLine("Number of available documents: {0}", count);

         XmlQueryContext qctx = mgr.createQueryContext(XmlQueryContext.Eager);

         XmlResults results = mgr.query(
@"for $h in collection('dbxml:c:/temp/bdb-hello/hello.dbxml')/hello
return $h", qctx);

         while (results.hasNext())
            Console.WriteLine(results.next().asString());

         cont.close();
         mgr.close();
      }
   }
}

kick it on DotNetKicks.com

October 19, 2008

Linq to MySQL, based on Matt Warren’s provider

On each release Matt Warren’s IQueryable provider is getting more and more interesting. On this post I’ll show you how easy is to plug-in your custom QueryFormatter to start querying MySQL databases.

Step 1: Download Matt Warren’s provider

The code on this post is based on release 11. Although I cannot ensure it will work with newer releases it is always recommended that you download the latest.

Step 2: Create a custom QueryFormatter class

The following code is a custom QueryFormatter for MySQL.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace Sample {

   internal class MySqlQueryFormatter : QueryFormatter {

      protected override Expression VisitNamedValue(NamedValueExpression value) {
         sb.Append("?" + value.Name);
         return value;
      }

      protected override Expression VisitSelect(SelectExpression select) {
         sb.Append("SELECT ");
         if (select.IsDistinct) {
            sb.Append("DISTINCT ");
         }

         if (select.Columns.Count > 0) {
            for (int i = 0, n = select.Columns.Count; i < n; i++) {
               ColumnDeclaration column = select.Columns[i];
               if (i > 0) {
                  sb.Append(", ");
               }
               ColumnExpression c = this.VisitValue(column.Expression) as ColumnExpression;
               if (!string.IsNullOrEmpty(column.Name) && (c == null || c.Name != column.Name)) {
                  sb.Append(" AS ");
                  sb.Append(column.Name);
               }
            }
         } else {
            sb.Append("NULL ");
            if (this.isNested) {
               sb.Append("AS tmp ");
            }
         }
         if (select.From != null) {
            this.AppendNewLine(Indentation.Same);
            sb.Append("FROM ");
            this.VisitSource(select.From);
         }
         if (select.Where != null) {
            this.AppendNewLine(Indentation.Same);
            sb.Append("WHERE ");
            this.VisitPredicate(select.Where);
         }
         if (select.GroupBy != null && select.GroupBy.Count > 0) {
            this.AppendNewLine(Indentation.Same);
            sb.Append("GROUP BY ");
            for (int i = 0, n = select.GroupBy.Count; i < n; i++) {
               if (i > 0) {
                  sb.Append(", ");
               }
               this.VisitValue(select.GroupBy[i]);
            }
         }
         if (select.OrderBy != null && select.OrderBy.Count > 0) {
            this.AppendNewLine(Indentation.Same);
            sb.Append("ORDER BY ");
            for (int i = 0, n = select.OrderBy.Count; i < n; i++) {
               OrderExpression exp = select.OrderBy[i];
               if (i > 0) {
                  sb.Append(", ");
               }
               this.VisitValue(exp.Expression);
               if (exp.OrderType != OrderType.Ascending) {
                  sb.Append(" DESC");
               }
            }
         }
         if (select.Take != null) {
            this.AppendNewLine(Indentation.Same);
            sb.Append("LIMIT ");
            this.Visit(select.Take);
            sb.Append(" ");
         }
         if (select.Skip != null) {
            sb.Append("OFFSET ");
            this.Visit(select.Skip);
            sb.Append(" ");
         }
         return select;
      }
   }
}

Try to build and you’ll notice that MySqlQueryFormatter is trying to access a lot of QueryFormatter members that are private, so you’ll need to make those protected.

Since all interaction with QueryFormatter is done through a single static method called Format, which creates an instance of the same type, we need to change the type of the created instance to MySqlQueryFormatter.

// line 22, QueryFormatter.cs
QueryFormatter formatter = new MySqlQueryFormatter();

This is the fast way to get things working, a better approach would be to have a QueryFormatter property on DbQueryProvider.

Step 3: Comment the following two lines in DbQueryProvider.Translate method

// line 123-124, DbQueryProvider.cs
//expression = SkipRewriter.Rewrite(expression);
//expression = OrderByRewriter.Rewrite(expression);

Since these calls are used to support SQL Server’s complicated syntax for paging, for MySQL we don’t need them.

And that’s it!

kick it on DotNetKicks.com

August 17, 2008

CSS design patterns: Helper classes

CSS can be one of the most frustrating technologies in web development. Things like browser inconsistencies/hacks, quirks|standards modes, conditional comments, etc. are things I wish I didn’t have to worry about. To make it even worse, CSS lacks of one of the most fundamental features in any language, variables. Is it possible to write reusable CSS?

Helper classes are reusable rules that use class selectors (sometimes combined with type|ID selectors). Helper classes are designed to let you:

  1. Apply style to an element without having to create a special rule for that element: This means you can write less CSS (I like that). You can apply multiple helper classes to an element, as opposed to creating a special class and declare multiple properties in it.
  2. Abstract away browser inconsistencies: 1 helper class can declare multiple properties that have the same effect, but target different browsers.
  3. Make documents more style readable: In server-side programming we are concerned to write readable programs, so by reading the code we can easily understand the program’s behaviour. When using helper classes in a document, by reading the code you should easily visualise it’s appearance. The class name should describe the effect of the rule, in other words, by knowing the class name we should have a solid idea of what the element will look like when that rule is applied.

Example 1: Combining rules
Given the following rules:

.underline { text-decoration: underline; }
.highlight { background-color: #ffc; }

…here is an example of how you can combine multiple rules by applying multiple classes to an element. As you can see it very easy to visualise how the element will render by reading the classes names.

<span class="underline highlight">very important text</a>

Example 2: Abstracting away browser inconsistencies

.block { display: block; }
.inline-block { display: -moz-inline-box; display: inline-block; }

The .block class is useful when you need an inline element to behave like a block element, can be applied to span, a, label, etc. The .inline-block class shows how we can use helper classes to handle different browsers.

Example 3: Powerful selectors

.float_r { float: right; }
p img.float_r { margin-left: 0.5em; }

I like the second rule very much, because it shows how helper classes can help us write more powerful CSS. This rule is not a helper class, but takes advantage of helper classes, it says: for all images that are inside paragraphs and that are floating to the right, apply a 0.5em margin on the left, so there is a space between the image and the paragraph’s text.

By using helper classes we are basically tagging the elements with style information that, as opposed with inline styling, it’s not actually implemented. The last example looks very similar to an attribute selector, like input[type="text"], which is almost the same as an XPath query with a predicate. In essence all selectors are queries against the document’s structure and/or user-defined class names. If you use class names that describe a particular style then you can query against the document’s style.

Other people thinking alike:

http://www.mattvarone.com/2008/07/css-reusable-classes/
http://www.realmacsoftware.com/webshed/index_files/multiple-css-classes.php
http://www.aprilholle.com/technology-reviews/css-continued-part-2reduce-reuse-recycle/

kick it on DotNetKicks.com

January 3, 2008

Writing SQL using lambda expressions (not Linq)

Some of the code in this post may be outdated, I suggest visiting the project site at http://dbex.googlecode.com/

Persistence ignorance and type safety, this is what Linq gives us. I can’t get enough of the latter, but in most cases a generic query API is not what I need, specially when I’m not querying in-memory objects.

You know what I’m talking about, you work with SQL, XPath, etc. You know how to write queries and get the results you want. For instance, there are some things in SQL that I don’t know how to translate to Linq, and if they are going to look the same when translated back to SQL, like the column IN (subquery) syntax. Although you can instead write a join and get the same results I like this better because is more readable. Another concern are functions, what if you want to use a function that has no CLR mapping?

To address this problems and keep the type safety I wrote a class called SqlBuilder. Think of it as a StringBuider for SQL. Let’s take a look at an example:

var query = new SqlBuilder()
   .Select<Product>(p => new { Description = p.ProductName, ID = p.ProductID })
   .From<Product>().Where<Product>(p => p.CategoryID == 1);         

Debug.WriteLine(query);         

// -- the output:
// SELECT t0.ProductName AS Description, t0.ProductID AS ID
// FROM Product AS t0
// WHERE (t0.CategoryID = 1)

This looks nice, but could be better. First of all, the name of the table we want to query is ‘Products’ not ‘Product’. The SqlBuilder has no way of knowing that, unless we provide a MetaModel instance, which lives in the System.Data.Linq.Mapping namespace. This is the mapping API that Linq to Sql uses. Secondly, It would be nice if we could have the identifiers quoted. For that all we need is to provide a DbProviderFactory instance. Let’s change the constructor and run the example again:

var query2 = new SqlBuilder(SqlClientFactory.Instance, new AttributeMappingSource().GetModel(typeof(Product)))
   .Select<Product>(p => new { Description = p.ProductName, ID = p.ProductID })
   .From<Product>().Where<Product>(p => p.CategoryID == 1);         

Debug.WriteLine(query2);         

// -- the output:
// SELECT [t0].[ProductName] AS [Description], [t0].[ProductID] AS [ID]
// FROM [Products] AS [t0]
// WHERE ([t0].[CategoryID] = 1)

Now it looks perfect. We get what we write, and that’s what we want. Let’s take a look at a more complex example, this is Northwind’s ‘Product Sales for 1997′ view:

var query3 = new SqlBuilder(MySqlClientFactory.Instance, new AttributeMappingSource().GetModel(typeof(Product)))
   .Select<Product>(p => new object[] { p.Category.CategoryName, p.ProductName })
   .Select<OrderDetail>(od => new { ProductSales = Sql.Sum(Sql.Round((od.UnitPrice * od.Quantity * Convert.ToDecimal(((1 - od.Discount) / 100))) * 100, 2)) })
   .From<Product>().Join<Product, Category>(JoinType.InnerJoin, (p, c) => p.CategoryID == c.CategoryID)
   .Join<Product, OrderDetail>(JoinType.InnerJoin, (p, od) => p.ProductID == od.ProductID)
   .Join<OrderDetail, Order>(JoinType.InnerJoin, (od, o) => od.OrderID == o.OrderID)
   .Where<Order>(o => Sql.Between(o.ShippedDate, DateTime.Parse("1997-01-01"), DateTime.Parse("1997-12-31")))
   .GroupBy<Category>(c => c.CategoryName)
   .GroupBy<Product>(p => p.ProductName);         

Debug.WriteLine(query3);         

// -- the output:
// SELECT `t0`.`CategoryName`, `t1`.`ProductName`, Sum(Round((((`t2`.`UnitPrice` * `t2`.`Quantity`) * ((1 - `t2`.`Discount`) / 100)) * 100), 2)) AS `ProductSales`
// FROM `Products` AS `t1`
// INNER JOIN `Categories` AS `t0` ON (`t1`.`CategoryID` = `t0`.`CategoryID`)
// INNER JOIN `Order Details` AS `t2` ON (`t1`.`ProductID` = `t2`.`ProductID`)
// INNER JOIN `Orders` AS `t3` ON (`t2`.`OrderID` = `t3`.`OrderID`)
// WHERE `t3`.`ShippedDate` BETWEEN {0} AND {1}
// GROUP BY `t0`.`CategoryName`, `t1`.`ProductName`

Now I’m using the MySqlClientFactory just to show off it should work with any provider. Notice I’m using SQL functions, like Sum, Round and Between. Also notice I’m calling Select and GroupBy twice, but the second call appends “, ” instead of the clause name, that’s something you can configure if you write your own methods. Also you can see that there are two placeholders for the DateTime values. The values are cached and the parameter names are generated when you call ToCommand() and inserted in those placeholders.

You can extend the SqlBuilder class using extension methods to add more clauses and statements, and static methods that represent server functions. This is a static class called MySql that encapsulates some functionality available in MySql Server.

public static class MySql { 

   [SqlFunction(Template = "MATCH ({0}) AGAINST ({1})")]
   public static bool Match(object[] members, string searchExpression) {
      throw new InvalidOperationException();
   } 

   [SqlFunction(Template = "MATCH ({0}) AGAINST ({1} IN BOOLEAN MODE)")]
   public static bool MatchBoolean(object[] members, string searchExpression) {
      throw new InvalidOperationException();
   } 

   public static SqlBuilder Limit(this SqlBuilder builder, int maxRecords) {
      return Limit(builder, maxRecords, 0);
   } 

   [SqlClause(Name = "LIMIT", IncludeInCountCommand = false)]
   public static SqlBuilder Limit(this SqlBuilder builder, int maxRecords, int startIndex) { 

      MethodBase method = MethodBase.GetCurrentMethod();
      builder.OnClauseBuilding(new ClauseBuildingEventArgs(method)); 

      StringBuilder sb = new StringBuilder();
      sb.Append(maxRecords); 

      if (startIndex > 0) {
         sb.Append(" OFFSET ");
         sb.Append(startIndex);
      } 

      builder.OnClauseBuilt(new ClauseBuiltEventArgs(method, sb.ToString())); 

      return builder;
   }
}

You can see there are 2 functions, called Match and MatchBoolean, denoted by the SqlFunction attribute (mandatory). The SqlFunction.Template property is optional and useful for those functions that don’t look like functions at all. The Limit clause uses the SqlClause attribute which is optional. SqlBuilder also builds a second command for retriving the total number of records the main command is supposed to return. This is specially useful when doing paging. The SqlClause.IncludeInCountCommand indicates if the clause should be appended to the count command, which is not the case for Limit and OrderBy.

I hope you’ll find this useful enough to give it a try, specially for those who don’t want to give up the power of writing SQL.

kick it on DotNetKicks.com