SQLiteItemRepository.cs 11 KB

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