SqliteUserRepository.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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.Persistence
  14. {
  15. /// <summary>
  16. /// Class SQLiteUserRepository
  17. /// </summary>
  18. public class SqliteUserRepository : IUserRepository
  19. {
  20. private readonly ILogger _logger;
  21. private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
  22. private SQLiteConnection _connection;
  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. /// The _app paths
  41. /// </summary>
  42. private readonly IApplicationPaths _appPaths;
  43. /// <summary>
  44. /// Initializes a new instance of the <see cref="SqliteUserRepository" /> class.
  45. /// </summary>
  46. /// <param name="appPaths">The app paths.</param>
  47. /// <param name="jsonSerializer">The json serializer.</param>
  48. /// <param name="logManager">The log manager.</param>
  49. /// <exception cref="System.ArgumentNullException">appPaths</exception>
  50. public SqliteUserRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
  51. {
  52. if (appPaths == null)
  53. {
  54. throw new ArgumentNullException("appPaths");
  55. }
  56. if (jsonSerializer == null)
  57. {
  58. throw new ArgumentNullException("jsonSerializer");
  59. }
  60. _appPaths = appPaths;
  61. _jsonSerializer = jsonSerializer;
  62. _logger = logManager.GetLogger(GetType().Name);
  63. }
  64. /// <summary>
  65. /// Opens the connection to the database
  66. /// </summary>
  67. /// <returns>Task.</returns>
  68. public async Task Initialize()
  69. {
  70. var dbFile = Path.Combine(_appPaths.DataPath, "users.db");
  71. _connection = await SqliteExtensions.ConnectToDb(dbFile).ConfigureAwait(false);
  72. string[] queries = {
  73. "create table if not exists users (guid GUID primary key, data BLOB)",
  74. "create index if not exists idx_users on users(guid)",
  75. "create table if not exists schema_version (table_name primary key, version)",
  76. //pragmas
  77. "pragma temp_store = memory"
  78. };
  79. _connection.RunQueries(queries, _logger);
  80. }
  81. /// <summary>
  82. /// Save a user in the repo
  83. /// </summary>
  84. /// <param name="user">The user.</param>
  85. /// <param name="cancellationToken">The cancellation token.</param>
  86. /// <returns>Task.</returns>
  87. /// <exception cref="System.ArgumentNullException">user</exception>
  88. public async Task SaveUser(User user, CancellationToken cancellationToken)
  89. {
  90. if (user == null)
  91. {
  92. throw new ArgumentNullException("user");
  93. }
  94. if (cancellationToken == null)
  95. {
  96. throw new ArgumentNullException("cancellationToken");
  97. }
  98. cancellationToken.ThrowIfCancellationRequested();
  99. var serialized = _jsonSerializer.SerializeToBytes(user);
  100. cancellationToken.ThrowIfCancellationRequested();
  101. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  102. SQLiteTransaction transaction = null;
  103. try
  104. {
  105. transaction = _connection.BeginTransaction();
  106. using (var cmd = _connection.CreateCommand())
  107. {
  108. cmd.CommandText = "replace into users (guid, data) values (@1, @2)";
  109. cmd.AddParam("@1", user.Id);
  110. cmd.AddParam("@2", serialized);
  111. cmd.Transaction = transaction;
  112. await cmd.ExecuteNonQueryAsync(cancellationToken);
  113. }
  114. transaction.Commit();
  115. }
  116. catch (OperationCanceledException)
  117. {
  118. if (transaction != null)
  119. {
  120. transaction.Rollback();
  121. }
  122. throw;
  123. }
  124. catch (Exception e)
  125. {
  126. _logger.ErrorException("Failed to save user:", e);
  127. if (transaction != null)
  128. {
  129. transaction.Rollback();
  130. }
  131. throw;
  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 = reader.GetMemoryStream(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 cmd.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
  194. }
  195. transaction.Commit();
  196. }
  197. catch (OperationCanceledException)
  198. {
  199. if (transaction != null)
  200. {
  201. transaction.Rollback();
  202. }
  203. throw;
  204. }
  205. catch (Exception e)
  206. {
  207. _logger.ErrorException("Failed to delete user:", e);
  208. if (transaction != null)
  209. {
  210. transaction.Rollback();
  211. }
  212. throw;
  213. }
  214. finally
  215. {
  216. if (transaction != null)
  217. {
  218. transaction.Dispose();
  219. }
  220. _writeLock.Release();
  221. }
  222. }
  223. /// <summary>
  224. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  225. /// </summary>
  226. public void Dispose()
  227. {
  228. Dispose(true);
  229. GC.SuppressFinalize(this);
  230. }
  231. private readonly object _disposeLock = new object();
  232. /// <summary>
  233. /// Releases unmanaged and - optionally - managed resources.
  234. /// </summary>
  235. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  236. protected virtual void Dispose(bool dispose)
  237. {
  238. if (dispose)
  239. {
  240. try
  241. {
  242. lock (_disposeLock)
  243. {
  244. if (_connection != null)
  245. {
  246. if (_connection.IsOpen())
  247. {
  248. _connection.Close();
  249. }
  250. _connection.Dispose();
  251. _connection = null;
  252. }
  253. }
  254. }
  255. catch (Exception ex)
  256. {
  257. _logger.ErrorException("Error disposing database", ex);
  258. }
  259. }
  260. }
  261. }
  262. }