BaseSqliteRepository.cs 6.5 KB

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