SQLiteUserDataRepository.cs 7.2 KB

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