SqliteItemRepository.cs 17 KB

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