SqliteItemRepository.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  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.IO;
  11. using System.Linq;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Server.Implementations.Persistence
  15. {
  16. /// <summary>
  17. /// Class SQLiteItemRepository
  18. /// </summary>
  19. public class SqliteItemRepository : IItemRepository
  20. {
  21. private IDbConnection _connection;
  22. private readonly ILogger _logger;
  23. private readonly TypeMapper _typeMapper = new TypeMapper();
  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 IDbCommand _saveItemCommand;
  48. private readonly string _criticReviewsPath;
  49. private SqliteChapterRepository _chapterRepository;
  50. private SqliteMediaStreamsRepository _mediaStreamsRepository;
  51. private IDbCommand _deleteChildrenCommand;
  52. private IDbCommand _saveChildrenCommand;
  53. private IDbCommand _deleteItemCommand;
  54. /// <summary>
  55. /// Initializes a new instance of the <see cref="SqliteItemRepository"/> class.
  56. /// </summary>
  57. /// <param name="appPaths">The app paths.</param>
  58. /// <param name="jsonSerializer">The json serializer.</param>
  59. /// <param name="logManager">The log manager.</param>
  60. /// <exception cref="System.ArgumentNullException">
  61. /// appPaths
  62. /// or
  63. /// jsonSerializer
  64. /// </exception>
  65. public SqliteItemRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
  66. {
  67. if (appPaths == null)
  68. {
  69. throw new ArgumentNullException("appPaths");
  70. }
  71. if (jsonSerializer == null)
  72. {
  73. throw new ArgumentNullException("jsonSerializer");
  74. }
  75. _appPaths = appPaths;
  76. _jsonSerializer = jsonSerializer;
  77. _criticReviewsPath = Path.Combine(_appPaths.DataPath, "critic-reviews");
  78. _logger = logManager.GetLogger(GetType().Name);
  79. var chapterDbFile = Path.Combine(_appPaths.DataPath, "chapters.db");
  80. var chapterConnection = SqliteExtensions.ConnectToDb(chapterDbFile, _logger).Result;
  81. _chapterRepository = new SqliteChapterRepository(chapterConnection, logManager);
  82. var mediaStreamsDbFile = Path.Combine(_appPaths.DataPath, "mediainfo.db");
  83. var mediaStreamsConnection = SqliteExtensions.ConnectToDb(mediaStreamsDbFile, _logger).Result;
  84. _mediaStreamsRepository = new SqliteMediaStreamsRepository(mediaStreamsConnection, logManager);
  85. }
  86. /// <summary>
  87. /// Opens the connection to the database
  88. /// </summary>
  89. /// <returns>Task.</returns>
  90. public async Task Initialize()
  91. {
  92. var dbFile = Path.Combine(_appPaths.DataPath, "library.db");
  93. _connection = await SqliteExtensions.ConnectToDb(dbFile, _logger).ConfigureAwait(false);
  94. string[] queries = {
  95. "create table if not exists TypedBaseItems (guid GUID primary key, type TEXT, data BLOB)",
  96. "create index if not exists idx_TypedBaseItems on TypedBaseItems(guid)",
  97. "create table if not exists ChildrenIds (ParentId GUID, ItemId GUID, PRIMARY KEY (ParentId, ItemId))",
  98. "create index if not exists idx_ChildrenIds on ChildrenIds(ParentId,ItemId)",
  99. //pragmas
  100. "pragma temp_store = memory",
  101. "pragma shrink_memory"
  102. };
  103. _connection.RunQueries(queries, _logger);
  104. PrepareStatements();
  105. _mediaStreamsRepository.Initialize();
  106. _chapterRepository.Initialize();
  107. _shrinkMemoryTimer = new SqliteShrinkMemoryTimer(_connection, _writeLock, _logger);
  108. }
  109. private SqliteShrinkMemoryTimer _shrinkMemoryTimer;
  110. /// <summary>
  111. /// The _write lock
  112. /// </summary>
  113. private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
  114. /// <summary>
  115. /// Prepares the statements.
  116. /// </summary>
  117. private void PrepareStatements()
  118. {
  119. _saveItemCommand = _connection.CreateCommand();
  120. _saveItemCommand.CommandText = "replace into TypedBaseItems (guid, type, data) values (@1, @2, @3)";
  121. _saveItemCommand.Parameters.Add(_saveItemCommand, "@1");
  122. _saveItemCommand.Parameters.Add(_saveItemCommand, "@2");
  123. _saveItemCommand.Parameters.Add(_saveItemCommand, "@3");
  124. _deleteChildrenCommand = _connection.CreateCommand();
  125. _deleteChildrenCommand.CommandText = "delete from ChildrenIds where ParentId=@ParentId";
  126. _deleteChildrenCommand.Parameters.Add(_deleteChildrenCommand, "@ParentId");
  127. _deleteItemCommand = _connection.CreateCommand();
  128. _deleteItemCommand.CommandText = "delete from TypedBaseItems where guid=@Id";
  129. _deleteItemCommand.Parameters.Add(_deleteItemCommand, "@Id");
  130. _saveChildrenCommand = _connection.CreateCommand();
  131. _saveChildrenCommand.CommandText = "replace into ChildrenIds (ParentId, ItemId) values (@ParentId, @ItemId)";
  132. _saveChildrenCommand.Parameters.Add(_saveChildrenCommand, "@ParentId");
  133. _saveChildrenCommand.Parameters.Add(_saveChildrenCommand, "@ItemId");
  134. }
  135. /// <summary>
  136. /// Save a standard item in the repo
  137. /// </summary>
  138. /// <param name="item">The item.</param>
  139. /// <param name="cancellationToken">The cancellation token.</param>
  140. /// <returns>Task.</returns>
  141. /// <exception cref="System.ArgumentNullException">item</exception>
  142. public Task SaveItem(BaseItem item, CancellationToken cancellationToken)
  143. {
  144. if (item == null)
  145. {
  146. throw new ArgumentNullException("item");
  147. }
  148. return SaveItems(new[] { item }, cancellationToken);
  149. }
  150. /// <summary>
  151. /// Saves the items.
  152. /// </summary>
  153. /// <param name="items">The items.</param>
  154. /// <param name="cancellationToken">The cancellation token.</param>
  155. /// <returns>Task.</returns>
  156. /// <exception cref="System.ArgumentNullException">
  157. /// items
  158. /// or
  159. /// cancellationToken
  160. /// </exception>
  161. public async Task SaveItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  162. {
  163. if (items == null)
  164. {
  165. throw new ArgumentNullException("items");
  166. }
  167. cancellationToken.ThrowIfCancellationRequested();
  168. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  169. IDbTransaction transaction = null;
  170. try
  171. {
  172. transaction = _connection.BeginTransaction();
  173. foreach (var item in items)
  174. {
  175. cancellationToken.ThrowIfCancellationRequested();
  176. _saveItemCommand.GetParameter(0).Value = item.Id;
  177. _saveItemCommand.GetParameter(1).Value = item.GetType().FullName;
  178. _saveItemCommand.GetParameter(2).Value = _jsonSerializer.SerializeToBytes(item);
  179. _saveItemCommand.Transaction = transaction;
  180. _saveItemCommand.ExecuteNonQuery();
  181. }
  182. transaction.Commit();
  183. }
  184. catch (OperationCanceledException)
  185. {
  186. if (transaction != null)
  187. {
  188. transaction.Rollback();
  189. }
  190. throw;
  191. }
  192. catch (Exception e)
  193. {
  194. _logger.ErrorException("Failed to save items:", e);
  195. if (transaction != null)
  196. {
  197. transaction.Rollback();
  198. }
  199. throw;
  200. }
  201. finally
  202. {
  203. if (transaction != null)
  204. {
  205. transaction.Dispose();
  206. }
  207. _writeLock.Release();
  208. }
  209. }
  210. /// <summary>
  211. /// Internal retrieve from items or users table
  212. /// </summary>
  213. /// <param name="id">The id.</param>
  214. /// <returns>BaseItem.</returns>
  215. /// <exception cref="System.ArgumentNullException">id</exception>
  216. /// <exception cref="System.ArgumentException"></exception>
  217. public BaseItem RetrieveItem(Guid id)
  218. {
  219. if (id == Guid.Empty)
  220. {
  221. throw new ArgumentNullException("id");
  222. }
  223. using (var cmd = _connection.CreateCommand())
  224. {
  225. cmd.CommandText = "select type,data from TypedBaseItems where guid = @guid";
  226. cmd.Parameters.Add(cmd, "@guid", DbType.Guid).Value = id;
  227. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  228. {
  229. if (reader.Read())
  230. {
  231. return GetItem(reader);
  232. }
  233. }
  234. return null;
  235. }
  236. }
  237. private BaseItem GetItem(IDataReader reader)
  238. {
  239. var typeString = reader.GetString(0);
  240. var type = _typeMapper.GetType(typeString);
  241. if (type == null)
  242. {
  243. _logger.Debug("Unknown type {0}", typeString);
  244. return null;
  245. }
  246. using (var stream = reader.GetMemoryStream(1))
  247. {
  248. return _jsonSerializer.DeserializeFromStream(stream, type) as BaseItem;
  249. }
  250. }
  251. /// <summary>
  252. /// Gets the critic reviews.
  253. /// </summary>
  254. /// <param name="itemId">The item id.</param>
  255. /// <returns>Task{IEnumerable{ItemReview}}.</returns>
  256. public IEnumerable<ItemReview> GetCriticReviews(Guid itemId)
  257. {
  258. try
  259. {
  260. var path = Path.Combine(_criticReviewsPath, itemId + ".json");
  261. return _jsonSerializer.DeserializeFromFile<List<ItemReview>>(path);
  262. }
  263. catch (DirectoryNotFoundException)
  264. {
  265. return new List<ItemReview>();
  266. }
  267. catch (FileNotFoundException)
  268. {
  269. return new List<ItemReview>();
  270. }
  271. }
  272. private readonly Task _cachedTask = Task.FromResult(true);
  273. /// <summary>
  274. /// Saves the critic reviews.
  275. /// </summary>
  276. /// <param name="itemId">The item id.</param>
  277. /// <param name="criticReviews">The critic reviews.</param>
  278. /// <returns>Task.</returns>
  279. public Task SaveCriticReviews(Guid itemId, IEnumerable<ItemReview> criticReviews)
  280. {
  281. Directory.CreateDirectory(_criticReviewsPath);
  282. var path = Path.Combine(_criticReviewsPath, itemId + ".json");
  283. _jsonSerializer.SerializeToFile(criticReviews.ToList(), path);
  284. return _cachedTask;
  285. }
  286. /// <summary>
  287. /// Gets chapters for an item
  288. /// </summary>
  289. /// <param name="id">The id.</param>
  290. /// <returns>IEnumerable{ChapterInfo}.</returns>
  291. /// <exception cref="System.ArgumentNullException">id</exception>
  292. public IEnumerable<ChapterInfo> GetChapters(Guid id)
  293. {
  294. return _chapterRepository.GetChapters(id);
  295. }
  296. /// <summary>
  297. /// Gets a single chapter for an item
  298. /// </summary>
  299. /// <param name="id">The id.</param>
  300. /// <param name="index">The index.</param>
  301. /// <returns>ChapterInfo.</returns>
  302. /// <exception cref="System.ArgumentNullException">id</exception>
  303. public ChapterInfo GetChapter(Guid id, int index)
  304. {
  305. return _chapterRepository.GetChapter(id, index);
  306. }
  307. /// <summary>
  308. /// Saves the chapters.
  309. /// </summary>
  310. /// <param name="id">The id.</param>
  311. /// <param name="chapters">The chapters.</param>
  312. /// <param name="cancellationToken">The cancellation token.</param>
  313. /// <returns>Task.</returns>
  314. /// <exception cref="System.ArgumentNullException">
  315. /// id
  316. /// or
  317. /// chapters
  318. /// or
  319. /// cancellationToken
  320. /// </exception>
  321. public Task SaveChapters(Guid id, IEnumerable<ChapterInfo> chapters, CancellationToken cancellationToken)
  322. {
  323. return _chapterRepository.SaveChapters(id, chapters, cancellationToken);
  324. }
  325. /// <summary>
  326. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  327. /// </summary>
  328. public void Dispose()
  329. {
  330. Dispose(true);
  331. GC.SuppressFinalize(this);
  332. }
  333. private readonly object _disposeLock = new object();
  334. /// <summary>
  335. /// Releases unmanaged and - optionally - managed resources.
  336. /// </summary>
  337. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  338. protected virtual void Dispose(bool dispose)
  339. {
  340. if (dispose)
  341. {
  342. try
  343. {
  344. lock (_disposeLock)
  345. {
  346. if (_shrinkMemoryTimer != null)
  347. {
  348. _shrinkMemoryTimer.Dispose();
  349. _shrinkMemoryTimer = null;
  350. }
  351. if (_connection != null)
  352. {
  353. if (_connection.IsOpen())
  354. {
  355. _connection.Close();
  356. }
  357. _connection.Dispose();
  358. _connection = null;
  359. }
  360. if (_chapterRepository != null)
  361. {
  362. _chapterRepository.Dispose();
  363. _chapterRepository = null;
  364. }
  365. if (_mediaStreamsRepository != null)
  366. {
  367. _mediaStreamsRepository.Dispose();
  368. _mediaStreamsRepository = null;
  369. }
  370. }
  371. }
  372. catch (Exception ex)
  373. {
  374. _logger.ErrorException("Error disposing database", ex);
  375. }
  376. }
  377. }
  378. public IEnumerable<Guid> GetChildren(Guid parentId)
  379. {
  380. if (parentId == Guid.Empty)
  381. {
  382. throw new ArgumentNullException("parentId");
  383. }
  384. using (var cmd = _connection.CreateCommand())
  385. {
  386. cmd.CommandText = "select ItemId from ChildrenIds where ParentId = @ParentId";
  387. cmd.Parameters.Add(cmd, "@ParentId", DbType.Guid).Value = parentId;
  388. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  389. {
  390. while (reader.Read())
  391. {
  392. yield return reader.GetGuid(0);
  393. }
  394. }
  395. }
  396. }
  397. public IEnumerable<BaseItem> GetChildrenItems(Guid parentId)
  398. {
  399. if (parentId == Guid.Empty)
  400. {
  401. throw new ArgumentNullException("parentId");
  402. }
  403. using (var cmd = _connection.CreateCommand())
  404. {
  405. cmd.CommandText = "select type,data from TypedBaseItems where guid in (select ItemId from ChildrenIds where ParentId = @ParentId)";
  406. cmd.Parameters.Add(cmd, "@ParentId", DbType.Guid).Value = parentId;
  407. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  408. {
  409. while (reader.Read())
  410. {
  411. var item = GetItem(reader);
  412. if (item != null)
  413. {
  414. yield return item;
  415. }
  416. }
  417. }
  418. }
  419. }
  420. public IEnumerable<BaseItem> GetItemsOfType(Type type)
  421. {
  422. if (type == null)
  423. {
  424. throw new ArgumentNullException("type");
  425. }
  426. using (var cmd = _connection.CreateCommand())
  427. {
  428. cmd.CommandText = "select type,data from TypedBaseItems where type = @type";
  429. cmd.Parameters.Add(cmd, "@type", DbType.String).Value = type.FullName;
  430. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  431. {
  432. while (reader.Read())
  433. {
  434. var item = GetItem(reader);
  435. if (item != null)
  436. {
  437. yield return item;
  438. }
  439. }
  440. }
  441. }
  442. }
  443. public async Task DeleteItem(Guid id, CancellationToken cancellationToken)
  444. {
  445. if (id == Guid.Empty)
  446. {
  447. throw new ArgumentNullException("id");
  448. }
  449. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  450. IDbTransaction transaction = null;
  451. try
  452. {
  453. transaction = _connection.BeginTransaction();
  454. // First delete children
  455. _deleteChildrenCommand.GetParameter(0).Value = id;
  456. _deleteChildrenCommand.Transaction = transaction;
  457. _deleteChildrenCommand.ExecuteNonQuery();
  458. // Delete the item
  459. _deleteItemCommand.GetParameter(0).Value = id;
  460. _deleteItemCommand.Transaction = transaction;
  461. _deleteItemCommand.ExecuteNonQuery();
  462. transaction.Commit();
  463. }
  464. catch (OperationCanceledException)
  465. {
  466. if (transaction != null)
  467. {
  468. transaction.Rollback();
  469. }
  470. throw;
  471. }
  472. catch (Exception e)
  473. {
  474. _logger.ErrorException("Failed to save children:", e);
  475. if (transaction != null)
  476. {
  477. transaction.Rollback();
  478. }
  479. throw;
  480. }
  481. finally
  482. {
  483. if (transaction != null)
  484. {
  485. transaction.Dispose();
  486. }
  487. _writeLock.Release();
  488. }
  489. }
  490. public async Task SaveChildren(Guid parentId, IEnumerable<Guid> children, CancellationToken cancellationToken)
  491. {
  492. if (parentId == Guid.Empty)
  493. {
  494. throw new ArgumentNullException("parentId");
  495. }
  496. if (children == null)
  497. {
  498. throw new ArgumentNullException("children");
  499. }
  500. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  501. IDbTransaction transaction = null;
  502. try
  503. {
  504. transaction = _connection.BeginTransaction();
  505. // First delete
  506. _deleteChildrenCommand.GetParameter(0).Value = parentId;
  507. _deleteChildrenCommand.Transaction = transaction;
  508. _deleteChildrenCommand.ExecuteNonQuery();
  509. foreach (var id in children)
  510. {
  511. cancellationToken.ThrowIfCancellationRequested();
  512. _saveChildrenCommand.GetParameter(0).Value = parentId;
  513. _saveChildrenCommand.GetParameter(1).Value = id;
  514. _saveChildrenCommand.Transaction = transaction;
  515. _saveChildrenCommand.ExecuteNonQuery();
  516. }
  517. transaction.Commit();
  518. }
  519. catch (OperationCanceledException)
  520. {
  521. if (transaction != null)
  522. {
  523. transaction.Rollback();
  524. }
  525. throw;
  526. }
  527. catch (Exception e)
  528. {
  529. _logger.ErrorException("Failed to save children:", e);
  530. if (transaction != null)
  531. {
  532. transaction.Rollback();
  533. }
  534. throw;
  535. }
  536. finally
  537. {
  538. if (transaction != null)
  539. {
  540. transaction.Dispose();
  541. }
  542. _writeLock.Release();
  543. }
  544. }
  545. public IEnumerable<MediaStream> GetMediaStreams(MediaStreamQuery query)
  546. {
  547. return _mediaStreamsRepository.GetMediaStreams(query);
  548. }
  549. public Task SaveMediaStreams(Guid id, IEnumerable<MediaStream> streams, CancellationToken cancellationToken)
  550. {
  551. return _mediaStreamsRepository.SaveMediaStreams(id, streams, cancellationToken);
  552. }
  553. }
  554. }