SQLiteRepository.cs 9.8 KB

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