BaseSqliteRepository.cs 6.7 KB

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