parent
95f471e8c3
commit
e677a57bf1
@ -0,0 +1,235 @@
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Common.IO;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Controller.Persistence;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using MediaBrowser.Model.Logging;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MediaBrowser.Server.Implementations.Persistence
|
||||
{
|
||||
public class JsonItemRepository : IItemRepository
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, SemaphoreSlim> _fileLocks = new ConcurrentDictionary<string, SemaphoreSlim>();
|
||||
|
||||
private SemaphoreSlim GetLock(string filename)
|
||||
{
|
||||
return _fileLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the repository
|
||||
/// </summary>
|
||||
/// <value>The name.</value>
|
||||
public string Name
|
||||
{
|
||||
get
|
||||
{
|
||||
return "Json";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the json serializer.
|
||||
/// </summary>
|
||||
/// <value>The json serializer.</value>
|
||||
private readonly IJsonSerializer _jsonSerializer;
|
||||
|
||||
private readonly string _criticReviewsPath;
|
||||
|
||||
private readonly FileSystemRepository _itemRepo;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JsonUserDataRepository" /> class.
|
||||
/// </summary>
|
||||
/// <param name="appPaths">The app paths.</param>
|
||||
/// <param name="jsonSerializer">The json serializer.</param>
|
||||
/// <param name="logManager">The log manager.</param>
|
||||
/// <exception cref="System.ArgumentNullException">appPaths</exception>
|
||||
public JsonItemRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
|
||||
{
|
||||
if (appPaths == null)
|
||||
{
|
||||
throw new ArgumentNullException("appPaths");
|
||||
}
|
||||
if (jsonSerializer == null)
|
||||
{
|
||||
throw new ArgumentNullException("jsonSerializer");
|
||||
}
|
||||
|
||||
_jsonSerializer = jsonSerializer;
|
||||
|
||||
_criticReviewsPath = Path.Combine(appPaths.DataPath, "critic-reviews");
|
||||
|
||||
_itemRepo = new FileSystemRepository(Path.Combine(appPaths.DataPath, "library"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the connection to the database
|
||||
/// </summary>
|
||||
/// <returns>Task.</returns>
|
||||
public Task Initialize()
|
||||
{
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Save a standard item in the repo
|
||||
/// </summary>
|
||||
/// <param name="item">The item.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>Task.</returns>
|
||||
/// <exception cref="System.ArgumentNullException">item</exception>
|
||||
public async Task SaveItem(BaseItem item, CancellationToken cancellationToken)
|
||||
{
|
||||
if (item == null)
|
||||
{
|
||||
throw new ArgumentNullException("item");
|
||||
}
|
||||
|
||||
if (!Directory.Exists(_criticReviewsPath))
|
||||
{
|
||||
Directory.CreateDirectory(_criticReviewsPath);
|
||||
}
|
||||
|
||||
var path = _itemRepo.GetResourcePath(item.Id + ".json");
|
||||
|
||||
var parentPath = Path.GetDirectoryName(path);
|
||||
if (!Directory.Exists(parentPath))
|
||||
{
|
||||
Directory.CreateDirectory(parentPath);
|
||||
}
|
||||
|
||||
var semaphore = GetLock(path);
|
||||
|
||||
await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
try
|
||||
{
|
||||
_jsonSerializer.SerializeToFile(item, path);
|
||||
}
|
||||
finally
|
||||
{
|
||||
semaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves the items.
|
||||
/// </summary>
|
||||
/// <param name="items">The items.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>Task.</returns>
|
||||
/// <exception cref="System.ArgumentNullException">
|
||||
/// items
|
||||
/// or
|
||||
/// cancellationToken
|
||||
/// </exception>
|
||||
public Task SaveItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
|
||||
{
|
||||
if (items == null)
|
||||
{
|
||||
throw new ArgumentNullException("items");
|
||||
}
|
||||
|
||||
if (cancellationToken == null)
|
||||
{
|
||||
throw new ArgumentNullException("cancellationToken");
|
||||
}
|
||||
|
||||
var tasks = items.Select(i => SaveItem(i, cancellationToken));
|
||||
|
||||
return Task.WhenAll(tasks);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the item.
|
||||
/// </summary>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <param name="type">The type.</param>
|
||||
/// <returns>BaseItem.</returns>
|
||||
/// <exception cref="System.ArgumentNullException">id</exception>
|
||||
public BaseItem RetrieveItem(Guid id, Type type)
|
||||
{
|
||||
if (id == Guid.Empty)
|
||||
{
|
||||
throw new ArgumentNullException("id");
|
||||
}
|
||||
|
||||
var path = _itemRepo.GetResourcePath(id + ".json");
|
||||
|
||||
try
|
||||
{
|
||||
return (BaseItem)_jsonSerializer.DeserializeFromFile(type, path);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// File doesn't exist or is currently bring written to
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the critic reviews.
|
||||
/// </summary>
|
||||
/// <param name="itemId">The item id.</param>
|
||||
/// <returns>Task{IEnumerable{ItemReview}}.</returns>
|
||||
public Task<IEnumerable<ItemReview>> GetCriticReviews(Guid itemId)
|
||||
{
|
||||
return Task.Run<IEnumerable<ItemReview>>(() =>
|
||||
{
|
||||
var path = Path.Combine(_criticReviewsPath, itemId + ".json");
|
||||
|
||||
try
|
||||
{
|
||||
return _jsonSerializer.DeserializeFromFile<List<ItemReview>>(path);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// File doesn't exist or is currently bring written to
|
||||
return new List<ItemReview>();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves the critic reviews.
|
||||
/// </summary>
|
||||
/// <param name="itemId">The item id.</param>
|
||||
/// <param name="criticReviews">The critic reviews.</param>
|
||||
/// <returns>Task.</returns>
|
||||
public Task SaveCriticReviews(Guid itemId, IEnumerable<ItemReview> criticReviews)
|
||||
{
|
||||
return Task.Run(() =>
|
||||
{
|
||||
if (!Directory.Exists(_criticReviewsPath))
|
||||
{
|
||||
Directory.CreateDirectory(_criticReviewsPath);
|
||||
}
|
||||
|
||||
var path = Path.Combine(_criticReviewsPath, itemId + ".json");
|
||||
|
||||
_jsonSerializer.SerializeToFile(criticReviews.ToList(), path);
|
||||
});
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
// Wait up to two seconds for any existing writes to finish
|
||||
var locks = _fileLocks.Values.ToList()
|
||||
.Where(i => i.CurrentCount == 1)
|
||||
.Select(i => i.WaitAsync(2000));
|
||||
|
||||
var task = Task.WhenAll(locks);
|
||||
|
||||
Task.WaitAll(task);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,524 +0,0 @@
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Controller.Persistence;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using MediaBrowser.Model.Logging;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
using MediaBrowser.Server.Implementations.Reflection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.SQLite;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MediaBrowser.Server.Implementations.Sqlite
|
||||
{
|
||||
/// <summary>
|
||||
/// Class SQLiteItemRepository
|
||||
/// </summary>
|
||||
public class SQLiteItemRepository : SqliteRepository, IItemRepository
|
||||
{
|
||||
/// <summary>
|
||||
/// The _type mapper
|
||||
/// </summary>
|
||||
private readonly TypeMapper _typeMapper = new TypeMapper();
|
||||
|
||||
/// <summary>
|
||||
/// The repository name
|
||||
/// </summary>
|
||||
public const string RepositoryName = "SQLite";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the repository
|
||||
/// </summary>
|
||||
/// <value>The name.</value>
|
||||
public string Name
|
||||
{
|
||||
get
|
||||
{
|
||||
return RepositoryName;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the json serializer.
|
||||
/// </summary>
|
||||
/// <value>The json serializer.</value>
|
||||
private readonly IJsonSerializer _jsonSerializer;
|
||||
|
||||
/// <summary>
|
||||
/// The _app paths
|
||||
/// </summary>
|
||||
private readonly IApplicationPaths _appPaths;
|
||||
|
||||
/// <summary>
|
||||
/// The _save item command
|
||||
/// </summary>
|
||||
private SQLiteCommand _saveItemCommand;
|
||||
/// <summary>
|
||||
/// The _delete children command
|
||||
/// </summary>
|
||||
private SQLiteCommand _deleteChildrenCommand;
|
||||
/// <summary>
|
||||
/// The _save children command
|
||||
/// </summary>
|
||||
private SQLiteCommand _saveChildrenCommand;
|
||||
|
||||
private string _criticReviewsPath;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SQLiteUserDataRepository" /> class.
|
||||
/// </summary>
|
||||
/// <param name="appPaths">The app paths.</param>
|
||||
/// <param name="jsonSerializer">The json serializer.</param>
|
||||
/// <param name="logManager">The log manager.</param>
|
||||
/// <exception cref="System.ArgumentNullException">appPaths</exception>
|
||||
public SQLiteItemRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
|
||||
: base(logManager)
|
||||
{
|
||||
if (appPaths == null)
|
||||
{
|
||||
throw new ArgumentNullException("appPaths");
|
||||
}
|
||||
if (jsonSerializer == null)
|
||||
{
|
||||
throw new ArgumentNullException("jsonSerializer");
|
||||
}
|
||||
|
||||
_appPaths = appPaths;
|
||||
_jsonSerializer = jsonSerializer;
|
||||
|
||||
_criticReviewsPath = Path.Combine(_appPaths.DataPath, "critic-reviews");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the connection to the database
|
||||
/// </summary>
|
||||
/// <returns>Task.</returns>
|
||||
public async Task Initialize()
|
||||
{
|
||||
var dbFile = Path.Combine(_appPaths.DataPath, "library.db");
|
||||
|
||||
await ConnectToDb(dbFile).ConfigureAwait(false);
|
||||
|
||||
string[] queries = {
|
||||
|
||||
"create table if not exists items (guid GUID primary key, obj_type, data BLOB)",
|
||||
"create index if not exists idx_items on items(guid)",
|
||||
"create table if not exists children (guid GUID, child GUID)",
|
||||
"create unique index if not exists idx_children on children(guid, child)",
|
||||
"create table if not exists schema_version (table_name primary key, version)",
|
||||
//triggers
|
||||
TriggerSql,
|
||||
//pragmas
|
||||
"pragma temp_store = memory"
|
||||
};
|
||||
|
||||
RunQueries(queries);
|
||||
|
||||
PrepareStatements();
|
||||
}
|
||||
|
||||
//cascade delete triggers
|
||||
/// <summary>
|
||||
/// The trigger SQL
|
||||
/// </summary>
|
||||
protected string TriggerSql =
|
||||
@"CREATE TRIGGER if not exists delete_item
|
||||
AFTER DELETE
|
||||
ON items
|
||||
FOR EACH ROW
|
||||
BEGIN
|
||||
DELETE FROM children WHERE children.guid = old.child;
|
||||
DELETE FROM children WHERE children.child = old.child;
|
||||
END";
|
||||
|
||||
/// <summary>
|
||||
/// The _write lock
|
||||
/// </summary>
|
||||
private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
|
||||
|
||||
/// <summary>
|
||||
/// Prepares the statements.
|
||||
/// </summary>
|
||||
private void PrepareStatements()
|
||||
{
|
||||
_saveItemCommand = new SQLiteCommand
|
||||
{
|
||||
CommandText = "replace into items (guid, obj_type, data) values (@1, @2, @3)"
|
||||
};
|
||||
|
||||
_saveItemCommand.Parameters.Add(new SQLiteParameter("@1"));
|
||||
_saveItemCommand.Parameters.Add(new SQLiteParameter("@2"));
|
||||
_saveItemCommand.Parameters.Add(new SQLiteParameter("@3"));
|
||||
|
||||
_deleteChildrenCommand = new SQLiteCommand
|
||||
{
|
||||
CommandText = "delete from children where guid = @guid"
|
||||
};
|
||||
_deleteChildrenCommand.Parameters.Add(new SQLiteParameter("@guid"));
|
||||
|
||||
_saveChildrenCommand = new SQLiteCommand
|
||||
{
|
||||
CommandText = "replace into children (guid, child) values (@guid, @child)"
|
||||
};
|
||||
_saveChildrenCommand.Parameters.Add(new SQLiteParameter("@guid"));
|
||||
_saveChildrenCommand.Parameters.Add(new SQLiteParameter("@child"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Save a standard item in the repo
|
||||
/// </summary>
|
||||
/// <param name="item">The item.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>Task.</returns>
|
||||
/// <exception cref="System.ArgumentNullException">item</exception>
|
||||
public Task SaveItem(BaseItem item, CancellationToken cancellationToken)
|
||||
{
|
||||
if (item == null)
|
||||
{
|
||||
throw new ArgumentNullException("item");
|
||||
}
|
||||
|
||||
return SaveItems(new[] { item }, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves the items.
|
||||
/// </summary>
|
||||
/// <param name="items">The items.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>Task.</returns>
|
||||
/// <exception cref="System.ArgumentNullException">
|
||||
/// items
|
||||
/// or
|
||||
/// cancellationToken
|
||||
/// </exception>
|
||||
public async Task SaveItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
|
||||
{
|
||||
if (items == null)
|
||||
{
|
||||
throw new ArgumentNullException("items");
|
||||
}
|
||||
|
||||
if (cancellationToken == null)
|
||||
{
|
||||
throw new ArgumentNullException("cancellationToken");
|
||||
}
|
||||
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
SQLiteTransaction transaction = null;
|
||||
|
||||
try
|
||||
{
|
||||
transaction = Connection.BeginTransaction();
|
||||
|
||||
foreach (var item in items)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
_saveItemCommand.Parameters[0].Value = item.Id;
|
||||
_saveItemCommand.Parameters[1].Value = item.GetType().FullName;
|
||||
_saveItemCommand.Parameters[2].Value = _jsonSerializer.SerializeToBytes(item);
|
||||
|
||||
_saveItemCommand.Transaction = transaction;
|
||||
|
||||
await _saveItemCommand.ExecuteNonQueryAsync(cancellationToken);
|
||||
}
|
||||
|
||||
transaction.Commit();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
if (transaction != null)
|
||||
{
|
||||
transaction.Rollback();
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.ErrorException("Failed to save items:", e);
|
||||
|
||||
if (transaction != null)
|
||||
{
|
||||
transaction.Rollback();
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (transaction != null)
|
||||
{
|
||||
transaction.Dispose();
|
||||
}
|
||||
|
||||
_writeLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve a standard item from the repo
|
||||
/// </summary>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <returns>BaseItem.</returns>
|
||||
/// <exception cref="System.ArgumentNullException">id</exception>
|
||||
/// <exception cref="System.ArgumentException"></exception>
|
||||
public BaseItem GetItem(Guid id)
|
||||
{
|
||||
if (id == Guid.Empty)
|
||||
{
|
||||
throw new ArgumentNullException("id");
|
||||
}
|
||||
|
||||
return RetrieveItemInternal(id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the items.
|
||||
/// </summary>
|
||||
/// <param name="ids">The ids.</param>
|
||||
/// <returns>IEnumerable{BaseItem}.</returns>
|
||||
/// <exception cref="System.ArgumentNullException">ids</exception>
|
||||
public IEnumerable<BaseItem> GetItems(IEnumerable<Guid> ids)
|
||||
{
|
||||
if (ids == null)
|
||||
{
|
||||
throw new ArgumentNullException("ids");
|
||||
}
|
||||
|
||||
return ids.Select(RetrieveItemInternal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Internal retrieve from items or users table
|
||||
/// </summary>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <returns>BaseItem.</returns>
|
||||
/// <exception cref="System.ArgumentNullException">id</exception>
|
||||
/// <exception cref="System.ArgumentException"></exception>
|
||||
protected BaseItem RetrieveItemInternal(Guid id)
|
||||
{
|
||||
if (id == Guid.Empty)
|
||||
{
|
||||
throw new ArgumentNullException("id");
|
||||
}
|
||||
|
||||
using (var cmd = Connection.CreateCommand())
|
||||
{
|
||||
cmd.CommandText = "select obj_type,data from items where guid = @guid";
|
||||
var guidParam = cmd.Parameters.Add("@guid", DbType.Guid);
|
||||
guidParam.Value = id;
|
||||
|
||||
using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
|
||||
{
|
||||
if (reader.Read())
|
||||
{
|
||||
var type = reader.GetString(0);
|
||||
using (var stream = GetStream(reader, 1))
|
||||
{
|
||||
var itemType = _typeMapper.GetType(type);
|
||||
|
||||
if (itemType == null)
|
||||
{
|
||||
Logger.Error("Cannot find type {0}. Probably belongs to plug-in that is no longer loaded.", type);
|
||||
return null;
|
||||
}
|
||||
|
||||
var item = _jsonSerializer.DeserializeFromStream(stream, itemType);
|
||||
return item as BaseItem;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve all the children of the given folder
|
||||
/// </summary>
|
||||
/// <param name="parent">The parent.</param>
|
||||
/// <returns>IEnumerable{BaseItem}.</returns>
|
||||
/// <exception cref="System.ArgumentNullException"></exception>
|
||||
public IEnumerable<BaseItem> RetrieveChildren(Folder parent)
|
||||
{
|
||||
if (parent == null)
|
||||
{
|
||||
throw new ArgumentNullException();
|
||||
}
|
||||
|
||||
using (var cmd = Connection.CreateCommand())
|
||||
{
|
||||
cmd.CommandText = "select obj_type,data from items where guid in (select child from children where guid = @guid)";
|
||||
var guidParam = cmd.Parameters.Add("@guid", DbType.Guid);
|
||||
guidParam.Value = parent.Id;
|
||||
|
||||
using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
|
||||
{
|
||||
while (reader.Read())
|
||||
{
|
||||
var type = reader.GetString(0);
|
||||
|
||||
using (var stream = GetStream(reader, 1))
|
||||
{
|
||||
var itemType = _typeMapper.GetType(type);
|
||||
if (itemType == null)
|
||||
{
|
||||
Logger.Error("Cannot find type {0}. Probably belongs to plug-in that is no longer loaded.", type);
|
||||
continue;
|
||||
}
|
||||
var item = _jsonSerializer.DeserializeFromStream(stream, itemType) as BaseItem;
|
||||
if (item != null)
|
||||
{
|
||||
item.Parent = parent;
|
||||
yield return item;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Save references to all the children for the given folder
|
||||
/// (Doesn't actually save the child entities)
|
||||
/// </summary>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <param name="children">The children.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>Task.</returns>
|
||||
/// <exception cref="System.ArgumentNullException">id</exception>
|
||||
public async Task SaveChildren(Guid id, IEnumerable<BaseItem> children, CancellationToken cancellationToken)
|
||||
{
|
||||
if (id == Guid.Empty)
|
||||
{
|
||||
throw new ArgumentNullException("id");
|
||||
}
|
||||
|
||||
if (children == null)
|
||||
{
|
||||
throw new ArgumentNullException("children");
|
||||
}
|
||||
|
||||
if (cancellationToken == null)
|
||||
{
|
||||
throw new ArgumentNullException("cancellationToken");
|
||||
}
|
||||
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
SQLiteTransaction transaction = null;
|
||||
|
||||
try
|
||||
{
|
||||
transaction = Connection.BeginTransaction();
|
||||
|
||||
// Delete exising children
|
||||
_deleteChildrenCommand.Parameters[0].Value = id;
|
||||
_deleteChildrenCommand.Transaction = transaction;
|
||||
await _deleteChildrenCommand.ExecuteNonQueryAsync(cancellationToken);
|
||||
|
||||
// Save new children
|
||||
foreach (var child in children)
|
||||
{
|
||||
_saveChildrenCommand.Transaction = transaction;
|
||||
|
||||
_saveChildrenCommand.Parameters[0].Value = id;
|
||||
_saveChildrenCommand.Parameters[1].Value = child.Id;
|
||||
|
||||
await _saveChildrenCommand.ExecuteNonQueryAsync(cancellationToken);
|
||||
}
|
||||
|
||||
transaction.Commit();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
if (transaction != null)
|
||||
{
|
||||
transaction.Rollback();
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.ErrorException("Failed to save children:", e);
|
||||
|
||||
if (transaction != null)
|
||||
{
|
||||
transaction.Rollback();
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (transaction != null)
|
||||
{
|
||||
transaction.Dispose();
|
||||
}
|
||||
|
||||
_writeLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the critic reviews.
|
||||
/// </summary>
|
||||
/// <param name="itemId">The item id.</param>
|
||||
/// <returns>Task{IEnumerable{ItemReview}}.</returns>
|
||||
public Task<IEnumerable<ItemReview>> GetCriticReviews(Guid itemId)
|
||||
{
|
||||
return Task.Run<IEnumerable<ItemReview>>(() =>
|
||||
{
|
||||
|
||||
try
|
||||
{
|
||||
var path = Path.Combine(_criticReviewsPath, itemId + ".json");
|
||||
|
||||
return _jsonSerializer.DeserializeFromFile<List<ItemReview>>(path);
|
||||
}
|
||||
catch (DirectoryNotFoundException)
|
||||
{
|
||||
return new List<ItemReview>();
|
||||
}
|
||||
catch (FileNotFoundException)
|
||||
{
|
||||
return new List<ItemReview>();
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves the critic reviews.
|
||||
/// </summary>
|
||||
/// <param name="itemId">The item id.</param>
|
||||
/// <param name="criticReviews">The critic reviews.</param>
|
||||
/// <returns>Task.</returns>
|
||||
public Task SaveCriticReviews(Guid itemId, IEnumerable<ItemReview> criticReviews)
|
||||
{
|
||||
return Task.Run(() =>
|
||||
{
|
||||
if (!Directory.Exists(_criticReviewsPath))
|
||||
{
|
||||
Directory.CreateDirectory(_criticReviewsPath);
|
||||
}
|
||||
|
||||
var path = Path.Combine(_criticReviewsPath, itemId + ".json");
|
||||
|
||||
_jsonSerializer.SerializeToFile(criticReviews.ToList(), path);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -1,183 +0,0 @@
|
||||
using MediaBrowser.Model.Logging;
|
||||
using System;
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using System.Data.SQLite;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MediaBrowser.Server.Implementations.Sqlite
|
||||
{
|
||||
/// <summary>
|
||||
/// Class SqliteRepository
|
||||
/// </summary>
|
||||
public abstract class SqliteRepository : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// The db file name
|
||||
/// </summary>
|
||||
protected string DbFileName;
|
||||
/// <summary>
|
||||
/// The connection
|
||||
/// </summary>
|
||||
protected SQLiteConnection Connection;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the logger.
|
||||
/// </summary>
|
||||
/// <value>The logger.</value>
|
||||
protected ILogger Logger { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SqliteRepository" /> class.
|
||||
/// </summary>
|
||||
/// <param name="logManager">The log manager.</param>
|
||||
/// <exception cref="System.ArgumentNullException">logger</exception>
|
||||
protected SqliteRepository(ILogManager logManager)
|
||||
{
|
||||
if (logManager == null)
|
||||
{
|
||||
throw new ArgumentNullException("logManager");
|
||||
}
|
||||
|
||||
Logger = logManager.GetLogger(GetType().Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Connects to DB.
|
||||
/// </summary>
|
||||
/// <param name="dbPath">The db path.</param>
|
||||
/// <returns>Task{System.Boolean}.</returns>
|
||||
/// <exception cref="System.ArgumentNullException">dbPath</exception>
|
||||
protected Task ConnectToDb(string dbPath)
|
||||
{
|
||||
if (string.IsNullOrEmpty(dbPath))
|
||||
{
|
||||
throw new ArgumentNullException("dbPath");
|
||||
}
|
||||
|
||||
DbFileName = dbPath;
|
||||
var connectionstr = new SQLiteConnectionStringBuilder
|
||||
{
|
||||
PageSize = 4096,
|
||||
CacheSize = 40960,
|
||||
SyncMode = SynchronizationModes.Off,
|
||||
DataSource = dbPath,
|
||||
JournalMode = SQLiteJournalModeEnum.Wal
|
||||
};
|
||||
|
||||
Connection = new SQLiteConnection(connectionstr.ConnectionString);
|
||||
|
||||
return Connection.OpenAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the queries.
|
||||
/// </summary>
|
||||
/// <param name="queries">The queries.</param>
|
||||
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
|
||||
/// <exception cref="System.ArgumentNullException">queries</exception>
|
||||
protected void RunQueries(string[] queries)
|
||||
{
|
||||
if (queries == null)
|
||||
{
|
||||
throw new ArgumentNullException("queries");
|
||||
}
|
||||
|
||||
using (var tran = Connection.BeginTransaction())
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var cmd = Connection.CreateCommand())
|
||||
{
|
||||
foreach (var query in queries)
|
||||
{
|
||||
cmd.Transaction = tran;
|
||||
cmd.CommandText = query;
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
|
||||
tran.Commit();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.ErrorException("Error running queries", e);
|
||||
tran.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
private readonly object _disposeLock = new object();
|
||||
|
||||
/// <summary>
|
||||
/// Releases unmanaged and - optionally - managed resources.
|
||||
/// </summary>
|
||||
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
|
||||
protected virtual void Dispose(bool dispose)
|
||||
{
|
||||
if (dispose)
|
||||
{
|
||||
try
|
||||
{
|
||||
lock (_disposeLock)
|
||||
{
|
||||
if (Connection != null)
|
||||
{
|
||||
if (Connection.IsOpen())
|
||||
{
|
||||
Connection.Close();
|
||||
}
|
||||
|
||||
Connection.Dispose();
|
||||
Connection = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.ErrorException("Error disposing database", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a stream from a DataReader at a given ordinal
|
||||
/// </summary>
|
||||
/// <param name="reader">The reader.</param>
|
||||
/// <param name="ordinal">The ordinal.</param>
|
||||
/// <returns>Stream.</returns>
|
||||
/// <exception cref="System.ArgumentNullException">reader</exception>
|
||||
protected static Stream GetStream(IDataReader reader, int ordinal)
|
||||
{
|
||||
if (reader == null)
|
||||
{
|
||||
throw new ArgumentNullException("reader");
|
||||
}
|
||||
|
||||
var memoryStream = new MemoryStream();
|
||||
var num = 0L;
|
||||
var array = new byte[4096];
|
||||
long bytes;
|
||||
do
|
||||
{
|
||||
bytes = reader.GetBytes(ordinal, num, array, 0, array.Length);
|
||||
memoryStream.Write(array, 0, (int)bytes);
|
||||
num += bytes;
|
||||
}
|
||||
while (bytes > 0L);
|
||||
memoryStream.Position = 0;
|
||||
return memoryStream;
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in new issue