SqliteUserRepository.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. using MediaBrowser.Controller;
  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.Persistence
  13. {
  14. /// <summary>
  15. /// Class SQLiteUserRepository
  16. /// </summary>
  17. public class SqliteUserRepository : BaseSqliteRepository, IUserRepository
  18. {
  19. private readonly IJsonSerializer _jsonSerializer;
  20. public SqliteUserRepository(ILogManager logManager, IServerApplicationPaths appPaths, IJsonSerializer jsonSerializer, IDbConnector dbConnector) : base(logManager, dbConnector)
  21. {
  22. _jsonSerializer = jsonSerializer;
  23. DbFilePath = Path.Combine(appPaths.DataPath, "users.db");
  24. }
  25. /// <summary>
  26. /// Gets the name of the repository
  27. /// </summary>
  28. /// <value>The name.</value>
  29. public string Name
  30. {
  31. get
  32. {
  33. return "SQLite";
  34. }
  35. }
  36. /// <summary>
  37. /// Opens the connection to the database
  38. /// </summary>
  39. /// <returns>Task.</returns>
  40. public async Task Initialize()
  41. {
  42. using (var connection = await CreateConnection().ConfigureAwait(false))
  43. {
  44. string[] queries = {
  45. "create table if not exists users (guid GUID primary key, data BLOB)",
  46. "create index if not exists idx_users on users(guid)",
  47. "create table if not exists schema_version (table_name primary key, version)",
  48. //pragmas
  49. "pragma temp_store = memory",
  50. "pragma shrink_memory"
  51. };
  52. connection.RunQueries(queries, Logger);
  53. }
  54. }
  55. /// <summary>
  56. /// Save a user in the repo
  57. /// </summary>
  58. /// <param name="user">The user.</param>
  59. /// <param name="cancellationToken">The cancellation token.</param>
  60. /// <returns>Task.</returns>
  61. /// <exception cref="System.ArgumentNullException">user</exception>
  62. public async Task SaveUser(User user, CancellationToken cancellationToken)
  63. {
  64. if (user == null)
  65. {
  66. throw new ArgumentNullException("user");
  67. }
  68. cancellationToken.ThrowIfCancellationRequested();
  69. var serialized = _jsonSerializer.SerializeToBytes(user);
  70. cancellationToken.ThrowIfCancellationRequested();
  71. using (var connection = await CreateConnection().ConfigureAwait(false))
  72. {
  73. IDbTransaction transaction = null;
  74. try
  75. {
  76. transaction = connection.BeginTransaction();
  77. using (var cmd = connection.CreateCommand())
  78. {
  79. cmd.CommandText = "replace into users (guid, data) values (@1, @2)";
  80. cmd.Parameters.Add(cmd, "@1", DbType.Guid).Value = user.Id;
  81. cmd.Parameters.Add(cmd, "@2", DbType.Binary).Value = serialized;
  82. cmd.Transaction = transaction;
  83. cmd.ExecuteNonQuery();
  84. }
  85. transaction.Commit();
  86. }
  87. catch (OperationCanceledException)
  88. {
  89. if (transaction != null)
  90. {
  91. transaction.Rollback();
  92. }
  93. throw;
  94. }
  95. catch (Exception e)
  96. {
  97. Logger.ErrorException("Failed to save user:", e);
  98. if (transaction != null)
  99. {
  100. transaction.Rollback();
  101. }
  102. throw;
  103. }
  104. finally
  105. {
  106. if (transaction != null)
  107. {
  108. transaction.Dispose();
  109. }
  110. }
  111. }
  112. }
  113. /// <summary>
  114. /// Retrieve all users from the database
  115. /// </summary>
  116. /// <returns>IEnumerable{User}.</returns>
  117. public IEnumerable<User> RetrieveAllUsers()
  118. {
  119. var list = new List<User>();
  120. using (var connection = CreateConnection(true).Result)
  121. {
  122. using (var cmd = connection.CreateCommand())
  123. {
  124. cmd.CommandText = "select guid,data from users";
  125. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  126. {
  127. while (reader.Read())
  128. {
  129. var id = reader.GetGuid(0);
  130. using (var stream = reader.GetMemoryStream(1))
  131. {
  132. var user = _jsonSerializer.DeserializeFromStream<User>(stream);
  133. user.Id = id;
  134. list.Add(user);
  135. }
  136. }
  137. }
  138. }
  139. }
  140. return list;
  141. }
  142. /// <summary>
  143. /// Deletes the user.
  144. /// </summary>
  145. /// <param name="user">The user.</param>
  146. /// <param name="cancellationToken">The cancellation token.</param>
  147. /// <returns>Task.</returns>
  148. /// <exception cref="System.ArgumentNullException">user</exception>
  149. public async Task DeleteUser(User user, CancellationToken cancellationToken)
  150. {
  151. if (user == null)
  152. {
  153. throw new ArgumentNullException("user");
  154. }
  155. cancellationToken.ThrowIfCancellationRequested();
  156. using (var connection = await CreateConnection().ConfigureAwait(false))
  157. {
  158. IDbTransaction transaction = null;
  159. try
  160. {
  161. transaction = connection.BeginTransaction();
  162. using (var cmd = connection.CreateCommand())
  163. {
  164. cmd.CommandText = "delete from users where guid=@guid";
  165. cmd.Parameters.Add(cmd, "@guid", DbType.Guid).Value = user.Id;
  166. cmd.Transaction = transaction;
  167. cmd.ExecuteNonQuery();
  168. }
  169. transaction.Commit();
  170. }
  171. catch (OperationCanceledException)
  172. {
  173. if (transaction != null)
  174. {
  175. transaction.Rollback();
  176. }
  177. throw;
  178. }
  179. catch (Exception e)
  180. {
  181. Logger.ErrorException("Failed to delete user:", e);
  182. if (transaction != null)
  183. {
  184. transaction.Rollback();
  185. }
  186. throw;
  187. }
  188. finally
  189. {
  190. if (transaction != null)
  191. {
  192. transaction.Dispose();
  193. }
  194. }
  195. }
  196. }
  197. }
  198. }