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