-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
DatabaseHelper.cs
113 lines (97 loc) · 3.38 KB
/
DatabaseHelper.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
using System;
using System.Data.Common;
using System.Data.Linq;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using LINQPad;
namespace ExecutionPlanVisualizer.Helpers
{
internal abstract class DatabaseHelper
{
private DbConnection _dbConnection;
public static DatabaseHelper Create<T>(DataContextBase dataContextBase, IQueryable<T> queryable)
{
if (dataContextBase != null)
{
return new LinqToSqlDatabaseHelper(dataContextBase);
}
var table = queryable as ITable;
if (table != null)
{
return new LinqToSqlDatabaseHelper(table.Context);
}
var dataQueryType = typeof(DataContext).Assembly.GetType("System.Data.Linq.DataQuery`1");
if (queryable.GetType().GetGenericTypeDefinition() == dataQueryType)
{
var contextField = queryable.GetType().GetField("context", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
var context = contextField?.GetValue(queryable) as DataContext;
if (context != null)
{
return new LinqToSqlDatabaseHelper(context);
}
}
return new EntityFrameworkDatabaseHelper();
}
public DbConnection Connection
{
get
{
if (_dbConnection == null)
{
throw new InvalidOperationException("Connection has not been set.");
}
return _dbConnection;
}
set { _dbConnection = value; }
}
public virtual string GetSqlServerQueryExecutionPlan<T>(IQueryable<T> queryable)
{
using (var command = CreateCommand(queryable))
{
try
{
Connection.Open();
using (var setStatisticsCommand = Connection.CreateCommand())
{
setStatisticsCommand.CommandText = "SET STATISTICS XML ON";
setStatisticsCommand.ExecuteNonQuery();
}
using (var reader = command.ExecuteReader())
{
while (reader.NextResult())
{
if (reader.GetName(0) == "Microsoft SQL Server 2005 XML Showplan")
{
reader.Read();
return reader.GetString(0);
}
}
}
return null;
}
finally
{
Connection.Close();
}
}
}
public virtual async Task CreateIndexAsync(string script)
{
try
{
await Connection.OpenAsync();
using (var command = Connection.CreateCommand())
{
command.CommandText = script;
var result = await command.ExecuteNonQueryAsync();
}
}
finally
{
Connection.Close();
}
}
protected abstract DbCommand CreateCommand(IQueryable queryable);
}
}