SqliteItemRepository.cs 22 KB

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