SQLiteItemRepository.cs 9.8 KB

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