SQLiteRepository.cs 9.6 KB

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