2
0

SqliteUserRepository.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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 guid,data from users";
  122. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  123. {
  124. while (reader.Read())
  125. {
  126. var id = reader.GetGuid(0);
  127. using (var stream = reader.GetMemoryStream(1))
  128. {
  129. var user = _jsonSerializer.DeserializeFromStream<User>(stream);
  130. user.Id = id;
  131. yield return user;
  132. }
  133. }
  134. }
  135. }
  136. }
  137. /// <summary>
  138. /// Deletes the user.
  139. /// </summary>
  140. /// <param name="user">The user.</param>
  141. /// <param name="cancellationToken">The cancellation token.</param>
  142. /// <returns>Task.</returns>
  143. /// <exception cref="System.ArgumentNullException">user</exception>
  144. public async Task DeleteUser(User user, CancellationToken cancellationToken)
  145. {
  146. if (user == null)
  147. {
  148. throw new ArgumentNullException("user");
  149. }
  150. cancellationToken.ThrowIfCancellationRequested();
  151. await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  152. IDbTransaction transaction = null;
  153. try
  154. {
  155. transaction = _connection.BeginTransaction();
  156. using (var cmd = _connection.CreateCommand())
  157. {
  158. cmd.CommandText = "delete from users where guid=@guid";
  159. cmd.Parameters.Add(cmd, "@guid", DbType.Guid).Value = user.Id;
  160. cmd.Transaction = transaction;
  161. cmd.ExecuteNonQuery();
  162. }
  163. transaction.Commit();
  164. }
  165. catch (OperationCanceledException)
  166. {
  167. if (transaction != null)
  168. {
  169. transaction.Rollback();
  170. }
  171. throw;
  172. }
  173. catch (Exception e)
  174. {
  175. Logger.ErrorException("Failed to delete user:", e);
  176. if (transaction != null)
  177. {
  178. transaction.Rollback();
  179. }
  180. throw;
  181. }
  182. finally
  183. {
  184. if (transaction != null)
  185. {
  186. transaction.Dispose();
  187. }
  188. WriteLock.Release();
  189. }
  190. }
  191. protected override void CloseConnection()
  192. {
  193. if (_connection != null)
  194. {
  195. if (_connection.IsOpen())
  196. {
  197. _connection.Close();
  198. }
  199. _connection.Dispose();
  200. _connection = null;
  201. }
  202. }
  203. }
  204. }