SqliteItemRepository.cs 20 KB

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