SqliteUserRepository.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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).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. if (cancellationToken == null)
  87. {
  88. throw new ArgumentNullException("cancellationToken");
  89. }
  90. cancellationToken.ThrowIfCancellationRequested();
  91. var serialized = _jsonSerializer.SerializeToBytes(user);
  92. cancellationToken.ThrowIfCancellationRequested();
  93. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  94. IDbTransaction transaction = null;
  95. try
  96. {
  97. transaction = _connection.BeginTransaction();
  98. using (var cmd = _connection.CreateCommand())
  99. {
  100. cmd.CommandText = "replace into users (guid, data) values (@1, @2)";
  101. cmd.Parameters.Add(cmd, "@1", DbType.Guid).Value = user.Id;
  102. cmd.Parameters.Add(cmd, "@2", DbType.Binary).Value = serialized;
  103. cmd.Transaction = transaction;
  104. cmd.ExecuteNonQuery();
  105. }
  106. transaction.Commit();
  107. }
  108. catch (OperationCanceledException)
  109. {
  110. if (transaction != null)
  111. {
  112. transaction.Rollback();
  113. }
  114. throw;
  115. }
  116. catch (Exception e)
  117. {
  118. _logger.ErrorException("Failed to save user:", e);
  119. if (transaction != null)
  120. {
  121. transaction.Rollback();
  122. }
  123. throw;
  124. }
  125. finally
  126. {
  127. if (transaction != null)
  128. {
  129. transaction.Dispose();
  130. }
  131. _writeLock.Release();
  132. }
  133. }
  134. /// <summary>
  135. /// Retrieve all users from the database
  136. /// </summary>
  137. /// <returns>IEnumerable{User}.</returns>
  138. public IEnumerable<User> RetrieveAllUsers()
  139. {
  140. using (var cmd = _connection.CreateCommand())
  141. {
  142. cmd.CommandText = "select data from users";
  143. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  144. {
  145. while (reader.Read())
  146. {
  147. using (var stream = reader.GetMemoryStream(0))
  148. {
  149. var user = _jsonSerializer.DeserializeFromStream<User>(stream);
  150. yield return user;
  151. }
  152. }
  153. }
  154. }
  155. }
  156. /// <summary>
  157. /// Deletes the user.
  158. /// </summary>
  159. /// <param name="user">The user.</param>
  160. /// <param name="cancellationToken">The cancellation token.</param>
  161. /// <returns>Task.</returns>
  162. /// <exception cref="System.ArgumentNullException">user</exception>
  163. public async Task DeleteUser(User user, CancellationToken cancellationToken)
  164. {
  165. if (user == null)
  166. {
  167. throw new ArgumentNullException("user");
  168. }
  169. if (cancellationToken == null)
  170. {
  171. throw new ArgumentNullException("cancellationToken");
  172. }
  173. cancellationToken.ThrowIfCancellationRequested();
  174. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  175. IDbTransaction transaction = null;
  176. try
  177. {
  178. transaction = _connection.BeginTransaction();
  179. using (var cmd = _connection.CreateCommand())
  180. {
  181. cmd.CommandText = "delete from users where guid=@guid";
  182. cmd.Parameters.Add(cmd, "@guid", DbType.Guid).Value = user.Id;
  183. cmd.Transaction = transaction;
  184. cmd.ExecuteNonQuery();
  185. }
  186. transaction.Commit();
  187. }
  188. catch (OperationCanceledException)
  189. {
  190. if (transaction != null)
  191. {
  192. transaction.Rollback();
  193. }
  194. throw;
  195. }
  196. catch (Exception e)
  197. {
  198. _logger.ErrorException("Failed to delete user:", e);
  199. if (transaction != null)
  200. {
  201. transaction.Rollback();
  202. }
  203. throw;
  204. }
  205. finally
  206. {
  207. if (transaction != null)
  208. {
  209. transaction.Dispose();
  210. }
  211. _writeLock.Release();
  212. }
  213. }
  214. /// <summary>
  215. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  216. /// </summary>
  217. public void Dispose()
  218. {
  219. Dispose(true);
  220. GC.SuppressFinalize(this);
  221. }
  222. private readonly object _disposeLock = new object();
  223. /// <summary>
  224. /// Releases unmanaged and - optionally - managed resources.
  225. /// </summary>
  226. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  227. protected virtual void Dispose(bool dispose)
  228. {
  229. if (dispose)
  230. {
  231. try
  232. {
  233. lock (_disposeLock)
  234. {
  235. if (_connection != null)
  236. {
  237. if (_connection.IsOpen())
  238. {
  239. _connection.Close();
  240. }
  241. _connection.Dispose();
  242. _connection = null;
  243. }
  244. }
  245. }
  246. catch (Exception ex)
  247. {
  248. _logger.ErrorException("Error disposing database", ex);
  249. }
  250. }
  251. }
  252. }
  253. }