SqliteItemRepository.cs 17 KB

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