-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathResultMapper.cs
More file actions
308 lines (276 loc) · 11.1 KB
/
ResultMapper.cs
File metadata and controls
308 lines (276 loc) · 11.1 KB
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
using PlanViewer.Core.Models;
namespace PlanViewer.Core.Output;
/// <summary>
/// Maps parsed plan models to the structured CLI output format.
/// </summary>
public static class ResultMapper
{
public static AnalysisResult Map(ParsedPlan plan, string source, ServerMetadata? metadata = null)
{
var result = new AnalysisResult
{
PlanSource = source,
SqlServerVersion = plan.BuildVersion,
SqlServerBuild = plan.Build
};
foreach (var batch in plan.Batches)
{
foreach (var stmt in batch.Statements)
{
result.Statements.Add(MapStatement(stmt));
}
}
result.Summary = BuildSummary(result);
if (metadata != null)
{
result.ServerContext = new ServerContextResult
{
ServerName = metadata.ServerName,
ProductVersion = metadata.ProductVersion,
ProductLevel = metadata.ProductLevel,
Edition = metadata.Edition,
IsAzure = metadata.IsAzure,
CpuCount = metadata.CpuCount,
PhysicalMemoryMB = metadata.PhysicalMemoryMB,
MaxDop = metadata.MaxDop,
CostThresholdForParallelism = metadata.CostThresholdForParallelism,
MaxServerMemoryMB = metadata.MaxServerMemoryMB
};
if (metadata.Database != null)
{
var dbm = metadata.Database;
result.ServerContext.Database = new DatabaseContextResult
{
Name = dbm.Name,
CompatibilityLevel = dbm.CompatibilityLevel,
CollationName = dbm.CollationName,
SnapshotIsolationState = dbm.SnapshotIsolationState,
ReadCommittedSnapshot = dbm.IsReadCommittedSnapshotOn,
AutoCreateStats = dbm.IsAutoCreateStatsOn,
AutoUpdateStats = dbm.IsAutoUpdateStatsOn,
AutoUpdateStatsAsync = dbm.IsAutoUpdateStatsAsyncOn,
ParameterizationForced = dbm.IsParameterizationForced
};
foreach (var sc in dbm.NonDefaultScopedConfigs)
{
result.ServerContext.Database.NonDefaultScopedConfigs.Add(new ScopedConfigResult
{
Name = sc.Name,
Value = sc.Value,
ValueForSecondary = sc.ValueForSecondary
});
}
}
}
return result;
}
private static StatementResult MapStatement(PlanStatement stmt)
{
var result = new StatementResult
{
StatementText = stmt.StatementText,
StatementType = stmt.StatementType,
EstimatedCost = stmt.StatementSubTreeCost,
EstimatedRows = stmt.StatementEstRows,
OptimizationLevel = stmt.StatementOptmLevel,
EarlyAbortReason = stmt.StatementOptmEarlyAbortReason,
CardinalityEstimationModel = stmt.CardinalityEstimationModelVersion,
CompileTimeMs = stmt.CompileTimeMs,
CompileMemoryKB = stmt.CompileMemoryKB,
CachedPlanSizeKB = stmt.CachedPlanSizeKB,
DegreeOfParallelism = stmt.DegreeOfParallelism,
NonParallelReason = stmt.NonParallelPlanReason,
QueryHash = stmt.QueryHash,
QueryPlanHash = stmt.QueryPlanHash,
BatchModeOnRowStore = stmt.BatchModeOnRowStoreUsed
};
// Memory grant
if (stmt.MemoryGrant != null)
{
result.MemoryGrant = new MemoryGrantResult
{
RequestedKB = stmt.MemoryGrant.RequestedMemoryKB,
GrantedKB = stmt.MemoryGrant.GrantedMemoryKB,
MaxUsedKB = stmt.MemoryGrant.MaxUsedMemoryKB,
GrantWaitMs = stmt.MemoryGrant.GrantWaitTimeMs,
FeedbackAdjusted = stmt.MemoryGrant.IsMemoryGrantFeedbackAdjusted,
EstimatedAvailableMemoryGrantKB = stmt.HardwareProperties?.EstimatedAvailableMemoryGrant ?? 0
};
}
// Query time (actual plans)
if (stmt.QueryTimeStats != null)
{
result.QueryTime = new QueryTimeResult
{
CpuTimeMs = stmt.QueryTimeStats.CpuTimeMs,
ElapsedTimeMs = stmt.QueryTimeStats.ElapsedTimeMs
};
}
// Wait stats (actual plans only)
foreach (var w in stmt.WaitStats)
{
result.WaitStats.Add(new WaitStatResult
{
WaitType = w.WaitType,
WaitTimeMs = w.WaitTimeMs,
WaitCount = w.WaitCount
});
}
// Parameters — flag potential sniffing issues
foreach (var p in stmt.Parameters)
{
var pr = new ParameterResult
{
Name = p.Name,
DataType = p.DataType,
CompiledValue = p.CompiledValue,
RuntimeValue = p.RuntimeValue
};
// Sniffing flag: compiled and runtime values both present but differ
if (!string.IsNullOrEmpty(p.CompiledValue) &&
!string.IsNullOrEmpty(p.RuntimeValue) &&
p.CompiledValue != p.RuntimeValue)
{
pr.SniffingIssue = true;
}
result.Parameters.Add(pr);
}
// Statement-level warnings
foreach (var w in stmt.PlanWarnings)
{
result.Warnings.Add(new WarningResult
{
Type = w.WarningType,
Severity = w.Severity.ToString(),
Message = w.Message,
MaxBenefitPercent = w.MaxBenefitPercent,
ActionableFix = w.ActionableFix
});
}
// Missing indexes
foreach (var mi in stmt.MissingIndexes)
{
result.MissingIndexes.Add(new MissingIndexResult
{
Table = $"{mi.Database}.{mi.Schema}.{mi.Table}",
Impact = mi.Impact,
EqualityColumns = mi.EqualityColumns,
InequalityColumns = mi.InequalityColumns,
IncludeColumns = mi.IncludeColumns,
CreateStatement = mi.CreateStatement
});
}
// Operator tree
if (stmt.RootNode != null)
{
result.OperatorTree = MapNode(stmt.RootNode);
}
// Plan guide
if (!string.IsNullOrEmpty(stmt.PlanGuideName))
result.PlanGuide = $"{stmt.PlanGuideDB}.{stmt.PlanGuideName}";
// Query Store hints
if (!string.IsNullOrEmpty(stmt.QueryStoreStatementHintText))
result.QueryStoreHint = stmt.QueryStoreStatementHintText;
// Trace flags
foreach (var tf in stmt.TraceFlags)
result.TraceFlags.Add($"TF{tf.Value} ({tf.Scope}{(tf.IsCompileTime ? ", compile-time" : "")})");
// Cursor
if (!string.IsNullOrEmpty(stmt.CursorName))
{
result.Cursor = new CursorResult
{
Name = stmt.CursorName,
ActualType = stmt.CursorActualType,
RequestedType = stmt.CursorRequestedType,
Concurrency = stmt.CursorConcurrency,
ForwardOnly = stmt.CursorForwardOnly
};
}
return result;
}
private static OperatorResult MapNode(PlanNode node)
{
var result = new OperatorResult
{
NodeId = node.NodeId,
PhysicalOp = node.PhysicalOp,
LogicalOp = node.LogicalOp,
CostPercent = node.CostPercent,
EstimatedRows = node.EstimateRows,
EstimatedCost = node.EstimatedOperatorCost,
EstimatedIO = node.EstimateIO,
EstimatedCPU = node.EstimateCPU,
EstimatedRowSize = node.EstimatedRowSize,
ObjectName = node.FullObjectName ?? node.ObjectName,
IndexName = node.IndexName,
DatabaseName = node.DatabaseName,
SeekPredicates = node.SeekPredicates,
Predicate = node.Predicate,
OutputColumns = node.OutputColumns,
HashKeysBuild = node.HashKeysBuild,
HashKeysProbe = node.HashKeysProbe,
OuterReferences = node.OuterReferences,
OrderBy = node.OrderBy,
GroupBy = node.GroupBy,
Parallel = node.Parallel,
ExecutionMode = node.ExecutionMode,
ActualExecutionMode = node.ActualExecutionMode
};
// Actual stats (only include when present)
if (node.HasActualStats)
{
result.ActualRows = node.ActualRows;
result.ActualExecutions = node.ActualExecutions;
result.ActualElapsedMs = node.ActualElapsedMs;
result.ActualCpuMs = node.ActualCPUMs;
result.ActualLogicalReads = node.ActualLogicalReads;
result.ActualPhysicalReads = node.ActualPhysicalReads;
}
// Operator warnings
foreach (var w in node.Warnings)
{
result.Warnings.Add(new WarningResult
{
Type = w.WarningType,
Severity = w.Severity.ToString(),
Message = w.Message,
Operator = $"{node.PhysicalOp} (Node {node.NodeId})",
NodeId = node.NodeId,
MaxBenefitPercent = w.MaxBenefitPercent,
ActionableFix = w.ActionableFix
});
}
// Children
foreach (var child in node.Children)
result.Children.Add(MapNode(child));
return result;
}
private static AnalysisSummary BuildSummary(AnalysisResult result)
{
var allWarnings = new List<WarningResult>();
foreach (var stmt in result.Statements)
{
allWarnings.AddRange(stmt.Warnings);
CollectNodeWarnings(stmt.OperatorTree, allWarnings);
}
return new AnalysisSummary
{
TotalStatements = result.Statements.Count,
TotalWarnings = allWarnings.Count,
CriticalWarnings = allWarnings.Count(w => w.Severity == "Critical"),
MissingIndexes = result.Statements.Sum(s => s.MissingIndexes.Count),
HasActualStats = result.Statements.Any(s => s.QueryTime != null),
MaxEstimatedCost = result.Statements.Count > 0
? result.Statements.Max(s => s.EstimatedCost)
: 0,
WarningTypes = allWarnings.Select(w => w.Type).Distinct().OrderBy(t => t).ToList()
};
}
private static void CollectNodeWarnings(OperatorResult? node, List<WarningResult> warnings)
{
if (node == null) return;
warnings.AddRange(node.Warnings);
foreach (var child in node.Children)
CollectNodeWarnings(child, warnings);
}
}