forked from samus/mongodb-csharp
-
Notifications
You must be signed in to change notification settings - Fork 9
/
DocumentFormatter.cs
414 lines (366 loc) · 15.6 KB
/
DocumentFormatter.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
using MongoDB.Linq.Expressions;
using MongoDB.Util;
namespace MongoDB.Linq.Translators
{
internal class DocumentFormatter : MongoExpressionVisitor
{
private Document _query;
private Stack<Scope> _scopes;
private bool _hasPredicate;
internal Document FormatDocument(Expression expression)
{
_query = new Document();
_scopes = new Stack<Scope>();
Visit(expression);
return _query;
}
protected override Expression VisitBinary(BinaryExpression b)
{
int scopeDepth = _scopes.Count;
bool hasPredicate = b.NodeType != ExpressionType.And && b.NodeType != ExpressionType.AndAlso && b.NodeType != ExpressionType.Or && b.NodeType != ExpressionType.OrElse;
VisitPredicate(b.Left, hasPredicate);
switch (b.NodeType)
{
case ExpressionType.Equal:
break;
case ExpressionType.GreaterThan:
PushConditionScope("$gt");
break;
case ExpressionType.GreaterThanOrEqual:
PushConditionScope("$gte");
break;
case ExpressionType.LessThan:
PushConditionScope("$lt");
break;
case ExpressionType.LessThanOrEqual:
PushConditionScope("$lte");
break;
case ExpressionType.NotEqual:
PushConditionScope("$ne");
break;
case ExpressionType.Modulo:
throw new NotImplementedException();
case ExpressionType.And:
case ExpressionType.AndAlso:
break;
default:
throw new NotSupportedException(string.Format("The operation {0} is not supported.", b.NodeType));
}
VisitPredicate(b.Right, false);
while (_scopes.Count > scopeDepth)
PopConditionScope();
return b;
}
protected override Expression VisitConstant(ConstantExpression c)
{
AddCondition(c.Value);
return c;
}
protected override Expression VisitField(FieldExpression f)
{
if (!_hasPredicate)
{
PushConditionScope(f.Name);
AddCondition(true);
PopConditionScope();
}
else
PushConditionScope(f.Name);
return f;
}
protected override Expression VisitMemberAccess(MemberExpression m)
{
if (m.Member.DeclaringType == typeof(Array))
{
if (m.Member.Name == "Length")
{
VisitPredicate(m.Expression, true);
PushConditionScope("$size");
return m;
}
}
else if (typeof(ICollection).IsAssignableFrom(m.Member.DeclaringType))
{
if (m.Member.Name == "Count")
{
VisitPredicate(m.Expression, true);
PushConditionScope("$size");
return m;
}
}
else if (typeof(ICollection<>).IsOpenTypeAssignableFrom(m.Member.DeclaringType))
{
if (m.Member.Name == "Count")
{
VisitPredicate(m.Expression, true);
PushConditionScope("$size");
return m;
}
}
throw new NotSupportedException(string.Format("The member {0} is not supported.", m.Member.Name));
}
protected override Expression VisitMethodCall(MethodCallExpression m)
{
FieldExpression field;
if (m.Method.DeclaringType == typeof(Queryable) || m.Method.DeclaringType == typeof(Enumerable))
{
switch (m.Method.Name)
{
case "Any":
if(m.Arguments.Count != 2)
throw new NotSupportedException("Only the Any method with 2 arguments is supported.");
field = m.Arguments[0] as FieldExpression;
if (field == null)
throw new InvalidQueryException("A mongo field must be a part of the Contains method.");
VisitPredicate(field, true);
PushConditionScope("$elemMatch");
VisitPredicate(m.Arguments[1], true);
PopConditionScope(); //elemMatch
PopConditionScope(); //field
return m;
case "Contains":
if (m.Arguments.Count != 2)
throw new NotSupportedException("Only the Contains method with 2 arguments is supported.");
field = m.Arguments[0] as FieldExpression;
if (field != null)
{
VisitPredicate(field, true);
AddCondition(EvaluateConstant<object>(m.Arguments[1]));
PopConditionScope();
return m;
}
field = m.Arguments[1] as FieldExpression;
if (field == null)
throw new InvalidQueryException("A mongo field must be a part of the Contains method.");
VisitPredicate(field, true);
AddCondition("$in", EvaluateConstant<IEnumerable>(m.Arguments[0]));
PopConditionScope();
return m;
case "Count":
if (m.Arguments.Count == 1)
{
Visit(m.Arguments[0]);
PushConditionScope("$size");
return m;
}
throw new NotSupportedException("The method Count with a predicate is not supported for field.");
case "SequenceEqual":
field = m.Arguments[0] as FieldExpression;
if (field != null)
{
VisitPredicate(field, true);
AddCondition(EvaluateConstant<object>(m.Arguments[1]));
PopConditionScope();
}
return m;
}
}
else if(typeof(ICollection<>).IsOpenTypeAssignableFrom(m.Method.DeclaringType) || typeof(IList).IsAssignableFrom(m.Method.DeclaringType))
{
switch(m.Method.Name)
{
case "Contains":
field = m.Arguments[0] as FieldExpression;
if (field != null)
{
VisitPredicate(field, true);
AddCondition("$in", EvaluateConstant<IEnumerable>(m.Object).OfType<object>().ToArray());
PopConditionScope();
return m;
}
field = m.Object as FieldExpression;
if (field != null)
{
VisitPredicate(m.Object, true);
AddCondition(EvaluateConstant<object>(m.Arguments[0]));
PopConditionScope();
return m;
}
throw new InvalidQueryException(string.Format("The mongo field must be the argument in method {0}.", m.Method.Name));
}
}
else if (m.Method.DeclaringType == typeof(string))
{
field = m.Object as FieldExpression;
if (field == null)
throw new InvalidQueryException(string.Format("The mongo field must be the operator for a string operation of type {0}.", m.Method.Name));
VisitPredicate(field, true);
var value = EvaluateConstant<string>(m.Arguments[0]);
switch(m.Method.Name)
{
case "StartsWith":
AddCondition(new MongoRegex(string.Format("^{0}", value)));
break;
case "EndsWith":
AddCondition(new MongoRegex(string.Format("{0}$", value)));
break;
case "Contains":
AddCondition(new MongoRegex(string.Format("{0}", value)));
break;
default:
throw new NotSupportedException(string.Format("The string method {0} is not supported.", m.Method.Name));
}
PopConditionScope();
return m;
}
else if (m.Method.DeclaringType == typeof(Regex))
{
if (m.Method.Name == "IsMatch")
{
field = m.Arguments[0] as FieldExpression;
if (field == null)
throw new InvalidQueryException(string.Format("The mongo field must be the operator for a string operation of type {0}.", m.Method.Name));
VisitPredicate(field, true);
string value;
if (m.Object == null)
value = EvaluateConstant<string>(m.Arguments[1]);
else
throw new InvalidQueryException(string.Format("Only the static Regex.IsMatch is supported.", m.Method.Name));
var regexOptions = RegexOptions.None;
if (m.Arguments.Count > 2)
regexOptions = EvaluateConstant<RegexOptions>(m.Arguments[2]);
AddCondition(new MongoRegex(value, regexOptions));
PopConditionScope();
return m;
}
}
else if (m.Method.DeclaringType.IsArray)
{
if (m.Method.Name == "Contains")
{
field = m.Object as FieldExpression;
if (field != null)
{
VisitPredicate(field, true);
AddCondition(EvaluateConstant<object>(m.Arguments[0]));
PopConditionScope();
return m;
}
field = m.Arguments[0] as FieldExpression;
if (field == null)
throw new InvalidQueryException("A mongo field must be a part of the Contains method.");
VisitPredicate(field, true);
AddCondition("$in", EvaluateConstant<IEnumerable>(m.Object));
PopConditionScope();
return m;
}
}
throw new NotSupportedException(string.Format("The method {0} is not supported.", m.Method.Name));
}
protected override Expression VisitUnary(UnaryExpression u)
{
switch (u.NodeType)
{
case ExpressionType.Not:
PushConditionScope("$not");
VisitPredicate(u.Operand, false);
PopConditionScope();
break;
case ExpressionType.ArrayLength:
Visit(u.Operand);
PushConditionScope("$size");
break;
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
Visit(u.Operand);
break;
default:
throw new NotSupportedException(string.Format("The unary operator {0} is not supported.", u.NodeType));
}
return u;
}
private void AddCondition(object value)
{
_scopes.Peek().AddCondition(value ?? NullPlaceHolder.Instance);
}
private void AddCondition(string name, object value)
{
PushConditionScope(name);
AddCondition(value);
PopConditionScope();
}
private void PushConditionScope(string name)
{
if (_scopes.Count == 0)
_scopes.Push(new Scope(name, _query[name]));
else
_scopes.Push(_scopes.Peek().CreateChildScope(name));
}
private void PopConditionScope()
{
var scope = _scopes.Pop();
if (scope.Value == null)
return;
var doc = _query;
foreach (var s in _scopes.Reverse()) //as if it were a queue
{
var sub = doc[s.Key];
if (sub == null)
doc[s.Key] = sub = new Document();
else if (!(sub is Document))
throw new InvalidQueryException();
doc = (Document)sub;
}
if (scope.Value is NullPlaceHolder)
doc[scope.Key] = null;
else
doc[scope.Key] = scope.Value;
}
private void VisitPredicate(Expression expression, bool hasPredicate)
{
var oldHasPredicate = _hasPredicate;
_hasPredicate = hasPredicate;
Visit(expression);
_hasPredicate = oldHasPredicate;
}
private static T EvaluateConstant<T>(Expression e)
{
if (e.NodeType != ExpressionType.Constant)
throw new ArgumentException("Expression must be a constant.");
return (T)((ConstantExpression)e).Value;
}
private static bool IsBoolean(Expression expression)
{
return expression.Type == typeof(bool) || expression.Type == typeof(bool?);
}
private class NullPlaceHolder
{
public static readonly NullPlaceHolder Instance = new NullPlaceHolder();
private NullPlaceHolder()
{ }
}
private class Scope
{
public string Key { get; private set; }
public object Value { get; private set; }
public Scope(string key, object initialValue)
{
Key = key;
Value = initialValue;
}
public void AddCondition(object value)
{
if (Value is Document)
{
if (!(value is Document))
throw new InvalidQueryException();
((Document)Value).Merge((Document)value);
}
else
Value = value;
}
public Scope CreateChildScope(string name)
{
if (Value is Document)
return new Scope(name, ((Document)Value)[name]);
return new Scope(name, null);
}
}
}
}