BaseSqliteRepository.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Threading;
  6. using Jellyfin.Extensions;
  7. using Microsoft.Data.Sqlite;
  8. using Microsoft.Extensions.Logging;
  9. namespace Emby.Server.Implementations.Data
  10. {
  11. public abstract class BaseSqliteRepository : IDisposable
  12. {
  13. private bool _disposed = false;
  14. private SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
  15. private SqliteConnection _writeConnection;
  16. /// <summary>
  17. /// Initializes a new instance of the <see cref="BaseSqliteRepository"/> class.
  18. /// </summary>
  19. /// <param name="logger">The logger.</param>
  20. protected BaseSqliteRepository(ILogger<BaseSqliteRepository> logger)
  21. {
  22. Logger = logger;
  23. }
  24. /// <summary>
  25. /// Gets or sets the path to the DB file.
  26. /// </summary>
  27. protected string DbFilePath { get; set; }
  28. /// <summary>
  29. /// Gets the logger.
  30. /// </summary>
  31. /// <value>The logger.</value>
  32. protected ILogger<BaseSqliteRepository> Logger { get; }
  33. /// <summary>
  34. /// Gets the cache size.
  35. /// </summary>
  36. /// <value>The cache size or null.</value>
  37. protected virtual int? CacheSize => null;
  38. /// <summary>
  39. /// Gets the locking mode. <see href="https://www.sqlite.org/pragma.html#pragma_locking_mode" />.
  40. /// </summary>
  41. protected virtual string LockingMode => "NORMAL";
  42. /// <summary>
  43. /// Gets the journal mode. <see href="https://www.sqlite.org/pragma.html#pragma_journal_mode" />.
  44. /// </summary>
  45. /// <value>The journal mode.</value>
  46. protected virtual string JournalMode => "WAL";
  47. /// <summary>
  48. /// Gets the journal size limit. <see href="https://www.sqlite.org/pragma.html#pragma_journal_size_limit" />.
  49. /// The default (-1) is overridden to prevent unconstrained WAL size, as reported by users.
  50. /// </summary>
  51. /// <value>The journal size limit.</value>
  52. protected virtual int? JournalSizeLimit => 134_217_728; // 128MiB
  53. /// <summary>
  54. /// Gets the page size.
  55. /// </summary>
  56. /// <value>The page size or null.</value>
  57. protected virtual int? PageSize => null;
  58. /// <summary>
  59. /// Gets the temp store mode.
  60. /// </summary>
  61. /// <value>The temp store mode.</value>
  62. /// <see cref="TempStoreMode"/>
  63. protected virtual TempStoreMode TempStore => TempStoreMode.Memory;
  64. /// <summary>
  65. /// Gets the synchronous mode.
  66. /// </summary>
  67. /// <value>The synchronous mode or null.</value>
  68. /// <see cref="SynchronousMode"/>
  69. protected virtual SynchronousMode? Synchronous => SynchronousMode.Normal;
  70. public virtual void Initialize()
  71. {
  72. // Configuration and pragmas can affect VACUUM so it needs to be last.
  73. using (var connection = GetConnection())
  74. {
  75. connection.Execute("VACUUM");
  76. }
  77. }
  78. protected ManagedConnection GetConnection(bool readOnly = false)
  79. {
  80. if (!readOnly)
  81. {
  82. _writeLock.Wait();
  83. if (_writeConnection is not null)
  84. {
  85. return new ManagedConnection(_writeConnection, _writeLock);
  86. }
  87. var writeConnection = new SqliteConnection($"Filename={DbFilePath};Pooling=False");
  88. writeConnection.Open();
  89. if (CacheSize.HasValue)
  90. {
  91. writeConnection.Execute("PRAGMA cache_size=" + CacheSize.Value);
  92. }
  93. if (!string.IsNullOrWhiteSpace(LockingMode))
  94. {
  95. writeConnection.Execute("PRAGMA locking_mode=" + LockingMode);
  96. }
  97. if (!string.IsNullOrWhiteSpace(JournalMode))
  98. {
  99. writeConnection.Execute("PRAGMA journal_mode=" + JournalMode);
  100. }
  101. if (JournalSizeLimit.HasValue)
  102. {
  103. writeConnection.Execute("PRAGMA journal_size_limit=" + JournalSizeLimit.Value);
  104. }
  105. if (Synchronous.HasValue)
  106. {
  107. writeConnection.Execute("PRAGMA synchronous=" + (int)Synchronous.Value);
  108. }
  109. if (PageSize.HasValue)
  110. {
  111. writeConnection.Execute("PRAGMA page_size=" + PageSize.Value);
  112. }
  113. writeConnection.Execute("PRAGMA temp_store=" + (int)TempStore);
  114. return new ManagedConnection(_writeConnection = writeConnection, _writeLock);
  115. }
  116. var connection = new SqliteConnection($"Filename={DbFilePath};Mode=ReadOnly");
  117. connection.Open();
  118. if (CacheSize.HasValue)
  119. {
  120. connection.Execute("PRAGMA cache_size=" + CacheSize.Value);
  121. }
  122. if (!string.IsNullOrWhiteSpace(LockingMode))
  123. {
  124. connection.Execute("PRAGMA locking_mode=" + LockingMode);
  125. }
  126. if (!string.IsNullOrWhiteSpace(JournalMode))
  127. {
  128. connection.Execute("PRAGMA journal_mode=" + JournalMode);
  129. }
  130. if (JournalSizeLimit.HasValue)
  131. {
  132. connection.Execute("PRAGMA journal_size_limit=" + JournalSizeLimit.Value);
  133. }
  134. if (Synchronous.HasValue)
  135. {
  136. connection.Execute("PRAGMA synchronous=" + (int)Synchronous.Value);
  137. }
  138. if (PageSize.HasValue)
  139. {
  140. connection.Execute("PRAGMA page_size=" + PageSize.Value);
  141. }
  142. connection.Execute("PRAGMA temp_store=" + (int)TempStore);
  143. return new ManagedConnection(connection, null);
  144. }
  145. public SqliteCommand PrepareStatement(ManagedConnection connection, string sql)
  146. {
  147. var command = connection.CreateCommand();
  148. command.CommandText = sql;
  149. return command;
  150. }
  151. protected bool TableExists(ManagedConnection connection, string name)
  152. {
  153. using var statement = PrepareStatement(connection, "select DISTINCT tbl_name from sqlite_master");
  154. foreach (var row in statement.ExecuteQuery())
  155. {
  156. if (string.Equals(name, row.GetString(0), StringComparison.OrdinalIgnoreCase))
  157. {
  158. return true;
  159. }
  160. }
  161. return false;
  162. }
  163. protected List<string> GetColumnNames(ManagedConnection connection, string table)
  164. {
  165. var columnNames = new List<string>();
  166. foreach (var row in connection.Query("PRAGMA table_info(" + table + ")"))
  167. {
  168. if (row.TryGetString(1, out var columnName))
  169. {
  170. columnNames.Add(columnName);
  171. }
  172. }
  173. return columnNames;
  174. }
  175. protected void AddColumn(ManagedConnection connection, string table, string columnName, string type, List<string> existingColumnNames)
  176. {
  177. if (existingColumnNames.Contains(columnName, StringComparison.OrdinalIgnoreCase))
  178. {
  179. return;
  180. }
  181. connection.Execute("alter table " + table + " add column " + columnName + " " + type + " NULL");
  182. }
  183. protected void CheckDisposed()
  184. {
  185. ObjectDisposedException.ThrowIf(_disposed, this);
  186. }
  187. /// <inheritdoc />
  188. public void Dispose()
  189. {
  190. Dispose(true);
  191. GC.SuppressFinalize(this);
  192. }
  193. /// <summary>
  194. /// Releases unmanaged and - optionally - managed resources.
  195. /// </summary>
  196. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  197. protected virtual void Dispose(bool dispose)
  198. {
  199. if (_disposed)
  200. {
  201. return;
  202. }
  203. if (dispose)
  204. {
  205. _writeLock.Wait();
  206. try
  207. {
  208. _writeConnection.Dispose();
  209. }
  210. finally
  211. {
  212. _writeLock.Release();
  213. }
  214. _writeLock.Dispose();
  215. }
  216. _writeConnection = null;
  217. _writeLock = null;
  218. _disposed = true;
  219. }
  220. }
  221. }