SqliteItemRepository.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Persistence;
  4. using MediaBrowser.Model.Entities;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Model.Serialization;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Data;
  10. using System.Data.SQLite;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. namespace MediaBrowser.Server.Implementations.Persistence
  16. {
  17. /// <summary>
  18. /// Class SQLiteItemRepository
  19. /// </summary>
  20. public class SqliteItemRepository : SqliteRepository, IItemRepository
  21. {
  22. /// <summary>
  23. /// The repository name
  24. /// </summary>
  25. public const string RepositoryName = "SQLite";
  26. /// <summary>
  27. /// Gets the name of the repository
  28. /// </summary>
  29. /// <value>The name.</value>
  30. public string Name
  31. {
  32. get
  33. {
  34. return RepositoryName;
  35. }
  36. }
  37. /// <summary>
  38. /// Gets the json serializer.
  39. /// </summary>
  40. /// <value>The json serializer.</value>
  41. private readonly IJsonSerializer _jsonSerializer;
  42. /// <summary>
  43. /// The _app paths
  44. /// </summary>
  45. private readonly IApplicationPaths _appPaths;
  46. /// <summary>
  47. /// The _save item command
  48. /// </summary>
  49. private SQLiteCommand _saveItemCommand;
  50. private readonly string _criticReviewsPath;
  51. /// <summary>
  52. /// Initializes a new instance of the <see cref="SqliteItemRepository"/> class.
  53. /// </summary>
  54. /// <param name="appPaths">The app paths.</param>
  55. /// <param name="jsonSerializer">The json serializer.</param>
  56. /// <param name="logManager">The log manager.</param>
  57. /// <exception cref="System.ArgumentNullException">
  58. /// appPaths
  59. /// or
  60. /// jsonSerializer
  61. /// </exception>
  62. public SqliteItemRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
  63. : base(logManager)
  64. {
  65. if (appPaths == null)
  66. {
  67. throw new ArgumentNullException("appPaths");
  68. }
  69. if (jsonSerializer == null)
  70. {
  71. throw new ArgumentNullException("jsonSerializer");
  72. }
  73. _appPaths = appPaths;
  74. _jsonSerializer = jsonSerializer;
  75. _criticReviewsPath = Path.Combine(_appPaths.DataPath, "critic-reviews");
  76. }
  77. /// <summary>
  78. /// Opens the connection to the database
  79. /// </summary>
  80. /// <returns>Task.</returns>
  81. public async Task Initialize()
  82. {
  83. var dbFile = Path.Combine(_appPaths.DataPath, "library.db");
  84. await ConnectToDb(dbFile).ConfigureAwait(false);
  85. string[] queries = {
  86. "create table if not exists baseitems (guid GUID primary key, data BLOB)",
  87. "create index if not exists idx_baseitems on baseitems(guid)",
  88. "create table if not exists schema_version (table_name primary key, version)",
  89. //pragmas
  90. "pragma temp_store = memory"
  91. };
  92. RunQueries(queries);
  93. PrepareStatements();
  94. }
  95. /// <summary>
  96. /// The _write lock
  97. /// </summary>
  98. private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
  99. /// <summary>
  100. /// Prepares the statements.
  101. /// </summary>
  102. private void PrepareStatements()
  103. {
  104. _saveItemCommand = new SQLiteCommand
  105. {
  106. CommandText = "replace into baseitems (guid, data) values (@1, @2)"
  107. };
  108. _saveItemCommand.Parameters.Add(new SQLiteParameter("@1"));
  109. _saveItemCommand.Parameters.Add(new SQLiteParameter("@2"));
  110. }
  111. /// <summary>
  112. /// Save a standard item in the repo
  113. /// </summary>
  114. /// <param name="item">The item.</param>
  115. /// <param name="cancellationToken">The cancellation token.</param>
  116. /// <returns>Task.</returns>
  117. /// <exception cref="System.ArgumentNullException">item</exception>
  118. public Task SaveItem(BaseItem item, CancellationToken cancellationToken)
  119. {
  120. if (item == null)
  121. {
  122. throw new ArgumentNullException("item");
  123. }
  124. return SaveItems(new[] { item }, cancellationToken);
  125. }
  126. /// <summary>
  127. /// Saves the items.
  128. /// </summary>
  129. /// <param name="items">The items.</param>
  130. /// <param name="cancellationToken">The cancellation token.</param>
  131. /// <returns>Task.</returns>
  132. /// <exception cref="System.ArgumentNullException">
  133. /// items
  134. /// or
  135. /// cancellationToken
  136. /// </exception>
  137. public async Task SaveItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  138. {
  139. if (items == null)
  140. {
  141. throw new ArgumentNullException("items");
  142. }
  143. if (cancellationToken == null)
  144. {
  145. throw new ArgumentNullException("cancellationToken");
  146. }
  147. cancellationToken.ThrowIfCancellationRequested();
  148. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  149. SQLiteTransaction transaction = null;
  150. try
  151. {
  152. transaction = Connection.BeginTransaction();
  153. foreach (var item in items)
  154. {
  155. cancellationToken.ThrowIfCancellationRequested();
  156. _saveItemCommand.Parameters[0].Value = item.Id;
  157. _saveItemCommand.Parameters[1].Value = _jsonSerializer.SerializeToBytes(item);
  158. _saveItemCommand.Transaction = transaction;
  159. await _saveItemCommand.ExecuteNonQueryAsync(cancellationToken);
  160. }
  161. transaction.Commit();
  162. }
  163. catch (OperationCanceledException)
  164. {
  165. if (transaction != null)
  166. {
  167. transaction.Rollback();
  168. }
  169. throw;
  170. }
  171. catch (Exception e)
  172. {
  173. Logger.ErrorException("Failed to save items:", e);
  174. if (transaction != null)
  175. {
  176. transaction.Rollback();
  177. }
  178. throw;
  179. }
  180. finally
  181. {
  182. if (transaction != null)
  183. {
  184. transaction.Dispose();
  185. }
  186. _writeLock.Release();
  187. }
  188. }
  189. /// <summary>
  190. /// Internal retrieve from items or users table
  191. /// </summary>
  192. /// <param name="id">The id.</param>
  193. /// <param name="type">The type.</param>
  194. /// <returns>BaseItem.</returns>
  195. /// <exception cref="System.ArgumentNullException">id</exception>
  196. /// <exception cref="System.ArgumentException"></exception>
  197. public BaseItem RetrieveItem(Guid id, Type type)
  198. {
  199. if (id == Guid.Empty)
  200. {
  201. throw new ArgumentNullException("id");
  202. }
  203. using (var cmd = Connection.CreateCommand())
  204. {
  205. cmd.CommandText = "select data from baseitems where guid = @guid";
  206. var guidParam = cmd.Parameters.Add("@guid", DbType.Guid);
  207. guidParam.Value = id;
  208. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  209. {
  210. if (reader.Read())
  211. {
  212. using (var stream = GetStream(reader, 0))
  213. {
  214. return _jsonSerializer.DeserializeFromStream(stream, type) as BaseItem;
  215. }
  216. }
  217. }
  218. return null;
  219. }
  220. }
  221. /// <summary>
  222. /// Gets the critic reviews.
  223. /// </summary>
  224. /// <param name="itemId">The item id.</param>
  225. /// <returns>Task{IEnumerable{ItemReview}}.</returns>
  226. public Task<IEnumerable<ItemReview>> GetCriticReviews(Guid itemId)
  227. {
  228. return Task.Run<IEnumerable<ItemReview>>(() =>
  229. {
  230. try
  231. {
  232. var path = Path.Combine(_criticReviewsPath, itemId + ".json");
  233. return _jsonSerializer.DeserializeFromFile<List<ItemReview>>(path);
  234. }
  235. catch (DirectoryNotFoundException)
  236. {
  237. return new List<ItemReview>();
  238. }
  239. catch (FileNotFoundException)
  240. {
  241. return new List<ItemReview>();
  242. }
  243. });
  244. }
  245. /// <summary>
  246. /// Saves the critic reviews.
  247. /// </summary>
  248. /// <param name="itemId">The item id.</param>
  249. /// <param name="criticReviews">The critic reviews.</param>
  250. /// <returns>Task.</returns>
  251. public Task SaveCriticReviews(Guid itemId, IEnumerable<ItemReview> criticReviews)
  252. {
  253. return Task.Run(() =>
  254. {
  255. if (!Directory.Exists(_criticReviewsPath))
  256. {
  257. Directory.CreateDirectory(_criticReviewsPath);
  258. }
  259. var path = Path.Combine(_criticReviewsPath, itemId + ".json");
  260. _jsonSerializer.SerializeToFile(criticReviews.ToList(), path);
  261. });
  262. }
  263. }
  264. }