SQLiteUserRepository.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. using (var cmd = connection.CreateCommand())
  113. {
  114. cmd.CommandText = "replace into users (guid, data) values (@1, @2)";
  115. cmd.AddParam("@1", user.Id);
  116. cmd.AddParam("@2", serialized);
  117. using (var tran = connection.BeginTransaction())
  118. {
  119. try
  120. {
  121. cmd.Transaction = tran;
  122. await cmd.ExecuteNonQueryAsync(cancellationToken);
  123. tran.Commit();
  124. }
  125. catch (OperationCanceledException)
  126. {
  127. tran.Rollback();
  128. }
  129. catch (Exception e)
  130. {
  131. Logger.ErrorException("Failed to commit transaction.", e);
  132. tran.Rollback();
  133. }
  134. }
  135. }
  136. }
  137. /// <summary>
  138. /// Retrieve all users from the database
  139. /// </summary>
  140. /// <returns>IEnumerable{User}.</returns>
  141. public IEnumerable<User> RetrieveAllUsers()
  142. {
  143. using (var cmd = connection.CreateCommand())
  144. {
  145. cmd.CommandText = "select data from users";
  146. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  147. {
  148. while (reader.Read())
  149. {
  150. using (var stream = GetStream(reader, 0))
  151. {
  152. var user = _jsonSerializer.DeserializeFromStream<User>(stream);
  153. yield return user;
  154. }
  155. }
  156. }
  157. }
  158. }
  159. /// <summary>
  160. /// Deletes the user.
  161. /// </summary>
  162. /// <param name="user">The user.</param>
  163. /// <param name="cancellationToken">The cancellation token.</param>
  164. /// <returns>Task.</returns>
  165. /// <exception cref="System.ArgumentNullException">user</exception>
  166. public Task DeleteUser(User user, CancellationToken cancellationToken)
  167. {
  168. if (user == null)
  169. {
  170. throw new ArgumentNullException("user");
  171. }
  172. if (cancellationToken == null)
  173. {
  174. throw new ArgumentNullException("cancellationToken");
  175. }
  176. cancellationToken.ThrowIfCancellationRequested();
  177. using (var cmd = connection.CreateCommand())
  178. {
  179. cmd.CommandText = "delete from users where guid=@guid";
  180. var guidParam = cmd.Parameters.Add("@guid", DbType.Guid);
  181. guidParam.Value = user.Id;
  182. return ExecuteCommand(cmd);
  183. }
  184. }
  185. }
  186. }