SqliteItemRepository.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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. /// <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. _saveChildrenCommand = _connection.CreateCommand();
  128. _saveChildrenCommand.CommandText = "replace into ChildrenIds (ParentId, ItemId) values (@ParentId, @ItemId)";
  129. _saveChildrenCommand.Parameters.Add(_saveChildrenCommand, "@ParentId");
  130. _saveChildrenCommand.Parameters.Add(_saveChildrenCommand, "@ItemId");
  131. }
  132. /// <summary>
  133. /// Save a standard item in the repo
  134. /// </summary>
  135. /// <param name="item">The item.</param>
  136. /// <param name="cancellationToken">The cancellation token.</param>
  137. /// <returns>Task.</returns>
  138. /// <exception cref="System.ArgumentNullException">item</exception>
  139. public Task SaveItem(BaseItem item, CancellationToken cancellationToken)
  140. {
  141. if (item == null)
  142. {
  143. throw new ArgumentNullException("item");
  144. }
  145. return SaveItems(new[] { item }, cancellationToken);
  146. }
  147. /// <summary>
  148. /// Saves the items.
  149. /// </summary>
  150. /// <param name="items">The items.</param>
  151. /// <param name="cancellationToken">The cancellation token.</param>
  152. /// <returns>Task.</returns>
  153. /// <exception cref="System.ArgumentNullException">
  154. /// items
  155. /// or
  156. /// cancellationToken
  157. /// </exception>
  158. public async Task SaveItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  159. {
  160. if (items == null)
  161. {
  162. throw new ArgumentNullException("items");
  163. }
  164. cancellationToken.ThrowIfCancellationRequested();
  165. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  166. IDbTransaction transaction = null;
  167. try
  168. {
  169. transaction = _connection.BeginTransaction();
  170. foreach (var item in items)
  171. {
  172. cancellationToken.ThrowIfCancellationRequested();
  173. _saveItemCommand.GetParameter(0).Value = item.Id;
  174. _saveItemCommand.GetParameter(1).Value = item.GetType().FullName;
  175. _saveItemCommand.GetParameter(2).Value = _jsonSerializer.SerializeToBytes(item);
  176. _saveItemCommand.Transaction = transaction;
  177. _saveItemCommand.ExecuteNonQuery();
  178. }
  179. transaction.Commit();
  180. }
  181. catch (OperationCanceledException)
  182. {
  183. if (transaction != null)
  184. {
  185. transaction.Rollback();
  186. }
  187. throw;
  188. }
  189. catch (Exception e)
  190. {
  191. _logger.ErrorException("Failed to save items:", e);
  192. if (transaction != null)
  193. {
  194. transaction.Rollback();
  195. }
  196. throw;
  197. }
  198. finally
  199. {
  200. if (transaction != null)
  201. {
  202. transaction.Dispose();
  203. }
  204. _writeLock.Release();
  205. }
  206. }
  207. /// <summary>
  208. /// Internal retrieve from items or users table
  209. /// </summary>
  210. /// <param name="id">The id.</param>
  211. /// <returns>BaseItem.</returns>
  212. /// <exception cref="System.ArgumentNullException">id</exception>
  213. /// <exception cref="System.ArgumentException"></exception>
  214. public BaseItem RetrieveItem(Guid id)
  215. {
  216. if (id == Guid.Empty)
  217. {
  218. throw new ArgumentNullException("id");
  219. }
  220. using (var cmd = _connection.CreateCommand())
  221. {
  222. cmd.CommandText = "select type,data from TypedBaseItems where guid = @guid";
  223. cmd.Parameters.Add(cmd, "@guid", DbType.Guid).Value = id;
  224. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  225. {
  226. if (reader.Read())
  227. {
  228. var typeString = reader.GetString(0);
  229. var type = _typeMapper.GetType(typeString);
  230. if (type == null)
  231. {
  232. _logger.Debug("Unknown type {0}", typeString);
  233. return null;
  234. }
  235. using (var stream = reader.GetMemoryStream(1))
  236. {
  237. return _jsonSerializer.DeserializeFromStream(stream, type) as BaseItem;
  238. }
  239. }
  240. }
  241. return null;
  242. }
  243. }
  244. /// <summary>
  245. /// Gets the critic reviews.
  246. /// </summary>
  247. /// <param name="itemId">The item id.</param>
  248. /// <returns>Task{IEnumerable{ItemReview}}.</returns>
  249. public IEnumerable<ItemReview> GetCriticReviews(Guid itemId)
  250. {
  251. try
  252. {
  253. var path = Path.Combine(_criticReviewsPath, itemId + ".json");
  254. return _jsonSerializer.DeserializeFromFile<List<ItemReview>>(path);
  255. }
  256. catch (DirectoryNotFoundException)
  257. {
  258. return new List<ItemReview>();
  259. }
  260. catch (FileNotFoundException)
  261. {
  262. return new List<ItemReview>();
  263. }
  264. }
  265. private readonly Task _cachedTask = Task.FromResult(true);
  266. /// <summary>
  267. /// Saves the critic reviews.
  268. /// </summary>
  269. /// <param name="itemId">The item id.</param>
  270. /// <param name="criticReviews">The critic reviews.</param>
  271. /// <returns>Task.</returns>
  272. public Task SaveCriticReviews(Guid itemId, IEnumerable<ItemReview> criticReviews)
  273. {
  274. Directory.CreateDirectory(_criticReviewsPath);
  275. var path = Path.Combine(_criticReviewsPath, itemId + ".json");
  276. _jsonSerializer.SerializeToFile(criticReviews.ToList(), path);
  277. return _cachedTask;
  278. }
  279. /// <summary>
  280. /// Gets chapters for an item
  281. /// </summary>
  282. /// <param name="id">The id.</param>
  283. /// <returns>IEnumerable{ChapterInfo}.</returns>
  284. /// <exception cref="System.ArgumentNullException">id</exception>
  285. public IEnumerable<ChapterInfo> GetChapters(Guid id)
  286. {
  287. return _chapterRepository.GetChapters(id);
  288. }
  289. /// <summary>
  290. /// Gets a single chapter for an item
  291. /// </summary>
  292. /// <param name="id">The id.</param>
  293. /// <param name="index">The index.</param>
  294. /// <returns>ChapterInfo.</returns>
  295. /// <exception cref="System.ArgumentNullException">id</exception>
  296. public ChapterInfo GetChapter(Guid id, int index)
  297. {
  298. return _chapterRepository.GetChapter(id, index);
  299. }
  300. /// <summary>
  301. /// Saves the chapters.
  302. /// </summary>
  303. /// <param name="id">The id.</param>
  304. /// <param name="chapters">The chapters.</param>
  305. /// <param name="cancellationToken">The cancellation token.</param>
  306. /// <returns>Task.</returns>
  307. /// <exception cref="System.ArgumentNullException">
  308. /// id
  309. /// or
  310. /// chapters
  311. /// or
  312. /// cancellationToken
  313. /// </exception>
  314. public Task SaveChapters(Guid id, IEnumerable<ChapterInfo> chapters, CancellationToken cancellationToken)
  315. {
  316. return _chapterRepository.SaveChapters(id, chapters, cancellationToken);
  317. }
  318. /// <summary>
  319. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  320. /// </summary>
  321. public void Dispose()
  322. {
  323. Dispose(true);
  324. GC.SuppressFinalize(this);
  325. }
  326. private readonly object _disposeLock = new object();
  327. /// <summary>
  328. /// Releases unmanaged and - optionally - managed resources.
  329. /// </summary>
  330. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  331. protected virtual void Dispose(bool dispose)
  332. {
  333. if (dispose)
  334. {
  335. try
  336. {
  337. lock (_disposeLock)
  338. {
  339. if (_shrinkMemoryTimer != null)
  340. {
  341. _shrinkMemoryTimer.Dispose();
  342. _shrinkMemoryTimer = null;
  343. }
  344. if (_connection != null)
  345. {
  346. if (_connection.IsOpen())
  347. {
  348. _connection.Close();
  349. }
  350. _connection.Dispose();
  351. _connection = null;
  352. }
  353. if (_chapterRepository != null)
  354. {
  355. _chapterRepository.Dispose();
  356. _chapterRepository = null;
  357. }
  358. if (_mediaStreamsRepository != null)
  359. {
  360. _mediaStreamsRepository.Dispose();
  361. _mediaStreamsRepository = null;
  362. }
  363. }
  364. }
  365. catch (Exception ex)
  366. {
  367. _logger.ErrorException("Error disposing database", ex);
  368. }
  369. }
  370. }
  371. public IEnumerable<Guid> GetChildren(Guid parentId)
  372. {
  373. if (parentId == Guid.Empty)
  374. {
  375. throw new ArgumentNullException("parentId");
  376. }
  377. using (var cmd = _connection.CreateCommand())
  378. {
  379. cmd.CommandText = "select ItemId from ChildrenIds where ParentId = @ParentId";
  380. cmd.Parameters.Add(cmd, "@ParentId", DbType.Guid).Value = parentId;
  381. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  382. {
  383. while (reader.Read())
  384. {
  385. yield return reader.GetGuid(0);
  386. }
  387. }
  388. }
  389. }
  390. public async Task SaveChildren(Guid parentId, IEnumerable<Guid> children, CancellationToken cancellationToken)
  391. {
  392. if (parentId == Guid.Empty)
  393. {
  394. throw new ArgumentNullException("parentId");
  395. }
  396. if (children == null)
  397. {
  398. throw new ArgumentNullException("children");
  399. }
  400. cancellationToken.ThrowIfCancellationRequested();
  401. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  402. IDbTransaction transaction = null;
  403. try
  404. {
  405. transaction = _connection.BeginTransaction();
  406. // First delete
  407. _deleteChildrenCommand.GetParameter(0).Value = parentId;
  408. _deleteChildrenCommand.Transaction = transaction;
  409. _deleteChildrenCommand.ExecuteNonQuery();
  410. foreach (var id in children)
  411. {
  412. cancellationToken.ThrowIfCancellationRequested();
  413. _saveChildrenCommand.GetParameter(0).Value = parentId;
  414. _saveChildrenCommand.GetParameter(1).Value = id;
  415. _saveChildrenCommand.Transaction = transaction;
  416. _saveChildrenCommand.ExecuteNonQuery();
  417. }
  418. transaction.Commit();
  419. }
  420. catch (OperationCanceledException)
  421. {
  422. if (transaction != null)
  423. {
  424. transaction.Rollback();
  425. }
  426. throw;
  427. }
  428. catch (Exception e)
  429. {
  430. _logger.ErrorException("Failed to save children:", e);
  431. if (transaction != null)
  432. {
  433. transaction.Rollback();
  434. }
  435. throw;
  436. }
  437. finally
  438. {
  439. if (transaction != null)
  440. {
  441. transaction.Dispose();
  442. }
  443. _writeLock.Release();
  444. }
  445. }
  446. public IEnumerable<MediaStream> GetMediaStreams(MediaStreamQuery query)
  447. {
  448. return _mediaStreamsRepository.GetMediaStreams(query);
  449. }
  450. public Task SaveMediaStreams(Guid id, IEnumerable<MediaStream> streams, CancellationToken cancellationToken)
  451. {
  452. return _mediaStreamsRepository.SaveMediaStreams(id, streams, cancellationToken);
  453. }
  454. }
  455. }