Sunday, September 7, 2014

Intercepting SQL in NHibernate for Test Uses

Found an implementation for interceptor:

public class NHSQLInterceptor : EmptyInterceptor, IInterceptor
{
    NHibernate.SqlCommand.SqlString IInterceptor.OnPrepareStatement(NHibernate.SqlCommand.SqlString sql)
    {
        // SQL.NHibernateSQL is static property
        SQL.NHibernateSQL = sql.ToString();
        return sql;
    }
}



On configuration:

var config = new Configuration();
...
...
config.SetInterceptor(new SQLInterceptor());
...
...
ISessionFactory factory = config.BuildSessionFactory();
...
...
factory.OpenSession(config.Interceptor); // turns out passing the interceptor to session is not needed, interceptors still gets called despite removing this



Then I found something simpler on stackoverflow:
public class SqlStatementInterceptor : EmptyInterceptor
{
    public override NHibernate.SqlCommand.SqlString OnPrepareStatement(NHibernate.SqlCommand.SqlString sql)
    {
        SQL.NHibernateSQL = sql.ToString();
        return sql;
    }
}



Happy Coding!

No comments:

Post a Comment