SqliteItemRepository.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. private SQLiteCommand _deleteChildrenCommand;
  51. private SQLiteCommand _saveChildrenCommand;
  52. /// <summary>
  53. /// Initializes a new instance of the <see cref="SqliteItemRepository"/> class.
  54. /// </summary>
  55. /// <param name="appPaths">The app paths.</param>
  56. /// <param name="jsonSerializer">The json serializer.</param>
  57. /// <param name="logManager">The log manager.</param>
  58. /// <exception cref="System.ArgumentNullException">
  59. /// appPaths
  60. /// or
  61. /// jsonSerializer
  62. /// </exception>
  63. public SqliteItemRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager 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. _logger = logManager.GetLogger(GetType().Name);
  77. _chapterRepository = new SqliteChapterRepository(appPaths, logManager);
  78. }
  79. /// <summary>
  80. /// Opens the connection to the database
  81. /// </summary>
  82. /// <returns>Task.</returns>
  83. public async Task Initialize()
  84. {
  85. var dbFile = Path.Combine(_appPaths.DataPath, "library.db");
  86. _connection = await SqliteExtensions.ConnectToDb(dbFile).ConfigureAwait(false);
  87. string[] queries = {
  88. "create table if not exists baseitems (guid GUID primary key, data BLOB)",
  89. "create index if not exists idx_baseitems on baseitems(guid)",
  90. "create table if not exists ChildDefinitions (ParentId GUID, ItemId GUID, Type TEXT, PRIMARY KEY (ParentId, ItemId))",
  91. "create index if not exists idx_ChildDefinitions on ChildDefinitions(ParentId,ItemId)",
  92. //pragmas
  93. "pragma temp_store = memory"
  94. };
  95. _connection.RunQueries(queries, _logger);
  96. PrepareStatements();
  97. await _chapterRepository.Initialize().ConfigureAwait(false);
  98. }
  99. /// <summary>
  100. /// The _write lock
  101. /// </summary>
  102. private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
  103. /// <summary>
  104. /// Prepares the statements.
  105. /// </summary>
  106. private void PrepareStatements()
  107. {
  108. _saveItemCommand = new SQLiteCommand
  109. {
  110. CommandText = "replace into baseitems (guid, data) values (@1, @2)"
  111. };
  112. _saveItemCommand.Parameters.Add(new SQLiteParameter("@1"));
  113. _saveItemCommand.Parameters.Add(new SQLiteParameter("@2"));
  114. _deleteChildrenCommand = new SQLiteCommand
  115. {
  116. CommandText = "delete from ChildDefinitions where ParentId=@ParentId"
  117. };
  118. _deleteChildrenCommand.Parameters.Add(new SQLiteParameter("@ParentId"));
  119. _saveChildrenCommand = new SQLiteCommand
  120. {
  121. CommandText = "replace into ChildDefinitions (ParentId, ItemId, Type) values (@ParentId, @ItemId, @Type)"
  122. };
  123. _saveChildrenCommand.Parameters.Add(new SQLiteParameter("@ParentId"));
  124. _saveChildrenCommand.Parameters.Add(new SQLiteParameter("@ItemId"));
  125. _saveChildrenCommand.Parameters.Add(new SQLiteParameter("@Type"));
  126. }
  127. /// <summary>
  128. /// Save a standard item in the repo
  129. /// </summary>
  130. /// <param name="item">The item.</param>
  131. /// <param name="cancellationToken">The cancellation token.</param>
  132. /// <returns>Task.</returns>
  133. /// <exception cref="System.ArgumentNullException">item</exception>
  134. public Task SaveItem(BaseItem item, CancellationToken cancellationToken)
  135. {
  136. if (item == null)
  137. {
  138. throw new ArgumentNullException("item");
  139. }
  140. return SaveItems(new[] { item }, cancellationToken);
  141. }
  142. /// <summary>
  143. /// Saves the items.
  144. /// </summary>
  145. /// <param name="items">The items.</param>
  146. /// <param name="cancellationToken">The cancellation token.</param>
  147. /// <returns>Task.</returns>
  148. /// <exception cref="System.ArgumentNullException">
  149. /// items
  150. /// or
  151. /// cancellationToken
  152. /// </exception>
  153. public async Task SaveItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  154. {
  155. if (items == null)
  156. {
  157. throw new ArgumentNullException("items");
  158. }
  159. if (cancellationToken == null)
  160. {
  161. throw new ArgumentNullException("cancellationToken");
  162. }
  163. cancellationToken.ThrowIfCancellationRequested();
  164. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  165. SQLiteTransaction transaction = null;
  166. try
  167. {
  168. transaction = _connection.BeginTransaction();
  169. foreach (var item in items)
  170. {
  171. cancellationToken.ThrowIfCancellationRequested();
  172. _saveItemCommand.Parameters[0].Value = item.Id;
  173. _saveItemCommand.Parameters[1].Value = _jsonSerializer.SerializeToBytes(item);
  174. _saveItemCommand.Transaction = transaction;
  175. await _saveItemCommand.ExecuteNonQueryAsync(cancellationToken);
  176. }
  177. transaction.Commit();
  178. }
  179. catch (OperationCanceledException)
  180. {
  181. if (transaction != null)
  182. {
  183. transaction.Rollback();
  184. }
  185. throw;
  186. }
  187. catch (Exception e)
  188. {
  189. _logger.ErrorException("Failed to save items:", e);
  190. if (transaction != null)
  191. {
  192. transaction.Rollback();
  193. }
  194. throw;
  195. }
  196. finally
  197. {
  198. if (transaction != null)
  199. {
  200. transaction.Dispose();
  201. }
  202. _writeLock.Release();
  203. }
  204. }
  205. /// <summary>
  206. /// Internal retrieve from items or users table
  207. /// </summary>
  208. /// <param name="id">The id.</param>
  209. /// <param name="type">The type.</param>
  210. /// <returns>BaseItem.</returns>
  211. /// <exception cref="System.ArgumentNullException">id</exception>
  212. /// <exception cref="System.ArgumentException"></exception>
  213. public BaseItem RetrieveItem(Guid id, Type type)
  214. {
  215. if (id == Guid.Empty)
  216. {
  217. throw new ArgumentNullException("id");
  218. }
  219. using (var cmd = _connection.CreateCommand())
  220. {
  221. cmd.CommandText = "select data from baseitems where guid = @guid";
  222. var guidParam = cmd.Parameters.Add("@guid", DbType.Guid);
  223. guidParam.Value = id;
  224. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  225. {
  226. if (reader.Read())
  227. {
  228. using (var stream = reader.GetMemoryStream(0))
  229. {
  230. return _jsonSerializer.DeserializeFromStream(stream, type) as BaseItem;
  231. }
  232. }
  233. }
  234. return null;
  235. }
  236. }
  237. /// <summary>
  238. /// Gets the critic reviews.
  239. /// </summary>
  240. /// <param name="itemId">The item id.</param>
  241. /// <returns>Task{IEnumerable{ItemReview}}.</returns>
  242. public Task<IEnumerable<ItemReview>> GetCriticReviews(Guid itemId)
  243. {
  244. return Task.Run<IEnumerable<ItemReview>>(() =>
  245. {
  246. try
  247. {
  248. var path = Path.Combine(_criticReviewsPath, itemId + ".json");
  249. return _jsonSerializer.DeserializeFromFile<List<ItemReview>>(path);
  250. }
  251. catch (DirectoryNotFoundException)
  252. {
  253. return new List<ItemReview>();
  254. }
  255. catch (FileNotFoundException)
  256. {
  257. return new List<ItemReview>();
  258. }
  259. });
  260. }
  261. /// <summary>
  262. /// Saves the critic reviews.
  263. /// </summary>
  264. /// <param name="itemId">The item id.</param>
  265. /// <param name="criticReviews">The critic reviews.</param>
  266. /// <returns>Task.</returns>
  267. public Task SaveCriticReviews(Guid itemId, IEnumerable<ItemReview> criticReviews)
  268. {
  269. return Task.Run(() =>
  270. {
  271. if (!Directory.Exists(_criticReviewsPath))
  272. {
  273. Directory.CreateDirectory(_criticReviewsPath);
  274. }
  275. var path = Path.Combine(_criticReviewsPath, itemId + ".json");
  276. _jsonSerializer.SerializeToFile(criticReviews.ToList(), path);
  277. });
  278. }
  279. /// <summary>
  280. /// Gets chapters for an item
  281. /// </summary>
  282. /// <param name="id">The id.</param>
  283. /// <returns>IEnumerable{ChapterInfo}.</returns>
  284. /// <exception cref="System.ArgumentNullException">id</exception>
  285. public IEnumerable<ChapterInfo> GetChapters(Guid id)
  286. {
  287. return _chapterRepository.GetChapters(id);
  288. }
  289. /// <summary>
  290. /// Gets a single chapter for an item
  291. /// </summary>
  292. /// <param name="id">The id.</param>
  293. /// <param name="index">The index.</param>
  294. /// <returns>ChapterInfo.</returns>
  295. /// <exception cref="System.ArgumentNullException">id</exception>
  296. public ChapterInfo GetChapter(Guid id, int index)
  297. {
  298. return _chapterRepository.GetChapter(id, index);
  299. }
  300. /// <summary>
  301. /// Saves the chapters.
  302. /// </summary>
  303. /// <param name="id">The id.</param>
  304. /// <param name="chapters">The chapters.</param>
  305. /// <param name="cancellationToken">The cancellation token.</param>
  306. /// <returns>Task.</returns>
  307. /// <exception cref="System.ArgumentNullException">
  308. /// id
  309. /// or
  310. /// chapters
  311. /// or
  312. /// cancellationToken
  313. /// </exception>
  314. public Task SaveChapters(Guid id, IEnumerable<ChapterInfo> chapters, CancellationToken cancellationToken)
  315. {
  316. return _chapterRepository.SaveChapters(id, chapters, cancellationToken);
  317. }
  318. /// <summary>
  319. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  320. /// </summary>
  321. public void Dispose()
  322. {
  323. Dispose(true);
  324. GC.SuppressFinalize(this);
  325. }
  326. private readonly object _disposeLock = new object();
  327. /// <summary>
  328. /// Releases unmanaged and - optionally - managed resources.
  329. /// </summary>
  330. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  331. protected virtual void Dispose(bool dispose)
  332. {
  333. if (dispose)
  334. {
  335. try
  336. {
  337. lock (_disposeLock)
  338. {
  339. if (_connection != null)
  340. {
  341. if (_connection.IsOpen())
  342. {
  343. _connection.Close();
  344. }
  345. _connection.Dispose();
  346. _connection = null;
  347. }
  348. }
  349. }
  350. catch (Exception ex)
  351. {
  352. _logger.ErrorException("Error disposing database", ex);
  353. }
  354. if (_chapterRepository != null)
  355. {
  356. _chapterRepository.Dispose();
  357. _chapterRepository = null;
  358. }
  359. }
  360. }
  361. public IEnumerable<ChildDefinition> GetChildren(Guid parentId)
  362. {
  363. if (parentId == Guid.Empty)
  364. {
  365. throw new ArgumentNullException("parentId");
  366. }
  367. using (var cmd = _connection.CreateCommand())
  368. {
  369. cmd.CommandText = "select ItemId,Type from ChildDefinitions where ParentId = @ParentId";
  370. cmd.Parameters.Add("@ParentId", DbType.Guid).Value = parentId;
  371. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  372. {
  373. while (reader.Read())
  374. {
  375. yield return new ChildDefinition
  376. {
  377. ItemId = reader.GetGuid(0),
  378. Type = reader.GetString(1)
  379. };
  380. }
  381. }
  382. }
  383. }
  384. public async Task SaveChildren(Guid parentId, IEnumerable<ChildDefinition> children, CancellationToken cancellationToken)
  385. {
  386. if (parentId == Guid.Empty)
  387. {
  388. throw new ArgumentNullException("parentId");
  389. }
  390. if (children == null)
  391. {
  392. throw new ArgumentNullException("children");
  393. }
  394. if (cancellationToken == null)
  395. {
  396. throw new ArgumentNullException("cancellationToken");
  397. }
  398. cancellationToken.ThrowIfCancellationRequested();
  399. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  400. SQLiteTransaction transaction = null;
  401. try
  402. {
  403. transaction = _connection.BeginTransaction();
  404. // First delete
  405. _deleteChildrenCommand.Parameters[0].Value = parentId;
  406. _deleteChildrenCommand.Transaction = transaction;
  407. await _deleteChildrenCommand.ExecuteNonQueryAsync(cancellationToken);
  408. foreach (var chapter in children)
  409. {
  410. cancellationToken.ThrowIfCancellationRequested();
  411. _saveChildrenCommand.Parameters[0].Value = parentId;
  412. _saveChildrenCommand.Parameters[1].Value = chapter.ItemId;
  413. _saveChildrenCommand.Parameters[2].Value = chapter.Type;
  414. _saveChildrenCommand.Transaction = transaction;
  415. await _saveChildrenCommand.ExecuteNonQueryAsync(cancellationToken);
  416. }
  417. transaction.Commit();
  418. }
  419. catch (OperationCanceledException)
  420. {
  421. if (transaction != null)
  422. {
  423. transaction.Rollback();
  424. }
  425. throw;
  426. }
  427. catch (Exception e)
  428. {
  429. _logger.ErrorException("Failed to save children:", e);
  430. if (transaction != null)
  431. {
  432. transaction.Rollback();
  433. }
  434. throw;
  435. }
  436. finally
  437. {
  438. if (transaction != null)
  439. {
  440. transaction.Dispose();
  441. }
  442. _writeLock.Release();
  443. }
  444. }
  445. }
  446. }