Skip to content

Instantly share code, notes, and snippets.

@hotgazpacho
Last active December 17, 2015 02:39
Show Gist options
  • Save hotgazpacho/5537932 to your computer and use it in GitHub Desktop.
Save hotgazpacho/5537932 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Data.Common;
using ApprovalTests.Persistence;
using ApprovalUtilities.Persistence.Database;
using QueryObjects;
using NHibernate;
using NHibernate.AdoNet.Util;
namespace Approvals
{
public class SqlInterceptor : EmptyInterceptor
{
public SqlInterceptor()
{
ExecutedSql = new List<string>();
}
public List<string> ExecutedSql { get; private set; }
public override NHibernate.SqlCommand.SqlString OnPrepareStatement(NHibernate.SqlCommand.SqlString sql)
{
ExecutedSql.Add(sql.ToString());
return base.OnPrepareStatement(sql);
}
}
public class QueryObjectAdaptor<T> : IDatabaseToExecuteableQueryAdaptor
{
readonly Query<T> _query;
readonly SqlInterceptor _interceptor;
public QueryObjectAdaptor(Query<T> query, SqlInterceptor interceptor)
{
_query = query;
_interceptor = interceptor;
}
public string GetQuery()
{
_query.Execute();
var sql = string.Join(Environment.NewLine, _interceptor.ExecutedSql);
var formatSql = FormatSql(sql);
return formatSql;
}
public DbConnection GetConnection()
{
return (DbConnection) _query.Session.Connection;
}
public string FormatSql(string sqlString)
{
return FormatStyle.Basic.Formatter.Format(sqlString);
}
}
public static class QueryApprovals
{
public static void Verify<T>(Query<T> query, ISessionFactory sessionFactory)
{
var interceptor = new SqlInterceptor();
using (var session = sessionFactory.OpenSession(interceptor))
using (var transaction = session.BeginTransaction())
{
query.Session = session;
DatabaseApprovals.Verify(new QueryObjectAdaptor<T>(query, interceptor));
transaction.Rollback();
}
}
}
}
using NHibernate;
namespace QueryObjects
{
public interface IQuery<out TResult>
{
TResult Execute();
}
public abstract class Query<T> : IQuery<T>
{
public ISession Session { get; set; }
public abstract T Execute();
protected TResult ExecuteQuery<TResult>(Query<TResult> query)
{
query.Session = Session;
return query.Execute();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment