SQLiteRepository.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. /// Gets the logger.
  27. /// </summary>
  28. /// <value>The logger.</value>
  29. protected ILogger Logger { get; private set; }
  30. /// <summary>
  31. /// Initializes a new instance of the <see cref="SqliteRepository" /> class.
  32. /// </summary>
  33. /// <param name="logManager">The log manager.</param>
  34. /// <exception cref="System.ArgumentNullException">logger</exception>
  35. protected SqliteRepository(ILogManager logManager)
  36. {
  37. if (logManager == null)
  38. {
  39. throw new ArgumentNullException("logManager");
  40. }
  41. Logger = logManager.GetLogger(GetType().Name);
  42. }
  43. /// <summary>
  44. /// Connects to DB.
  45. /// </summary>
  46. /// <param name="dbPath">The db path.</param>
  47. /// <returns>Task{System.Boolean}.</returns>
  48. /// <exception cref="System.ArgumentNullException">dbPath</exception>
  49. protected async Task ConnectToDb(string dbPath)
  50. {
  51. if (string.IsNullOrEmpty(dbPath))
  52. {
  53. throw new ArgumentNullException("dbPath");
  54. }
  55. DbFileName = dbPath;
  56. var connectionstr = new SQLiteConnectionStringBuilder
  57. {
  58. PageSize = 4096,
  59. CacheSize = 40960,
  60. SyncMode = SynchronizationModes.Off,
  61. DataSource = dbPath,
  62. JournalMode = SQLiteJournalModeEnum.Memory
  63. };
  64. Connection = new SQLiteConnection(connectionstr.ConnectionString);
  65. await Connection.OpenAsync().ConfigureAwait(false);
  66. }
  67. /// <summary>
  68. /// Runs the queries.
  69. /// </summary>
  70. /// <param name="queries">The queries.</param>
  71. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  72. /// <exception cref="System.ArgumentNullException">queries</exception>
  73. protected void RunQueries(string[] queries)
  74. {
  75. if (queries == null)
  76. {
  77. throw new ArgumentNullException("queries");
  78. }
  79. using (var tran = Connection.BeginTransaction())
  80. {
  81. try
  82. {
  83. using (var cmd = Connection.CreateCommand())
  84. {
  85. foreach (var query in queries)
  86. {
  87. cmd.Transaction = tran;
  88. cmd.CommandText = query;
  89. cmd.ExecuteNonQuery();
  90. }
  91. }
  92. tran.Commit();
  93. }
  94. catch (Exception e)
  95. {
  96. Logger.ErrorException("Error running queries", e);
  97. tran.Rollback();
  98. throw;
  99. }
  100. }
  101. }
  102. /// <summary>
  103. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  104. /// </summary>
  105. public void Dispose()
  106. {
  107. Dispose(true);
  108. GC.SuppressFinalize(this);
  109. }
  110. private readonly object _disposeLock = new object();
  111. /// <summary>
  112. /// Releases unmanaged and - optionally - managed resources.
  113. /// </summary>
  114. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  115. protected virtual void Dispose(bool dispose)
  116. {
  117. if (dispose)
  118. {
  119. try
  120. {
  121. lock (_disposeLock)
  122. {
  123. if (Connection != null)
  124. {
  125. if (Connection.IsOpen())
  126. {
  127. Connection.Close();
  128. }
  129. Connection.Dispose();
  130. Connection = null;
  131. }
  132. }
  133. }
  134. catch (Exception ex)
  135. {
  136. Logger.ErrorException("Error disposing database", ex);
  137. }
  138. }
  139. }
  140. /// <summary>
  141. /// Executes the command.
  142. /// </summary>
  143. /// <param name="cmd">The CMD.</param>
  144. /// <returns>Task.</returns>
  145. /// <exception cref="System.ArgumentNullException">cmd</exception>
  146. public async Task ExecuteCommand(DbCommand cmd)
  147. {
  148. if (cmd == null)
  149. {
  150. throw new ArgumentNullException("cmd");
  151. }
  152. using (var tran = Connection.BeginTransaction())
  153. {
  154. try
  155. {
  156. cmd.Connection = Connection;
  157. cmd.Transaction = tran;
  158. await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);
  159. tran.Commit();
  160. }
  161. catch (Exception e)
  162. {
  163. Logger.ErrorException("Failed to commit transaction.", e);
  164. tran.Rollback();
  165. }
  166. }
  167. }
  168. /// <summary>
  169. /// Gets a stream from a DataReader at a given ordinal
  170. /// </summary>
  171. /// <param name="reader">The reader.</param>
  172. /// <param name="ordinal">The ordinal.</param>
  173. /// <returns>Stream.</returns>
  174. /// <exception cref="System.ArgumentNullException">reader</exception>
  175. protected static Stream GetStream(IDataReader reader, int ordinal)
  176. {
  177. if (reader == null)
  178. {
  179. throw new ArgumentNullException("reader");
  180. }
  181. var memoryStream = new MemoryStream();
  182. var num = 0L;
  183. var array = new byte[4096];
  184. long bytes;
  185. do
  186. {
  187. bytes = reader.GetBytes(ordinal, num, array, 0, array.Length);
  188. memoryStream.Write(array, 0, (int)bytes);
  189. num += bytes;
  190. }
  191. while (bytes > 0L);
  192. memoryStream.Position = 0;
  193. return memoryStream;
  194. }
  195. }
  196. }