forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqlServerStorage.cs
More file actions
217 lines (194 loc) · 7.86 KB
/
SqlServerStorage.cs
File metadata and controls
217 lines (194 loc) · 7.86 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
#if !NETSTANDARD2_0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.SqlClient;
using System.Data.Common;
using ServiceStack.OrmLite.Dapper;
namespace ServiceStack.MiniProfiler.Storage
{
/// <summary>
/// Understands how to store a <see cref="Profiler"/> to a MSSQL database.
/// </summary>
public class SqlServerStorage : DatabaseStorageBase
{
/// <summary>
/// Returns a new <see cref="SqlServerStorage"/>.
/// </summary>
public SqlServerStorage(string connectionString)
: base(connectionString)
{
}
/// <summary>
/// Stores <param name="profiler"/> to dbo.MiniProfilers under its <see cref="Profiler.Id"/>;
/// stores all child Timings and SqlTimings to their respective tables.
/// </summary>
public override void Save(Profiler profiler)
{
const string sql =
@"insert into MiniProfilers
(Id,
Name,
Started,
MachineName,
[User],
Level,
RootTimingId,
DurationMilliseconds,
DurationMillisecondsInSql,
HasSqlTimings,
HasDuplicateSqlTimings,
HasTrivialTimings,
HasAllTrivialTimings,
TrivialDurationThresholdMilliseconds,
HasUserViewed,
Json)
select @Id,
@Name,
@Started,
@MachineName,
@User,
@Level,
@RootTimingId,
@DurationMilliseconds,
@DurationMillisecondsInSql,
@HasSqlTimings,
@HasDuplicateSqlTimings,
@HasTrivialTimings,
@HasAllTrivialTimings,
@TrivialDurationThresholdMilliseconds,
@HasUserViewed,
@Json
where not exists (select 1 from MiniProfilers where Id = @Id)"; // this syntax works on both mssql and sqlite
using (var conn = GetOpenConnection())
{
var insertCount = conn.Execute(sql, new
{
Id = profiler.Id,
Name = profiler.Name.Truncate(200),
Started = profiler.Started,
MachineName = profiler.MachineName.Truncate(100),
User = profiler.User.Truncate(100),
Level = profiler.Level,
RootTimingId = profiler.Root.Id,
DurationMilliseconds = profiler.DurationMilliseconds,
DurationMillisecondsInSql = profiler.DurationMillisecondsInSql,
HasSqlTimings = profiler.HasSqlTimings,
HasDuplicateSqlTimings = profiler.HasDuplicateSqlTimings,
HasTrivialTimings = profiler.HasTrivialTimings,
HasAllTrivialTimings = profiler.HasAllTrivialTimings,
TrivialDurationThresholdMilliseconds = profiler.TrivialDurationThresholdMilliseconds,
HasUserViewed = profiler.HasUserViewed,
Json = profiler.Root.ToJson()
});
}
}
private static readonly Dictionary<Type, string> LoadSqlStatements = new Dictionary<Type, string>
{
{ typeof(Profiler), "select * from MiniProfilers where Id = @id" }
};
private static readonly string LoadSqlBatch = string.Join("\n", LoadSqlStatements.Select(pair => pair.Value).ToArray());
/// <summary>
/// Loads the MiniProfiler identifed by 'id' from the database.
/// </summary>
public override Profiler Load(Guid id)
{
using (var conn = GetOpenConnection())
{
var idParameter = new { id };
var result = LoadIndividually(conn, idParameter);
if (result != null)
{
// HACK: stored dates are utc, but are pulled out as local time
result.Started = new DateTime(result.Started.Ticks, DateTimeKind.Utc);
// loading a profiler means we've viewed it
if (!result.HasUserViewed)
{
conn.Execute("update MiniProfilers set HasUserViewed = 1 where Id = @id", idParameter);
}
}
return result;
}
}
private Profiler LoadIndividually(DbConnection conn, object idParameter)
{
var result = LoadFor<Profiler>(conn, idParameter).SingleOrDefault();
if (result != null)
{
if (!String.IsNullOrWhiteSpace(result.Json))
{
result.Root = result.Json.FromJson<Timing>();
}
}
return result;
}
private List<T> LoadFor<T>(DbConnection conn, object idParameter)
{
return conn.Query<T>(LoadSqlStatements[typeof(T)], idParameter).ToList();
}
/// <summary>
/// Returns a list of <see cref="Profiler.Id"/>s that haven't been seen by <paramref name="user"/>.
/// </summary>
/// <param name="user">User identified by the current <see cref="Profiler.Settings.UserProvider"/>.</param>
public override List<Guid> GetUnviewedIds(string user)
{
const string sql =
@"select Id
from MiniProfilers
where [User] = @user
and HasUserViewed = 0
order by Started";
using (var conn = GetOpenConnection())
{
return conn.Query<Guid>(sql, new { user }).ToList();
}
}
/// <summary>
/// Returns a connection to Sql Server.
/// </summary>
protected override DbConnection GetConnection()
{
return new SqlConnection(ConnectionString);
}
/// <summary>
/// Creates needed tables. Run this once on your database.
/// </summary>
/// <remarks>
/// Works in sql server and sqlite (with documented removals).
/// </remarks>
public const string TableCreationScript =
@"create table MiniProfilers
(
RowId integer not null identity constraint PK_MiniProfilers primary key clustered, -- Need a clustered primary key for SQL Azure
Id uniqueidentifier not null, -- don't cluster on a guid
Name nvarchar(200) not null,
Started datetime not null,
MachineName nvarchar(100) null,
[User] nvarchar(100) null,
Level tinyint null,
RootTimingId uniqueidentifier null,
DurationMilliseconds decimal(7, 1) not null,
DurationMillisecondsInSql decimal(7, 1) null,
HasSqlTimings bit not null,
HasDuplicateSqlTimings bit not null,
HasTrivialTimings bit not null,
HasAllTrivialTimings bit not null,
TrivialDurationThresholdMilliseconds decimal(5, 1) null,
HasUserViewed bit not null,
Json nvarchar(max)
);
-- displaying results selects everything based on the main MiniProfilers.Id column
create unique nonclustered index IX_MiniProfilers_Id on MiniProfilers (Id);
-- speeds up a query that is called on every .Stop()
create nonclustered index IX_MiniProfilers_User_HasUserViewed_Includes on MiniProfilers ([User], HasUserViewed) include (Id, [Started]);
";
}
public static class MiniProfilerExt
{
public static string Truncate(this string s, int maxLength)
{
return s != null && s.Length > maxLength ? s.Substring(0, maxLength) : s;
}
}
}
#endif