SQLiteUserRepository.cs 6.6 KB

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