SqliteUserRepository.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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 : IUserRepository
  18. {
  19. private readonly ILogger _logger;
  20. private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
  21. private IDbConnection _connection;
  22. private readonly IServerApplicationPaths _appPaths;
  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 "SQLite";
  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. /// Initializes a new instance of the <see cref="SqliteUserRepository" /> class.
  41. /// </summary>
  42. /// <param name="jsonSerializer">The json serializer.</param>
  43. /// <param name="logManager">The log manager.</param>
  44. /// <param name="appPaths">The app paths.</param>
  45. /// <exception cref="System.ArgumentNullException">appPaths</exception>
  46. public SqliteUserRepository(IJsonSerializer jsonSerializer, ILogManager logManager, IServerApplicationPaths appPaths)
  47. {
  48. if (jsonSerializer == null)
  49. {
  50. throw new ArgumentNullException("jsonSerializer");
  51. }
  52. _jsonSerializer = jsonSerializer;
  53. _appPaths = appPaths;
  54. _logger = logManager.GetLogger(GetType().Name);
  55. }
  56. /// <summary>
  57. /// Opens the connection to the database
  58. /// </summary>
  59. /// <returns>Task.</returns>
  60. public async Task Initialize()
  61. {
  62. var dbFile = Path.Combine(_appPaths.DataPath, "users.db");
  63. _connection = await SqliteExtensions.ConnectToDb(dbFile, _logger).ConfigureAwait(false);
  64. string[] queries = {
  65. "create table if not exists users (guid GUID primary key, data BLOB)",
  66. "create index if not exists idx_users on users(guid)",
  67. "create table if not exists schema_version (table_name primary key, version)",
  68. //pragmas
  69. "pragma temp_store = memory"
  70. };
  71. _connection.RunQueries(queries, _logger);
  72. }
  73. /// <summary>
  74. /// Save a user in the repo
  75. /// </summary>
  76. /// <param name="user">The user.</param>
  77. /// <param name="cancellationToken">The cancellation token.</param>
  78. /// <returns>Task.</returns>
  79. /// <exception cref="System.ArgumentNullException">user</exception>
  80. public async Task SaveUser(User user, CancellationToken cancellationToken)
  81. {
  82. if (user == null)
  83. {
  84. throw new ArgumentNullException("user");
  85. }
  86. cancellationToken.ThrowIfCancellationRequested();
  87. var serialized = _jsonSerializer.SerializeToBytes(user);
  88. cancellationToken.ThrowIfCancellationRequested();
  89. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  90. IDbTransaction transaction = null;
  91. try
  92. {
  93. transaction = _connection.BeginTransaction();
  94. using (var cmd = _connection.CreateCommand())
  95. {
  96. cmd.CommandText = "replace into users (guid, data) values (@1, @2)";
  97. cmd.Parameters.Add(cmd, "@1", DbType.Guid).Value = user.Id;
  98. cmd.Parameters.Add(cmd, "@2", DbType.Binary).Value = serialized;
  99. cmd.Transaction = transaction;
  100. cmd.ExecuteNonQuery();
  101. }
  102. transaction.Commit();
  103. }
  104. catch (OperationCanceledException)
  105. {
  106. if (transaction != null)
  107. {
  108. transaction.Rollback();
  109. }
  110. throw;
  111. }
  112. catch (Exception e)
  113. {
  114. _logger.ErrorException("Failed to save user:", e);
  115. if (transaction != null)
  116. {
  117. transaction.Rollback();
  118. }
  119. throw;
  120. }
  121. finally
  122. {
  123. if (transaction != null)
  124. {
  125. transaction.Dispose();
  126. }
  127. _writeLock.Release();
  128. }
  129. }
  130. /// <summary>
  131. /// Retrieve all users from the database
  132. /// </summary>
  133. /// <returns>IEnumerable{User}.</returns>
  134. public IEnumerable<User> RetrieveAllUsers()
  135. {
  136. using (var cmd = _connection.CreateCommand())
  137. {
  138. cmd.CommandText = "select data from users";
  139. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  140. {
  141. while (reader.Read())
  142. {
  143. using (var stream = reader.GetMemoryStream(0))
  144. {
  145. var user = _jsonSerializer.DeserializeFromStream<User>(stream);
  146. yield return user;
  147. }
  148. }
  149. }
  150. }
  151. }
  152. /// <summary>
  153. /// Deletes the user.
  154. /// </summary>
  155. /// <param name="user">The user.</param>
  156. /// <param name="cancellationToken">The cancellation token.</param>
  157. /// <returns>Task.</returns>
  158. /// <exception cref="System.ArgumentNullException">user</exception>
  159. public async Task DeleteUser(User user, CancellationToken cancellationToken)
  160. {
  161. if (user == null)
  162. {
  163. throw new ArgumentNullException("user");
  164. }
  165. cancellationToken.ThrowIfCancellationRequested();
  166. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  167. IDbTransaction transaction = null;
  168. try
  169. {
  170. transaction = _connection.BeginTransaction();
  171. using (var cmd = _connection.CreateCommand())
  172. {
  173. cmd.CommandText = "delete from users where guid=@guid";
  174. cmd.Parameters.Add(cmd, "@guid", DbType.Guid).Value = user.Id;
  175. cmd.Transaction = transaction;
  176. cmd.ExecuteNonQuery();
  177. }
  178. transaction.Commit();
  179. }
  180. catch (OperationCanceledException)
  181. {
  182. if (transaction != null)
  183. {
  184. transaction.Rollback();
  185. }
  186. throw;
  187. }
  188. catch (Exception e)
  189. {
  190. _logger.ErrorException("Failed to delete user:", e);
  191. if (transaction != null)
  192. {
  193. transaction.Rollback();
  194. }
  195. throw;
  196. }
  197. finally
  198. {
  199. if (transaction != null)
  200. {
  201. transaction.Dispose();
  202. }
  203. _writeLock.Release();
  204. }
  205. }
  206. /// <summary>
  207. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  208. /// </summary>
  209. public void Dispose()
  210. {
  211. Dispose(true);
  212. GC.SuppressFinalize(this);
  213. }
  214. private readonly object _disposeLock = new object();
  215. /// <summary>
  216. /// Releases unmanaged and - optionally - managed resources.
  217. /// </summary>
  218. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  219. protected virtual void Dispose(bool dispose)
  220. {
  221. if (dispose)
  222. {
  223. try
  224. {
  225. lock (_disposeLock)
  226. {
  227. if (_connection != null)
  228. {
  229. if (_connection.IsOpen())
  230. {
  231. _connection.Close();
  232. }
  233. _connection.Dispose();
  234. _connection = null;
  235. }
  236. }
  237. }
  238. catch (Exception ex)
  239. {
  240. _logger.ErrorException("Error disposing database", ex);
  241. }
  242. }
  243. }
  244. }
  245. }