BaseSqliteRepository.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5. using Microsoft.Extensions.Logging;
  6. using SQLitePCL.pretty;
  7. namespace Emby.Server.Implementations.Data
  8. {
  9. public abstract class BaseSqliteRepository : IDisposable
  10. {
  11. private bool _disposed = false;
  12. protected BaseSqliteRepository(ILogger logger)
  13. {
  14. Logger = logger;
  15. }
  16. protected string DbFilePath { get; set; }
  17. protected ILogger Logger { get; }
  18. protected virtual ConnectionFlags DefaultConnectionFlags => ConnectionFlags.NoMutex;
  19. protected TransactionMode TransactionMode => TransactionMode.Deferred;
  20. protected TransactionMode ReadTransactionMode => TransactionMode.Deferred;
  21. protected virtual int? CacheSize => null;
  22. protected virtual string JournalMode => "WAL";
  23. protected virtual int? PageSize => null;
  24. protected virtual TempStoreMode TempStore => TempStoreMode.Default;
  25. protected virtual SynchronousMode? Synchronous => null;
  26. protected SemaphoreSlim WriteLock = new SemaphoreSlim(1, 1);
  27. protected SQLiteDatabaseConnection WriteConnection;
  28. protected ManagedConnection GetConnection(bool _ = false)
  29. {
  30. WriteLock.Wait();
  31. if (WriteConnection != null)
  32. {
  33. return new ManagedConnection(WriteConnection, WriteLock);
  34. }
  35. WriteConnection = SQLite3.Open(
  36. DbFilePath,
  37. DefaultConnectionFlags | ConnectionFlags.Create | ConnectionFlags.ReadWrite,
  38. null);
  39. if (CacheSize.HasValue)
  40. {
  41. WriteConnection.Execute("PRAGMA cache_size=" + (int)CacheSize.Value);
  42. }
  43. if (!string.IsNullOrWhiteSpace(JournalMode))
  44. {
  45. WriteConnection.Execute("PRAGMA journal_mode=" + JournalMode);
  46. }
  47. if (Synchronous.HasValue)
  48. {
  49. WriteConnection.Execute("PRAGMA synchronous=" + (int)Synchronous.Value);
  50. }
  51. if (PageSize.HasValue)
  52. {
  53. WriteConnection.Execute("PRAGMA page_size=" + (int)PageSize.Value);
  54. }
  55. WriteConnection.Execute("PRAGMA temp_store=" + (int)TempStore);
  56. return new ManagedConnection(WriteConnection, WriteLock);
  57. }
  58. public IStatement PrepareStatement(ManagedConnection connection, string sql)
  59. => connection.PrepareStatement(sql);
  60. public IStatement PrepareStatement(IDatabaseConnection connection, string sql)
  61. => connection.PrepareStatement(sql);
  62. public IEnumerable<IStatement> PrepareAll(IDatabaseConnection connection, IEnumerable<string> sql)
  63. => sql.Select(connection.PrepareStatement);
  64. protected bool TableExists(ManagedConnection connection, string name)
  65. {
  66. return connection.RunInTransaction(db =>
  67. {
  68. using (var statement = PrepareStatement(db, "select DISTINCT tbl_name from sqlite_master"))
  69. {
  70. foreach (var row in statement.ExecuteQuery())
  71. {
  72. if (string.Equals(name, row.GetString(0), StringComparison.OrdinalIgnoreCase))
  73. {
  74. return true;
  75. }
  76. }
  77. }
  78. return false;
  79. }, ReadTransactionMode);
  80. }
  81. protected List<string> GetColumnNames(IDatabaseConnection connection, string table)
  82. {
  83. var list = new List<string>();
  84. foreach (var row in connection.Query("PRAGMA table_info(" + table + ")"))
  85. {
  86. if (row[1].SQLiteType != SQLiteType.Null)
  87. {
  88. var name = row[1].ToString();
  89. list.Add(name);
  90. }
  91. }
  92. return list;
  93. }
  94. protected void AddColumn(IDatabaseConnection connection, string table, string columnName, string type, List<string> existingColumnNames)
  95. {
  96. if (existingColumnNames.Contains(columnName, StringComparer.OrdinalIgnoreCase))
  97. {
  98. return;
  99. }
  100. connection.Execute("alter table " + table + " add column " + columnName + " " + type + " NULL");
  101. }
  102. protected void CheckDisposed()
  103. {
  104. if (_disposed)
  105. {
  106. throw new ObjectDisposedException(GetType().Name, "Object has been disposed and cannot be accessed.");
  107. }
  108. }
  109. public void Dispose()
  110. {
  111. Dispose(true);
  112. GC.SuppressFinalize(this);
  113. }
  114. /// <summary>
  115. /// Releases unmanaged and - optionally - managed resources.
  116. /// </summary>
  117. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  118. protected virtual void Dispose(bool dispose)
  119. {
  120. if (_disposed)
  121. {
  122. return;
  123. }
  124. if (dispose)
  125. {
  126. WriteLock.Wait();
  127. try
  128. {
  129. WriteConnection.Dispose();
  130. }
  131. finally
  132. {
  133. WriteLock.Release();
  134. }
  135. WriteLock.Dispose();
  136. }
  137. WriteConnection = null;
  138. WriteLock = null;
  139. _disposed = true;
  140. }
  141. }
  142. public enum SynchronousMode
  143. {
  144. Off = 0,
  145. Normal = 1,
  146. Full = 2,
  147. Extra = 3
  148. }
  149. public enum TempStoreMode
  150. {
  151. Default = 0,
  152. File = 1,
  153. Memory = 2
  154. }
  155. }