BaseSqliteRepository.cs 6.3 KB

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