SQLiteUserRepository.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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.Data.SQLite;
  10. using System.IO;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. namespace MediaBrowser.Server.Implementations.Sqlite
  14. {
  15. /// <summary>
  16. /// Class SQLiteUserRepository
  17. /// </summary>
  18. public class SQLiteUserRepository : SqliteRepository, IUserRepository
  19. {
  20. /// <summary>
  21. /// The repository name
  22. /// </summary>
  23. public const string RepositoryName = "SQLite";
  24. private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
  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 RepositoryName;
  34. }
  35. }
  36. /// <summary>
  37. /// Gets the json serializer.
  38. /// </summary>
  39. /// <value>The json serializer.</value>
  40. private readonly IJsonSerializer _jsonSerializer;
  41. /// <summary>
  42. /// The _app paths
  43. /// </summary>
  44. private readonly IApplicationPaths _appPaths;
  45. /// <summary>
  46. /// Initializes a new instance of the <see cref="SQLiteUserDataRepository" /> class.
  47. /// </summary>
  48. /// <param name="appPaths">The app paths.</param>
  49. /// <param name="jsonSerializer">The json serializer.</param>
  50. /// <param name="logManager">The log manager.</param>
  51. /// <exception cref="System.ArgumentNullException">appPaths</exception>
  52. public SQLiteUserRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
  53. : base(logManager)
  54. {
  55. if (appPaths == null)
  56. {
  57. throw new ArgumentNullException("appPaths");
  58. }
  59. if (jsonSerializer == null)
  60. {
  61. throw new ArgumentNullException("jsonSerializer");
  62. }
  63. _appPaths = appPaths;
  64. _jsonSerializer = jsonSerializer;
  65. }
  66. /// <summary>
  67. /// Opens the connection to the database
  68. /// </summary>
  69. /// <returns>Task.</returns>
  70. public async Task Initialize()
  71. {
  72. var dbFile = Path.Combine(_appPaths.DataPath, "users.db");
  73. await ConnectToDb(dbFile).ConfigureAwait(false);
  74. string[] queries = {
  75. "create table if not exists users (guid GUID primary key, data BLOB)",
  76. "create index if not exists idx_users on users(guid)",
  77. "create table if not exists schema_version (table_name primary key, version)",
  78. //pragmas
  79. "pragma temp_store = memory"
  80. };
  81. RunQueries(queries);
  82. }
  83. /// <summary>
  84. /// Save a user in the repo
  85. /// </summary>
  86. /// <param name="user">The user.</param>
  87. /// <param name="cancellationToken">The cancellation token.</param>
  88. /// <returns>Task.</returns>
  89. /// <exception cref="System.ArgumentNullException">user</exception>
  90. public async Task SaveUser(User user, CancellationToken cancellationToken)
  91. {
  92. if (user == null)
  93. {
  94. throw new ArgumentNullException("user");
  95. }
  96. if (cancellationToken == null)
  97. {
  98. throw new ArgumentNullException("cancellationToken");
  99. }
  100. cancellationToken.ThrowIfCancellationRequested();
  101. var serialized = _jsonSerializer.SerializeToBytes(user);
  102. cancellationToken.ThrowIfCancellationRequested();
  103. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  104. SQLiteTransaction transaction = null;
  105. try
  106. {
  107. transaction = Connection.BeginTransaction();
  108. using (var cmd = Connection.CreateCommand())
  109. {
  110. cmd.CommandText = "replace into users (guid, data) values (@1, @2)";
  111. cmd.AddParam("@1", user.Id);
  112. cmd.AddParam("@2", serialized);
  113. cmd.Transaction = transaction;
  114. await cmd.ExecuteNonQueryAsync(cancellationToken);
  115. }
  116. transaction.Commit();
  117. }
  118. catch (OperationCanceledException)
  119. {
  120. if (transaction != null)
  121. {
  122. transaction.Rollback();
  123. }
  124. throw;
  125. }
  126. catch (Exception e)
  127. {
  128. Logger.ErrorException("Failed to save user:", e);
  129. if (transaction != null)
  130. {
  131. transaction.Rollback();
  132. }
  133. throw;
  134. }
  135. finally
  136. {
  137. if (transaction != null)
  138. {
  139. transaction.Dispose();
  140. }
  141. _writeLock.Release();
  142. }
  143. }
  144. /// <summary>
  145. /// Retrieve all users from the database
  146. /// </summary>
  147. /// <returns>IEnumerable{User}.</returns>
  148. public IEnumerable<User> RetrieveAllUsers()
  149. {
  150. using (var cmd = Connection.CreateCommand())
  151. {
  152. cmd.CommandText = "select data from users";
  153. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  154. {
  155. while (reader.Read())
  156. {
  157. using (var stream = GetStream(reader, 0))
  158. {
  159. var user = _jsonSerializer.DeserializeFromStream<User>(stream);
  160. yield return user;
  161. }
  162. }
  163. }
  164. }
  165. }
  166. /// <summary>
  167. /// Deletes the user.
  168. /// </summary>
  169. /// <param name="user">The user.</param>
  170. /// <param name="cancellationToken">The cancellation token.</param>
  171. /// <returns>Task.</returns>
  172. /// <exception cref="System.ArgumentNullException">user</exception>
  173. public async Task DeleteUser(User user, CancellationToken cancellationToken)
  174. {
  175. if (user == null)
  176. {
  177. throw new ArgumentNullException("user");
  178. }
  179. if (cancellationToken == null)
  180. {
  181. throw new ArgumentNullException("cancellationToken");
  182. }
  183. cancellationToken.ThrowIfCancellationRequested();
  184. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  185. SQLiteTransaction transaction = null;
  186. try
  187. {
  188. transaction = Connection.BeginTransaction();
  189. using (var cmd = Connection.CreateCommand())
  190. {
  191. cmd.CommandText = "delete from users where guid=@guid";
  192. var guidParam = cmd.Parameters.Add("@guid", DbType.Guid);
  193. guidParam.Value = user.Id;
  194. cmd.Transaction = transaction;
  195. await cmd.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
  196. }
  197. transaction.Commit();
  198. }
  199. catch (OperationCanceledException)
  200. {
  201. if (transaction != null)
  202. {
  203. transaction.Rollback();
  204. }
  205. throw;
  206. }
  207. catch (Exception e)
  208. {
  209. Logger.ErrorException("Failed to delete user:", e);
  210. if (transaction != null)
  211. {
  212. transaction.Rollback();
  213. }
  214. throw;
  215. }
  216. finally
  217. {
  218. if (transaction != null)
  219. {
  220. transaction.Dispose();
  221. }
  222. _writeLock.Release();
  223. }
  224. }
  225. }
  226. }