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

114 lines
3.0 KiB
C#
Raw Normal View History

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