SQLiteItemRepository.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. using MediaBrowser.Common.Serialization;
  2. using MediaBrowser.Controller.Entities;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel.Composition;
  6. using System.Data;
  7. using System.IO;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. namespace MediaBrowser.Controller.Persistence.SQLite
  11. {
  12. /// <summary>
  13. /// Class SQLiteItemRepository
  14. /// </summary>
  15. [Export(typeof(IItemRepository))]
  16. public class SQLiteItemRepository : SqliteRepository, IItemRepository
  17. {
  18. /// <summary>
  19. /// The _type mapper
  20. /// </summary>
  21. private readonly TypeMapper _typeMapper = new TypeMapper();
  22. /// <summary>
  23. /// The repository name
  24. /// </summary>
  25. public const string RepositoryName = "SQLite";
  26. /// <summary>
  27. /// Gets the name of the repository
  28. /// </summary>
  29. /// <value>The name.</value>
  30. public string Name
  31. {
  32. get
  33. {
  34. return RepositoryName;
  35. }
  36. }
  37. /// <summary>
  38. /// Opens the connection to the database
  39. /// </summary>
  40. /// <returns>Task.</returns>
  41. public async Task Initialize()
  42. {
  43. var dbFile = Path.Combine(Kernel.Instance.ApplicationPaths.DataPath, "library.db");
  44. await ConnectToDB(dbFile).ConfigureAwait(false);
  45. string[] queries = {
  46. "create table if not exists items (guid GUID primary key, obj_type, data BLOB)",
  47. "create index if not exists idx_items on items(guid)",
  48. "create table if not exists children (guid GUID, child GUID)",
  49. "create unique index if not exists idx_children on children(guid, child)",
  50. "create table if not exists schema_version (table_name primary key, version)",
  51. //triggers
  52. TriggerSql,
  53. //pragmas
  54. "pragma temp_store = memory"
  55. };
  56. RunQueries(queries);
  57. }
  58. //cascade delete triggers
  59. /// <summary>
  60. /// The trigger SQL
  61. /// </summary>
  62. protected string TriggerSql =
  63. @"CREATE TRIGGER if not exists delete_item
  64. AFTER DELETE
  65. ON items
  66. FOR EACH ROW
  67. BEGIN
  68. DELETE FROM children WHERE children.guid = old.child;
  69. DELETE FROM children WHERE children.child = old.child;
  70. END";
  71. /// <summary>
  72. /// Save a standard item in the repo
  73. /// </summary>
  74. /// <param name="item">The item.</param>
  75. /// <param name="cancellationToken">The cancellation token.</param>
  76. /// <returns>Task.</returns>
  77. /// <exception cref="System.ArgumentNullException">item</exception>
  78. public Task SaveItem(BaseItem item, CancellationToken cancellationToken)
  79. {
  80. if (item == null)
  81. {
  82. throw new ArgumentNullException("item");
  83. }
  84. if (cancellationToken == null)
  85. {
  86. throw new ArgumentNullException("cancellationToken");
  87. }
  88. cancellationToken.ThrowIfCancellationRequested();
  89. return Task.Run(() =>
  90. {
  91. var serialized = JsonSerializer.SerializeToBytes(item);
  92. cancellationToken.ThrowIfCancellationRequested();
  93. var cmd = connection.CreateCommand();
  94. cmd.CommandText = "replace into items (guid, obj_type, data) values (@1, @2, @3)";
  95. cmd.AddParam("@1", item.Id);
  96. cmd.AddParam("@2", item.GetType().FullName);
  97. cmd.AddParam("@3", serialized);
  98. QueueCommand(cmd);
  99. });
  100. }
  101. /// <summary>
  102. /// Retrieve a standard item from the repo
  103. /// </summary>
  104. /// <param name="id">The id.</param>
  105. /// <returns>BaseItem.</returns>
  106. /// <exception cref="System.ArgumentException"></exception>
  107. public BaseItem RetrieveItem(Guid id)
  108. {
  109. if (id == Guid.Empty)
  110. {
  111. throw new ArgumentException();
  112. }
  113. return RetrieveItemInternal(id);
  114. }
  115. /// <summary>
  116. /// Internal retrieve from items or users table
  117. /// </summary>
  118. /// <param name="id">The id.</param>
  119. /// <returns>BaseItem.</returns>
  120. /// <exception cref="System.ArgumentException"></exception>
  121. protected BaseItem RetrieveItemInternal(Guid id)
  122. {
  123. if (id == Guid.Empty)
  124. {
  125. throw new ArgumentException();
  126. }
  127. var cmd = connection.CreateCommand();
  128. cmd.CommandText = "select obj_type,data from items where guid = @guid";
  129. var guidParam = cmd.Parameters.Add("@guid", DbType.Guid);
  130. guidParam.Value = id;
  131. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  132. {
  133. if (reader.Read())
  134. {
  135. var type = reader.GetString(0);
  136. using (var stream = GetStream(reader, 1))
  137. {
  138. var itemType = _typeMapper.GetType(type);
  139. if (itemType == null)
  140. {
  141. Logger.Error("Cannot find type {0}. Probably belongs to plug-in that is no longer loaded.", type);
  142. return null;
  143. }
  144. var item = JsonSerializer.DeserializeFromStream(stream, itemType);
  145. return item as BaseItem;
  146. }
  147. }
  148. }
  149. return null;
  150. }
  151. /// <summary>
  152. /// Retrieve all the children of the given folder
  153. /// </summary>
  154. /// <param name="parent">The parent.</param>
  155. /// <returns>IEnumerable{BaseItem}.</returns>
  156. /// <exception cref="System.ArgumentNullException"></exception>
  157. public IEnumerable<BaseItem> RetrieveChildren(Folder parent)
  158. {
  159. if (parent == null)
  160. {
  161. throw new ArgumentNullException();
  162. }
  163. var cmd = connection.CreateCommand();
  164. cmd.CommandText = "select obj_type,data from items where guid in (select child from children where guid = @guid)";
  165. var guidParam = cmd.Parameters.Add("@guid", DbType.Guid);
  166. guidParam.Value = parent.Id;
  167. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  168. {
  169. while (reader.Read())
  170. {
  171. var type = reader.GetString(0);
  172. using (var stream = GetStream(reader, 1))
  173. {
  174. var itemType = _typeMapper.GetType(type);
  175. if (itemType == null)
  176. {
  177. Logger.Error("Cannot find type {0}. Probably belongs to plug-in that is no longer loaded.",type);
  178. continue;
  179. }
  180. var item = JsonSerializer.DeserializeFromStream(stream, itemType) as BaseItem;
  181. if (item != null)
  182. {
  183. item.Parent = parent;
  184. yield return item;
  185. }
  186. }
  187. }
  188. }
  189. }
  190. /// <summary>
  191. /// Save references to all the children for the given folder
  192. /// (Doesn't actually save the child entities)
  193. /// </summary>
  194. /// <param name="id">The id.</param>
  195. /// <param name="children">The children.</param>
  196. /// <param name="cancellationToken">The cancellation token.</param>
  197. /// <returns>Task.</returns>
  198. /// <exception cref="System.ArgumentNullException">id</exception>
  199. public Task SaveChildren(Guid id, IEnumerable<BaseItem> children, CancellationToken cancellationToken)
  200. {
  201. if (id == Guid.Empty)
  202. {
  203. throw new ArgumentNullException("id");
  204. }
  205. if (children == null)
  206. {
  207. throw new ArgumentNullException("children");
  208. }
  209. if (cancellationToken == null)
  210. {
  211. throw new ArgumentNullException("cancellationToken");
  212. }
  213. cancellationToken.ThrowIfCancellationRequested();
  214. return Task.Run(() =>
  215. {
  216. var cmd = connection.CreateCommand();
  217. cmd.CommandText = "delete from children where guid = @guid";
  218. cmd.AddParam("@guid", id);
  219. QueueCommand(cmd);
  220. foreach (var child in children)
  221. {
  222. var guid = child.Id;
  223. cmd = connection.CreateCommand();
  224. cmd.AddParam("@guid", id);
  225. cmd.CommandText = "replace into children (guid, child) values (@guid, @child)";
  226. var childParam = cmd.Parameters.Add("@child", DbType.Guid);
  227. childParam.Value = guid;
  228. QueueCommand(cmd);
  229. }
  230. });
  231. }
  232. }
  233. }