SqliteUserRepository.cs 9.0 KB

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