SQLiteRepository.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. var cmd = connection.CreateCommand();
  112. foreach (var query in queries)
  113. {
  114. cmd.Transaction = tran;
  115. cmd.CommandText = query;
  116. cmd.ExecuteNonQuery();
  117. }
  118. tran.Commit();
  119. }
  120. catch (Exception e)
  121. {
  122. Logger.ErrorException("Error running queries", e);
  123. tran.Rollback();
  124. throw;
  125. }
  126. }
  127. }
  128. /// <summary>
  129. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  130. /// </summary>
  131. public void Dispose()
  132. {
  133. Dispose(true);
  134. GC.SuppressFinalize(this);
  135. }
  136. /// <summary>
  137. /// Releases unmanaged and - optionally - managed resources.
  138. /// </summary>
  139. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  140. protected virtual void Dispose(bool dispose)
  141. {
  142. if (dispose)
  143. {
  144. try
  145. {
  146. if (connection != null)
  147. {
  148. if (EnableDelayedCommands)
  149. {
  150. FlushOnDispose();
  151. }
  152. if (connection.IsOpen())
  153. {
  154. connection.Close();
  155. }
  156. connection.Dispose();
  157. }
  158. if (FlushTimer != null)
  159. {
  160. FlushTimer.Dispose();
  161. FlushTimer = null;
  162. }
  163. }
  164. catch (Exception ex)
  165. {
  166. Logger.ErrorException("Error disposing database", ex);
  167. }
  168. }
  169. }
  170. /// <summary>
  171. /// Flushes the on dispose.
  172. /// </summary>
  173. private void FlushOnDispose()
  174. {
  175. // If we're not already flushing, do it now
  176. if (!IsFlushing)
  177. {
  178. Flush(null);
  179. }
  180. // Don't dispose in the middle of a flush
  181. while (IsFlushing)
  182. {
  183. Thread.Sleep(25);
  184. }
  185. }
  186. /// <summary>
  187. /// Queues the command.
  188. /// </summary>
  189. /// <param name="cmd">The CMD.</param>
  190. /// <exception cref="System.ArgumentNullException">cmd</exception>
  191. protected void QueueCommand(SQLiteCommand cmd)
  192. {
  193. if (cmd == null)
  194. {
  195. throw new ArgumentNullException("cmd");
  196. }
  197. delayedCommands.Enqueue(cmd);
  198. }
  199. /// <summary>
  200. /// The is flushing
  201. /// </summary>
  202. private bool IsFlushing;
  203. /// <summary>
  204. /// Flushes the specified sender.
  205. /// </summary>
  206. /// <param name="sender">The sender.</param>
  207. private void Flush(object sender)
  208. {
  209. // Cannot call Count on a ConcurrentQueue since it's an O(n) operation
  210. // Use IsEmpty instead
  211. if (delayedCommands.IsEmpty)
  212. {
  213. FlushTimer.Change(TimeSpan.FromMilliseconds(FlushInterval), TimeSpan.FromMilliseconds(-1));
  214. return;
  215. }
  216. if (IsFlushing)
  217. {
  218. return;
  219. }
  220. IsFlushing = true;
  221. var numCommands = 0;
  222. using (var tran = connection.BeginTransaction())
  223. {
  224. try
  225. {
  226. while (!delayedCommands.IsEmpty)
  227. {
  228. SQLiteCommand command;
  229. delayedCommands.TryDequeue(out command);
  230. command.Connection = connection;
  231. command.Transaction = tran;
  232. command.ExecuteNonQuery();
  233. numCommands++;
  234. }
  235. tran.Commit();
  236. }
  237. catch (Exception e)
  238. {
  239. Logger.ErrorException("Failed to commit transaction.", e);
  240. tran.Rollback();
  241. }
  242. }
  243. Logger.Debug("SQL Delayed writer executed " + numCommands + " commands");
  244. FlushTimer.Change(TimeSpan.FromMilliseconds(FlushInterval), TimeSpan.FromMilliseconds(-1));
  245. IsFlushing = false;
  246. }
  247. /// <summary>
  248. /// Executes the command.
  249. /// </summary>
  250. /// <param name="cmd">The CMD.</param>
  251. /// <returns>Task.</returns>
  252. /// <exception cref="System.ArgumentNullException">cmd</exception>
  253. public async Task ExecuteCommand(DbCommand cmd)
  254. {
  255. if (cmd == null)
  256. {
  257. throw new ArgumentNullException("cmd");
  258. }
  259. using (var tran = connection.BeginTransaction())
  260. {
  261. try
  262. {
  263. cmd.Connection = connection;
  264. cmd.Transaction = tran;
  265. await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);
  266. tran.Commit();
  267. }
  268. catch (Exception e)
  269. {
  270. Logger.ErrorException("Failed to commit transaction.", e);
  271. tran.Rollback();
  272. }
  273. }
  274. }
  275. /// <summary>
  276. /// Gets a stream from a DataReader at a given ordinal
  277. /// </summary>
  278. /// <param name="reader">The reader.</param>
  279. /// <param name="ordinal">The ordinal.</param>
  280. /// <returns>Stream.</returns>
  281. /// <exception cref="System.ArgumentNullException">reader</exception>
  282. protected static Stream GetStream(IDataReader reader, int ordinal)
  283. {
  284. if (reader == null)
  285. {
  286. throw new ArgumentNullException("reader");
  287. }
  288. var memoryStream = new MemoryStream();
  289. var num = 0L;
  290. var array = new byte[4096];
  291. long bytes;
  292. do
  293. {
  294. bytes = reader.GetBytes(ordinal, num, array, 0, array.Length);
  295. memoryStream.Write(array, 0, (int)bytes);
  296. num += bytes;
  297. }
  298. while (bytes > 0L);
  299. memoryStream.Position = 0;
  300. return memoryStream;
  301. }
  302. }
  303. }