SqliteDisplayPreferencesRepository.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Controller.Persistence;
  3. using MediaBrowser.Model.Entities;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Serialization;
  6. using System;
  7. using System.Data;
  8. using System.Data.SQLite;
  9. using System.IO;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. namespace MediaBrowser.Server.Implementations.Persistence
  13. {
  14. /// <summary>
  15. /// Class SQLiteDisplayPreferencesRepository
  16. /// </summary>
  17. public class SqliteDisplayPreferencesRepository : IDisplayPreferencesRepository
  18. {
  19. private SQLiteConnection _connection;
  20. private readonly ILogger _logger;
  21. /// <summary>
  22. /// Gets the name of the repository
  23. /// </summary>
  24. /// <value>The name.</value>
  25. public string Name
  26. {
  27. get
  28. {
  29. return "SQLite";
  30. }
  31. }
  32. /// <summary>
  33. /// The _json serializer
  34. /// </summary>
  35. private readonly IJsonSerializer _jsonSerializer;
  36. /// <summary>
  37. /// The _app paths
  38. /// </summary>
  39. private readonly IApplicationPaths _appPaths;
  40. private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
  41. /// <summary>
  42. /// Initializes a new instance of the <see cref="SqliteDisplayPreferencesRepository" /> class.
  43. /// </summary>
  44. /// <param name="appPaths">The app paths.</param>
  45. /// <param name="jsonSerializer">The json serializer.</param>
  46. /// <param name="logManager">The log manager.</param>
  47. /// <exception cref="System.ArgumentNullException">
  48. /// jsonSerializer
  49. /// or
  50. /// appPaths
  51. /// </exception>
  52. public SqliteDisplayPreferencesRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
  53. {
  54. if (jsonSerializer == null)
  55. {
  56. throw new ArgumentNullException("jsonSerializer");
  57. }
  58. if (appPaths == null)
  59. {
  60. throw new ArgumentNullException("appPaths");
  61. }
  62. _jsonSerializer = jsonSerializer;
  63. _appPaths = appPaths;
  64. _logger = logManager.GetLogger(GetType().Name);
  65. }
  66. /// <summary>
  67. /// Opens the connection to the database
  68. /// </summary>
  69. /// <returns>Task.</returns>
  70. public async Task Initialize()
  71. {
  72. var dbFile = Path.Combine(_appPaths.DataPath, "displaypreferences.db");
  73. _connection = await SqliteExtensions.ConnectToDb(dbFile).ConfigureAwait(false);
  74. string[] queries = {
  75. "create table if not exists displaypreferences (id GUID, data BLOB)",
  76. "create unique index if not exists displaypreferencesindex on displaypreferences (id)",
  77. "create table if not exists schema_version (table_name primary key, version)",
  78. //pragmas
  79. "pragma temp_store = memory"
  80. };
  81. _connection.RunQueries(queries, _logger);
  82. }
  83. /// <summary>
  84. /// Save the display preferences associated with an item in the repo
  85. /// </summary>
  86. /// <param name="displayPreferences">The display preferences.</param>
  87. /// <param name="cancellationToken">The cancellation token.</param>
  88. /// <returns>Task.</returns>
  89. /// <exception cref="System.ArgumentNullException">item</exception>
  90. public async Task SaveDisplayPreferences(DisplayPreferences displayPreferences, CancellationToken cancellationToken)
  91. {
  92. if (displayPreferences == null)
  93. {
  94. throw new ArgumentNullException("displayPreferences");
  95. }
  96. if (displayPreferences.Id == Guid.Empty)
  97. {
  98. throw new ArgumentNullException("displayPreferences.Id");
  99. }
  100. if (cancellationToken == null)
  101. {
  102. throw new ArgumentNullException("cancellationToken");
  103. }
  104. cancellationToken.ThrowIfCancellationRequested();
  105. var serialized = _jsonSerializer.SerializeToBytes(displayPreferences);
  106. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  107. SQLiteTransaction transaction = null;
  108. try
  109. {
  110. transaction = _connection.BeginTransaction();
  111. using (var cmd = _connection.CreateCommand())
  112. {
  113. cmd.CommandText = "replace into displaypreferences (id, data) values (@1, @2)";
  114. cmd.AddParam("@1", displayPreferences.Id);
  115. cmd.AddParam("@2", serialized);
  116. cmd.Transaction = transaction;
  117. await cmd.ExecuteNonQueryAsync(cancellationToken);
  118. }
  119. transaction.Commit();
  120. }
  121. catch (OperationCanceledException)
  122. {
  123. if (transaction != null)
  124. {
  125. transaction.Rollback();
  126. }
  127. throw;
  128. }
  129. catch (Exception e)
  130. {
  131. _logger.ErrorException("Failed to save display preferences:", e);
  132. if (transaction != null)
  133. {
  134. transaction.Rollback();
  135. }
  136. throw;
  137. }
  138. finally
  139. {
  140. if (transaction != null)
  141. {
  142. transaction.Dispose();
  143. }
  144. _writeLock.Release();
  145. }
  146. }
  147. /// <summary>
  148. /// Gets the display preferences.
  149. /// </summary>
  150. /// <param name="displayPreferencesId">The display preferences id.</param>
  151. /// <returns>Task{DisplayPreferences}.</returns>
  152. /// <exception cref="System.ArgumentNullException">item</exception>
  153. public DisplayPreferences GetDisplayPreferences(Guid displayPreferencesId)
  154. {
  155. if (displayPreferencesId == Guid.Empty)
  156. {
  157. throw new ArgumentNullException("displayPreferencesId");
  158. }
  159. var cmd = _connection.CreateCommand();
  160. cmd.CommandText = "select data from displaypreferences where id = @id";
  161. var idParam = cmd.Parameters.Add("@id", DbType.Guid);
  162. idParam.Value = displayPreferencesId;
  163. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  164. {
  165. if (reader.Read())
  166. {
  167. using (var stream = reader.GetMemoryStream(0))
  168. {
  169. return _jsonSerializer.DeserializeFromStream<DisplayPreferences>(stream);
  170. }
  171. }
  172. }
  173. return new DisplayPreferences { Id = displayPreferencesId };
  174. }
  175. /// <summary>
  176. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  177. /// </summary>
  178. public void Dispose()
  179. {
  180. Dispose(true);
  181. GC.SuppressFinalize(this);
  182. }
  183. private readonly object _disposeLock = new object();
  184. /// <summary>
  185. /// Releases unmanaged and - optionally - managed resources.
  186. /// </summary>
  187. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  188. protected virtual void Dispose(bool dispose)
  189. {
  190. if (dispose)
  191. {
  192. try
  193. {
  194. lock (_disposeLock)
  195. {
  196. if (_connection != null)
  197. {
  198. if (_connection.IsOpen())
  199. {
  200. _connection.Close();
  201. }
  202. _connection.Dispose();
  203. _connection = null;
  204. }
  205. }
  206. }
  207. catch (Exception ex)
  208. {
  209. _logger.ErrorException("Error disposing database", ex);
  210. }
  211. }
  212. }
  213. }
  214. }