BaseSqliteRepository.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Threading;
  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 journal mode. <see href="https://www.sqlite.org/pragma.html#pragma_journal_mode" />.
  54. /// </summary>
  55. /// <value>The journal mode.</value>
  56. protected virtual string JournalMode => "TRUNCATE";
  57. /// <summary>
  58. /// Gets the page size.
  59. /// </summary>
  60. /// <value>The page size or null.</value>
  61. protected virtual int? PageSize => null;
  62. /// <summary>
  63. /// Gets the temp store mode.
  64. /// </summary>
  65. /// <value>The temp store mode.</value>
  66. /// <see cref="TempStoreMode"/>
  67. protected virtual TempStoreMode TempStore => TempStoreMode.Default;
  68. /// <summary>
  69. /// Gets the synchronous mode.
  70. /// </summary>
  71. /// <value>The synchronous mode or null.</value>
  72. /// <see cref="SynchronousMode"/>
  73. protected virtual SynchronousMode? Synchronous => null;
  74. /// <summary>
  75. /// Gets or sets the write lock.
  76. /// </summary>
  77. /// <value>The write lock.</value>
  78. protected SemaphoreSlim WriteLock { get; set; } = new SemaphoreSlim(1, 1);
  79. /// <summary>
  80. /// Gets or sets the write connection.
  81. /// </summary>
  82. /// <value>The write connection.</value>
  83. protected SQLiteDatabaseConnection WriteConnection { get; set; }
  84. protected ManagedConnection GetConnection(bool _ = false)
  85. {
  86. WriteLock.Wait();
  87. if (WriteConnection != null)
  88. {
  89. return new ManagedConnection(WriteConnection, WriteLock);
  90. }
  91. WriteConnection = SQLite3.Open(
  92. DbFilePath,
  93. DefaultConnectionFlags | ConnectionFlags.Create | ConnectionFlags.ReadWrite,
  94. null);
  95. if (CacheSize.HasValue)
  96. {
  97. WriteConnection.Execute("PRAGMA cache_size=" + CacheSize.Value);
  98. }
  99. if (!string.IsNullOrWhiteSpace(JournalMode))
  100. {
  101. WriteConnection.Execute("PRAGMA journal_mode=" + JournalMode);
  102. }
  103. if (Synchronous.HasValue)
  104. {
  105. WriteConnection.Execute("PRAGMA synchronous=" + (int)Synchronous.Value);
  106. }
  107. if (PageSize.HasValue)
  108. {
  109. WriteConnection.Execute("PRAGMA page_size=" + PageSize.Value);
  110. }
  111. WriteConnection.Execute("PRAGMA temp_store=" + (int)TempStore);
  112. // Configuration and pragmas can affect VACUUM so it needs to be last.
  113. WriteConnection.Execute("VACUUM");
  114. return new ManagedConnection(WriteConnection, WriteLock);
  115. }
  116. public IStatement PrepareStatement(ManagedConnection connection, string sql)
  117. => connection.PrepareStatement(sql);
  118. public IStatement PrepareStatement(IDatabaseConnection connection, string sql)
  119. => connection.PrepareStatement(sql);
  120. public IStatement[] PrepareAll(IDatabaseConnection connection, IReadOnlyList<string> sql)
  121. {
  122. int len = sql.Count;
  123. IStatement[] statements = new IStatement[len];
  124. for (int i = 0; i < len; i++)
  125. {
  126. statements[i] = connection.PrepareStatement(sql[i]);
  127. }
  128. return statements;
  129. }
  130. protected bool TableExists(ManagedConnection connection, string name)
  131. {
  132. return connection.RunInTransaction(
  133. db =>
  134. {
  135. using (var statement = PrepareStatement(db, "select DISTINCT tbl_name from sqlite_master"))
  136. {
  137. foreach (var row in statement.ExecuteQuery())
  138. {
  139. if (string.Equals(name, row.GetString(0), StringComparison.OrdinalIgnoreCase))
  140. {
  141. return true;
  142. }
  143. }
  144. }
  145. return false;
  146. }, ReadTransactionMode);
  147. }
  148. protected List<string> GetColumnNames(IDatabaseConnection connection, string table)
  149. {
  150. var columnNames = new List<string>();
  151. foreach (var row in connection.Query("PRAGMA table_info(" + table + ")"))
  152. {
  153. if (row.TryGetString(1, out var columnName))
  154. {
  155. columnNames.Add(columnName);
  156. }
  157. }
  158. return columnNames;
  159. }
  160. protected void AddColumn(IDatabaseConnection connection, string table, string columnName, string type, List<string> existingColumnNames)
  161. {
  162. if (existingColumnNames.Contains(columnName, StringComparer.OrdinalIgnoreCase))
  163. {
  164. return;
  165. }
  166. connection.Execute("alter table " + table + " add column " + columnName + " " + type + " NULL");
  167. }
  168. protected void CheckDisposed()
  169. {
  170. if (_disposed)
  171. {
  172. throw new ObjectDisposedException(GetType().Name, "Object has been disposed and cannot be accessed.");
  173. }
  174. }
  175. /// <inheritdoc />
  176. public void Dispose()
  177. {
  178. Dispose(true);
  179. GC.SuppressFinalize(this);
  180. }
  181. /// <summary>
  182. /// Releases unmanaged and - optionally - managed resources.
  183. /// </summary>
  184. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  185. protected virtual void Dispose(bool dispose)
  186. {
  187. if (_disposed)
  188. {
  189. return;
  190. }
  191. if (dispose)
  192. {
  193. WriteLock.Wait();
  194. try
  195. {
  196. WriteConnection?.Dispose();
  197. }
  198. finally
  199. {
  200. WriteLock.Release();
  201. }
  202. WriteLock.Dispose();
  203. }
  204. WriteConnection = null;
  205. WriteLock = null;
  206. _disposed = true;
  207. }
  208. }
  209. /// <summary>
  210. /// The disk synchronization mode, controls how aggressively SQLite will write data
  211. /// all the way out to physical storage.
  212. /// </summary>
  213. public enum SynchronousMode
  214. {
  215. /// <summary>
  216. /// SQLite continues without syncing as soon as it has handed data off to the operating system.
  217. /// </summary>
  218. Off = 0,
  219. /// <summary>
  220. /// SQLite database engine will still sync at the most critical moments.
  221. /// </summary>
  222. Normal = 1,
  223. /// <summary>
  224. /// SQLite database engine will use the xSync method of the VFS
  225. /// to ensure that all content is safely written to the disk surface prior to continuing.
  226. /// </summary>
  227. Full = 2,
  228. /// <summary>
  229. /// EXTRA synchronous is like FULL with the addition that the directory containing a rollback journal
  230. /// is synced after that journal is unlinked to commit a transaction in DELETE mode.
  231. /// </summary>
  232. Extra = 3
  233. }
  234. /// <summary>
  235. /// Storage mode used by temporary database files.
  236. /// </summary>
  237. public enum TempStoreMode
  238. {
  239. /// <summary>
  240. /// The compile-time C preprocessor macro SQLITE_TEMP_STORE
  241. /// is used to determine where temporary tables and indices are stored.
  242. /// </summary>
  243. Default = 0,
  244. /// <summary>
  245. /// Temporary tables and indices are stored in a file.
  246. /// </summary>
  247. File = 1,
  248. /// <summary>
  249. /// Temporary tables and indices are kept in as if they were pure in-memory databases memory.
  250. /// </summary>
  251. Memory = 2
  252. }
  253. }