BaseSqliteRepository.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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. protected string DbFilePath { get; set; }
  12. protected ILogger Logger { get; }
  13. protected BaseSqliteRepository(ILogger logger)
  14. {
  15. Logger = logger;
  16. }
  17. protected TransactionMode TransactionMode => TransactionMode.Deferred;
  18. protected TransactionMode ReadTransactionMode => TransactionMode.Deferred;
  19. protected virtual ConnectionFlags DefaultConnectionFlags => ConnectionFlags.NoMutex;
  20. protected SemaphoreSlim WriteLock = new SemaphoreSlim(1, 1);
  21. protected SQLiteDatabaseConnection WriteConnection;
  22. private string _defaultWal;
  23. protected ManagedConnection GetConnection(bool _ = false)
  24. {
  25. WriteLock.Wait();
  26. if (WriteConnection != null)
  27. {
  28. return new ManagedConnection(WriteConnection, WriteLock);
  29. }
  30. WriteConnection = SQLite3.Open(
  31. DbFilePath,
  32. DefaultConnectionFlags | ConnectionFlags.Create | ConnectionFlags.ReadWrite,
  33. null);
  34. if (string.IsNullOrWhiteSpace(_defaultWal))
  35. {
  36. _defaultWal = WriteConnection.Query("PRAGMA journal_mode").SelectScalarString().First();
  37. Logger.LogInformation("Default journal_mode for {0} is {1}", DbFilePath, _defaultWal);
  38. }
  39. if (EnableTempStoreMemory)
  40. {
  41. WriteConnection.Execute("PRAGMA temp_store = memory");
  42. }
  43. else
  44. {
  45. WriteConnection.Execute("PRAGMA temp_store = file");
  46. }
  47. return new ManagedConnection(WriteConnection, WriteLock);
  48. }
  49. public IStatement PrepareStatement(ManagedConnection connection, string sql)
  50. => connection.PrepareStatement(sql);
  51. public IStatement PrepareStatement(IDatabaseConnection connection, string sql)
  52. => connection.PrepareStatement(sql);
  53. public IEnumerable<IStatement> PrepareAllSafe(IDatabaseConnection connection, IEnumerable<string> sql)
  54. => sql.Select(connection.PrepareStatement);
  55. protected bool TableExists(ManagedConnection connection, string name)
  56. {
  57. return connection.RunInTransaction(db =>
  58. {
  59. using (var statement = PrepareStatement(db, "select DISTINCT tbl_name from sqlite_master"))
  60. {
  61. foreach (var row in statement.ExecuteQuery())
  62. {
  63. if (string.Equals(name, row.GetString(0), StringComparison.OrdinalIgnoreCase))
  64. {
  65. return true;
  66. }
  67. }
  68. }
  69. return false;
  70. }, ReadTransactionMode);
  71. }
  72. protected void RunDefaultInitialization(ManagedConnection db)
  73. {
  74. var queries = new List<string>
  75. {
  76. "PRAGMA journal_mode=WAL",
  77. "PRAGMA page_size=4096",
  78. "PRAGMA synchronous=Normal"
  79. };
  80. if (EnableTempStoreMemory)
  81. {
  82. queries.AddRange(new List<string>
  83. {
  84. "pragma default_temp_store = memory",
  85. "pragma temp_store = memory"
  86. });
  87. }
  88. else
  89. {
  90. queries.AddRange(new List<string>
  91. {
  92. "pragma temp_store = file"
  93. });
  94. }
  95. db.ExecuteAll(string.Join(";", queries));
  96. Logger.LogInformation("PRAGMA synchronous=" + db.Query("PRAGMA synchronous").SelectScalarString().First());
  97. }
  98. protected virtual bool EnableTempStoreMemory => true;
  99. private bool _disposed;
  100. protected void CheckDisposed()
  101. {
  102. if (_disposed)
  103. {
  104. throw new ObjectDisposedException(GetType().Name, "Object has been disposed and cannot be accessed.");
  105. }
  106. }
  107. public void Dispose()
  108. {
  109. Dispose(true);
  110. GC.SuppressFinalize(this);
  111. }
  112. private readonly object _disposeLock = new object();
  113. /// <summary>
  114. /// Releases unmanaged and - optionally - managed resources.
  115. /// </summary>
  116. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  117. protected virtual void Dispose(bool dispose)
  118. {
  119. if (_disposed)
  120. {
  121. return;
  122. }
  123. if (dispose)
  124. {
  125. WriteLock.Wait();
  126. try
  127. {
  128. WriteConnection.Dispose();
  129. }
  130. finally
  131. {
  132. WriteLock.Release();
  133. }
  134. WriteLock.Dispose();
  135. }
  136. WriteConnection = null;
  137. WriteLock = null;
  138. _disposed = true;
  139. }
  140. protected List<string> GetColumnNames(IDatabaseConnection connection, string table)
  141. {
  142. var list = new List<string>();
  143. foreach (var row in connection.Query("PRAGMA table_info(" + table + ")"))
  144. {
  145. if (row[1].SQLiteType != SQLiteType.Null)
  146. {
  147. var name = row[1].ToString();
  148. list.Add(name);
  149. }
  150. }
  151. return list;
  152. }
  153. protected void AddColumn(IDatabaseConnection connection, string table, string columnName, string type, List<string> existingColumnNames)
  154. {
  155. if (existingColumnNames.Contains(columnName, StringComparer.OrdinalIgnoreCase))
  156. {
  157. return;
  158. }
  159. connection.Execute("alter table " + table + " add column " + columnName + " " + type + " NULL");
  160. }
  161. }
  162. }