SqliteItemRepository.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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. CheckDisposed();
  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. CheckDisposed();
  225. using (var cmd = _connection.CreateCommand())
  226. {
  227. cmd.CommandText = "select type,data from TypedBaseItems where guid = @guid";
  228. cmd.Parameters.Add(cmd, "@guid", DbType.Guid).Value = id;
  229. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  230. {
  231. if (reader.Read())
  232. {
  233. return GetItem(reader);
  234. }
  235. }
  236. return null;
  237. }
  238. }
  239. private BaseItem GetItem(IDataReader reader)
  240. {
  241. var typeString = reader.GetString(0);
  242. var type = _typeMapper.GetType(typeString);
  243. if (type == null)
  244. {
  245. _logger.Debug("Unknown type {0}", typeString);
  246. return null;
  247. }
  248. using (var stream = reader.GetMemoryStream(1))
  249. {
  250. return _jsonSerializer.DeserializeFromStream(stream, type) as BaseItem;
  251. }
  252. }
  253. /// <summary>
  254. /// Gets the critic reviews.
  255. /// </summary>
  256. /// <param name="itemId">The item id.</param>
  257. /// <returns>Task{IEnumerable{ItemReview}}.</returns>
  258. public IEnumerable<ItemReview> GetCriticReviews(Guid itemId)
  259. {
  260. try
  261. {
  262. var path = Path.Combine(_criticReviewsPath, itemId + ".json");
  263. return _jsonSerializer.DeserializeFromFile<List<ItemReview>>(path);
  264. }
  265. catch (DirectoryNotFoundException)
  266. {
  267. return new List<ItemReview>();
  268. }
  269. catch (FileNotFoundException)
  270. {
  271. return new List<ItemReview>();
  272. }
  273. }
  274. private readonly Task _cachedTask = Task.FromResult(true);
  275. /// <summary>
  276. /// Saves the critic reviews.
  277. /// </summary>
  278. /// <param name="itemId">The item id.</param>
  279. /// <param name="criticReviews">The critic reviews.</param>
  280. /// <returns>Task.</returns>
  281. public Task SaveCriticReviews(Guid itemId, IEnumerable<ItemReview> criticReviews)
  282. {
  283. Directory.CreateDirectory(_criticReviewsPath);
  284. var path = Path.Combine(_criticReviewsPath, itemId + ".json");
  285. _jsonSerializer.SerializeToFile(criticReviews.ToList(), path);
  286. return _cachedTask;
  287. }
  288. /// <summary>
  289. /// Gets chapters for an item
  290. /// </summary>
  291. /// <param name="id">The id.</param>
  292. /// <returns>IEnumerable{ChapterInfo}.</returns>
  293. /// <exception cref="System.ArgumentNullException">id</exception>
  294. public IEnumerable<ChapterInfo> GetChapters(Guid id)
  295. {
  296. CheckDisposed();
  297. return _chapterRepository.GetChapters(id);
  298. }
  299. /// <summary>
  300. /// Gets a single chapter for an item
  301. /// </summary>
  302. /// <param name="id">The id.</param>
  303. /// <param name="index">The index.</param>
  304. /// <returns>ChapterInfo.</returns>
  305. /// <exception cref="System.ArgumentNullException">id</exception>
  306. public ChapterInfo GetChapter(Guid id, int index)
  307. {
  308. CheckDisposed();
  309. return _chapterRepository.GetChapter(id, index);
  310. }
  311. /// <summary>
  312. /// Saves the chapters.
  313. /// </summary>
  314. /// <param name="id">The id.</param>
  315. /// <param name="chapters">The chapters.</param>
  316. /// <param name="cancellationToken">The cancellation token.</param>
  317. /// <returns>Task.</returns>
  318. /// <exception cref="System.ArgumentNullException">
  319. /// id
  320. /// or
  321. /// chapters
  322. /// or
  323. /// cancellationToken
  324. /// </exception>
  325. public Task SaveChapters(Guid id, IEnumerable<ChapterInfo> chapters, CancellationToken cancellationToken)
  326. {
  327. CheckDisposed();
  328. return _chapterRepository.SaveChapters(id, chapters, cancellationToken);
  329. }
  330. /// <summary>
  331. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  332. /// </summary>
  333. public void Dispose()
  334. {
  335. Dispose(true);
  336. GC.SuppressFinalize(this);
  337. }
  338. private readonly object _disposeLock = new object();
  339. private bool _disposed;
  340. private void CheckDisposed()
  341. {
  342. if (_disposed)
  343. {
  344. throw new ObjectDisposedException(GetType().Name + " has been disposed and cannot be accessed.");
  345. }
  346. }
  347. /// <summary>
  348. /// Releases unmanaged and - optionally - managed resources.
  349. /// </summary>
  350. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  351. protected virtual void Dispose(bool dispose)
  352. {
  353. if (dispose)
  354. {
  355. _disposed = true;
  356. try
  357. {
  358. lock (_disposeLock)
  359. {
  360. if (_shrinkMemoryTimer != null)
  361. {
  362. _shrinkMemoryTimer.Dispose();
  363. _shrinkMemoryTimer = null;
  364. }
  365. if (_connection != null)
  366. {
  367. if (_connection.IsOpen())
  368. {
  369. _connection.Close();
  370. }
  371. _connection.Dispose();
  372. _connection = null;
  373. }
  374. if (_chapterRepository != null)
  375. {
  376. _chapterRepository.Dispose();
  377. _chapterRepository = null;
  378. }
  379. if (_mediaStreamsRepository != null)
  380. {
  381. _mediaStreamsRepository.Dispose();
  382. _mediaStreamsRepository = null;
  383. }
  384. }
  385. }
  386. catch (Exception ex)
  387. {
  388. _logger.ErrorException("Error disposing database", ex);
  389. }
  390. }
  391. }
  392. public IEnumerable<Guid> GetChildren(Guid parentId)
  393. {
  394. if (parentId == Guid.Empty)
  395. {
  396. throw new ArgumentNullException("parentId");
  397. }
  398. CheckDisposed();
  399. using (var cmd = _connection.CreateCommand())
  400. {
  401. cmd.CommandText = "select ItemId from ChildrenIds where ParentId = @ParentId";
  402. cmd.Parameters.Add(cmd, "@ParentId", DbType.Guid).Value = parentId;
  403. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  404. {
  405. while (reader.Read())
  406. {
  407. yield return reader.GetGuid(0);
  408. }
  409. }
  410. }
  411. }
  412. public IEnumerable<BaseItem> GetChildrenItems(Guid parentId)
  413. {
  414. if (parentId == Guid.Empty)
  415. {
  416. throw new ArgumentNullException("parentId");
  417. }
  418. CheckDisposed();
  419. using (var cmd = _connection.CreateCommand())
  420. {
  421. cmd.CommandText = "select type,data from TypedBaseItems where guid in (select ItemId from ChildrenIds where ParentId = @ParentId)";
  422. cmd.Parameters.Add(cmd, "@ParentId", DbType.Guid).Value = parentId;
  423. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  424. {
  425. while (reader.Read())
  426. {
  427. var item = GetItem(reader);
  428. if (item != null)
  429. {
  430. yield return item;
  431. }
  432. }
  433. }
  434. }
  435. }
  436. public IEnumerable<Guid> GetItemsOfType(Type type)
  437. {
  438. if (type == null)
  439. {
  440. throw new ArgumentNullException("type");
  441. }
  442. CheckDisposed();
  443. using (var cmd = _connection.CreateCommand())
  444. {
  445. cmd.CommandText = "select guid from TypedBaseItems where type = @type";
  446. cmd.Parameters.Add(cmd, "@type", DbType.String).Value = type.FullName;
  447. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  448. {
  449. while (reader.Read())
  450. {
  451. yield return reader.GetGuid(0);
  452. }
  453. }
  454. }
  455. }
  456. public async Task DeleteItem(Guid id, CancellationToken cancellationToken)
  457. {
  458. if (id == Guid.Empty)
  459. {
  460. throw new ArgumentNullException("id");
  461. }
  462. CheckDisposed();
  463. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  464. IDbTransaction transaction = null;
  465. try
  466. {
  467. transaction = _connection.BeginTransaction();
  468. // First delete children
  469. _deleteChildrenCommand.GetParameter(0).Value = id;
  470. _deleteChildrenCommand.Transaction = transaction;
  471. _deleteChildrenCommand.ExecuteNonQuery();
  472. // Delete the item
  473. _deleteItemCommand.GetParameter(0).Value = id;
  474. _deleteItemCommand.Transaction = transaction;
  475. _deleteItemCommand.ExecuteNonQuery();
  476. transaction.Commit();
  477. }
  478. catch (OperationCanceledException)
  479. {
  480. if (transaction != null)
  481. {
  482. transaction.Rollback();
  483. }
  484. throw;
  485. }
  486. catch (Exception e)
  487. {
  488. _logger.ErrorException("Failed to save children:", e);
  489. if (transaction != null)
  490. {
  491. transaction.Rollback();
  492. }
  493. throw;
  494. }
  495. finally
  496. {
  497. if (transaction != null)
  498. {
  499. transaction.Dispose();
  500. }
  501. _writeLock.Release();
  502. }
  503. }
  504. public async Task SaveChildren(Guid parentId, IEnumerable<Guid> children, CancellationToken cancellationToken)
  505. {
  506. if (parentId == Guid.Empty)
  507. {
  508. throw new ArgumentNullException("parentId");
  509. }
  510. if (children == null)
  511. {
  512. throw new ArgumentNullException("children");
  513. }
  514. CheckDisposed();
  515. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  516. IDbTransaction transaction = null;
  517. try
  518. {
  519. transaction = _connection.BeginTransaction();
  520. // First delete
  521. _deleteChildrenCommand.GetParameter(0).Value = parentId;
  522. _deleteChildrenCommand.Transaction = transaction;
  523. _deleteChildrenCommand.ExecuteNonQuery();
  524. foreach (var id in children)
  525. {
  526. cancellationToken.ThrowIfCancellationRequested();
  527. _saveChildrenCommand.GetParameter(0).Value = parentId;
  528. _saveChildrenCommand.GetParameter(1).Value = id;
  529. _saveChildrenCommand.Transaction = transaction;
  530. _saveChildrenCommand.ExecuteNonQuery();
  531. }
  532. transaction.Commit();
  533. }
  534. catch (OperationCanceledException)
  535. {
  536. if (transaction != null)
  537. {
  538. transaction.Rollback();
  539. }
  540. throw;
  541. }
  542. catch (Exception e)
  543. {
  544. _logger.ErrorException("Failed to save children:", e);
  545. if (transaction != null)
  546. {
  547. transaction.Rollback();
  548. }
  549. throw;
  550. }
  551. finally
  552. {
  553. if (transaction != null)
  554. {
  555. transaction.Dispose();
  556. }
  557. _writeLock.Release();
  558. }
  559. }
  560. public IEnumerable<MediaStream> GetMediaStreams(MediaStreamQuery query)
  561. {
  562. CheckDisposed();
  563. return _mediaStreamsRepository.GetMediaStreams(query);
  564. }
  565. public Task SaveMediaStreams(Guid id, IEnumerable<MediaStream> streams, CancellationToken cancellationToken)
  566. {
  567. CheckDisposed();
  568. return _mediaStreamsRepository.SaveMediaStreams(id, streams, cancellationToken);
  569. }
  570. }
  571. }