SQLiteItemRepository.cs 11 KB

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