SQLiteRepository.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. using MediaBrowser.Model.Logging;
  2. using System;
  3. using System.Data;
  4. using System.Data.Common;
  5. using System.Data.SQLite;
  6. using System.IO;
  7. using System.Threading.Tasks;
  8. namespace MediaBrowser.Server.Implementations.Sqlite
  9. {
  10. /// <summary>
  11. /// Class SqliteRepository
  12. /// </summary>
  13. public abstract class SqliteRepository : IDisposable
  14. {
  15. /// <summary>
  16. /// The db file name
  17. /// </summary>
  18. protected string DbFileName;
  19. /// <summary>
  20. /// The connection
  21. /// </summary>
  22. protected SQLiteConnection Connection;
  23. /// <summary>
  24. /// Gets the logger.
  25. /// </summary>
  26. /// <value>The logger.</value>
  27. protected ILogger Logger { get; private set; }
  28. /// <summary>
  29. /// Initializes a new instance of the <see cref="SqliteRepository" /> class.
  30. /// </summary>
  31. /// <param name="logManager">The log manager.</param>
  32. /// <exception cref="System.ArgumentNullException">logger</exception>
  33. protected SqliteRepository(ILogManager logManager)
  34. {
  35. if (logManager == null)
  36. {
  37. throw new ArgumentNullException("logManager");
  38. }
  39. Logger = logManager.GetLogger(GetType().Name);
  40. }
  41. /// <summary>
  42. /// Connects to DB.
  43. /// </summary>
  44. /// <param name="dbPath">The db path.</param>
  45. /// <returns>Task{System.Boolean}.</returns>
  46. /// <exception cref="System.ArgumentNullException">dbPath</exception>
  47. protected async Task ConnectToDb(string dbPath)
  48. {
  49. if (string.IsNullOrEmpty(dbPath))
  50. {
  51. throw new ArgumentNullException("dbPath");
  52. }
  53. DbFileName = dbPath;
  54. var connectionstr = new SQLiteConnectionStringBuilder
  55. {
  56. PageSize = 4096,
  57. CacheSize = 40960,
  58. SyncMode = SynchronizationModes.Off,
  59. DataSource = dbPath,
  60. JournalMode = SQLiteJournalModeEnum.Memory
  61. };
  62. Connection = new SQLiteConnection(connectionstr.ConnectionString);
  63. await Connection.OpenAsync().ConfigureAwait(false);
  64. }
  65. /// <summary>
  66. /// Runs the queries.
  67. /// </summary>
  68. /// <param name="queries">The queries.</param>
  69. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  70. /// <exception cref="System.ArgumentNullException">queries</exception>
  71. protected void RunQueries(string[] queries)
  72. {
  73. if (queries == null)
  74. {
  75. throw new ArgumentNullException("queries");
  76. }
  77. using (var tran = Connection.BeginTransaction())
  78. {
  79. try
  80. {
  81. using (var cmd = Connection.CreateCommand())
  82. {
  83. foreach (var query in queries)
  84. {
  85. cmd.Transaction = tran;
  86. cmd.CommandText = query;
  87. cmd.ExecuteNonQuery();
  88. }
  89. }
  90. tran.Commit();
  91. }
  92. catch (Exception e)
  93. {
  94. Logger.ErrorException("Error running queries", e);
  95. tran.Rollback();
  96. throw;
  97. }
  98. }
  99. }
  100. /// <summary>
  101. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  102. /// </summary>
  103. public void Dispose()
  104. {
  105. Dispose(true);
  106. GC.SuppressFinalize(this);
  107. }
  108. private readonly object _disposeLock = new object();
  109. /// <summary>
  110. /// Releases unmanaged and - optionally - managed resources.
  111. /// </summary>
  112. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  113. protected virtual void Dispose(bool dispose)
  114. {
  115. if (dispose)
  116. {
  117. try
  118. {
  119. lock (_disposeLock)
  120. {
  121. if (Connection != null)
  122. {
  123. if (Connection.IsOpen())
  124. {
  125. Connection.Close();
  126. }
  127. Connection.Dispose();
  128. Connection = null;
  129. }
  130. }
  131. }
  132. catch (Exception ex)
  133. {
  134. Logger.ErrorException("Error disposing database", ex);
  135. }
  136. }
  137. }
  138. /// <summary>
  139. /// Gets a stream from a DataReader at a given ordinal
  140. /// </summary>
  141. /// <param name="reader">The reader.</param>
  142. /// <param name="ordinal">The ordinal.</param>
  143. /// <returns>Stream.</returns>
  144. /// <exception cref="System.ArgumentNullException">reader</exception>
  145. protected static Stream GetStream(IDataReader reader, int ordinal)
  146. {
  147. if (reader == null)
  148. {
  149. throw new ArgumentNullException("reader");
  150. }
  151. var memoryStream = new MemoryStream();
  152. var num = 0L;
  153. var array = new byte[4096];
  154. long bytes;
  155. do
  156. {
  157. bytes = reader.GetBytes(ordinal, num, array, 0, array.Length);
  158. memoryStream.Write(array, 0, (int)bytes);
  159. num += bytes;
  160. }
  161. while (bytes > 0L);
  162. memoryStream.Position = 0;
  163. return memoryStream;
  164. }
  165. }
  166. }