SqliteUserRepository.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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 IDbConnection _connection;
  20. private readonly IServerApplicationPaths _appPaths;
  21. private readonly IJsonSerializer _jsonSerializer;
  22. public SqliteUserRepository(ILogManager logManager, IServerApplicationPaths appPaths, IJsonSerializer jsonSerializer) : base(logManager)
  23. {
  24. _appPaths = appPaths;
  25. _jsonSerializer = jsonSerializer;
  26. }
  27. /// <summary>
  28. /// Gets the name of the repository
  29. /// </summary>
  30. /// <value>The name.</value>
  31. public string Name
  32. {
  33. get
  34. {
  35. return "SQLite";
  36. }
  37. }
  38. /// <summary>
  39. /// Opens the connection to the database
  40. /// </summary>
  41. /// <returns>Task.</returns>
  42. public async Task Initialize()
  43. {
  44. var dbFile = Path.Combine(_appPaths.DataPath, "users.db");
  45. _connection = await SqliteExtensions.ConnectToDb(dbFile, Logger).ConfigureAwait(false);
  46. string[] queries = {
  47. "create table if not exists users (guid GUID primary key, data BLOB)",
  48. "create index if not exists idx_users on users(guid)",
  49. "create table if not exists schema_version (table_name primary key, version)",
  50. //pragmas
  51. "pragma temp_store = memory",
  52. "pragma shrink_memory"
  53. };
  54. _connection.RunQueries(queries, Logger);
  55. }
  56. /// <summary>
  57. /// Save a user in the repo
  58. /// </summary>
  59. /// <param name="user">The user.</param>
  60. /// <param name="cancellationToken">The cancellation token.</param>
  61. /// <returns>Task.</returns>
  62. /// <exception cref="System.ArgumentNullException">user</exception>
  63. public async Task SaveUser(User user, CancellationToken cancellationToken)
  64. {
  65. if (user == null)
  66. {
  67. throw new ArgumentNullException("user");
  68. }
  69. cancellationToken.ThrowIfCancellationRequested();
  70. var serialized = _jsonSerializer.SerializeToBytes(user);
  71. cancellationToken.ThrowIfCancellationRequested();
  72. await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  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. WriteLock.Release();
  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. using (var cmd = _connection.CreateCommand())
  120. {
  121. cmd.CommandText = "select data from users";
  122. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  123. {
  124. while (reader.Read())
  125. {
  126. using (var stream = reader.GetMemoryStream(0))
  127. {
  128. var user = _jsonSerializer.DeserializeFromStream<User>(stream);
  129. yield return user;
  130. }
  131. }
  132. }
  133. }
  134. }
  135. /// <summary>
  136. /// Deletes the user.
  137. /// </summary>
  138. /// <param name="user">The user.</param>
  139. /// <param name="cancellationToken">The cancellation token.</param>
  140. /// <returns>Task.</returns>
  141. /// <exception cref="System.ArgumentNullException">user</exception>
  142. public async Task DeleteUser(User user, CancellationToken cancellationToken)
  143. {
  144. if (user == null)
  145. {
  146. throw new ArgumentNullException("user");
  147. }
  148. cancellationToken.ThrowIfCancellationRequested();
  149. await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  150. IDbTransaction transaction = null;
  151. try
  152. {
  153. transaction = _connection.BeginTransaction();
  154. using (var cmd = _connection.CreateCommand())
  155. {
  156. cmd.CommandText = "delete from users where guid=@guid";
  157. cmd.Parameters.Add(cmd, "@guid", DbType.Guid).Value = user.Id;
  158. cmd.Transaction = transaction;
  159. cmd.ExecuteNonQuery();
  160. }
  161. transaction.Commit();
  162. }
  163. catch (OperationCanceledException)
  164. {
  165. if (transaction != null)
  166. {
  167. transaction.Rollback();
  168. }
  169. throw;
  170. }
  171. catch (Exception e)
  172. {
  173. Logger.ErrorException("Failed to delete user:", e);
  174. if (transaction != null)
  175. {
  176. transaction.Rollback();
  177. }
  178. throw;
  179. }
  180. finally
  181. {
  182. if (transaction != null)
  183. {
  184. transaction.Dispose();
  185. }
  186. WriteLock.Release();
  187. }
  188. }
  189. protected override void CloseConnection()
  190. {
  191. if (_connection != null)
  192. {
  193. if (_connection.IsOpen())
  194. {
  195. _connection.Close();
  196. }
  197. _connection.Dispose();
  198. _connection = null;
  199. }
  200. }
  201. }
  202. }