SqliteItemRepository.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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 : IItemRepository
  21. {
  22. private SQLiteConnection _connection;
  23. private readonly ILogger _logger;
  24. /// <summary>
  25. /// Gets the name of the repository
  26. /// </summary>
  27. /// <value>The name.</value>
  28. public string Name
  29. {
  30. get
  31. {
  32. return "SQLite";
  33. }
  34. }
  35. /// <summary>
  36. /// Gets the json serializer.
  37. /// </summary>
  38. /// <value>The json serializer.</value>
  39. private readonly IJsonSerializer _jsonSerializer;
  40. /// <summary>
  41. /// The _app paths
  42. /// </summary>
  43. private readonly IApplicationPaths _appPaths;
  44. /// <summary>
  45. /// The _save item command
  46. /// </summary>
  47. private SQLiteCommand _saveItemCommand;
  48. private readonly string _criticReviewsPath;
  49. private SqliteChapterRepository _chapterRepository;
  50. /// <summary>
  51. /// Initializes a new instance of the <see cref="SqliteItemRepository"/> class.
  52. /// </summary>
  53. /// <param name="appPaths">The app paths.</param>
  54. /// <param name="jsonSerializer">The json serializer.</param>
  55. /// <param name="logManager">The log manager.</param>
  56. /// <exception cref="System.ArgumentNullException">
  57. /// appPaths
  58. /// or
  59. /// jsonSerializer
  60. /// </exception>
  61. public SqliteItemRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
  62. {
  63. if (appPaths == null)
  64. {
  65. throw new ArgumentNullException("appPaths");
  66. }
  67. if (jsonSerializer == null)
  68. {
  69. throw new ArgumentNullException("jsonSerializer");
  70. }
  71. _appPaths = appPaths;
  72. _jsonSerializer = jsonSerializer;
  73. _criticReviewsPath = Path.Combine(_appPaths.DataPath, "critic-reviews");
  74. _logger = logManager.GetLogger(GetType().Name);
  75. _chapterRepository = new SqliteChapterRepository(appPaths, logManager);
  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. _connection = await SqliteExtensions.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. //pragmas
  89. "pragma temp_store = memory"
  90. };
  91. _connection.RunQueries(queries, _logger);
  92. PrepareStatements();
  93. await _chapterRepository.Initialize().ConfigureAwait(false);
  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 = reader.GetMemoryStream(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. /// <summary>
  264. /// Gets chapters for an item
  265. /// </summary>
  266. /// <param name="id">The id.</param>
  267. /// <returns>IEnumerable{ChapterInfo}.</returns>
  268. /// <exception cref="System.ArgumentNullException">id</exception>
  269. public IEnumerable<ChapterInfo> GetChapters(Guid id)
  270. {
  271. return _chapterRepository.GetChapters(id);
  272. }
  273. /// <summary>
  274. /// Gets a single chapter for an item
  275. /// </summary>
  276. /// <param name="id">The id.</param>
  277. /// <param name="index">The index.</param>
  278. /// <returns>ChapterInfo.</returns>
  279. /// <exception cref="System.ArgumentNullException">id</exception>
  280. public ChapterInfo GetChapter(Guid id, int index)
  281. {
  282. return _chapterRepository.GetChapter(id, index);
  283. }
  284. /// <summary>
  285. /// Saves the chapters.
  286. /// </summary>
  287. /// <param name="id">The id.</param>
  288. /// <param name="chapters">The chapters.</param>
  289. /// <param name="cancellationToken">The cancellation token.</param>
  290. /// <returns>Task.</returns>
  291. /// <exception cref="System.ArgumentNullException">
  292. /// id
  293. /// or
  294. /// chapters
  295. /// or
  296. /// cancellationToken
  297. /// </exception>
  298. public Task SaveChapters(Guid id, IEnumerable<ChapterInfo> chapters, CancellationToken cancellationToken)
  299. {
  300. return _chapterRepository.SaveChapters(id, chapters, cancellationToken);
  301. }
  302. /// <summary>
  303. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  304. /// </summary>
  305. public void Dispose()
  306. {
  307. Dispose(true);
  308. GC.SuppressFinalize(this);
  309. }
  310. private readonly object _disposeLock = new object();
  311. /// <summary>
  312. /// Releases unmanaged and - optionally - managed resources.
  313. /// </summary>
  314. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  315. protected virtual void Dispose(bool dispose)
  316. {
  317. if (dispose)
  318. {
  319. try
  320. {
  321. lock (_disposeLock)
  322. {
  323. if (_connection != null)
  324. {
  325. if (_connection.IsOpen())
  326. {
  327. _connection.Close();
  328. }
  329. _connection.Dispose();
  330. _connection = null;
  331. }
  332. }
  333. }
  334. catch (Exception ex)
  335. {
  336. _logger.ErrorException("Error disposing database", ex);
  337. }
  338. if (_chapterRepository != null)
  339. {
  340. _chapterRepository.Dispose();
  341. _chapterRepository = null;
  342. }
  343. }
  344. }
  345. }
  346. }