jellyfin/MediaBrowser.Server.Implementations/Persistence/BaseSqliteRepository.cs

114 lines
3.0 KiB
C#
Raw Normal View History

2015-05-02 22:59:01 +00:00
using MediaBrowser.Model.Logging;
using System;
2016-02-10 18:13:24 +00:00
using System.Data;
2015-05-02 22:59:01 +00:00
using System.Threading;
2016-02-10 18:13:24 +00:00
using System.Threading.Tasks;
2015-05-02 22:59:01 +00:00
namespace MediaBrowser.Server.Implementations.Persistence
{
public abstract class BaseSqliteRepository : IDisposable
{
2016-06-25 05:16:54 +00:00
protected SemaphoreSlim WriteLock = new SemaphoreSlim(1, 1);
2016-06-11 15:55:05 +00:00
protected readonly IDbConnector DbConnector;
2015-05-02 22:59:01 +00:00
protected ILogger Logger;
2016-06-11 15:55:05 +00:00
protected string DbFilePath { get; set; }
protected BaseSqliteRepository(ILogManager logManager, IDbConnector dbConnector)
2015-05-02 22:59:01 +00:00
{
2016-06-11 15:55:05 +00:00
DbConnector = dbConnector;
2015-05-02 22:59:01 +00:00
Logger = logManager.GetLogger(GetType().Name);
}
protected virtual bool EnableConnectionPooling
{
get { return true; }
}
2016-06-11 20:12:01 +00:00
protected virtual async Task<IDbConnection> CreateConnection(bool isReadOnly = false)
2016-06-11 15:55:05 +00:00
{
2016-06-11 20:12:01 +00:00
var connection = await DbConnector.Connect(DbFilePath, false, true).ConfigureAwait(false);
connection.RunQueries(new[]
2016-06-11 20:12:01 +00:00
{
"pragma temp_store = memory"
}, Logger);
return connection;
2016-06-11 15:55:05 +00:00
}
2016-02-10 18:13:24 +00:00
private bool _disposed;
protected void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name + " has been disposed and cannot be accessed.");
}
}
2015-05-02 22:59:01 +00:00
public void Dispose()
{
2016-02-10 18:13:24 +00:00
_disposed = true;
2015-05-02 22:59:01 +00:00
Dispose(true);
GC.SuppressFinalize(this);
2015-05-02 22:59:01 +00:00
}
2016-02-10 18:13:24 +00:00
protected async Task Vacuum(IDbConnection connection)
{
CheckDisposed();
await WriteLock.WaitAsync().ConfigureAwait(false);
2016-02-10 18:13:24 +00:00
try
{
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = "vacuum";
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
Logger.ErrorException("Failed to vacuum:", e);
throw;
}
finally
{
WriteLock.Release();
}
2016-02-10 18:13:24 +00:00
}
private readonly object _disposeLock = new object();
2015-05-02 22:59:01 +00:00
/// <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)
{
WriteLock.Wait();
CloseConnection();
}
}
catch (Exception ex)
{
Logger.ErrorException("Error disposing database", ex);
}
}
}
protected virtual void CloseConnection()
{
2016-06-11 15:55:05 +00:00
}
2015-05-02 22:59:01 +00:00
}
}