Last active
December 17, 2015 02:39
-
-
Save hotgazpacho/5537932 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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