SqliteItemRepository.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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. /// <summary>
  54. /// Initializes a new instance of the <see cref="SqliteItemRepository"/> class.
  55. /// </summary>
  56. /// <param name="appPaths">The app paths.</param>
  57. /// <param name="jsonSerializer">The json serializer.</param>
  58. /// <param name="logManager">The log manager.</param>
  59. /// <exception cref="System.ArgumentNullException">
  60. /// appPaths
  61. /// or
  62. /// jsonSerializer
  63. /// </exception>
  64. public SqliteItemRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
  65. {
  66. if (appPaths == null)
  67. {
  68. throw new ArgumentNullException("appPaths");
  69. }
  70. if (jsonSerializer == null)
  71. {
  72. throw new ArgumentNullException("jsonSerializer");
  73. }
  74. _appPaths = appPaths;
  75. _jsonSerializer = jsonSerializer;
  76. _criticReviewsPath = Path.Combine(_appPaths.DataPath, "critic-reviews");
  77. _logger = logManager.GetLogger(GetType().Name);
  78. var chapterDbFile = Path.Combine(_appPaths.DataPath, "chapters.db");
  79. var chapterConnection = SqliteExtensions.ConnectToDb(chapterDbFile, _logger).Result;
  80. _chapterRepository = new SqliteChapterRepository(chapterConnection, logManager);
  81. var mediaStreamsDbFile = Path.Combine(_appPaths.DataPath, "mediainfo.db");
  82. var mediaStreamsConnection = SqliteExtensions.ConnectToDb(mediaStreamsDbFile, _logger).Result;
  83. _mediaStreamsRepository = new SqliteMediaStreamsRepository(mediaStreamsConnection, logManager);
  84. }
  85. /// <summary>
  86. /// Opens the connection to the database
  87. /// </summary>
  88. /// <returns>Task.</returns>
  89. public async Task Initialize()
  90. {
  91. var dbFile = Path.Combine(_appPaths.DataPath, "library.db");
  92. _connection = await SqliteExtensions.ConnectToDb(dbFile, _logger).ConfigureAwait(false);
  93. string[] queries = {
  94. "create table if not exists TypedBaseItems (guid GUID primary key, type TEXT, data BLOB)",
  95. "create index if not exists idx_TypedBaseItems on TypedBaseItems(guid)",
  96. "create table if not exists ChildrenIds (ParentId GUID, ItemId GUID, PRIMARY KEY (ParentId, ItemId))",
  97. "create index if not exists idx_ChildrenIds on ChildrenIds(ParentId,ItemId)",
  98. //pragmas
  99. "pragma temp_store = memory"
  100. };
  101. _connection.RunQueries(queries, _logger);
  102. PrepareStatements();
  103. _mediaStreamsRepository.Initialize();
  104. _chapterRepository.Initialize();
  105. }
  106. /// <summary>
  107. /// The _write lock
  108. /// </summary>
  109. private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
  110. /// <summary>
  111. /// Prepares the statements.
  112. /// </summary>
  113. private void PrepareStatements()
  114. {
  115. _saveItemCommand = _connection.CreateCommand();
  116. _saveItemCommand.CommandText = "replace into TypedBaseItems (guid, type, data) values (@1, @2, @3)";
  117. _saveItemCommand.Parameters.Add(_saveItemCommand, "@1");
  118. _saveItemCommand.Parameters.Add(_saveItemCommand, "@2");
  119. _saveItemCommand.Parameters.Add(_saveItemCommand, "@3");
  120. _deleteChildrenCommand = _connection.CreateCommand();
  121. _deleteChildrenCommand.CommandText = "delete from ChildrenIds where ParentId=@ParentId";
  122. _deleteChildrenCommand.Parameters.Add(_deleteChildrenCommand, "@ParentId");
  123. _saveChildrenCommand = _connection.CreateCommand();
  124. _saveChildrenCommand.CommandText = "replace into ChildrenIds (ParentId, ItemId) values (@ParentId, @ItemId)";
  125. _saveChildrenCommand.Parameters.Add(_saveChildrenCommand, "@ParentId");
  126. _saveChildrenCommand.Parameters.Add(_saveChildrenCommand, "@ItemId");
  127. }
  128. /// <summary>
  129. /// Save a standard item in the repo
  130. /// </summary>
  131. /// <param name="item">The item.</param>
  132. /// <param name="cancellationToken">The cancellation token.</param>
  133. /// <returns>Task.</returns>
  134. /// <exception cref="System.ArgumentNullException">item</exception>
  135. public Task SaveItem(BaseItem item, CancellationToken cancellationToken)
  136. {
  137. if (item == null)
  138. {
  139. throw new ArgumentNullException("item");
  140. }
  141. return SaveItems(new[] { item }, cancellationToken);
  142. }
  143. /// <summary>
  144. /// Saves the items.
  145. /// </summary>
  146. /// <param name="items">The items.</param>
  147. /// <param name="cancellationToken">The cancellation token.</param>
  148. /// <returns>Task.</returns>
  149. /// <exception cref="System.ArgumentNullException">
  150. /// items
  151. /// or
  152. /// cancellationToken
  153. /// </exception>
  154. public async Task SaveItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  155. {
  156. if (items == null)
  157. {
  158. throw new ArgumentNullException("items");
  159. }
  160. cancellationToken.ThrowIfCancellationRequested();
  161. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  162. IDbTransaction transaction = null;
  163. try
  164. {
  165. transaction = _connection.BeginTransaction();
  166. foreach (var item in items)
  167. {
  168. cancellationToken.ThrowIfCancellationRequested();
  169. _saveItemCommand.GetParameter(0).Value = item.Id;
  170. _saveItemCommand.GetParameter(1).Value = item.GetType().FullName;
  171. _saveItemCommand.GetParameter(2).Value = _jsonSerializer.SerializeToBytes(item);
  172. _saveItemCommand.Transaction = transaction;
  173. _saveItemCommand.ExecuteNonQuery();
  174. }
  175. transaction.Commit();
  176. }
  177. catch (OperationCanceledException)
  178. {
  179. if (transaction != null)
  180. {
  181. transaction.Rollback();
  182. }
  183. throw;
  184. }
  185. catch (Exception e)
  186. {
  187. _logger.ErrorException("Failed to save items:", e);
  188. if (transaction != null)
  189. {
  190. transaction.Rollback();
  191. }
  192. throw;
  193. }
  194. finally
  195. {
  196. if (transaction != null)
  197. {
  198. transaction.Dispose();
  199. }
  200. _writeLock.Release();
  201. }
  202. }
  203. /// <summary>
  204. /// Internal retrieve from items or users table
  205. /// </summary>
  206. /// <param name="id">The id.</param>
  207. /// <returns>BaseItem.</returns>
  208. /// <exception cref="System.ArgumentNullException">id</exception>
  209. /// <exception cref="System.ArgumentException"></exception>
  210. public BaseItem RetrieveItem(Guid id)
  211. {
  212. if (id == Guid.Empty)
  213. {
  214. throw new ArgumentNullException("id");
  215. }
  216. using (var cmd = _connection.CreateCommand())
  217. {
  218. cmd.CommandText = "select type,data from TypedBaseItems where guid = @guid";
  219. cmd.Parameters.Add(cmd, "@guid", DbType.Guid).Value = id;
  220. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  221. {
  222. if (reader.Read())
  223. {
  224. var typeString = reader.GetString(0);
  225. var type = _typeMapper.GetType(typeString);
  226. if (type == null)
  227. {
  228. _logger.Debug("Unknown type {0}", typeString);
  229. return null;
  230. }
  231. using (var stream = reader.GetMemoryStream(1))
  232. {
  233. return _jsonSerializer.DeserializeFromStream(stream, type) as BaseItem;
  234. }
  235. }
  236. }
  237. return null;
  238. }
  239. }
  240. /// <summary>
  241. /// Gets the critic reviews.
  242. /// </summary>
  243. /// <param name="itemId">The item id.</param>
  244. /// <returns>Task{IEnumerable{ItemReview}}.</returns>
  245. public IEnumerable<ItemReview> GetCriticReviews(Guid itemId)
  246. {
  247. try
  248. {
  249. var path = Path.Combine(_criticReviewsPath, itemId + ".json");
  250. return _jsonSerializer.DeserializeFromFile<List<ItemReview>>(path);
  251. }
  252. catch (DirectoryNotFoundException)
  253. {
  254. return new List<ItemReview>();
  255. }
  256. catch (FileNotFoundException)
  257. {
  258. return new List<ItemReview>();
  259. }
  260. }
  261. /// <summary>
  262. /// Saves the critic reviews.
  263. /// </summary>
  264. /// <param name="itemId">The item id.</param>
  265. /// <param name="criticReviews">The critic reviews.</param>
  266. /// <returns>Task.</returns>
  267. public Task SaveCriticReviews(Guid itemId, IEnumerable<ItemReview> criticReviews)
  268. {
  269. Directory.CreateDirectory(_criticReviewsPath);
  270. var path = Path.Combine(_criticReviewsPath, itemId + ".json");
  271. _jsonSerializer.SerializeToFile(criticReviews.ToList(), path);
  272. return Task.FromResult(true);
  273. }
  274. /// <summary>
  275. /// Gets chapters for an item
  276. /// </summary>
  277. /// <param name="id">The id.</param>
  278. /// <returns>IEnumerable{ChapterInfo}.</returns>
  279. /// <exception cref="System.ArgumentNullException">id</exception>
  280. public IEnumerable<ChapterInfo> GetChapters(Guid id)
  281. {
  282. return _chapterRepository.GetChapters(id);
  283. }
  284. /// <summary>
  285. /// Gets a single chapter for an item
  286. /// </summary>
  287. /// <param name="id">The id.</param>
  288. /// <param name="index">The index.</param>
  289. /// <returns>ChapterInfo.</returns>
  290. /// <exception cref="System.ArgumentNullException">id</exception>
  291. public ChapterInfo GetChapter(Guid id, int index)
  292. {
  293. return _chapterRepository.GetChapter(id, index);
  294. }
  295. /// <summary>
  296. /// Saves the chapters.
  297. /// </summary>
  298. /// <param name="id">The id.</param>
  299. /// <param name="chapters">The chapters.</param>
  300. /// <param name="cancellationToken">The cancellation token.</param>
  301. /// <returns>Task.</returns>
  302. /// <exception cref="System.ArgumentNullException">
  303. /// id
  304. /// or
  305. /// chapters
  306. /// or
  307. /// cancellationToken
  308. /// </exception>
  309. public Task SaveChapters(Guid id, IEnumerable<ChapterInfo> chapters, CancellationToken cancellationToken)
  310. {
  311. return _chapterRepository.SaveChapters(id, chapters, cancellationToken);
  312. }
  313. /// <summary>
  314. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  315. /// </summary>
  316. public void Dispose()
  317. {
  318. Dispose(true);
  319. GC.SuppressFinalize(this);
  320. }
  321. private readonly object _disposeLock = new object();
  322. /// <summary>
  323. /// Releases unmanaged and - optionally - managed resources.
  324. /// </summary>
  325. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  326. protected virtual void Dispose(bool dispose)
  327. {
  328. if (dispose)
  329. {
  330. try
  331. {
  332. lock (_disposeLock)
  333. {
  334. if (_connection != null)
  335. {
  336. if (_connection.IsOpen())
  337. {
  338. _connection.Close();
  339. }
  340. _connection.Dispose();
  341. _connection = null;
  342. }
  343. }
  344. }
  345. catch (Exception ex)
  346. {
  347. _logger.ErrorException("Error disposing database", ex);
  348. }
  349. if (_chapterRepository != null)
  350. {
  351. _chapterRepository.Dispose();
  352. _chapterRepository = null;
  353. }
  354. if (_mediaStreamsRepository != null)
  355. {
  356. _mediaStreamsRepository.Dispose();
  357. _mediaStreamsRepository = null;
  358. }
  359. }
  360. }
  361. public IEnumerable<Guid> GetChildren(Guid parentId)
  362. {
  363. if (parentId == Guid.Empty)
  364. {
  365. throw new ArgumentNullException("parentId");
  366. }
  367. using (var cmd = _connection.CreateCommand())
  368. {
  369. cmd.CommandText = "select ItemId from ChildrenIds where ParentId = @ParentId";
  370. cmd.Parameters.Add(cmd, "@ParentId", DbType.Guid).Value = parentId;
  371. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  372. {
  373. while (reader.Read())
  374. {
  375. yield return reader.GetGuid(0);
  376. }
  377. }
  378. }
  379. }
  380. public async Task SaveChildren(Guid parentId, IEnumerable<Guid> children, CancellationToken cancellationToken)
  381. {
  382. if (parentId == Guid.Empty)
  383. {
  384. throw new ArgumentNullException("parentId");
  385. }
  386. if (children == null)
  387. {
  388. throw new ArgumentNullException("children");
  389. }
  390. cancellationToken.ThrowIfCancellationRequested();
  391. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  392. IDbTransaction transaction = null;
  393. try
  394. {
  395. transaction = _connection.BeginTransaction();
  396. // First delete
  397. _deleteChildrenCommand.GetParameter(0).Value = parentId;
  398. _deleteChildrenCommand.Transaction = transaction;
  399. _deleteChildrenCommand.ExecuteNonQuery();
  400. foreach (var id in children)
  401. {
  402. cancellationToken.ThrowIfCancellationRequested();
  403. _saveChildrenCommand.GetParameter(0).Value = parentId;
  404. _saveChildrenCommand.GetParameter(1).Value = id;
  405. _saveChildrenCommand.Transaction = transaction;
  406. _saveChildrenCommand.ExecuteNonQuery();
  407. }
  408. transaction.Commit();
  409. }
  410. catch (OperationCanceledException)
  411. {
  412. if (transaction != null)
  413. {
  414. transaction.Rollback();
  415. }
  416. throw;
  417. }
  418. catch (Exception e)
  419. {
  420. _logger.ErrorException("Failed to save children:", e);
  421. if (transaction != null)
  422. {
  423. transaction.Rollback();
  424. }
  425. throw;
  426. }
  427. finally
  428. {
  429. if (transaction != null)
  430. {
  431. transaction.Dispose();
  432. }
  433. _writeLock.Release();
  434. }
  435. }
  436. public IEnumerable<MediaStream> GetMediaStreams(MediaStreamQuery query)
  437. {
  438. return _mediaStreamsRepository.GetMediaStreams(query);
  439. }
  440. public Task SaveMediaStreams(Guid id, IEnumerable<MediaStream> streams, CancellationToken cancellationToken)
  441. {
  442. return _mediaStreamsRepository.SaveMediaStreams(id, streams, cancellationToken);
  443. }
  444. }
  445. }