SQLiteUserRepository.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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 SQLiteUserRepository
  16. /// </summary>
  17. public class SQLiteUserRepository : SqliteRepository, IUserRepository
  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 the json serializer.
  36. /// </summary>
  37. /// <value>The json serializer.</value>
  38. private readonly IJsonSerializer _jsonSerializer;
  39. /// <summary>
  40. /// The _app paths
  41. /// </summary>
  42. private readonly IApplicationPaths _appPaths;
  43. /// <summary>
  44. /// Gets a value indicating whether [enable delayed commands].
  45. /// </summary>
  46. /// <value><c>true</c> if [enable delayed commands]; otherwise, <c>false</c>.</value>
  47. protected override bool EnableDelayedCommands
  48. {
  49. get
  50. {
  51. return false;
  52. }
  53. }
  54. /// <summary>
  55. /// Initializes a new instance of the <see cref="SQLiteUserDataRepository" /> class.
  56. /// </summary>
  57. /// <param name="appPaths">The app paths.</param>
  58. /// <param name="jsonSerializer">The json serializer.</param>
  59. /// <param name="logManager">The log manager.</param>
  60. /// <exception cref="System.ArgumentNullException">appPaths</exception>
  61. public SQLiteUserRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
  62. : base(logManager)
  63. {
  64. if (appPaths == null)
  65. {
  66. throw new ArgumentNullException("appPaths");
  67. }
  68. if (jsonSerializer == null)
  69. {
  70. throw new ArgumentNullException("jsonSerializer");
  71. }
  72. _appPaths = appPaths;
  73. _jsonSerializer = jsonSerializer;
  74. }
  75. /// <summary>
  76. /// Opens the connection to the database
  77. /// </summary>
  78. /// <returns>Task.</returns>
  79. public async Task Initialize()
  80. {
  81. var dbFile = Path.Combine(_appPaths.DataPath, "users.db");
  82. await ConnectToDB(dbFile).ConfigureAwait(false);
  83. string[] queries = {
  84. "create table if not exists users (guid GUID primary key, data BLOB)",
  85. "create index if not exists idx_users on users(guid)",
  86. "create table if not exists schema_version (table_name primary key, version)",
  87. //pragmas
  88. "pragma temp_store = memory"
  89. };
  90. RunQueries(queries);
  91. }
  92. /// <summary>
  93. /// Save a user in the repo
  94. /// </summary>
  95. /// <param name="user">The user.</param>
  96. /// <param name="cancellationToken">The cancellation token.</param>
  97. /// <returns>Task.</returns>
  98. /// <exception cref="System.ArgumentNullException">user</exception>
  99. public async Task SaveUser(User user, CancellationToken cancellationToken)
  100. {
  101. if (user == null)
  102. {
  103. throw new ArgumentNullException("user");
  104. }
  105. if (cancellationToken == null)
  106. {
  107. throw new ArgumentNullException("cancellationToken");
  108. }
  109. cancellationToken.ThrowIfCancellationRequested();
  110. var serialized = _jsonSerializer.SerializeToBytes(user);
  111. cancellationToken.ThrowIfCancellationRequested();
  112. var cmd = connection.CreateCommand();
  113. cmd.CommandText = "replace into users (guid, data) values (@1, @2)";
  114. cmd.AddParam("@1", user.Id);
  115. cmd.AddParam("@2", serialized);
  116. using (var tran = connection.BeginTransaction())
  117. {
  118. try
  119. {
  120. cmd.Transaction = tran;
  121. await cmd.ExecuteNonQueryAsync(cancellationToken);
  122. tran.Commit();
  123. }
  124. catch (OperationCanceledException)
  125. {
  126. tran.Rollback();
  127. }
  128. catch (Exception e)
  129. {
  130. Logger.ErrorException("Failed to commit transaction.", e);
  131. tran.Rollback();
  132. }
  133. }
  134. }
  135. /// <summary>
  136. /// Retrieve all users from the database
  137. /// </summary>
  138. /// <returns>IEnumerable{User}.</returns>
  139. public IEnumerable<User> RetrieveAllUsers()
  140. {
  141. var cmd = connection.CreateCommand();
  142. cmd.CommandText = "select data from users";
  143. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  144. {
  145. while (reader.Read())
  146. {
  147. using (var stream = GetStream(reader, 0))
  148. {
  149. var user = _jsonSerializer.DeserializeFromStream<User>(stream);
  150. yield return user;
  151. }
  152. }
  153. }
  154. }
  155. /// <summary>
  156. /// Deletes the user.
  157. /// </summary>
  158. /// <param name="user">The user.</param>
  159. /// <param name="cancellationToken">The cancellation token.</param>
  160. /// <returns>Task.</returns>
  161. /// <exception cref="System.ArgumentNullException">user</exception>
  162. public Task DeleteUser(User user, CancellationToken cancellationToken)
  163. {
  164. if (user == null)
  165. {
  166. throw new ArgumentNullException("user");
  167. }
  168. if (cancellationToken == null)
  169. {
  170. throw new ArgumentNullException("cancellationToken");
  171. }
  172. return Task.Run(() =>
  173. {
  174. cancellationToken.ThrowIfCancellationRequested();
  175. var cmd = connection.CreateCommand();
  176. cmd.CommandText = "delete from users where guid=@guid";
  177. var guidParam = cmd.Parameters.Add("@guid", DbType.Guid);
  178. guidParam.Value = user.Id;
  179. return ExecuteCommand(cmd);
  180. });
  181. }
  182. }
  183. }