BaseSqliteRepository.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using MediaBrowser.Model.Logging;
  2. using System;
  3. using System.Data;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. namespace MediaBrowser.Server.Implementations.Persistence
  7. {
  8. public abstract class BaseSqliteRepository : IDisposable
  9. {
  10. protected readonly SemaphoreSlim WriteLock = new SemaphoreSlim(1, 1);
  11. protected readonly IDbConnector DbConnector;
  12. protected ILogger Logger;
  13. protected string DbFilePath { get; set; }
  14. protected BaseSqliteRepository(ILogManager logManager, IDbConnector dbConnector)
  15. {
  16. DbConnector = dbConnector;
  17. Logger = logManager.GetLogger(GetType().Name);
  18. }
  19. protected virtual async Task<IDbConnection> CreateConnection(bool isReadOnly = false)
  20. {
  21. var connection = await DbConnector.Connect(DbFilePath, false, true).ConfigureAwait(false);
  22. connection.RunQueries(new []
  23. {
  24. "pragma temp_store = memory"
  25. }, Logger);
  26. return connection;
  27. }
  28. private bool _disposed;
  29. protected void CheckDisposed()
  30. {
  31. if (_disposed)
  32. {
  33. throw new ObjectDisposedException(GetType().Name + " has been disposed and cannot be accessed.");
  34. }
  35. }
  36. public void Dispose()
  37. {
  38. _disposed = true;
  39. Dispose(true);
  40. GC.SuppressFinalize(this);
  41. }
  42. protected async Task Vacuum(IDbConnection connection)
  43. {
  44. CheckDisposed();
  45. try
  46. {
  47. using (var cmd = connection.CreateCommand())
  48. {
  49. cmd.CommandText = "vacuum";
  50. cmd.ExecuteNonQuery();
  51. }
  52. }
  53. catch (Exception e)
  54. {
  55. Logger.ErrorException("Failed to vacuum:", e);
  56. throw;
  57. }
  58. }
  59. private readonly object _disposeLock = new object();
  60. /// <summary>
  61. /// Releases unmanaged and - optionally - managed resources.
  62. /// </summary>
  63. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  64. protected virtual void Dispose(bool dispose)
  65. {
  66. if (dispose)
  67. {
  68. try
  69. {
  70. lock (_disposeLock)
  71. {
  72. WriteLock.Wait();
  73. CloseConnection();
  74. }
  75. }
  76. catch (Exception ex)
  77. {
  78. Logger.ErrorException("Error disposing database", ex);
  79. }
  80. }
  81. }
  82. protected virtual void CloseConnection()
  83. {
  84. }
  85. }
  86. }