SQLiteRepository.cs 9.1 KB

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