SqliteItemRepository.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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. }
  108. /// <summary>
  109. /// The _write lock
  110. /// </summary>
  111. private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
  112. /// <summary>
  113. /// Prepares the statements.
  114. /// </summary>
  115. private void PrepareStatements()
  116. {
  117. _saveItemCommand = _connection.CreateCommand();
  118. _saveItemCommand.CommandText = "replace into TypedBaseItems (guid, type, data) values (@1, @2, @3)";
  119. _saveItemCommand.Parameters.Add(_saveItemCommand, "@1");
  120. _saveItemCommand.Parameters.Add(_saveItemCommand, "@2");
  121. _saveItemCommand.Parameters.Add(_saveItemCommand, "@3");
  122. _deleteChildrenCommand = _connection.CreateCommand();
  123. _deleteChildrenCommand.CommandText = "delete from ChildrenIds where ParentId=@ParentId";
  124. _deleteChildrenCommand.Parameters.Add(_deleteChildrenCommand, "@ParentId");
  125. _deleteItemCommand = _connection.CreateCommand();
  126. _deleteItemCommand.CommandText = "delete from TypedBaseItems where guid=@Id";
  127. _deleteItemCommand.Parameters.Add(_deleteItemCommand, "@Id");
  128. _saveChildrenCommand = _connection.CreateCommand();
  129. _saveChildrenCommand.CommandText = "replace into ChildrenIds (ParentId, ItemId) values (@ParentId, @ItemId)";
  130. _saveChildrenCommand.Parameters.Add(_saveChildrenCommand, "@ParentId");
  131. _saveChildrenCommand.Parameters.Add(_saveChildrenCommand, "@ItemId");
  132. }
  133. /// <summary>
  134. /// Save a standard item in the repo
  135. /// </summary>
  136. /// <param name="item">The item.</param>
  137. /// <param name="cancellationToken">The cancellation token.</param>
  138. /// <returns>Task.</returns>
  139. /// <exception cref="System.ArgumentNullException">item</exception>
  140. public Task SaveItem(BaseItem item, CancellationToken cancellationToken)
  141. {
  142. if (item == null)
  143. {
  144. throw new ArgumentNullException("item");
  145. }
  146. return SaveItems(new[] { item }, cancellationToken);
  147. }
  148. /// <summary>
  149. /// Saves the items.
  150. /// </summary>
  151. /// <param name="items">The items.</param>
  152. /// <param name="cancellationToken">The cancellation token.</param>
  153. /// <returns>Task.</returns>
  154. /// <exception cref="System.ArgumentNullException">
  155. /// items
  156. /// or
  157. /// cancellationToken
  158. /// </exception>
  159. public async Task SaveItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  160. {
  161. if (items == null)
  162. {
  163. throw new ArgumentNullException("items");
  164. }
  165. cancellationToken.ThrowIfCancellationRequested();
  166. CheckDisposed();
  167. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  168. IDbTransaction transaction = null;
  169. try
  170. {
  171. transaction = _connection.BeginTransaction();
  172. foreach (var item in items)
  173. {
  174. cancellationToken.ThrowIfCancellationRequested();
  175. _saveItemCommand.GetParameter(0).Value = item.Id;
  176. _saveItemCommand.GetParameter(1).Value = item.GetType().FullName;
  177. _saveItemCommand.GetParameter(2).Value = _jsonSerializer.SerializeToBytes(item);
  178. _saveItemCommand.Transaction = transaction;
  179. _saveItemCommand.ExecuteNonQuery();
  180. }
  181. transaction.Commit();
  182. }
  183. catch (OperationCanceledException)
  184. {
  185. if (transaction != null)
  186. {
  187. transaction.Rollback();
  188. }
  189. throw;
  190. }
  191. catch (Exception e)
  192. {
  193. _logger.ErrorException("Failed to save items:", e);
  194. if (transaction != null)
  195. {
  196. transaction.Rollback();
  197. }
  198. throw;
  199. }
  200. finally
  201. {
  202. if (transaction != null)
  203. {
  204. transaction.Dispose();
  205. }
  206. _writeLock.Release();
  207. }
  208. }
  209. /// <summary>
  210. /// Internal retrieve from items or users table
  211. /// </summary>
  212. /// <param name="id">The id.</param>
  213. /// <returns>BaseItem.</returns>
  214. /// <exception cref="System.ArgumentNullException">id</exception>
  215. /// <exception cref="System.ArgumentException"></exception>
  216. public BaseItem RetrieveItem(Guid id)
  217. {
  218. if (id == Guid.Empty)
  219. {
  220. throw new ArgumentNullException("id");
  221. }
  222. CheckDisposed();
  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. CheckDisposed();
  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. CheckDisposed();
  307. return _chapterRepository.GetChapter(id, index);
  308. }
  309. /// <summary>
  310. /// Saves the chapters.
  311. /// </summary>
  312. /// <param name="id">The id.</param>
  313. /// <param name="chapters">The chapters.</param>
  314. /// <param name="cancellationToken">The cancellation token.</param>
  315. /// <returns>Task.</returns>
  316. /// <exception cref="System.ArgumentNullException">
  317. /// id
  318. /// or
  319. /// chapters
  320. /// or
  321. /// cancellationToken
  322. /// </exception>
  323. public Task SaveChapters(Guid id, IEnumerable<ChapterInfo> chapters, CancellationToken cancellationToken)
  324. {
  325. CheckDisposed();
  326. return _chapterRepository.SaveChapters(id, chapters, cancellationToken);
  327. }
  328. /// <summary>
  329. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  330. /// </summary>
  331. public void Dispose()
  332. {
  333. Dispose(true);
  334. GC.SuppressFinalize(this);
  335. }
  336. private readonly object _disposeLock = new object();
  337. private bool _disposed;
  338. private void CheckDisposed()
  339. {
  340. if (_disposed)
  341. {
  342. throw new ObjectDisposedException(GetType().Name + " has been disposed and cannot be accessed.");
  343. }
  344. }
  345. /// <summary>
  346. /// Releases unmanaged and - optionally - managed resources.
  347. /// </summary>
  348. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  349. protected virtual void Dispose(bool dispose)
  350. {
  351. if (dispose)
  352. {
  353. _disposed = true;
  354. try
  355. {
  356. lock (_disposeLock)
  357. {
  358. _writeLock.Wait();
  359. if (_connection != null)
  360. {
  361. if (_connection.IsOpen())
  362. {
  363. _connection.Close();
  364. }
  365. _connection.Dispose();
  366. _connection = null;
  367. }
  368. if (_chapterRepository != null)
  369. {
  370. _chapterRepository.Dispose();
  371. _chapterRepository = null;
  372. }
  373. if (_mediaStreamsRepository != null)
  374. {
  375. _mediaStreamsRepository.Dispose();
  376. _mediaStreamsRepository = null;
  377. }
  378. }
  379. }
  380. catch (Exception ex)
  381. {
  382. _logger.ErrorException("Error disposing database", ex);
  383. }
  384. }
  385. }
  386. public IEnumerable<Guid> GetChildren(Guid parentId)
  387. {
  388. if (parentId == Guid.Empty)
  389. {
  390. throw new ArgumentNullException("parentId");
  391. }
  392. CheckDisposed();
  393. using (var cmd = _connection.CreateCommand())
  394. {
  395. cmd.CommandText = "select ItemId from ChildrenIds where ParentId = @ParentId";
  396. cmd.Parameters.Add(cmd, "@ParentId", DbType.Guid).Value = parentId;
  397. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  398. {
  399. while (reader.Read())
  400. {
  401. yield return reader.GetGuid(0);
  402. }
  403. }
  404. }
  405. }
  406. public IEnumerable<BaseItem> GetChildrenItems(Guid parentId)
  407. {
  408. if (parentId == Guid.Empty)
  409. {
  410. throw new ArgumentNullException("parentId");
  411. }
  412. CheckDisposed();
  413. using (var cmd = _connection.CreateCommand())
  414. {
  415. cmd.CommandText = "select type,data from TypedBaseItems where guid in (select ItemId from ChildrenIds where ParentId = @ParentId)";
  416. cmd.Parameters.Add(cmd, "@ParentId", DbType.Guid).Value = parentId;
  417. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  418. {
  419. while (reader.Read())
  420. {
  421. var item = GetItem(reader);
  422. if (item != null)
  423. {
  424. yield return item;
  425. }
  426. }
  427. }
  428. }
  429. }
  430. public IEnumerable<BaseItem> GetItemsOfType(Type type)
  431. {
  432. if (type == null)
  433. {
  434. throw new ArgumentNullException("type");
  435. }
  436. CheckDisposed();
  437. using (var cmd = _connection.CreateCommand())
  438. {
  439. cmd.CommandText = "select type,data from TypedBaseItems where type = @type";
  440. cmd.Parameters.Add(cmd, "@type", DbType.String).Value = type.FullName;
  441. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  442. {
  443. while (reader.Read())
  444. {
  445. var item = GetItem(reader);
  446. if (item != null)
  447. {
  448. yield return item;
  449. }
  450. }
  451. }
  452. }
  453. }
  454. public IEnumerable<Guid> GetItemIdsOfType(Type type)
  455. {
  456. if (type == null)
  457. {
  458. throw new ArgumentNullException("type");
  459. }
  460. CheckDisposed();
  461. using (var cmd = _connection.CreateCommand())
  462. {
  463. cmd.CommandText = "select guid from TypedBaseItems where type = @type";
  464. cmd.Parameters.Add(cmd, "@type", DbType.String).Value = type.FullName;
  465. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  466. {
  467. while (reader.Read())
  468. {
  469. yield return reader.GetGuid(0);
  470. }
  471. }
  472. }
  473. }
  474. public async Task DeleteItem(Guid id, CancellationToken cancellationToken)
  475. {
  476. if (id == Guid.Empty)
  477. {
  478. throw new ArgumentNullException("id");
  479. }
  480. CheckDisposed();
  481. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  482. IDbTransaction transaction = null;
  483. try
  484. {
  485. transaction = _connection.BeginTransaction();
  486. // First delete children
  487. _deleteChildrenCommand.GetParameter(0).Value = id;
  488. _deleteChildrenCommand.Transaction = transaction;
  489. _deleteChildrenCommand.ExecuteNonQuery();
  490. // Delete the item
  491. _deleteItemCommand.GetParameter(0).Value = id;
  492. _deleteItemCommand.Transaction = transaction;
  493. _deleteItemCommand.ExecuteNonQuery();
  494. transaction.Commit();
  495. }
  496. catch (OperationCanceledException)
  497. {
  498. if (transaction != null)
  499. {
  500. transaction.Rollback();
  501. }
  502. throw;
  503. }
  504. catch (Exception e)
  505. {
  506. _logger.ErrorException("Failed to save children:", e);
  507. if (transaction != null)
  508. {
  509. transaction.Rollback();
  510. }
  511. throw;
  512. }
  513. finally
  514. {
  515. if (transaction != null)
  516. {
  517. transaction.Dispose();
  518. }
  519. _writeLock.Release();
  520. }
  521. }
  522. public async Task SaveChildren(Guid parentId, IEnumerable<Guid> children, CancellationToken cancellationToken)
  523. {
  524. if (parentId == Guid.Empty)
  525. {
  526. throw new ArgumentNullException("parentId");
  527. }
  528. if (children == null)
  529. {
  530. throw new ArgumentNullException("children");
  531. }
  532. CheckDisposed();
  533. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  534. IDbTransaction transaction = null;
  535. try
  536. {
  537. transaction = _connection.BeginTransaction();
  538. // First delete
  539. _deleteChildrenCommand.GetParameter(0).Value = parentId;
  540. _deleteChildrenCommand.Transaction = transaction;
  541. _deleteChildrenCommand.ExecuteNonQuery();
  542. foreach (var id in children)
  543. {
  544. cancellationToken.ThrowIfCancellationRequested();
  545. _saveChildrenCommand.GetParameter(0).Value = parentId;
  546. _saveChildrenCommand.GetParameter(1).Value = id;
  547. _saveChildrenCommand.Transaction = transaction;
  548. _saveChildrenCommand.ExecuteNonQuery();
  549. }
  550. transaction.Commit();
  551. }
  552. catch (OperationCanceledException)
  553. {
  554. if (transaction != null)
  555. {
  556. transaction.Rollback();
  557. }
  558. throw;
  559. }
  560. catch (Exception e)
  561. {
  562. _logger.ErrorException("Failed to save children:", e);
  563. if (transaction != null)
  564. {
  565. transaction.Rollback();
  566. }
  567. throw;
  568. }
  569. finally
  570. {
  571. if (transaction != null)
  572. {
  573. transaction.Dispose();
  574. }
  575. _writeLock.Release();
  576. }
  577. }
  578. public IEnumerable<MediaStream> GetMediaStreams(MediaStreamQuery query)
  579. {
  580. CheckDisposed();
  581. return _mediaStreamsRepository.GetMediaStreams(query);
  582. }
  583. public Task SaveMediaStreams(Guid id, IEnumerable<MediaStream> streams, CancellationToken cancellationToken)
  584. {
  585. CheckDisposed();
  586. return _mediaStreamsRepository.SaveMediaStreams(id, streams, cancellationToken);
  587. }
  588. }
  589. }