SQLiteItemRepository.cs 9.5 KB

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