SqliteUserRepository.cs 9.1 KB

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