SQLiteItemRepository.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. using System.Linq;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Persistence;
  5. using MediaBrowser.Model.Entities;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Serialization;
  8. using MediaBrowser.Server.Implementations.Reflection;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Data;
  12. using System.IO;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. namespace MediaBrowser.Server.Implementations.Sqlite
  16. {
  17. /// <summary>
  18. /// Class SQLiteItemRepository
  19. /// </summary>
  20. public class SQLiteItemRepository : SqliteRepository, IItemRepository
  21. {
  22. /// <summary>
  23. /// The _type mapper
  24. /// </summary>
  25. private readonly TypeMapper _typeMapper = new TypeMapper();
  26. /// <summary>
  27. /// The repository name
  28. /// </summary>
  29. public const string RepositoryName = "SQLite";
  30. /// <summary>
  31. /// Gets the name of the repository
  32. /// </summary>
  33. /// <value>The name.</value>
  34. public string Name
  35. {
  36. get
  37. {
  38. return RepositoryName;
  39. }
  40. }
  41. /// <summary>
  42. /// Gets the json serializer.
  43. /// </summary>
  44. /// <value>The json serializer.</value>
  45. private readonly IJsonSerializer _jsonSerializer;
  46. /// <summary>
  47. /// The _app paths
  48. /// </summary>
  49. private readonly IApplicationPaths _appPaths;
  50. /// <summary>
  51. /// Initializes a new instance of the <see cref="SQLiteUserDataRepository" /> class.
  52. /// </summary>
  53. /// <param name="appPaths">The app paths.</param>
  54. /// <param name="jsonSerializer">The json serializer.</param>
  55. /// <param name="logManager">The log manager.</param>
  56. /// <exception cref="System.ArgumentNullException">appPaths</exception>
  57. public SQLiteItemRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
  58. : base(logManager)
  59. {
  60. if (appPaths == null)
  61. {
  62. throw new ArgumentNullException("appPaths");
  63. }
  64. if (jsonSerializer == null)
  65. {
  66. throw new ArgumentNullException("jsonSerializer");
  67. }
  68. _appPaths = appPaths;
  69. _jsonSerializer = jsonSerializer;
  70. }
  71. /// <summary>
  72. /// Opens the connection to the database
  73. /// </summary>
  74. /// <returns>Task.</returns>
  75. public async Task Initialize()
  76. {
  77. var dbFile = Path.Combine(_appPaths.DataPath, "library.db");
  78. await ConnectToDb(dbFile).ConfigureAwait(false);
  79. string[] queries = {
  80. "create table if not exists items (guid GUID primary key, obj_type, data BLOB)",
  81. "create index if not exists idx_items on items(guid)",
  82. "create table if not exists children (guid GUID, child GUID)",
  83. "create unique index if not exists idx_children on children(guid, child)",
  84. "create table if not exists schema_version (table_name primary key, version)",
  85. //triggers
  86. TriggerSql,
  87. //pragmas
  88. "pragma temp_store = memory"
  89. };
  90. RunQueries(queries);
  91. }
  92. //cascade delete triggers
  93. /// <summary>
  94. /// The trigger SQL
  95. /// </summary>
  96. protected string TriggerSql =
  97. @"CREATE TRIGGER if not exists delete_item
  98. AFTER DELETE
  99. ON items
  100. FOR EACH ROW
  101. BEGIN
  102. DELETE FROM children WHERE children.guid = old.child;
  103. DELETE FROM children WHERE children.child = old.child;
  104. END";
  105. /// <summary>
  106. /// Save a standard item in the repo
  107. /// </summary>
  108. /// <param name="item">The item.</param>
  109. /// <param name="cancellationToken">The cancellation token.</param>
  110. /// <returns>Task.</returns>
  111. /// <exception cref="System.ArgumentNullException">item</exception>
  112. public Task SaveItem(BaseItem item, CancellationToken cancellationToken)
  113. {
  114. if (item == null)
  115. {
  116. throw new ArgumentNullException("item");
  117. }
  118. if (cancellationToken == null)
  119. {
  120. throw new ArgumentNullException("cancellationToken");
  121. }
  122. cancellationToken.ThrowIfCancellationRequested();
  123. return Task.Run(() =>
  124. {
  125. var serialized = _jsonSerializer.SerializeToBytes(item);
  126. cancellationToken.ThrowIfCancellationRequested();
  127. var cmd = connection.CreateCommand();
  128. cmd.CommandText = "replace into items (guid, obj_type, data) values (@1, @2, @3)";
  129. cmd.AddParam("@1", item.Id);
  130. cmd.AddParam("@2", item.GetType().FullName);
  131. cmd.AddParam("@3", serialized);
  132. QueueCommand(cmd);
  133. });
  134. }
  135. /// <summary>
  136. /// Retrieve a standard item from the repo
  137. /// </summary>
  138. /// <param name="id">The id.</param>
  139. /// <returns>BaseItem.</returns>
  140. /// <exception cref="System.ArgumentException"></exception>
  141. public BaseItem GetItem(Guid id)
  142. {
  143. if (id == Guid.Empty)
  144. {
  145. throw new ArgumentNullException("id");
  146. }
  147. return RetrieveItemInternal(id);
  148. }
  149. /// <summary>
  150. /// Retrieves the items.
  151. /// </summary>
  152. /// <param name="ids">The ids.</param>
  153. /// <returns>IEnumerable{BaseItem}.</returns>
  154. /// <exception cref="System.ArgumentNullException">ids</exception>
  155. public IEnumerable<BaseItem> GetItems(IEnumerable<Guid> ids)
  156. {
  157. if (ids == null)
  158. {
  159. throw new ArgumentNullException("ids");
  160. }
  161. return ids.Select(RetrieveItemInternal);
  162. }
  163. /// <summary>
  164. /// Internal retrieve from items or users table
  165. /// </summary>
  166. /// <param name="id">The id.</param>
  167. /// <returns>BaseItem.</returns>
  168. /// <exception cref="System.ArgumentException"></exception>
  169. protected BaseItem RetrieveItemInternal(Guid id)
  170. {
  171. if (id == Guid.Empty)
  172. {
  173. throw new ArgumentNullException("id");
  174. }
  175. using (var cmd = connection.CreateCommand())
  176. {
  177. cmd.CommandText = "select obj_type,data from items where guid = @guid";
  178. var guidParam = cmd.Parameters.Add("@guid", DbType.Guid);
  179. guidParam.Value = id;
  180. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  181. {
  182. if (reader.Read())
  183. {
  184. var type = reader.GetString(0);
  185. using (var stream = GetStream(reader, 1))
  186. {
  187. var itemType = _typeMapper.GetType(type);
  188. if (itemType == null)
  189. {
  190. Logger.Error("Cannot find type {0}. Probably belongs to plug-in that is no longer loaded.", type);
  191. return null;
  192. }
  193. var item = _jsonSerializer.DeserializeFromStream(stream, itemType);
  194. return item as BaseItem;
  195. }
  196. }
  197. }
  198. return null;
  199. }
  200. }
  201. /// <summary>
  202. /// Retrieve all the children of the given folder
  203. /// </summary>
  204. /// <param name="parent">The parent.</param>
  205. /// <returns>IEnumerable{BaseItem}.</returns>
  206. /// <exception cref="System.ArgumentNullException"></exception>
  207. public IEnumerable<BaseItem> RetrieveChildren(Folder parent)
  208. {
  209. if (parent == null)
  210. {
  211. throw new ArgumentNullException();
  212. }
  213. using (var cmd = connection.CreateCommand())
  214. {
  215. cmd.CommandText = "select obj_type,data from items where guid in (select child from children where guid = @guid)";
  216. var guidParam = cmd.Parameters.Add("@guid", DbType.Guid);
  217. guidParam.Value = parent.Id;
  218. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  219. {
  220. while (reader.Read())
  221. {
  222. var type = reader.GetString(0);
  223. using (var stream = GetStream(reader, 1))
  224. {
  225. var itemType = _typeMapper.GetType(type);
  226. if (itemType == null)
  227. {
  228. Logger.Error("Cannot find type {0}. Probably belongs to plug-in that is no longer loaded.", type);
  229. continue;
  230. }
  231. var item = _jsonSerializer.DeserializeFromStream(stream, itemType) as BaseItem;
  232. if (item != null)
  233. {
  234. item.Parent = parent;
  235. yield return item;
  236. }
  237. }
  238. }
  239. }
  240. }
  241. }
  242. /// <summary>
  243. /// Save references to all the children for the given folder
  244. /// (Doesn't actually save the child entities)
  245. /// </summary>
  246. /// <param name="id">The id.</param>
  247. /// <param name="children">The children.</param>
  248. /// <param name="cancellationToken">The cancellation token.</param>
  249. /// <returns>Task.</returns>
  250. /// <exception cref="System.ArgumentNullException">id</exception>
  251. public Task SaveChildren(Guid id, IEnumerable<BaseItem> children, CancellationToken cancellationToken)
  252. {
  253. if (id == Guid.Empty)
  254. {
  255. throw new ArgumentNullException("id");
  256. }
  257. if (children == null)
  258. {
  259. throw new ArgumentNullException("children");
  260. }
  261. if (cancellationToken == null)
  262. {
  263. throw new ArgumentNullException("cancellationToken");
  264. }
  265. cancellationToken.ThrowIfCancellationRequested();
  266. return Task.Run(() =>
  267. {
  268. var cmd = connection.CreateCommand();
  269. cmd.CommandText = "delete from children where guid = @guid";
  270. cmd.AddParam("@guid", id);
  271. QueueCommand(cmd);
  272. foreach (var child in children)
  273. {
  274. var guid = child.Id;
  275. cmd = connection.CreateCommand();
  276. cmd.AddParam("@guid", id);
  277. cmd.CommandText = "replace into children (guid, child) values (@guid, @child)";
  278. var childParam = cmd.Parameters.Add("@child", DbType.Guid);
  279. childParam.Value = guid;
  280. QueueCommand(cmd);
  281. }
  282. });
  283. }
  284. /// <summary>
  285. /// Gets the critic reviews path.
  286. /// </summary>
  287. /// <value>The critic reviews path.</value>
  288. private string CriticReviewsPath
  289. {
  290. get
  291. {
  292. var path = Path.Combine(_appPaths.DataPath, "critic-reviews");
  293. if (!Directory.Exists(path))
  294. {
  295. Directory.CreateDirectory(path);
  296. }
  297. return path;
  298. }
  299. }
  300. /// <summary>
  301. /// Gets the critic reviews.
  302. /// </summary>
  303. /// <param name="itemId">The item id.</param>
  304. /// <returns>Task{IEnumerable{ItemReview}}.</returns>
  305. public Task<IEnumerable<ItemReview>> GetCriticReviews(Guid itemId)
  306. {
  307. return Task.Run<IEnumerable<ItemReview>>(() =>
  308. {
  309. try
  310. {
  311. var path = Path.Combine(CriticReviewsPath, itemId + ".json");
  312. return _jsonSerializer.DeserializeFromFile<List<ItemReview>>(path);
  313. }
  314. catch (FileNotFoundException)
  315. {
  316. return new List<ItemReview>();
  317. }
  318. });
  319. }
  320. /// <summary>
  321. /// Saves the critic reviews.
  322. /// </summary>
  323. /// <param name="itemId">The item id.</param>
  324. /// <param name="criticReviews">The critic reviews.</param>
  325. /// <returns>Task.</returns>
  326. public Task SaveCriticReviews(Guid itemId, IEnumerable<ItemReview> criticReviews)
  327. {
  328. return Task.Run(() =>
  329. {
  330. var path = Path.Combine(CriticReviewsPath, itemId + ".json");
  331. _jsonSerializer.SerializeToFile(criticReviews.ToList(), path);
  332. });
  333. }
  334. }
  335. }