forked from Dongliang-y/DapperExtensions.Lambda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPredicates.cs
422 lines (375 loc) · 15.7 KB
/
Predicates.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using DapperExtensions.Mapper;
using DapperExtensions.Sql;
namespace DapperExtensions
{
public static class Predicates
{
/// <summary>
/// Factory method that creates a new IFieldPredicate predicate: [FieldName] [Operator] [Value].
/// Example: WHERE FirstName = 'Foo'
/// </summary>
/// <typeparam name="T">The type of the entity.</typeparam>
/// <param name="expression">An expression that returns the left operand [FieldName].</param>
/// <param name="op">The comparison operator.</param>
/// <param name="value">The value for the predicate.</param>
/// <param name="not">Effectively inverts the comparison operator. Example: WHERE FirstName <> 'Foo'.</param>
/// <returns>An instance of IFieldPredicate.</returns>
public static IFieldPredicate Field<T>(Expression<Func<T, object>> expression, Operator op, object value, bool not = false) where T : class
{
PropertyInfo propertyInfo = ReflectionHelper.GetProperty(expression) as PropertyInfo;
return new FieldPredicate<T>
{
PropertyName = propertyInfo.Name,
Operator = op,
Value = value,
Not = not
};
}
/// <summary>
/// Factory method that creates a new IPropertyPredicate predicate: [FieldName1] [Operator] [FieldName2]
/// Example: WHERE FirstName = LastName
/// </summary>
/// <typeparam name="T">The type of the entity for the left operand.</typeparam>
/// <typeparam name="T2">The type of the entity for the right operand.</typeparam>
/// <param name="expression">An expression that returns the left operand [FieldName1].</param>
/// <param name="op">The comparison operator.</param>
/// <param name="expression2">An expression that returns the right operand [FieldName2].</param>
/// <param name="not">Effectively inverts the comparison operator. Example: WHERE FirstName <> LastName </param>
/// <returns>An instance of IPropertyPredicate.</returns>
public static IPropertyPredicate Property<T, T2>(Expression<Func<T, object>> expression, Operator op, Expression<Func<T2, object>> expression2, bool not = false)
where T : class
where T2 : class
{
PropertyInfo propertyInfo = ReflectionHelper.GetProperty(expression) as PropertyInfo;
PropertyInfo propertyInfo2 = ReflectionHelper.GetProperty(expression2) as PropertyInfo;
return new PropertyPredicate<T, T2>
{
PropertyName = propertyInfo.Name,
PropertyName2 = propertyInfo2.Name,
Operator = op,
Not = not
};
}
/// <summary>
/// Factory method that creates a new IPredicateGroup predicate.
/// Predicate groups can be joined together with other predicate groups.
/// </summary>
/// <param name="op">The grouping operator to use when joining the predicates (AND / OR).</param>
/// <param name="predicate">A list of predicates to group.</param>
/// <returns>An instance of IPredicateGroup.</returns>
public static IPredicateGroup Group(GroupOperator op, params IPredicate[] predicate)
{
return new PredicateGroup
{
Operator = op,
Predicates = predicate
};
}
/// <summary>
/// Factory method that creates a new IExistsPredicate predicate.
/// </summary>
public static IExistsPredicate Exists<TSub>(IPredicate predicate, bool not = false)
where TSub : class
{
return new ExistsPredicate<TSub>
{
Not = not,
Predicate = predicate
};
}
/// <summary>
/// Factory method that creates a new IBetweenPredicate predicate.
/// </summary>
public static IBetweenPredicate Between<T>(Expression<Func<T, object>> expression, BetweenValues values, bool not = false)
where T : class
{
PropertyInfo propertyInfo = ReflectionHelper.GetProperty(expression) as PropertyInfo;
return new BetweenPredicate<T>
{
Not = not,
PropertyName = propertyInfo.Name,
Value = values
};
}
/// <summary>
/// Factory method that creates a new Sort which controls how the results will be sorted.
/// </summary>
public static ISort Sort<T>(Expression<Func<T, object>> expression, bool ascending = true)
{
PropertyInfo propertyInfo = ReflectionHelper.GetProperty(expression) as PropertyInfo;
return new Sort
{
PropertyName = propertyInfo.Name,
Ascending = ascending
};
}
}
public interface IPredicate
{
string GetSql(ISqlGenerator sqlGenerator, IDictionary<string, object> parameters);
}
public interface IBasePredicate : IPredicate
{
string PropertyName { get; set; }
}
public abstract class BasePredicate : IBasePredicate
{
public abstract string GetSql(ISqlGenerator sqlGenerator, IDictionary<string, object> parameters);
public string PropertyName { get; set; }
protected virtual string GetColumnName(Type entityType, ISqlGenerator sqlGenerator, string propertyName)
{
IClassMapper map = sqlGenerator.Configuration.GetMap(entityType);
if (map == null)
{
throw new NullReferenceException(string.Format("Map was not found for {0}", entityType));
}
IPropertyMap propertyMap = map.Properties.SingleOrDefault(p => p.Name == propertyName);
if (propertyMap == null)
{
throw new NullReferenceException(string.Format("{0} was not found for {1}", propertyName, entityType));
}
return sqlGenerator.GetColumnName(map, propertyMap, false);
}
}
public interface IComparePredicate : IBasePredicate
{
Operator Operator { get; set; }
bool Not { get; set; }
}
public abstract class ComparePredicate : BasePredicate
{
public Operator Operator { get; set; }
public bool Not { get; set; }
public virtual string GetOperatorString()
{
switch (Operator)
{
case Operator.Gt:
return Not ? "<=" : ">";
case Operator.Ge:
return Not ? "<" : ">=";
case Operator.Lt:
return Not ? ">=" : "<";
case Operator.Le:
return Not ? ">" : "<=";
case Operator.Like:
return Not ? "NOT LIKE" : "LIKE";
default:
return Not ? "<>" : "=";
}
}
}
public interface IFieldPredicate : IComparePredicate
{
object Value { get; set; }
}
public class FieldPredicate<T> : ComparePredicate, IFieldPredicate
where T : class
{
public object Value { get; set; }
public override string GetSql(ISqlGenerator sqlGenerator, IDictionary<string, object> parameters)
{
string columnName = GetColumnName(typeof(T), sqlGenerator, PropertyName);
if (Value == null)
{
return string.Format("({0} IS {1}NULL)", columnName, Not ? "NOT " : string.Empty);
}
if (Value is IEnumerable && !(Value is string))
{
if (Operator != Operator.Eq)
{
throw new ArgumentException("Operator must be set to Eq for Enumerable types");
}
List<string> @params = new List<string>();
foreach (var value in (IEnumerable)Value)
{
string valueParameterName = parameters.SetParameterName(this.PropertyName, value, sqlGenerator.Configuration.Dialect.ParameterPrefix);
@params.Add(valueParameterName);
}
if (@params.Count()== 0) //当参数为空是将会生成 where col in () 空参数的错误sql
{
return string.Format("({0} IS {1}NULL)", columnName, Not ? "NOT " : string.Empty);
}
if(@params.Count>30)
{
var frames = new StackTrace(true).GetFrames();
StringBuilder strMsg = new StringBuilder();
strMsg.Append($"条件语句中的 “***.Contains”参数过多 请尝试优化查下语句。!!!!!!!!!!");
foreach (var frame in frames)
{
var str = frame.ToString();
if (str.Contains(".cs"))
strMsg.AppendLine(str);
}
Debug.WriteLine(strMsg.ToString());
//#if DEBUG
// throw new Exception(strMsg.ToString());
//#else
// ZJJWEPlatform.Infrastructure.Loger.LogerHelper.Debug(strMsg.ToString(), "DapperExtensions");
//#endif
}
string paramStrings = @params.Aggregate(new StringBuilder(), (sb, s) => sb.Append((sb.Length != 0 ? ", " : string.Empty) + s), sb => sb.ToString());
return string.Format("({0} {1}IN ({2}))", columnName, Not ? "NOT " : string.Empty, paramStrings);
}
string parameterName = parameters.SetParameterName(this.PropertyName, this.Value, sqlGenerator.Configuration.Dialect.ParameterPrefix);
return string.Format("({0} {1} {2})", columnName, GetOperatorString(), parameterName);
}
}
public interface IPropertyPredicate : IComparePredicate
{
string PropertyName2 { get; set; }
}
public class PropertyPredicate<T, T2> : ComparePredicate, IPropertyPredicate
where T : class
where T2 : class
{
public string PropertyName2 { get; set; }
public override string GetSql(ISqlGenerator sqlGenerator, IDictionary<string, object> parameters)
{
string columnName = GetColumnName(typeof(T), sqlGenerator, PropertyName);
string columnName2 = GetColumnName(typeof(T2), sqlGenerator, PropertyName2);
return string.Format("({0} {1} {2})", columnName, GetOperatorString(), columnName2);
}
}
public struct BetweenValues
{
public object Value1 { get; set; }
public object Value2 { get; set; }
}
public interface IBetweenPredicate : IPredicate
{
string PropertyName { get; set; }
BetweenValues Value { get; set; }
bool Not { get; set; }
}
public class BetweenPredicate<T> : BasePredicate, IBetweenPredicate
where T : class
{
public override string GetSql(ISqlGenerator sqlGenerator, IDictionary<string, object> parameters)
{
string columnName = GetColumnName(typeof(T), sqlGenerator, PropertyName);
string propertyName1 = parameters.SetParameterName(this.PropertyName, this.Value.Value1, sqlGenerator.Configuration.Dialect.ParameterPrefix);
string propertyName2 = parameters.SetParameterName(this.PropertyName, this.Value.Value2, sqlGenerator.Configuration.Dialect.ParameterPrefix);
return string.Format("({0} {1}BETWEEN {2} AND {3})", columnName, Not ? "NOT " : string.Empty, propertyName1, propertyName2);
}
public BetweenValues Value { get; set; }
public bool Not { get; set; }
}
/// <summary>
/// Comparison operator for predicates.
/// </summary>
public enum Operator
{
/// <summary>
/// Equal to
/// </summary>
Eq,
/// <summary>
/// Greater than
/// </summary>
Gt,
/// <summary>
/// Greater than or equal to
/// </summary>
Ge,
/// <summary>
/// Less than
/// </summary>
Lt,
/// <summary>
/// Less than or equal to
/// </summary>
Le,
/// <summary>
/// Like (You can use % in the value to do wilcard searching)
/// </summary>
Like
}
public interface IPredicateGroup : IPredicate
{
GroupOperator Operator { get; set; }
IList<IPredicate> Predicates { get; set; }
}
/// <summary>
/// Groups IPredicates together using the specified group operator.
/// </summary>
public class PredicateGroup : IPredicateGroup
{
public GroupOperator Operator { get; set; }
public IList<IPredicate> Predicates { get; set; }
public string GetSql(ISqlGenerator sqlGenerator, IDictionary<string, object> parameters)
{
if (Predicates == null) return sqlGenerator.Configuration.Dialect.EmptyExpression;
string seperator = Operator == GroupOperator.And ? " AND " : " OR ";
var sql = "(" + Predicates.Aggregate(new StringBuilder(),
(sb, p) => (sb.Length == 0 ? sb : sb.Append(seperator)).Append(p.GetSql(sqlGenerator, parameters)),
sb =>
{
var s = sb.ToString();
if (s.Length == 0) return sqlGenerator.Configuration.Dialect.EmptyExpression;
return s;
}
) + ")";
if (parameters.Count() > parameters.Distinct().Count())
{
System.Diagnostics.Debug.WriteLine("重复的sql参数:" + sql, "DappersqlGernerator");
}
return sql;
}
}
public interface IExistsPredicate : IPredicate
{
IPredicate Predicate { get; set; }
bool Not { get; set; }
}
public class ExistsPredicate<TSub> : IExistsPredicate
where TSub : class
{
public IPredicate Predicate { get; set; }
public bool Not { get; set; }
public string GetSql(ISqlGenerator sqlGenerator, IDictionary<string, object> parameters)
{
IClassMapper mapSub = GetClassMapper(typeof(TSub), sqlGenerator.Configuration);
string sql = string.Format("({0}EXISTS (SELECT 1 FROM {1} WHERE {2}))",
Not ? "NOT " : string.Empty,
sqlGenerator.GetTableName(mapSub),
Predicate.GetSql(sqlGenerator, parameters));
return sql;
}
protected virtual IClassMapper GetClassMapper(Type type, IDapperExtensionsConfiguration configuration)
{
IClassMapper map = configuration.GetMap(type);
if (map == null)
{
throw new NullReferenceException(string.Format("Map was not found for {0}", type));
}
return map;
}
}
public interface ISort
{
string PropertyName { get; set; }
bool Ascending { get; set; }
}
public class Sort : ISort
{
public string PropertyName { get; set; }
public bool Ascending { get; set; }
}
/// <summary>
/// Operator to use when joining predicates in a PredicateGroup.
/// </summary>
public enum GroupOperator
{
And,
Or
}
}