SQLiteItemRepository.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 async Task SaveItem(BaseItem item, CancellationToken cancellationToken)
  155. {
  156. if (item == null)
  157. {
  158. throw new ArgumentNullException("item");
  159. }
  160. if (cancellationToken == null)
  161. {
  162. throw new ArgumentNullException("cancellationToken");
  163. }
  164. cancellationToken.ThrowIfCancellationRequested();
  165. var serialized = _jsonSerializer.SerializeToBytes(item);
  166. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  167. SQLiteTransaction transaction = null;
  168. try
  169. {
  170. transaction = Connection.BeginTransaction();
  171. _saveItemCommand.Parameters[0].Value = item.Id;
  172. _saveItemCommand.Parameters[1].Value = item.GetType().FullName;
  173. _saveItemCommand.Parameters[2].Value = serialized;
  174. _saveItemCommand.Transaction = transaction;
  175. await _saveItemCommand.ExecuteNonQueryAsync(cancellationToken);
  176. transaction.Commit();
  177. }
  178. catch (OperationCanceledException)
  179. {
  180. if (transaction != null)
  181. {
  182. transaction.Rollback();
  183. }
  184. }
  185. catch (Exception e)
  186. {
  187. Logger.ErrorException("Failed to save item:", e);
  188. if (transaction != null)
  189. {
  190. transaction.Rollback();
  191. }
  192. }
  193. finally
  194. {
  195. if (transaction != null)
  196. {
  197. transaction.Dispose();
  198. }
  199. _writeLock.Release();
  200. }
  201. }
  202. /// <summary>
  203. /// Retrieve a standard item from the repo
  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 GetItem(Guid id)
  210. {
  211. if (id == Guid.Empty)
  212. {
  213. throw new ArgumentNullException("id");
  214. }
  215. return RetrieveItemInternal(id);
  216. }
  217. /// <summary>
  218. /// Retrieves the items.
  219. /// </summary>
  220. /// <param name="ids">The ids.</param>
  221. /// <returns>IEnumerable{BaseItem}.</returns>
  222. /// <exception cref="System.ArgumentNullException">ids</exception>
  223. public IEnumerable<BaseItem> GetItems(IEnumerable<Guid> ids)
  224. {
  225. if (ids == null)
  226. {
  227. throw new ArgumentNullException("ids");
  228. }
  229. return ids.Select(RetrieveItemInternal);
  230. }
  231. /// <summary>
  232. /// Internal retrieve from items or users table
  233. /// </summary>
  234. /// <param name="id">The id.</param>
  235. /// <returns>BaseItem.</returns>
  236. /// <exception cref="System.ArgumentNullException">id</exception>
  237. /// <exception cref="System.ArgumentException"></exception>
  238. protected BaseItem RetrieveItemInternal(Guid id)
  239. {
  240. if (id == Guid.Empty)
  241. {
  242. throw new ArgumentNullException("id");
  243. }
  244. using (var cmd = Connection.CreateCommand())
  245. {
  246. cmd.CommandText = "select obj_type,data from items where guid = @guid";
  247. var guidParam = cmd.Parameters.Add("@guid", DbType.Guid);
  248. guidParam.Value = id;
  249. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  250. {
  251. if (reader.Read())
  252. {
  253. var type = reader.GetString(0);
  254. using (var stream = GetStream(reader, 1))
  255. {
  256. var itemType = _typeMapper.GetType(type);
  257. if (itemType == null)
  258. {
  259. Logger.Error("Cannot find type {0}. Probably belongs to plug-in that is no longer loaded.", type);
  260. return null;
  261. }
  262. var item = _jsonSerializer.DeserializeFromStream(stream, itemType);
  263. return item as BaseItem;
  264. }
  265. }
  266. }
  267. return null;
  268. }
  269. }
  270. /// <summary>
  271. /// Retrieve all the children of the given folder
  272. /// </summary>
  273. /// <param name="parent">The parent.</param>
  274. /// <returns>IEnumerable{BaseItem}.</returns>
  275. /// <exception cref="System.ArgumentNullException"></exception>
  276. public IEnumerable<BaseItem> RetrieveChildren(Folder parent)
  277. {
  278. if (parent == null)
  279. {
  280. throw new ArgumentNullException();
  281. }
  282. using (var cmd = Connection.CreateCommand())
  283. {
  284. cmd.CommandText = "select obj_type,data from items where guid in (select child from children where guid = @guid)";
  285. var guidParam = cmd.Parameters.Add("@guid", DbType.Guid);
  286. guidParam.Value = parent.Id;
  287. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  288. {
  289. while (reader.Read())
  290. {
  291. var type = reader.GetString(0);
  292. using (var stream = GetStream(reader, 1))
  293. {
  294. var itemType = _typeMapper.GetType(type);
  295. if (itemType == null)
  296. {
  297. Logger.Error("Cannot find type {0}. Probably belongs to plug-in that is no longer loaded.", type);
  298. continue;
  299. }
  300. var item = _jsonSerializer.DeserializeFromStream(stream, itemType) as BaseItem;
  301. if (item != null)
  302. {
  303. item.Parent = parent;
  304. yield return item;
  305. }
  306. }
  307. }
  308. }
  309. }
  310. }
  311. /// <summary>
  312. /// Save references to all the children for the given folder
  313. /// (Doesn't actually save the child entities)
  314. /// </summary>
  315. /// <param name="id">The id.</param>
  316. /// <param name="children">The children.</param>
  317. /// <param name="cancellationToken">The cancellation token.</param>
  318. /// <returns>Task.</returns>
  319. /// <exception cref="System.ArgumentNullException">id</exception>
  320. public async Task SaveChildren(Guid id, IEnumerable<BaseItem> children, CancellationToken cancellationToken)
  321. {
  322. if (id == Guid.Empty)
  323. {
  324. throw new ArgumentNullException("id");
  325. }
  326. if (children == null)
  327. {
  328. throw new ArgumentNullException("children");
  329. }
  330. if (cancellationToken == null)
  331. {
  332. throw new ArgumentNullException("cancellationToken");
  333. }
  334. cancellationToken.ThrowIfCancellationRequested();
  335. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  336. SQLiteTransaction transaction = null;
  337. try
  338. {
  339. transaction = Connection.BeginTransaction();
  340. // Delete exising children
  341. _deleteChildrenCommand.Parameters[0].Value = id;
  342. _deleteChildrenCommand.Transaction = transaction;
  343. await _deleteChildrenCommand.ExecuteNonQueryAsync(cancellationToken);
  344. // Save new children
  345. foreach (var child in children)
  346. {
  347. _saveChildrenCommand.Transaction = transaction;
  348. _saveChildrenCommand.Parameters[0].Value = id;
  349. _saveChildrenCommand.Parameters[1].Value = child.Id;
  350. await _saveChildrenCommand.ExecuteNonQueryAsync(cancellationToken);
  351. }
  352. transaction.Commit();
  353. }
  354. catch (OperationCanceledException)
  355. {
  356. if (transaction != null)
  357. {
  358. transaction.Rollback();
  359. }
  360. }
  361. catch (Exception e)
  362. {
  363. Logger.ErrorException("Failed to save item:", e);
  364. if (transaction != null)
  365. {
  366. transaction.Rollback();
  367. }
  368. }
  369. finally
  370. {
  371. if (transaction != null)
  372. {
  373. transaction.Dispose();
  374. }
  375. _writeLock.Release();
  376. }
  377. }
  378. /// <summary>
  379. /// Gets the critic reviews path.
  380. /// </summary>
  381. /// <value>The critic reviews path.</value>
  382. private string CriticReviewsPath
  383. {
  384. get
  385. {
  386. var path = Path.Combine(_appPaths.DataPath, "critic-reviews");
  387. if (!Directory.Exists(path))
  388. {
  389. Directory.CreateDirectory(path);
  390. }
  391. return path;
  392. }
  393. }
  394. /// <summary>
  395. /// Gets the critic reviews.
  396. /// </summary>
  397. /// <param name="itemId">The item id.</param>
  398. /// <returns>Task{IEnumerable{ItemReview}}.</returns>
  399. public Task<IEnumerable<ItemReview>> GetCriticReviews(Guid itemId)
  400. {
  401. return Task.Run<IEnumerable<ItemReview>>(() =>
  402. {
  403. try
  404. {
  405. var path = Path.Combine(CriticReviewsPath, itemId + ".json");
  406. return _jsonSerializer.DeserializeFromFile<List<ItemReview>>(path);
  407. }
  408. catch (FileNotFoundException)
  409. {
  410. return new List<ItemReview>();
  411. }
  412. });
  413. }
  414. /// <summary>
  415. /// Saves the critic reviews.
  416. /// </summary>
  417. /// <param name="itemId">The item id.</param>
  418. /// <param name="criticReviews">The critic reviews.</param>
  419. /// <returns>Task.</returns>
  420. public Task SaveCriticReviews(Guid itemId, IEnumerable<ItemReview> criticReviews)
  421. {
  422. return Task.Run(() =>
  423. {
  424. var path = Path.Combine(CriticReviewsPath, itemId + ".json");
  425. _jsonSerializer.SerializeToFile(criticReviews.ToList(), path);
  426. });
  427. }
  428. }
  429. }