SQLiteRepository.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. using MediaBrowser.Model.Logging;
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Data;
  5. using System.Data.Common;
  6. using System.Data.SQLite;
  7. using System.IO;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. namespace MediaBrowser.Server.Implementations.Sqlite
  11. {
  12. /// <summary>
  13. /// Class SqliteRepository
  14. /// </summary>
  15. public abstract class SqliteRepository : IDisposable
  16. {
  17. /// <summary>
  18. /// The db file name
  19. /// </summary>
  20. protected string dbFileName;
  21. /// <summary>
  22. /// The connection
  23. /// </summary>
  24. protected SQLiteConnection connection;
  25. /// <summary>
  26. /// The delayed commands
  27. /// </summary>
  28. protected ConcurrentQueue<SQLiteCommand> delayedCommands = new ConcurrentQueue<SQLiteCommand>();
  29. /// <summary>
  30. /// The flush interval
  31. /// </summary>
  32. private const int FlushInterval = 2000;
  33. /// <summary>
  34. /// The flush timer
  35. /// </summary>
  36. private Timer FlushTimer;
  37. /// <summary>
  38. /// Gets the logger.
  39. /// </summary>
  40. /// <value>The logger.</value>
  41. protected ILogger Logger { get; private set; }
  42. /// <summary>
  43. /// Gets a value indicating whether [enable delayed commands].
  44. /// </summary>
  45. /// <value><c>true</c> if [enable delayed commands]; otherwise, <c>false</c>.</value>
  46. protected virtual bool EnableDelayedCommands
  47. {
  48. get
  49. {
  50. return true;
  51. }
  52. }
  53. /// <summary>
  54. /// Initializes a new instance of the <see cref="SqliteRepository" /> class.
  55. /// </summary>
  56. /// <param name="logManager">The log manager.</param>
  57. /// <exception cref="System.ArgumentNullException">logger</exception>
  58. protected SqliteRepository(ILogManager logManager)
  59. {
  60. if (logManager == null)
  61. {
  62. throw new ArgumentNullException("logManager");
  63. }
  64. Logger = logManager.GetLogger(GetType().Name);
  65. }
  66. /// <summary>
  67. /// Connects to DB.
  68. /// </summary>
  69. /// <param name="dbPath">The db path.</param>
  70. /// <returns>Task{System.Boolean}.</returns>
  71. /// <exception cref="System.ArgumentNullException">dbPath</exception>
  72. protected async Task ConnectToDb(string dbPath)
  73. {
  74. if (string.IsNullOrEmpty(dbPath))
  75. {
  76. throw new ArgumentNullException("dbPath");
  77. }
  78. dbFileName = dbPath;
  79. var connectionstr = new SQLiteConnectionStringBuilder
  80. {
  81. PageSize = 4096,
  82. CacheSize = 40960,
  83. SyncMode = SynchronizationModes.Off,
  84. DataSource = dbPath,
  85. JournalMode = SQLiteJournalModeEnum.Memory
  86. };
  87. connection = new SQLiteConnection(connectionstr.ConnectionString);
  88. await connection.OpenAsync().ConfigureAwait(false);
  89. if (EnableDelayedCommands)
  90. {
  91. // Run once
  92. FlushTimer = new Timer(Flush, null, TimeSpan.FromMilliseconds(FlushInterval), TimeSpan.FromMilliseconds(-1));
  93. }
  94. }
  95. /// <summary>
  96. /// Runs the queries.
  97. /// </summary>
  98. /// <param name="queries">The queries.</param>
  99. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  100. /// <exception cref="System.ArgumentNullException">queries</exception>
  101. protected void RunQueries(string[] queries)
  102. {
  103. if (queries == null)
  104. {
  105. throw new ArgumentNullException("queries");
  106. }
  107. using (var tran = connection.BeginTransaction())
  108. {
  109. try
  110. {
  111. using (var cmd = connection.CreateCommand())
  112. {
  113. foreach (var query in queries)
  114. {
  115. cmd.Transaction = tran;
  116. cmd.CommandText = query;
  117. cmd.ExecuteNonQuery();
  118. }
  119. }
  120. tran.Commit();
  121. }
  122. catch (Exception e)
  123. {
  124. Logger.ErrorException("Error running queries", e);
  125. tran.Rollback();
  126. throw;
  127. }
  128. }
  129. }
  130. /// <summary>
  131. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  132. /// </summary>
  133. public void Dispose()
  134. {
  135. Dispose(true);
  136. GC.SuppressFinalize(this);
  137. }
  138. private readonly object _disposeLock = new object();
  139. /// <summary>
  140. /// Releases unmanaged and - optionally - managed resources.
  141. /// </summary>
  142. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  143. protected virtual void Dispose(bool dispose)
  144. {
  145. if (dispose)
  146. {
  147. try
  148. {
  149. lock (_disposeLock)
  150. {
  151. if (connection != null)
  152. {
  153. if (EnableDelayedCommands)
  154. {
  155. FlushOnDispose();
  156. }
  157. if (connection.IsOpen())
  158. {
  159. connection.Close();
  160. }
  161. connection.Dispose();
  162. connection = null;
  163. }
  164. if (FlushTimer != null)
  165. {
  166. FlushTimer.Dispose();
  167. FlushTimer = null;
  168. }
  169. }
  170. }
  171. catch (Exception ex)
  172. {
  173. Logger.ErrorException("Error disposing database", ex);
  174. }
  175. }
  176. }
  177. /// <summary>
  178. /// Flushes the on dispose.
  179. /// </summary>
  180. private void FlushOnDispose()
  181. {
  182. // If we're not already flushing, do it now
  183. if (!_isFlushing)
  184. {
  185. Flush(null);
  186. }
  187. // Don't dispose in the middle of a flush
  188. while (_isFlushing)
  189. {
  190. Thread.Sleep(25);
  191. }
  192. }
  193. /// <summary>
  194. /// Queues the command.
  195. /// </summary>
  196. /// <param name="cmd">The CMD.</param>
  197. /// <exception cref="System.ArgumentNullException">cmd</exception>
  198. protected void QueueCommand(SQLiteCommand cmd)
  199. {
  200. if (cmd == null)
  201. {
  202. throw new ArgumentNullException("cmd");
  203. }
  204. delayedCommands.Enqueue(cmd);
  205. }
  206. /// <summary>
  207. /// The is flushing
  208. /// </summary>
  209. private bool _isFlushing;
  210. /// <summary>
  211. /// Flushes the specified sender.
  212. /// </summary>
  213. /// <param name="sender">The sender.</param>
  214. private void Flush(object sender)
  215. {
  216. // Cannot call Count on a ConcurrentQueue since it's an O(n) operation
  217. // Use IsEmpty instead
  218. if (delayedCommands.IsEmpty)
  219. {
  220. FlushTimer.Change(TimeSpan.FromMilliseconds(FlushInterval), TimeSpan.FromMilliseconds(-1));
  221. return;
  222. }
  223. if (_isFlushing)
  224. {
  225. return;
  226. }
  227. _isFlushing = true;
  228. var numCommands = 0;
  229. using (var tran = connection.BeginTransaction())
  230. {
  231. try
  232. {
  233. while (!delayedCommands.IsEmpty)
  234. {
  235. SQLiteCommand command;
  236. delayedCommands.TryDequeue(out command);
  237. command.Connection = connection;
  238. command.Transaction = tran;
  239. command.ExecuteNonQuery();
  240. command.Dispose();
  241. numCommands++;
  242. }
  243. tran.Commit();
  244. }
  245. catch (Exception e)
  246. {
  247. Logger.ErrorException("Failed to commit transaction.", e);
  248. tran.Rollback();
  249. }
  250. }
  251. Logger.Debug("SQL Delayed writer executed " + numCommands + " commands");
  252. FlushTimer.Change(TimeSpan.FromMilliseconds(FlushInterval), TimeSpan.FromMilliseconds(-1));
  253. _isFlushing = false;
  254. }
  255. /// <summary>
  256. /// Executes the command.
  257. /// </summary>
  258. /// <param name="cmd">The CMD.</param>
  259. /// <returns>Task.</returns>
  260. /// <exception cref="System.ArgumentNullException">cmd</exception>
  261. public async Task ExecuteCommand(DbCommand cmd)
  262. {
  263. if (cmd == null)
  264. {
  265. throw new ArgumentNullException("cmd");
  266. }
  267. using (var tran = connection.BeginTransaction())
  268. {
  269. try
  270. {
  271. cmd.Connection = connection;
  272. cmd.Transaction = tran;
  273. await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);
  274. tran.Commit();
  275. }
  276. catch (Exception e)
  277. {
  278. Logger.ErrorException("Failed to commit transaction.", e);
  279. tran.Rollback();
  280. }
  281. }
  282. }
  283. /// <summary>
  284. /// Gets a stream from a DataReader at a given ordinal
  285. /// </summary>
  286. /// <param name="reader">The reader.</param>
  287. /// <param name="ordinal">The ordinal.</param>
  288. /// <returns>Stream.</returns>
  289. /// <exception cref="System.ArgumentNullException">reader</exception>
  290. protected static Stream GetStream(IDataReader reader, int ordinal)
  291. {
  292. if (reader == null)
  293. {
  294. throw new ArgumentNullException("reader");
  295. }
  296. var memoryStream = new MemoryStream();
  297. var num = 0L;
  298. var array = new byte[4096];
  299. long bytes;
  300. do
  301. {
  302. bytes = reader.GetBytes(ordinal, num, array, 0, array.Length);
  303. memoryStream.Write(array, 0, (int)bytes);
  304. num += bytes;
  305. }
  306. while (bytes > 0L);
  307. memoryStream.Position = 0;
  308. return memoryStream;
  309. }
  310. }
  311. }