SqliteItemRepository.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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. /// <summary>
  266. /// Saves the critic reviews.
  267. /// </summary>
  268. /// <param name="itemId">The item id.</param>
  269. /// <param name="criticReviews">The critic reviews.</param>
  270. /// <returns>Task.</returns>
  271. public Task SaveCriticReviews(Guid itemId, IEnumerable<ItemReview> criticReviews)
  272. {
  273. Directory.CreateDirectory(_criticReviewsPath);
  274. var path = Path.Combine(_criticReviewsPath, itemId + ".json");
  275. _jsonSerializer.SerializeToFile(criticReviews.ToList(), path);
  276. return Task.FromResult(true);
  277. }
  278. /// <summary>
  279. /// Gets chapters for an item
  280. /// </summary>
  281. /// <param name="id">The id.</param>
  282. /// <returns>IEnumerable{ChapterInfo}.</returns>
  283. /// <exception cref="System.ArgumentNullException">id</exception>
  284. public IEnumerable<ChapterInfo> GetChapters(Guid id)
  285. {
  286. return _chapterRepository.GetChapters(id);
  287. }
  288. /// <summary>
  289. /// Gets a single chapter for an item
  290. /// </summary>
  291. /// <param name="id">The id.</param>
  292. /// <param name="index">The index.</param>
  293. /// <returns>ChapterInfo.</returns>
  294. /// <exception cref="System.ArgumentNullException">id</exception>
  295. public ChapterInfo GetChapter(Guid id, int index)
  296. {
  297. return _chapterRepository.GetChapter(id, index);
  298. }
  299. /// <summary>
  300. /// Saves the chapters.
  301. /// </summary>
  302. /// <param name="id">The id.</param>
  303. /// <param name="chapters">The chapters.</param>
  304. /// <param name="cancellationToken">The cancellation token.</param>
  305. /// <returns>Task.</returns>
  306. /// <exception cref="System.ArgumentNullException">
  307. /// id
  308. /// or
  309. /// chapters
  310. /// or
  311. /// cancellationToken
  312. /// </exception>
  313. public Task SaveChapters(Guid id, IEnumerable<ChapterInfo> chapters, CancellationToken cancellationToken)
  314. {
  315. return _chapterRepository.SaveChapters(id, chapters, cancellationToken);
  316. }
  317. /// <summary>
  318. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  319. /// </summary>
  320. public void Dispose()
  321. {
  322. Dispose(true);
  323. GC.SuppressFinalize(this);
  324. }
  325. private readonly object _disposeLock = new object();
  326. /// <summary>
  327. /// Releases unmanaged and - optionally - managed resources.
  328. /// </summary>
  329. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  330. protected virtual void Dispose(bool dispose)
  331. {
  332. if (dispose)
  333. {
  334. try
  335. {
  336. lock (_disposeLock)
  337. {
  338. if (_shrinkMemoryTimer != null)
  339. {
  340. _shrinkMemoryTimer.Dispose();
  341. _shrinkMemoryTimer = null;
  342. }
  343. if (_connection != null)
  344. {
  345. if (_connection.IsOpen())
  346. {
  347. _connection.Close();
  348. }
  349. _connection.Dispose();
  350. _connection = null;
  351. }
  352. if (_chapterRepository != null)
  353. {
  354. _chapterRepository.Dispose();
  355. _chapterRepository = null;
  356. }
  357. if (_mediaStreamsRepository != null)
  358. {
  359. _mediaStreamsRepository.Dispose();
  360. _mediaStreamsRepository = null;
  361. }
  362. }
  363. }
  364. catch (Exception ex)
  365. {
  366. _logger.ErrorException("Error disposing database", ex);
  367. }
  368. }
  369. }
  370. public IEnumerable<Guid> GetChildren(Guid parentId)
  371. {
  372. if (parentId == Guid.Empty)
  373. {
  374. throw new ArgumentNullException("parentId");
  375. }
  376. using (var cmd = _connection.CreateCommand())
  377. {
  378. cmd.CommandText = "select ItemId from ChildrenIds where ParentId = @ParentId";
  379. cmd.Parameters.Add(cmd, "@ParentId", DbType.Guid).Value = parentId;
  380. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  381. {
  382. while (reader.Read())
  383. {
  384. yield return reader.GetGuid(0);
  385. }
  386. }
  387. }
  388. }
  389. public async Task SaveChildren(Guid parentId, IEnumerable<Guid> children, CancellationToken cancellationToken)
  390. {
  391. if (parentId == Guid.Empty)
  392. {
  393. throw new ArgumentNullException("parentId");
  394. }
  395. if (children == null)
  396. {
  397. throw new ArgumentNullException("children");
  398. }
  399. cancellationToken.ThrowIfCancellationRequested();
  400. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  401. IDbTransaction transaction = null;
  402. try
  403. {
  404. transaction = _connection.BeginTransaction();
  405. // First delete
  406. _deleteChildrenCommand.GetParameter(0).Value = parentId;
  407. _deleteChildrenCommand.Transaction = transaction;
  408. _deleteChildrenCommand.ExecuteNonQuery();
  409. foreach (var id in children)
  410. {
  411. cancellationToken.ThrowIfCancellationRequested();
  412. _saveChildrenCommand.GetParameter(0).Value = parentId;
  413. _saveChildrenCommand.GetParameter(1).Value = id;
  414. _saveChildrenCommand.Transaction = transaction;
  415. _saveChildrenCommand.ExecuteNonQuery();
  416. }
  417. transaction.Commit();
  418. }
  419. catch (OperationCanceledException)
  420. {
  421. if (transaction != null)
  422. {
  423. transaction.Rollback();
  424. }
  425. throw;
  426. }
  427. catch (Exception e)
  428. {
  429. _logger.ErrorException("Failed to save children:", e);
  430. if (transaction != null)
  431. {
  432. transaction.Rollback();
  433. }
  434. throw;
  435. }
  436. finally
  437. {
  438. if (transaction != null)
  439. {
  440. transaction.Dispose();
  441. }
  442. _writeLock.Release();
  443. }
  444. }
  445. public IEnumerable<MediaStream> GetMediaStreams(MediaStreamQuery query)
  446. {
  447. return _mediaStreamsRepository.GetMediaStreams(query);
  448. }
  449. public Task SaveMediaStreams(Guid id, IEnumerable<MediaStream> streams, CancellationToken cancellationToken)
  450. {
  451. return _mediaStreamsRepository.SaveMediaStreams(id, streams, cancellationToken);
  452. }
  453. }
  454. }