/
SoftFluent.FasterReader.xml
334 lines (306 loc) · 13.6 KB
/
SoftFluent.FasterReader.xml
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
<cf:project xmlns:cf="http://www.softfluent.com/codefluent/2005/1" xmlns:cfsm="http://www.softfluent.com/codefluent/producers.servicemodel/2007/1" xmlns:cfom="http://www.softfluent.com/codefluent/producers.model/2005/1" defaultNamespace="Whatever">
<cf:pattern name="CodeFluent FasterReader Aspect" namespaceUri="http://www.softfluent.com/codefluent/patterns/faster.reader/2014/1" preferredPrefix="_fr" step="Methods">
<cf:message class="_doc">
CodeFluent Entities - Sample FasterReader Aspect
Version 1.0.0.0 - 2014/03/12
Copyright 2007-2014 (C) SoftFluent S.A.S. All rights reserved.
</cf:message>
<cf:descriptor name="fastReader" targets="Property" defaultValue="false" displayName="Enable Fast Reader" typeName="boolean" description="Determines if the fast reder is enabled for collection loading." category="Faster Reader Aspect" />
</cf:pattern>
<?code @reference name="CodeFluent.Producers.CodeDom.dll" ?>
<?code @reference name="System.Data.dll" ?>
<?code @reference name="System.Core.dll" ?>
<?code @namespace name="CodeFluent.Model" ?>
<?code @namespace name="CodeFluent.Model.Code" ?>
<?code @namespace name="CodeFluent.Model.Rules" ?>
<?code @namespace name="CodeFluent.Producers.CodeDom" ?>
<?code @namespace name="CodeFluent.Runtime" ?>
<?code @namespace name="CodeFluent.Runtime.Utilities" ?>
<?code @namespace name="System" ?>
<?code @namespace name="System.CodeDom" ?>
<?code @namespace name="System.Collections.Generic" ?>
<?code @namespace name="System.Linq" ?>
<?code @namespace name="System.Text" ?>
<?code @member
const string FastReaderNamespaceUri = "http://www.softfluent.com/codefluent/patterns/faster.reader/2014/1";
public class FastProperty
{
public string Name;
public string ColumnName;
public CodeExpression Left;
public CodeTypeReference TypeRef;
public Type ClrType;
public int Index;
public bool IsNullable;
public Property Property;
// resolve various properties
public void Resolve(CodeTypeDeclaration type)
{
// the expression can be a field or a property
CodeFieldReferenceExpression fieldRef = Left as CodeFieldReferenceExpression;
if (fieldRef != null)
{
Name = fieldRef.FieldName;
CodeMemberField member = type.Members.OfType<CodeMemberField>().First(f => f.Name == Name);
TypeRef = member.Type;
PropertyDefinition def = UserData.GetPropertyDefinition(member);
if (def != null)
{
// the expression is the key property of a related entity
// to determine nullability, let's get to the "real" property
if (def.RelationPropertyDefinition != null && def.RelationPropertyDefinition.Property != null)
{
Property = def.RelationPropertyDefinition.Property;
}
else
{
Property = def.Property;
}
}
}
else
{
Name = ((CodePropertyReferenceExpression)Left).PropertyName;
CodeMemberProperty member = type.Members.OfType<CodeMemberProperty>().First(p => p.Name == Name);
TypeRef = member.Type;
PropertyDefinition def = UserData.GetPropertyDefinition(member);
if (def != null)
{
if (def.RelationPropertyDefinition != null && def.RelationPropertyDefinition.Property != null)
{
Property = def.RelationPropertyDefinition.Property;
}
else
{
Property = def.Property;
}
}
}
// NOTE: this supports only simple CLR types
ClrType = Type.GetType(TypeRef.BaseType, true);
if (ConvertUtilities.IsNullable(ClrType))
{
ClrType = Type.GetType(TypeRef.TypeArguments[0].BaseType, true);
IsNullable = true;
}
else
{
IsNullable = !ClrType.IsValueType || (Property != null && Property.IsNullable);
}
Console.WriteLine("prop:" + Property.Name + " nullable:" + Property.IsNullable + " mn:" + Property.IsModelNullable);
}
}
?>
<?code
// determines if a method is ok for tweak
Func<CodeMemberMethod, bool> isLoadMethod = (m) =>
{
if (m.Parameters.Count < 4) return false;
if (m.Parameters[0].Type.BaseType != typeof(int).FullName) return false; // pageIndex
if (m.Parameters[1].Type.BaseType != typeof(int).FullName) return false; // pageSize
if (m.Parameters[2].Type.BaseType != typeof(PageOptions).FullName) return false; // pageOptions
if (m.Parameters[3].Type.BaseType != typeof(System.Data.IDataReader).FullName) return false; // reader
return true;
};
// get the ReadRecord expression
Func<CodeMemberMethod, CodeMethodInvokeExpression> getReadRecord = (m) =>
{
CodeMethodInvokeExpression callReadRecord = null;
CodeDomUtilities.Visit(m, (obj) =>
{
if (callReadRecord != null) return;
CodeMethodInvokeExpression expr = obj as CodeMethodInvokeExpression;
if (expr != null && expr.Method.MethodName == "ReadRecord")
{
callReadRecord = expr;
}
});
return callReadRecord;
};
// get the CanAddEntity condition
Func<CodeMemberMethod, CodeConditionStatement> getCanAddEntity = (m) =>
{
CodeConditionStatement canAddEntity = null;
CodeDomUtilities.Visit(m, (obj) =>
{
if (canAddEntity != null) return;
CodeConditionStatement cond = obj as CodeConditionStatement;
if (cond == null) return;
CodeBinaryOperatorExpression expr = cond.Condition as CodeBinaryOperatorExpression;
if (expr == null) return;
CodeMethodInvokeExpression invoke = expr.Left as CodeMethodInvokeExpression;
if (invoke != null && invoke.Method.MethodName == "CanAddEntity")
{
canAddEntity = cond;
}
});
return canAddEntity;
};
// get the BaseContains condition
Func<CodeStatement, CodeConditionStatement> getBaseContains = (m) =>
{
CodeConditionStatement baseContains = null;
CodeDomUtilities.Visit(m, (obj) =>
{
if (baseContains != null) return;
CodeConditionStatement cond = obj as CodeConditionStatement;
if (cond == null) return;
CodeBinaryOperatorExpression expr = cond.Condition as CodeBinaryOperatorExpression;
if (expr == null) return;
CodeMethodInvokeExpression invoke = expr.Left as CodeMethodInvokeExpression;
if (invoke != null && invoke.Method.MethodName == "BaseContains")
{
baseContains = cond;
}
});
return baseContains;
};
// extract the list of entity properties that we will load using IDataReader unprotected/raw access
Func<CodeTypeDeclaration, CodeMemberMethod, List<FastProperty>> extractFastProperties = (t, m) =>
{
List<FastProperty> list = new List<FastProperty>();
CodeDomUtilities.Visit(m, (obj) =>
{
CodeAssignStatement assign = obj as CodeAssignStatement;
if (assign != null)
{
CodeMethodInvokeExpression expr = assign.Right as CodeMethodInvokeExpression;
if (expr != null && expr.Method.MethodName == "GetReaderValue" && expr.Parameters.Count > 1 && expr.Parameters[1] is CodePrimitiveExpression)
{
FastProperty prop = new FastProperty();
prop.Index = list.Count;
prop.ColumnName = (string)((CodePrimitiveExpression)expr.Parameters[1]).Value;
prop.Left = assign.Left;
prop.Resolve(t);
list.Add(prop);
}
}
});
return list;
};
CodeDomProducer codeDomProducer = Project.Producers.GetProducerInstance<CodeDomProducer>();
if (codeDomProducer != null)
{
codeDomProducer.CodeDomProduction += (sender, e) =>
{
CodeTypeDeclaration entityType;
CodeTypeDeclaration setType;
switch(e.EventType)
{
// a collection class is being written to disk. let's change it before that.
case CodeDomProductionEventType.SetCommitting:
Set set = UserData.GetBaseType((CodeCompileUnit)e.Argument) as Set; // get collection CodeDom type
if (!set.ItemEntity.GetAttributeValue("fastReader", FastReaderNamespaceUri, false))
break;
// get the CodeDom types
entityType = codeDomProducer.GetType(set.ItemEntity);
setType = codeDomProducer.GetType(set);
if (setType != null)
{
// search for methods with 4 params of type int, int, PageOptions, IDataReader
foreach(CodeMemberMethod method in setType.Members.OfType<CodeMemberMethod>().Where(m => isLoadMethod(m)))
{
CodeMethodInvokeExpression callReadRecord = getReadRecord(method);
CodeConditionStatement ifCanAddEntity = getCanAddEntity(method);
if (callReadRecord != null && ifCanAddEntity != null)
{
// declare the 'int[] indices' variable
CodeVariableDeclarationStatement indices = new CodeVariableDeclarationStatement(typeof(int[]), "indices", new CodePrimitiveExpression(null));
method.Statements.Insert(0, indices);
// hack the cast to do nothing, replace method name & args
((CodeCastExpression)callReadRecord.Method.TargetObject).TargetType = new CodeTypeReference(set.ItemEntity.ClrFullTypeName);
callReadRecord.Method.MethodName = "FastReadRecord";
CodeExpression readerArg = callReadRecord.Parameters[0];
callReadRecord.Parameters.Add(new CodeVariableReferenceExpression(indices.Name));
// add the indices check & one-time only resolve
CodeConditionStatement ifIndicesNull = new CodeConditionStatement();
ifIndicesNull.Condition = new CodeBinaryOperatorExpression(
new CodeVariableReferenceExpression("indices"),
CodeBinaryOperatorType.ValueEquality,
new CodePrimitiveExpression(null));
ifCanAddEntity.TrueStatements.Insert(0, ifIndicesNull);
ifIndicesNull.TrueStatements.Add(new CodeAssignStatement(
new CodeVariableReferenceExpression(indices.Name),
new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(set.ItemEntity.ClrFullTypeName), "GetRecordIndices", readerArg)));
// small optimization, just remove this check
CodeConditionStatement baseContains = getBaseContains(ifCanAddEntity);
if (baseContains != null)
{
baseContains.Condition = new CodePrimitiveExpression(true);
}
}
}
}
break;
// an entity class is being written to disk. let's change it before that.
case CodeDomProductionEventType.EntityCommitting:
Entity entity = UserData.GetBaseType((CodeCompileUnit)e.Argument) as Entity; // get entity CodeDom type
if (!entity.GetAttributeValue("fastReader", FastReaderNamespaceUri, false))
break;
// get the CodeDom type
entityType = codeDomProducer.GetType(entity);
if (entityType != null)
{
// get the ReadRecord CodeDom method
CodeMemberMethod readRecord = entityType.Members.OfType<CodeMemberMethod>().FirstOrDefault(m => m.Name == "ReadRecord");
if (readRecord != null)
{
// add a new "FastReadRecord" method
CodeMemberMethod fastReadRecord = new CodeMemberMethod();
fastReadRecord.Name = "FastReadRecord";
fastReadRecord.Attributes = MemberAttributes.FamilyAndAssembly; // internal
fastReadRecord.Parameters.Add(new CodeParameterDeclarationExpression(typeof(System.Data.IDataReader), "reader"));
fastReadRecord.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int[]), "indices"));
entityType.Members.Add(fastReadRecord);
// extract the interesting properties
List<FastProperty> props = extractFastProperties(entityType, readRecord);
foreach(var prop in props)
{
// if the property is nullable, we want to check reader.IsDBNull.
CodeStatementCollection statements;
if (prop.IsNullable)
{
CodeConditionStatement ifValueNotNull = new CodeConditionStatement();
ifValueNotNull.Condition = new CodeBinaryOperatorExpression(
new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("reader"), "IsDBNull", new CodePrimitiveExpression(prop.Index)),
CodeBinaryOperatorType.ValueEquality,
new CodePrimitiveExpression(false));
fastReadRecord.Statements.Add(ifValueNotNull);
statements = ifValueNotNull.TrueStatements;
}
else
{
statements = fastReadRecord.Statements;
}
// NOTE: this supports only standard CLR property types
string readerMethodName = "Get" + prop.ClrType.Name;
CodeAssignStatement assign = new CodeAssignStatement(prop.Left,
new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("reader"), readerMethodName,
new CodeIndexerExpression(new CodeVariableReferenceExpression("indices"), new CodePrimitiveExpression(prop.Index))));
statements.Add(assign);
}
// add the static indice computation method for a given IDataReader instance
CodeMemberMethod getRecordIndices = new CodeMemberMethod();
getRecordIndices.Name = "GetRecordIndices";
getRecordIndices.ReturnType = new CodeTypeReference(typeof(int[]));
getRecordIndices.Attributes = MemberAttributes.FamilyAndAssembly | MemberAttributes.Static; // internal static
getRecordIndices.Parameters.Add(new CodeParameterDeclarationExpression(typeof(System.Data.IDataReader), "reader"));
entityType.Members.Add(getRecordIndices);
CodeVariableDeclarationStatement indices = new CodeVariableDeclarationStatement(typeof(int[]), "indices", new CodeArrayCreateExpression(typeof(int), props.Count));
getRecordIndices.Statements.Add(indices);
foreach(var prop in props)
{
CodeAssignStatement assign = new CodeAssignStatement(
new CodeIndexerExpression(new CodeVariableReferenceExpression("indices"), new CodePrimitiveExpression(prop.Index)),
new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("reader"), "GetOrdinal", new CodePrimitiveExpression(prop.ColumnName)));
getRecordIndices.Statements.Add(assign);
}
getRecordIndices.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("indices")));
}
}
break;
}
};
}
?>
</cf:project>