SQLiteItemRepository.cs 9.7 KB

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