BaseSqliteRepository.cs 8.9 KB

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