forked from nhibernate/nhibernate-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCustomQueryModelRewriterTests.cs
91 lines (80 loc) · 2.45 KB
/
CustomQueryModelRewriterTests.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using NHibernate.Linq.Visitors;
using NUnit.Framework;
using Remotion.Linq;
using Remotion.Linq.Clauses;
using Remotion.Linq.Parsing;
namespace NHibernate.Test.Linq
{
[TestFixture]
public class CustomQueryModelRewriterTests : LinqTestCase
{
protected override void Configure(Cfg.Configuration configuration)
{
configuration.Properties[Cfg.Environment.QueryModelRewriterFactory] = typeof(QueryModelRewriterFactory).AssemblyQualifiedName;
}
[Test]
public void RewriteNullComparison()
{
// This example shows how to use the query model rewriter to
// make radical changes to the query. In this case, we rewrite
// a null comparison (which would translate into a IS NULL)
// into a comparison to "Thomas Hardy" (which translates to a = "Thomas Hardy").
var contacts = (from c in db.Customers where c.ContactName == null select c).ToList();
Assert.Greater(contacts.Count, 0);
Assert.IsTrue(contacts.Select(customer => customer.ContactName).All(c => c == "Thomas Hardy"));
}
[Serializable]
public class QueryModelRewriterFactory : IQueryModelRewriterFactory
{
public QueryModelVisitorBase CreateVisitor(VisitorParameters parameters)
{
return new CustomVisitor();
}
}
public class CustomVisitor : NhQueryModelVisitorBase
{
public override void VisitWhereClause(WhereClause whereClause, QueryModel queryModel, int index)
{
whereClause.TransformExpressions(new Visitor().Visit);
}
private class Visitor : RelinqExpressionVisitor
{
protected override Expression VisitBinary(BinaryExpression expression)
{
if (
expression.NodeType == ExpressionType.Equal ||
expression.NodeType == ExpressionType.NotEqual
)
{
var left = expression.Left;
var right = expression.Right;
bool reverse = false;
if (!(left is ConstantExpression) && right is ConstantExpression)
{
var tmp = left;
left = right;
right = tmp;
reverse = true;
}
var constant = left as ConstantExpression;
if (constant != null && constant.Value == null)
{
left = Expression.Constant("Thomas Hardy");
expression = Expression.MakeBinary(
expression.NodeType,
reverse ? right : left,
reverse ? left : right
);
}
}
return base.VisitBinary(expression);
}
}
}
}
}