BaseSqliteRepository.cs 9.3 KB

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