BaseSqliteRepository.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using Jellyfin.Extensions;
  6. using Microsoft.Extensions.Logging;
  7. using SQLitePCL.pretty;
  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 default connection flags.
  41. /// </summary>
  42. /// <value>The default connection flags.</value>
  43. protected virtual ConnectionFlags DefaultConnectionFlags => ConnectionFlags.NoMutex;
  44. /// <summary>
  45. /// Gets the transaction mode.
  46. /// </summary>
  47. /// <value>The transaction mode.</value>>
  48. protected TransactionMode TransactionMode => TransactionMode.Deferred;
  49. /// <summary>
  50. /// Gets the transaction mode for read-only operations.
  51. /// </summary>
  52. /// <value>The transaction mode.</value>
  53. protected TransactionMode ReadTransactionMode => TransactionMode.Deferred;
  54. /// <summary>
  55. /// Gets the cache size.
  56. /// </summary>
  57. /// <value>The cache size or null.</value>
  58. protected virtual int? CacheSize => null;
  59. /// <summary>
  60. /// Gets the locking mode. <see href="https://www.sqlite.org/pragma.html#pragma_locking_mode" />.
  61. /// </summary>
  62. protected virtual string LockingMode => "NORMAL";
  63. /// <summary>
  64. /// Gets the journal mode. <see href="https://www.sqlite.org/pragma.html#pragma_journal_mode" />.
  65. /// </summary>
  66. /// <value>The journal mode.</value>
  67. protected virtual string JournalMode => "WAL";
  68. /// <summary>
  69. /// Gets the journal size limit. <see href="https://www.sqlite.org/pragma.html#pragma_journal_size_limit" />.
  70. /// The default (-1) is overriden to prevent unconstrained WAL size, as reported by users.
  71. /// </summary>
  72. /// <value>The journal size limit.</value>
  73. protected virtual int? JournalSizeLimit => 134_217_728; // 128MiB
  74. /// <summary>
  75. /// Gets the page size.
  76. /// </summary>
  77. /// <value>The page size or null.</value>
  78. protected virtual int? PageSize => null;
  79. /// <summary>
  80. /// Gets the temp store mode.
  81. /// </summary>
  82. /// <value>The temp store mode.</value>
  83. /// <see cref="TempStoreMode"/>
  84. protected virtual TempStoreMode TempStore => TempStoreMode.Memory;
  85. /// <summary>
  86. /// Gets the synchronous mode.
  87. /// </summary>
  88. /// <value>The synchronous mode or null.</value>
  89. /// <see cref="SynchronousMode"/>
  90. protected virtual SynchronousMode? Synchronous => SynchronousMode.Normal;
  91. /// <summary>
  92. /// Gets or sets the write lock.
  93. /// </summary>
  94. /// <value>The write lock.</value>
  95. protected ConnectionPool WriteConnections { get; set; }
  96. /// <summary>
  97. /// Gets or sets the write connection.
  98. /// </summary>
  99. /// <value>The write connection.</value>
  100. protected ConnectionPool ReadConnections { get; set; }
  101. public virtual void Initialize()
  102. {
  103. WriteConnections = new ConnectionPool(WriteConnectionsCount, CreateWriteConnection);
  104. ReadConnections = new ConnectionPool(ReadConnectionsCount, CreateReadConnection);
  105. // Configuration and pragmas can affect VACUUM so it needs to be last.
  106. using (var connection = GetConnection())
  107. {
  108. connection.Execute("VACUUM");
  109. }
  110. }
  111. protected ManagedConnection GetConnection(bool readOnly = false)
  112. => readOnly ? ReadConnections.GetConnection() : WriteConnections.GetConnection();
  113. protected SQLiteDatabaseConnection CreateWriteConnection()
  114. {
  115. var writeConnection = SQLite3.Open(
  116. DbFilePath,
  117. DefaultConnectionFlags | ConnectionFlags.Create | ConnectionFlags.ReadWrite,
  118. null);
  119. if (CacheSize.HasValue)
  120. {
  121. writeConnection.Execute("PRAGMA cache_size=" + CacheSize.Value);
  122. }
  123. if (!string.IsNullOrWhiteSpace(LockingMode))
  124. {
  125. writeConnection.Execute("PRAGMA locking_mode=" + LockingMode);
  126. }
  127. if (!string.IsNullOrWhiteSpace(JournalMode))
  128. {
  129. writeConnection.Execute("PRAGMA journal_mode=" + JournalMode);
  130. }
  131. if (JournalSizeLimit.HasValue)
  132. {
  133. writeConnection.Execute("PRAGMA journal_size_limit=" + JournalSizeLimit.Value);
  134. }
  135. if (Synchronous.HasValue)
  136. {
  137. writeConnection.Execute("PRAGMA synchronous=" + (int)Synchronous.Value);
  138. }
  139. if (PageSize.HasValue)
  140. {
  141. writeConnection.Execute("PRAGMA page_size=" + PageSize.Value);
  142. }
  143. writeConnection.Execute("PRAGMA temp_store=" + (int)TempStore);
  144. return writeConnection;
  145. }
  146. protected SQLiteDatabaseConnection CreateReadConnection()
  147. {
  148. var connection = SQLite3.Open(
  149. DbFilePath,
  150. DefaultConnectionFlags | ConnectionFlags.ReadOnly,
  151. null);
  152. if (CacheSize.HasValue)
  153. {
  154. connection.Execute("PRAGMA cache_size=" + CacheSize.Value);
  155. }
  156. if (!string.IsNullOrWhiteSpace(LockingMode))
  157. {
  158. connection.Execute("PRAGMA locking_mode=" + LockingMode);
  159. }
  160. if (!string.IsNullOrWhiteSpace(JournalMode))
  161. {
  162. connection.Execute("PRAGMA journal_mode=" + JournalMode);
  163. }
  164. if (JournalSizeLimit.HasValue)
  165. {
  166. connection.Execute("PRAGMA journal_size_limit=" + JournalSizeLimit.Value);
  167. }
  168. if (Synchronous.HasValue)
  169. {
  170. connection.Execute("PRAGMA synchronous=" + (int)Synchronous.Value);
  171. }
  172. connection.Execute("PRAGMA temp_store=" + (int)TempStore);
  173. return connection;
  174. }
  175. public IStatement PrepareStatement(ManagedConnection connection, string sql)
  176. => connection.PrepareStatement(sql);
  177. public IStatement PrepareStatement(IDatabaseConnection connection, string sql)
  178. => connection.PrepareStatement(sql);
  179. protected bool TableExists(ManagedConnection connection, string name)
  180. {
  181. return connection.RunInTransaction(
  182. db =>
  183. {
  184. using (var statement = PrepareStatement(db, "select DISTINCT tbl_name from sqlite_master"))
  185. {
  186. foreach (var row in statement.ExecuteQuery())
  187. {
  188. if (string.Equals(name, row.GetString(0), StringComparison.OrdinalIgnoreCase))
  189. {
  190. return true;
  191. }
  192. }
  193. }
  194. return false;
  195. },
  196. ReadTransactionMode);
  197. }
  198. protected List<string> GetColumnNames(IDatabaseConnection connection, string table)
  199. {
  200. var columnNames = new List<string>();
  201. foreach (var row in connection.Query("PRAGMA table_info(" + table + ")"))
  202. {
  203. if (row.TryGetString(1, out var columnName))
  204. {
  205. columnNames.Add(columnName);
  206. }
  207. }
  208. return columnNames;
  209. }
  210. protected void AddColumn(IDatabaseConnection connection, string table, string columnName, string type, List<string> existingColumnNames)
  211. {
  212. if (existingColumnNames.Contains(columnName, StringComparison.OrdinalIgnoreCase))
  213. {
  214. return;
  215. }
  216. connection.Execute("alter table " + table + " add column " + columnName + " " + type + " NULL");
  217. }
  218. protected void CheckDisposed()
  219. {
  220. if (_disposed)
  221. {
  222. throw new ObjectDisposedException(GetType().Name, "Object has been disposed and cannot be accessed.");
  223. }
  224. }
  225. /// <inheritdoc />
  226. public void Dispose()
  227. {
  228. Dispose(true);
  229. GC.SuppressFinalize(this);
  230. }
  231. /// <summary>
  232. /// Releases unmanaged and - optionally - managed resources.
  233. /// </summary>
  234. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  235. protected virtual void Dispose(bool dispose)
  236. {
  237. if (_disposed)
  238. {
  239. return;
  240. }
  241. if (dispose)
  242. {
  243. WriteConnections.Dispose();
  244. ReadConnections.Dispose();
  245. }
  246. _disposed = true;
  247. }
  248. }
  249. }