SQLiteUserDataRepository.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Persistence;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Serialization;
  6. using System;
  7. using System.Data;
  8. using System.IO;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. namespace MediaBrowser.Server.Implementations.Sqlite
  12. {
  13. /// <summary>
  14. /// Class SQLiteUserDataRepository
  15. /// </summary>
  16. public class SQLiteUserDataRepository : SqliteRepository, IUserDataRepository
  17. {
  18. /// <summary>
  19. /// The repository name
  20. /// </summary>
  21. public const string RepositoryName = "SQLite";
  22. /// <summary>
  23. /// Gets the name of the repository
  24. /// </summary>
  25. /// <value>The name.</value>
  26. public string Name
  27. {
  28. get
  29. {
  30. return RepositoryName;
  31. }
  32. }
  33. /// <summary>
  34. /// Gets a value indicating whether [enable delayed commands].
  35. /// </summary>
  36. /// <value><c>true</c> if [enable delayed commands]; otherwise, <c>false</c>.</value>
  37. protected override bool EnableDelayedCommands
  38. {
  39. get
  40. {
  41. return false;
  42. }
  43. }
  44. /// <summary>
  45. /// The _protobuf serializer
  46. /// </summary>
  47. private readonly IJsonSerializer _jsonSerializer;
  48. /// <summary>
  49. /// The _app paths
  50. /// </summary>
  51. private readonly IApplicationPaths _appPaths;
  52. /// <summary>
  53. /// Initializes a new instance of the <see cref="SQLiteUserDataRepository" /> class.
  54. /// </summary>
  55. /// <param name="appPaths">The app paths.</param>
  56. /// <param name="jsonSerializer">The json serializer.</param>
  57. /// <param name="logManager">The log manager.</param>
  58. /// <exception cref="System.ArgumentNullException">protobufSerializer</exception>
  59. public SQLiteUserDataRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
  60. : base(logManager)
  61. {
  62. if (jsonSerializer == null)
  63. {
  64. throw new ArgumentNullException("jsonSerializer");
  65. }
  66. if (appPaths == null)
  67. {
  68. throw new ArgumentNullException("appPaths");
  69. }
  70. _jsonSerializer = jsonSerializer;
  71. _appPaths = appPaths;
  72. }
  73. /// <summary>
  74. /// Opens the connection to the database
  75. /// </summary>
  76. /// <returns>Task.</returns>
  77. public async Task Initialize()
  78. {
  79. var dbFile = Path.Combine(_appPaths.DataPath, "userdata.db");
  80. await ConnectToDB(dbFile).ConfigureAwait(false);
  81. string[] queries = {
  82. "create table if not exists userdata (id GUID, userId GUID, data BLOB)",
  83. "create unique index if not exists userdataindex on userdata (id, userId)",
  84. "create table if not exists schema_version (table_name primary key, version)",
  85. //pragmas
  86. "pragma temp_store = memory"
  87. };
  88. RunQueries(queries);
  89. }
  90. /// <summary>
  91. /// Saves the user data.
  92. /// </summary>
  93. /// <param name="userId">The user id.</param>
  94. /// <param name="userDataId">The user data id.</param>
  95. /// <param name="userData">The user data.</param>
  96. /// <param name="cancellationToken">The cancellation token.</param>
  97. /// <returns>Task.</returns>
  98. /// <exception cref="System.ArgumentNullException">
  99. /// userData
  100. /// or
  101. /// cancellationToken
  102. /// or
  103. /// userId
  104. /// or
  105. /// userDataId
  106. /// </exception>
  107. public async Task SaveUserData(Guid userId, Guid userDataId, UserItemData userData, CancellationToken cancellationToken)
  108. {
  109. if (userData == null)
  110. {
  111. throw new ArgumentNullException("userData");
  112. }
  113. if (cancellationToken == null)
  114. {
  115. throw new ArgumentNullException("cancellationToken");
  116. }
  117. if (userId == Guid.Empty)
  118. {
  119. throw new ArgumentNullException("userId");
  120. }
  121. if (userDataId == Guid.Empty)
  122. {
  123. throw new ArgumentNullException("userDataId");
  124. }
  125. cancellationToken.ThrowIfCancellationRequested();
  126. var serialized = _jsonSerializer.SerializeToBytes(userData);
  127. cancellationToken.ThrowIfCancellationRequested();
  128. var cmd = connection.CreateCommand();
  129. cmd.CommandText = "replace into userdata (id, userId, data) values (@1, @2, @3)";
  130. cmd.AddParam("@1", userDataId);
  131. cmd.AddParam("@2", userId);
  132. cmd.AddParam("@3", serialized);
  133. using (var tran = connection.BeginTransaction())
  134. {
  135. try
  136. {
  137. cmd.Transaction = tran;
  138. await cmd.ExecuteNonQueryAsync(cancellationToken);
  139. tran.Commit();
  140. }
  141. catch (OperationCanceledException)
  142. {
  143. tran.Rollback();
  144. }
  145. catch (Exception e)
  146. {
  147. Logger.ErrorException("Failed to commit transaction.", e);
  148. tran.Rollback();
  149. }
  150. }
  151. }
  152. /// <summary>
  153. /// Gets the user data.
  154. /// </summary>
  155. /// <param name="userId">The user id.</param>
  156. /// <param name="userDataId">The user data id.</param>
  157. /// <returns>Task{UserItemData}.</returns>
  158. /// <exception cref="System.ArgumentNullException">
  159. /// userId
  160. /// or
  161. /// userDataId
  162. /// </exception>
  163. public async Task<UserItemData> GetUserData(Guid userId, Guid userDataId)
  164. {
  165. if (userId == Guid.Empty)
  166. {
  167. throw new ArgumentNullException("userId");
  168. }
  169. if (userDataId == Guid.Empty)
  170. {
  171. throw new ArgumentNullException("userDataId");
  172. }
  173. var cmd = connection.CreateCommand();
  174. cmd.CommandText = "select data from userdata where id = @id and userId=@userId";
  175. var idParam = cmd.Parameters.Add("@id", DbType.Guid);
  176. idParam.Value = userDataId;
  177. var userIdParam = cmd.Parameters.Add("@userId", DbType.Guid);
  178. userIdParam.Value = userId;
  179. using (var reader = await cmd.ExecuteReaderAsync(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow).ConfigureAwait(false))
  180. {
  181. if (reader.Read())
  182. {
  183. using (var stream = GetStream(reader, 0))
  184. {
  185. return _jsonSerializer.DeserializeFromStream<UserItemData>(stream);
  186. }
  187. }
  188. }
  189. return null;
  190. }
  191. }
  192. }