SQLiteItemRepository.cs 11 KB

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