BaseSqliteRepository.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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.Extensions.Logging;
  8. using SQLitePCL.pretty;
  9. namespace Emby.Server.Implementations.Data
  10. {
  11. public abstract class BaseSqliteRepository : IDisposable
  12. {
  13. private bool _disposed = false;
  14. /// <summary>
  15. /// Initializes a new instance of the <see cref="BaseSqliteRepository"/> class.
  16. /// </summary>
  17. /// <param name="logger">The logger.</param>
  18. protected BaseSqliteRepository(ILogger<BaseSqliteRepository> logger)
  19. {
  20. Logger = logger;
  21. }
  22. /// <summary>
  23. /// Gets or sets the path to the DB file.
  24. /// </summary>
  25. /// <value>Path to the DB file.</value>
  26. protected string DbFilePath { get; set; }
  27. /// <summary>
  28. /// Gets the logger.
  29. /// </summary>
  30. /// <value>The logger.</value>
  31. protected ILogger<BaseSqliteRepository> Logger { get; }
  32. /// <summary>
  33. /// Gets the default connection flags.
  34. /// </summary>
  35. /// <value>The default connection flags.</value>
  36. protected virtual ConnectionFlags DefaultConnectionFlags => ConnectionFlags.NoMutex;
  37. /// <summary>
  38. /// Gets the transaction mode.
  39. /// </summary>
  40. /// <value>The transaction mode.</value>>
  41. protected TransactionMode TransactionMode => TransactionMode.Deferred;
  42. /// <summary>
  43. /// Gets the transaction mode for read-only operations.
  44. /// </summary>
  45. /// <value>The transaction mode.</value>
  46. protected TransactionMode ReadTransactionMode => TransactionMode.Deferred;
  47. /// <summary>
  48. /// Gets the cache size.
  49. /// </summary>
  50. /// <value>The cache size or null.</value>
  51. protected virtual int? CacheSize => null;
  52. /// <summary>
  53. /// Gets the locking mode. <see href="https://www.sqlite.org/pragma.html#pragma_locking_mode" />.
  54. /// </summary>
  55. protected virtual string LockingMode => "EXCLUSIVE";
  56. /// <summary>
  57. /// Gets the journal mode. <see href="https://www.sqlite.org/pragma.html#pragma_journal_mode" />.
  58. /// </summary>
  59. /// <value>The journal mode.</value>
  60. protected virtual string JournalMode => "WAL";
  61. /// <summary>
  62. /// Gets the journal size limit. <see href="https://www.sqlite.org/pragma.html#pragma_journal_size_limit" />.
  63. /// </summary>
  64. /// <value>The journal size limit.</value>
  65. protected virtual int? JournalSizeLimit => 0;
  66. /// <summary>
  67. /// Gets the page size.
  68. /// </summary>
  69. /// <value>The page size or null.</value>
  70. protected virtual int? PageSize => null;
  71. /// <summary>
  72. /// Gets the temp store mode.
  73. /// </summary>
  74. /// <value>The temp store mode.</value>
  75. /// <see cref="TempStoreMode"/>
  76. protected virtual TempStoreMode TempStore => TempStoreMode.Default;
  77. /// <summary>
  78. /// Gets the synchronous mode.
  79. /// </summary>
  80. /// <value>The synchronous mode or null.</value>
  81. /// <see cref="SynchronousMode"/>
  82. protected virtual SynchronousMode? Synchronous => SynchronousMode.Normal;
  83. /// <summary>
  84. /// Gets or sets the write lock.
  85. /// </summary>
  86. /// <value>The write lock.</value>
  87. protected SemaphoreSlim WriteLock { get; set; } = new SemaphoreSlim(1, 1);
  88. /// <summary>
  89. /// Gets or sets the write connection.
  90. /// </summary>
  91. /// <value>The write connection.</value>
  92. protected SQLiteDatabaseConnection WriteConnection { get; set; }
  93. protected ManagedConnection GetConnection(bool readOnly = false)
  94. {
  95. WriteLock.Wait();
  96. if (WriteConnection is not null)
  97. {
  98. return new ManagedConnection(WriteConnection, WriteLock);
  99. }
  100. WriteConnection = SQLite3.Open(
  101. DbFilePath,
  102. DefaultConnectionFlags | ConnectionFlags.Create | ConnectionFlags.ReadWrite,
  103. null);
  104. if (CacheSize.HasValue)
  105. {
  106. WriteConnection.Execute("PRAGMA cache_size=" + CacheSize.Value);
  107. }
  108. if (!string.IsNullOrWhiteSpace(LockingMode))
  109. {
  110. WriteConnection.Execute("PRAGMA locking_mode=" + LockingMode);
  111. }
  112. if (!string.IsNullOrWhiteSpace(JournalMode))
  113. {
  114. WriteConnection.Execute("PRAGMA journal_mode=" + JournalMode);
  115. }
  116. if (JournalSizeLimit.HasValue)
  117. {
  118. WriteConnection.Execute("PRAGMA journal_size_limit=" + JournalSizeLimit.Value);
  119. }
  120. if (Synchronous.HasValue)
  121. {
  122. WriteConnection.Execute("PRAGMA synchronous=" + (int)Synchronous.Value);
  123. }
  124. if (PageSize.HasValue)
  125. {
  126. WriteConnection.Execute("PRAGMA page_size=" + PageSize.Value);
  127. }
  128. WriteConnection.Execute("PRAGMA temp_store=" + (int)TempStore);
  129. // Configuration and pragmas can affect VACUUM so it needs to be last.
  130. WriteConnection.Execute("VACUUM");
  131. return new ManagedConnection(WriteConnection, WriteLock);
  132. }
  133. public IStatement PrepareStatement(ManagedConnection connection, string sql)
  134. => connection.PrepareStatement(sql);
  135. public IStatement PrepareStatement(IDatabaseConnection connection, string sql)
  136. => connection.PrepareStatement(sql);
  137. public IStatement[] PrepareAll(IDatabaseConnection connection, IReadOnlyList<string> sql)
  138. {
  139. int len = sql.Count;
  140. IStatement[] statements = new IStatement[len];
  141. for (int i = 0; i < len; i++)
  142. {
  143. statements[i] = connection.PrepareStatement(sql[i]);
  144. }
  145. return statements;
  146. }
  147. protected bool TableExists(ManagedConnection connection, string name)
  148. {
  149. return connection.RunInTransaction(
  150. db =>
  151. {
  152. using (var statement = PrepareStatement(db, "select DISTINCT tbl_name from sqlite_master"))
  153. {
  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. }
  162. return false;
  163. },
  164. ReadTransactionMode);
  165. }
  166. protected List<string> GetColumnNames(IDatabaseConnection connection, string table)
  167. {
  168. var columnNames = new List<string>();
  169. foreach (var row in connection.Query("PRAGMA table_info(" + table + ")"))
  170. {
  171. if (row.TryGetString(1, out var columnName))
  172. {
  173. columnNames.Add(columnName);
  174. }
  175. }
  176. return columnNames;
  177. }
  178. protected void AddColumn(IDatabaseConnection connection, string table, string columnName, string type, List<string> existingColumnNames)
  179. {
  180. if (existingColumnNames.Contains(columnName, StringComparison.OrdinalIgnoreCase))
  181. {
  182. return;
  183. }
  184. connection.Execute("alter table " + table + " add column " + columnName + " " + type + " NULL");
  185. }
  186. protected void CheckDisposed()
  187. {
  188. if (_disposed)
  189. {
  190. throw new ObjectDisposedException(GetType().Name, "Object has been disposed and cannot be accessed.");
  191. }
  192. }
  193. /// <inheritdoc />
  194. public void Dispose()
  195. {
  196. Dispose(true);
  197. GC.SuppressFinalize(this);
  198. }
  199. /// <summary>
  200. /// Releases unmanaged and - optionally - managed resources.
  201. /// </summary>
  202. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  203. protected virtual void Dispose(bool dispose)
  204. {
  205. if (_disposed)
  206. {
  207. return;
  208. }
  209. if (dispose)
  210. {
  211. WriteLock.Wait();
  212. try
  213. {
  214. WriteConnection?.Dispose();
  215. }
  216. finally
  217. {
  218. WriteLock.Release();
  219. }
  220. WriteLock.Dispose();
  221. }
  222. WriteConnection = null;
  223. WriteLock = null;
  224. _disposed = true;
  225. }
  226. }
  227. }