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
|
using MediaBrowser.Model.Logging;
using System;
using System.Collections.Concurrent;
using System.Data;
using System.Data.Common;
using System.Data.SQLite;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Server.Implementations.Sqlite
{
/// <summary>
/// Class SqliteRepository
/// </summary>
public abstract class SqliteRepository : IDisposable
{
/// <summary>
/// The db file name
/// </summary>
protected string dbFileName;
/// <summary>
/// The connection
/// </summary>
protected SQLiteConnection connection;
/// <summary>
/// The delayed commands
/// </summary>
protected ConcurrentQueue<SQLiteCommand> delayedCommands = new ConcurrentQueue<SQLiteCommand>();
/// <summary>
/// The flush interval
/// </summary>
private const int FlushInterval = 2000;
/// <summary>
/// The flush timer
/// </summary>
private Timer FlushTimer;
/// <summary>
/// Gets the logger.
/// </summary>
/// <value>The logger.</value>
protected ILogger Logger { get; private set; }
/// <summary>
/// Gets a value indicating whether [enable delayed commands].
/// </summary>
/// <value><c>true</c> if [enable delayed commands]; otherwise, <c>false</c>.</value>
protected virtual bool EnableDelayedCommands
{
get
{
return true;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="SqliteRepository" /> class.
/// </summary>
/// <param name="logManager">The log manager.</param>
/// <exception cref="System.ArgumentNullException">logger</exception>
protected SqliteRepository(ILogManager logManager)
{
if (logManager == null)
{
throw new ArgumentNullException("logManager");
}
Logger = logManager.GetLogger(GetType().Name);
}
/// <summary>
/// Connects to DB.
/// </summary>
/// <param name="dbPath">The db path.</param>
/// <returns>Task{System.Boolean}.</returns>
/// <exception cref="System.ArgumentNullException">dbPath</exception>
protected async Task ConnectToDB(string dbPath)
{
if (string.IsNullOrEmpty(dbPath))
{
throw new ArgumentNullException("dbPath");
}
dbFileName = dbPath;
var connectionstr = new SQLiteConnectionStringBuilder
{
PageSize = 4096,
CacheSize = 40960,
SyncMode = SynchronizationModes.Off,
DataSource = dbPath,
JournalMode = SQLiteJournalModeEnum.Memory
};
connection = new SQLiteConnection(connectionstr.ConnectionString);
await connection.OpenAsync().ConfigureAwait(false);
if (EnableDelayedCommands)
{
// Run once
FlushTimer = new Timer(Flush, null, TimeSpan.FromMilliseconds(FlushInterval), TimeSpan.FromMilliseconds(-1));
}
}
/// <summary>
/// Runs the queries.
/// </summary>
/// <param name="queries">The queries.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
/// <exception cref="System.ArgumentNullException">queries</exception>
protected void RunQueries(string[] queries)
{
if (queries == null)
{
throw new ArgumentNullException("queries");
}
using (var tran = connection.BeginTransaction())
{
try
{
var cmd = connection.CreateCommand();
foreach (var query in queries)
{
cmd.Transaction = tran;
cmd.CommandText = query;
cmd.ExecuteNonQuery();
}
tran.Commit();
}
catch (Exception e)
{
Logger.ErrorException("Error running queries", e);
tran.Rollback();
throw;
}
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool dispose)
{
if (dispose)
{
try
{
if (connection != null)
{
if (EnableDelayedCommands)
{
FlushOnDispose();
}
if (connection.IsOpen())
{
connection.Close();
}
connection.Dispose();
}
if (FlushTimer != null)
{
FlushTimer.Dispose();
FlushTimer = null;
}
}
catch (Exception ex)
{
Logger.ErrorException("Error disposing database", ex);
}
}
}
/// <summary>
/// Flushes the on dispose.
/// </summary>
private void FlushOnDispose()
{
// If we're not already flushing, do it now
if (!IsFlushing)
{
Flush(null);
}
// Don't dispose in the middle of a flush
while (IsFlushing)
{
Thread.Sleep(25);
}
}
/// <summary>
/// Queues the command.
/// </summary>
/// <param name="cmd">The CMD.</param>
/// <exception cref="System.ArgumentNullException">cmd</exception>
protected void QueueCommand(SQLiteCommand cmd)
{
if (cmd == null)
{
throw new ArgumentNullException("cmd");
}
delayedCommands.Enqueue(cmd);
}
/// <summary>
/// The is flushing
/// </summary>
private bool IsFlushing;
/// <summary>
/// Flushes the specified sender.
/// </summary>
/// <param name="sender">The sender.</param>
private void Flush(object sender)
{
// Cannot call Count on a ConcurrentQueue since it's an O(n) operation
// Use IsEmpty instead
if (delayedCommands.IsEmpty)
{
FlushTimer.Change(TimeSpan.FromMilliseconds(FlushInterval), TimeSpan.FromMilliseconds(-1));
return;
}
if (IsFlushing)
{
return;
}
IsFlushing = true;
var numCommands = 0;
using (var tran = connection.BeginTransaction())
{
try
{
while (!delayedCommands.IsEmpty)
{
SQLiteCommand command;
delayedCommands.TryDequeue(out command);
command.Connection = connection;
command.Transaction = tran;
command.ExecuteNonQuery();
numCommands++;
}
tran.Commit();
}
catch (Exception e)
{
Logger.ErrorException("Failed to commit transaction.", e);
tran.Rollback();
}
}
Logger.Info("SQL Delayed writer executed " + numCommands + " commands");
FlushTimer.Change(TimeSpan.FromMilliseconds(FlushInterval), TimeSpan.FromMilliseconds(-1));
IsFlushing = false;
}
/// <summary>
/// Executes the command.
/// </summary>
/// <param name="cmd">The CMD.</param>
/// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException">cmd</exception>
public async Task ExecuteCommand(DbCommand cmd)
{
if (cmd == null)
{
throw new ArgumentNullException("cmd");
}
using (var tran = connection.BeginTransaction())
{
try
{
cmd.Connection = connection;
cmd.Transaction = tran;
await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);
tran.Commit();
}
catch (Exception e)
{
Logger.ErrorException("Failed to commit transaction.", e);
tran.Rollback();
}
}
}
/// <summary>
/// Gets a stream from a DataReader at a given ordinal
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="ordinal">The ordinal.</param>
/// <returns>Stream.</returns>
/// <exception cref="System.ArgumentNullException">reader</exception>
protected static Stream GetStream(IDataReader reader, int ordinal)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
var memoryStream = new MemoryStream();
var num = 0L;
var array = new byte[4096];
long bytes;
do
{
bytes = reader.GetBytes(ordinal, num, array, 0, array.Length);
memoryStream.Write(array, 0, (int)bytes);
num += bytes;
}
while (bytes > 0L);
memoryStream.Position = 0;
return memoryStream;
}
}
}
|