SQLiteItemRepository.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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 MediaBrowser.Server.Implementations.Reflection;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Data;
  11. using System.Data.SQLite;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Server.Implementations.Sqlite
  17. {
  18. /// <summary>
  19. /// Class SQLiteItemRepository
  20. /// </summary>
  21. public class SQLiteItemRepository : SqliteRepository, IItemRepository
  22. {
  23. /// <summary>
  24. /// The _type mapper
  25. /// </summary>
  26. private readonly TypeMapper _typeMapper = new TypeMapper();
  27. /// <summary>
  28. /// The repository name
  29. /// </summary>
  30. public const string RepositoryName = "SQLite";
  31. /// <summary>
  32. /// Gets the name of the repository
  33. /// </summary>
  34. /// <value>The name.</value>
  35. public string Name
  36. {
  37. get
  38. {
  39. return RepositoryName;
  40. }
  41. }
  42. /// <summary>
  43. /// Gets the json serializer.
  44. /// </summary>
  45. /// <value>The json serializer.</value>
  46. private readonly IJsonSerializer _jsonSerializer;
  47. /// <summary>
  48. /// The _app paths
  49. /// </summary>
  50. private readonly IApplicationPaths _appPaths;
  51. /// <summary>
  52. /// The _save item command
  53. /// </summary>
  54. private SQLiteCommand _saveItemCommand;
  55. /// <summary>
  56. /// The _delete children command
  57. /// </summary>
  58. private SQLiteCommand _deleteChildrenCommand;
  59. /// <summary>
  60. /// The _save children command
  61. /// </summary>
  62. private SQLiteCommand _saveChildrenCommand;
  63. /// <summary>
  64. /// Initializes a new instance of the <see cref="SQLiteUserDataRepository" /> class.
  65. /// </summary>
  66. /// <param name="appPaths">The app paths.</param>
  67. /// <param name="jsonSerializer">The json serializer.</param>
  68. /// <param name="logManager">The log manager.</param>
  69. /// <exception cref="System.ArgumentNullException">appPaths</exception>
  70. public SQLiteItemRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
  71. : base(logManager)
  72. {
  73. if (appPaths == null)
  74. {
  75. throw new ArgumentNullException("appPaths");
  76. }
  77. if (jsonSerializer == null)
  78. {
  79. throw new ArgumentNullException("jsonSerializer");
  80. }
  81. _appPaths = appPaths;
  82. _jsonSerializer = jsonSerializer;
  83. }
  84. /// <summary>
  85. /// Opens the connection to the database
  86. /// </summary>
  87. /// <returns>Task.</returns>
  88. public async Task Initialize()
  89. {
  90. var dbFile = Path.Combine(_appPaths.DataPath, "library.db");
  91. await ConnectToDb(dbFile).ConfigureAwait(false);
  92. string[] queries = {
  93. "create table if not exists items (guid GUID primary key, obj_type, data BLOB)",
  94. "create index if not exists idx_items on items(guid)",
  95. "create table if not exists children (guid GUID, child GUID)",
  96. "create unique index if not exists idx_children on children(guid, child)",
  97. "create table if not exists schema_version (table_name primary key, version)",
  98. //triggers
  99. TriggerSql,
  100. //pragmas
  101. "pragma temp_store = memory"
  102. };
  103. RunQueries(queries);
  104. PrepareStatements();
  105. }
  106. //cascade delete triggers
  107. /// <summary>
  108. /// The trigger SQL
  109. /// </summary>
  110. protected string TriggerSql =
  111. @"CREATE TRIGGER if not exists delete_item
  112. AFTER DELETE
  113. ON items
  114. FOR EACH ROW
  115. BEGIN
  116. DELETE FROM children WHERE children.guid = old.child;
  117. DELETE FROM children WHERE children.child = old.child;
  118. END";
  119. /// <summary>
  120. /// The _write lock
  121. /// </summary>
  122. private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
  123. /// <summary>
  124. /// Prepares the statements.
  125. /// </summary>
  126. private void PrepareStatements()
  127. {
  128. _saveItemCommand = new SQLiteCommand
  129. {
  130. CommandText = "replace into items (guid, obj_type, data) values (@1, @2, @3)"
  131. };
  132. _saveItemCommand.Parameters.Add(new SQLiteParameter("@1"));
  133. _saveItemCommand.Parameters.Add(new SQLiteParameter("@2"));
  134. _saveItemCommand.Parameters.Add(new SQLiteParameter("@3"));
  135. _deleteChildrenCommand = new SQLiteCommand
  136. {
  137. CommandText = "delete from children where guid = @guid"
  138. };
  139. _deleteChildrenCommand.Parameters.Add(new SQLiteParameter("@guid"));
  140. _saveChildrenCommand = new SQLiteCommand
  141. {
  142. CommandText = "replace into children (guid, child) values (@guid, @child)"
  143. };
  144. _saveChildrenCommand.Parameters.Add(new SQLiteParameter("@guid"));
  145. _saveChildrenCommand.Parameters.Add(new SQLiteParameter("@child"));
  146. }
  147. /// <summary>
  148. /// Save a standard item in the repo
  149. /// </summary>
  150. /// <param name="item">The item.</param>
  151. /// <param name="cancellationToken">The cancellation token.</param>
  152. /// <returns>Task.</returns>
  153. /// <exception cref="System.ArgumentNullException">item</exception>
  154. public Task SaveItem(BaseItem item, CancellationToken cancellationToken)
  155. {
  156. if (item == null)
  157. {
  158. throw new ArgumentNullException("item");
  159. }
  160. return SaveItems(new[] { item }, cancellationToken);
  161. }
  162. /// <summary>
  163. /// Saves the items.
  164. /// </summary>
  165. /// <param name="items">The items.</param>
  166. /// <param name="cancellationToken">The cancellation token.</param>
  167. /// <returns>Task.</returns>
  168. /// <exception cref="System.ArgumentNullException">
  169. /// items
  170. /// or
  171. /// cancellationToken
  172. /// </exception>
  173. public async Task SaveItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  174. {
  175. if (items == null)
  176. {
  177. throw new ArgumentNullException("items");
  178. }
  179. if (cancellationToken == null)
  180. {
  181. throw new ArgumentNullException("cancellationToken");
  182. }
  183. cancellationToken.ThrowIfCancellationRequested();
  184. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  185. SQLiteTransaction transaction = null;
  186. try
  187. {
  188. transaction = Connection.BeginTransaction();
  189. foreach (var item in items)
  190. {
  191. cancellationToken.ThrowIfCancellationRequested();
  192. _saveItemCommand.Parameters[0].Value = item.Id;
  193. _saveItemCommand.Parameters[1].Value = item.GetType().FullName;
  194. _saveItemCommand.Parameters[2].Value = _jsonSerializer.SerializeToBytes(item);
  195. _saveItemCommand.Transaction = transaction;
  196. await _saveItemCommand.ExecuteNonQueryAsync(cancellationToken);
  197. }
  198. transaction.Commit();
  199. }
  200. catch (OperationCanceledException)
  201. {
  202. if (transaction != null)
  203. {
  204. transaction.Rollback();
  205. }
  206. throw;
  207. }
  208. catch (Exception e)
  209. {
  210. Logger.ErrorException("Failed to save items:", e);
  211. if (transaction != null)
  212. {
  213. transaction.Rollback();
  214. }
  215. throw;
  216. }
  217. finally
  218. {
  219. if (transaction != null)
  220. {
  221. transaction.Dispose();
  222. }
  223. _writeLock.Release();
  224. }
  225. }
  226. /// <summary>
  227. /// Retrieve a standard item from the repo
  228. /// </summary>
  229. /// <param name="id">The id.</param>
  230. /// <returns>BaseItem.</returns>
  231. /// <exception cref="System.ArgumentNullException">id</exception>
  232. /// <exception cref="System.ArgumentException"></exception>
  233. public BaseItem GetItem(Guid id)
  234. {
  235. if (id == Guid.Empty)
  236. {
  237. throw new ArgumentNullException("id");
  238. }
  239. return RetrieveItemInternal(id);
  240. }
  241. /// <summary>
  242. /// Retrieves the items.
  243. /// </summary>
  244. /// <param name="ids">The ids.</param>
  245. /// <returns>IEnumerable{BaseItem}.</returns>
  246. /// <exception cref="System.ArgumentNullException">ids</exception>
  247. public IEnumerable<BaseItem> GetItems(IEnumerable<Guid> ids)
  248. {
  249. if (ids == null)
  250. {
  251. throw new ArgumentNullException("ids");
  252. }
  253. return ids.Select(RetrieveItemInternal);
  254. }
  255. /// <summary>
  256. /// Internal retrieve from items or users table
  257. /// </summary>
  258. /// <param name="id">The id.</param>
  259. /// <returns>BaseItem.</returns>
  260. /// <exception cref="System.ArgumentNullException">id</exception>
  261. /// <exception cref="System.ArgumentException"></exception>
  262. protected BaseItem RetrieveItemInternal(Guid id)
  263. {
  264. if (id == Guid.Empty)
  265. {
  266. throw new ArgumentNullException("id");
  267. }
  268. using (var cmd = Connection.CreateCommand())
  269. {
  270. cmd.CommandText = "select obj_type,data from items where guid = @guid";
  271. var guidParam = cmd.Parameters.Add("@guid", DbType.Guid);
  272. guidParam.Value = id;
  273. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  274. {
  275. if (reader.Read())
  276. {
  277. var type = reader.GetString(0);
  278. using (var stream = GetStream(reader, 1))
  279. {
  280. var itemType = _typeMapper.GetType(type);
  281. if (itemType == null)
  282. {
  283. Logger.Error("Cannot find type {0}. Probably belongs to plug-in that is no longer loaded.", type);
  284. return null;
  285. }
  286. var item = _jsonSerializer.DeserializeFromStream(stream, itemType);
  287. return item as BaseItem;
  288. }
  289. }
  290. }
  291. return null;
  292. }
  293. }
  294. /// <summary>
  295. /// Retrieve all the children of the given folder
  296. /// </summary>
  297. /// <param name="parent">The parent.</param>
  298. /// <returns>IEnumerable{BaseItem}.</returns>
  299. /// <exception cref="System.ArgumentNullException"></exception>
  300. public IEnumerable<BaseItem> RetrieveChildren(Folder parent)
  301. {
  302. if (parent == null)
  303. {
  304. throw new ArgumentNullException();
  305. }
  306. using (var cmd = Connection.CreateCommand())
  307. {
  308. cmd.CommandText = "select obj_type,data from items where guid in (select child from children where guid = @guid)";
  309. var guidParam = cmd.Parameters.Add("@guid", DbType.Guid);
  310. guidParam.Value = parent.Id;
  311. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  312. {
  313. while (reader.Read())
  314. {
  315. var type = reader.GetString(0);
  316. using (var stream = GetStream(reader, 1))
  317. {
  318. var itemType = _typeMapper.GetType(type);
  319. if (itemType == null)
  320. {
  321. Logger.Error("Cannot find type {0}. Probably belongs to plug-in that is no longer loaded.", type);
  322. continue;
  323. }
  324. var item = _jsonSerializer.DeserializeFromStream(stream, itemType) as BaseItem;
  325. if (item != null)
  326. {
  327. item.Parent = parent;
  328. yield return item;
  329. }
  330. }
  331. }
  332. }
  333. }
  334. }
  335. /// <summary>
  336. /// Save references to all the children for the given folder
  337. /// (Doesn't actually save the child entities)
  338. /// </summary>
  339. /// <param name="id">The id.</param>
  340. /// <param name="children">The children.</param>
  341. /// <param name="cancellationToken">The cancellation token.</param>
  342. /// <returns>Task.</returns>
  343. /// <exception cref="System.ArgumentNullException">id</exception>
  344. public async Task SaveChildren(Guid id, IEnumerable<BaseItem> children, CancellationToken cancellationToken)
  345. {
  346. if (id == Guid.Empty)
  347. {
  348. throw new ArgumentNullException("id");
  349. }
  350. if (children == null)
  351. {
  352. throw new ArgumentNullException("children");
  353. }
  354. if (cancellationToken == null)
  355. {
  356. throw new ArgumentNullException("cancellationToken");
  357. }
  358. cancellationToken.ThrowIfCancellationRequested();
  359. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  360. SQLiteTransaction transaction = null;
  361. try
  362. {
  363. transaction = Connection.BeginTransaction();
  364. // Delete exising children
  365. _deleteChildrenCommand.Parameters[0].Value = id;
  366. _deleteChildrenCommand.Transaction = transaction;
  367. await _deleteChildrenCommand.ExecuteNonQueryAsync(cancellationToken);
  368. // Save new children
  369. foreach (var child in children)
  370. {
  371. _saveChildrenCommand.Transaction = transaction;
  372. _saveChildrenCommand.Parameters[0].Value = id;
  373. _saveChildrenCommand.Parameters[1].Value = child.Id;
  374. await _saveChildrenCommand.ExecuteNonQueryAsync(cancellationToken);
  375. }
  376. transaction.Commit();
  377. }
  378. catch (OperationCanceledException)
  379. {
  380. if (transaction != null)
  381. {
  382. transaction.Rollback();
  383. }
  384. throw;
  385. }
  386. catch (Exception e)
  387. {
  388. Logger.ErrorException("Failed to save children:", e);
  389. if (transaction != null)
  390. {
  391. transaction.Rollback();
  392. }
  393. throw;
  394. }
  395. finally
  396. {
  397. if (transaction != null)
  398. {
  399. transaction.Dispose();
  400. }
  401. _writeLock.Release();
  402. }
  403. }
  404. /// <summary>
  405. /// Gets the critic reviews path.
  406. /// </summary>
  407. /// <param name="create">if set to <c>true</c> [create].</param>
  408. /// <returns>System.String.</returns>
  409. private string GetCriticReviewsPath(bool create)
  410. {
  411. var path = Path.Combine(_appPaths.DataPath, "critic-reviews");
  412. if (create && !Directory.Exists(path))
  413. {
  414. Directory.CreateDirectory(path);
  415. }
  416. return path;
  417. }
  418. /// <summary>
  419. /// Gets the critic reviews.
  420. /// </summary>
  421. /// <param name="itemId">The item id.</param>
  422. /// <returns>Task{IEnumerable{ItemReview}}.</returns>
  423. public Task<IEnumerable<ItemReview>> GetCriticReviews(Guid itemId)
  424. {
  425. return Task.Run<IEnumerable<ItemReview>>(() =>
  426. {
  427. try
  428. {
  429. var path = Path.Combine(GetCriticReviewsPath(false), itemId + ".json");
  430. return _jsonSerializer.DeserializeFromFile<List<ItemReview>>(path);
  431. }
  432. catch (DirectoryNotFoundException)
  433. {
  434. return new List<ItemReview>();
  435. }
  436. catch (FileNotFoundException)
  437. {
  438. return new List<ItemReview>();
  439. }
  440. });
  441. }
  442. /// <summary>
  443. /// Saves the critic reviews.
  444. /// </summary>
  445. /// <param name="itemId">The item id.</param>
  446. /// <param name="criticReviews">The critic reviews.</param>
  447. /// <returns>Task.</returns>
  448. public Task SaveCriticReviews(Guid itemId, IEnumerable<ItemReview> criticReviews)
  449. {
  450. return Task.Run(() =>
  451. {
  452. var path = Path.Combine(GetCriticReviewsPath(true), itemId + ".json");
  453. _jsonSerializer.SerializeToFile(criticReviews.ToList(), path);
  454. });
  455. }
  456. }
  457. }