2
0

SQLiteUserRepository.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. }
  125. catch (Exception e)
  126. {
  127. Logger.ErrorException("Failed to save user:", e);
  128. if (transaction != null)
  129. {
  130. transaction.Rollback();
  131. }
  132. }
  133. finally
  134. {
  135. if (transaction != null)
  136. {
  137. transaction.Dispose();
  138. }
  139. _writeLock.Release();
  140. }
  141. }
  142. /// <summary>
  143. /// Retrieve all users from the database
  144. /// </summary>
  145. /// <returns>IEnumerable{User}.</returns>
  146. public IEnumerable<User> RetrieveAllUsers()
  147. {
  148. using (var cmd = Connection.CreateCommand())
  149. {
  150. cmd.CommandText = "select data from users";
  151. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  152. {
  153. while (reader.Read())
  154. {
  155. using (var stream = GetStream(reader, 0))
  156. {
  157. var user = _jsonSerializer.DeserializeFromStream<User>(stream);
  158. yield return user;
  159. }
  160. }
  161. }
  162. }
  163. }
  164. /// <summary>
  165. /// Deletes the user.
  166. /// </summary>
  167. /// <param name="user">The user.</param>
  168. /// <param name="cancellationToken">The cancellation token.</param>
  169. /// <returns>Task.</returns>
  170. /// <exception cref="System.ArgumentNullException">user</exception>
  171. public async Task DeleteUser(User user, CancellationToken cancellationToken)
  172. {
  173. if (user == null)
  174. {
  175. throw new ArgumentNullException("user");
  176. }
  177. if (cancellationToken == null)
  178. {
  179. throw new ArgumentNullException("cancellationToken");
  180. }
  181. cancellationToken.ThrowIfCancellationRequested();
  182. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  183. SQLiteTransaction transaction = null;
  184. try
  185. {
  186. transaction = Connection.BeginTransaction();
  187. using (var cmd = Connection.CreateCommand())
  188. {
  189. cmd.CommandText = "delete from users where guid=@guid";
  190. var guidParam = cmd.Parameters.Add("@guid", DbType.Guid);
  191. guidParam.Value = user.Id;
  192. cmd.Transaction = transaction;
  193. await ExecuteCommand(cmd).ConfigureAwait(false);
  194. }
  195. transaction.Commit();
  196. }
  197. catch (OperationCanceledException)
  198. {
  199. if (transaction != null)
  200. {
  201. transaction.Rollback();
  202. }
  203. }
  204. catch (Exception e)
  205. {
  206. Logger.ErrorException("Failed to delete user:", e);
  207. if (transaction != null)
  208. {
  209. transaction.Rollback();
  210. }
  211. }
  212. finally
  213. {
  214. if (transaction != null)
  215. {
  216. transaction.Dispose();
  217. }
  218. _writeLock.Release();
  219. }
  220. }
  221. }
  222. }