BaseSqliteRepository.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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 IStatement[] PrepareAll(IDatabaseConnection connection, IReadOnlyList<string> sql)
  120. {
  121. int len = sql.Count;
  122. IStatement[] statements = new IStatement[len];
  123. for (int i = 0; i < len; i++)
  124. {
  125. statements[i] = connection.PrepareStatement(sql[i]);
  126. }
  127. return statements;
  128. }
  129. protected bool TableExists(ManagedConnection connection, string name)
  130. {
  131. return connection.RunInTransaction(db =>
  132. {
  133. using (var statement = PrepareStatement(db, "select DISTINCT tbl_name from sqlite_master"))
  134. {
  135. foreach (var row in statement.ExecuteQuery())
  136. {
  137. if (string.Equals(name, row.GetString(0), StringComparison.OrdinalIgnoreCase))
  138. {
  139. return true;
  140. }
  141. }
  142. }
  143. return false;
  144. }, ReadTransactionMode);
  145. }
  146. protected List<string> GetColumnNames(IDatabaseConnection connection, string table)
  147. {
  148. var columnNames = new List<string>();
  149. foreach (var row in connection.Query("PRAGMA table_info(" + table + ")"))
  150. {
  151. if (row[1].SQLiteType != SQLiteType.Null)
  152. {
  153. var name = row[1].ToString();
  154. columnNames.Add(name);
  155. }
  156. }
  157. return columnNames;
  158. }
  159. protected void AddColumn(IDatabaseConnection connection, string table, string columnName, string type, List<string> existingColumnNames)
  160. {
  161. if (existingColumnNames.Contains(columnName, StringComparer.OrdinalIgnoreCase))
  162. {
  163. return;
  164. }
  165. connection.Execute("alter table " + table + " add column " + columnName + " " + type + " NULL");
  166. }
  167. protected void CheckDisposed()
  168. {
  169. if (_disposed)
  170. {
  171. throw new ObjectDisposedException(GetType().Name, "Object has been disposed and cannot be accessed.");
  172. }
  173. }
  174. /// <inheritdoc />
  175. public void Dispose()
  176. {
  177. Dispose(true);
  178. GC.SuppressFinalize(this);
  179. }
  180. /// <summary>
  181. /// Releases unmanaged and - optionally - managed resources.
  182. /// </summary>
  183. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  184. protected virtual void Dispose(bool dispose)
  185. {
  186. if (_disposed)
  187. {
  188. return;
  189. }
  190. if (dispose)
  191. {
  192. WriteLock.Wait();
  193. try
  194. {
  195. WriteConnection?.Dispose();
  196. }
  197. finally
  198. {
  199. WriteLock.Release();
  200. }
  201. WriteLock.Dispose();
  202. }
  203. WriteConnection = null;
  204. WriteLock = null;
  205. _disposed = true;
  206. }
  207. }
  208. /// <summary>
  209. /// The disk synchronization mode, controls how aggressively SQLite will write data
  210. /// all the way out to physical storage.
  211. /// </summary>
  212. public enum SynchronousMode
  213. {
  214. /// <summary>
  215. /// SQLite continues without syncing as soon as it has handed data off to the operating system.
  216. /// </summary>
  217. Off = 0,
  218. /// <summary>
  219. /// SQLite database engine will still sync at the most critical moments.
  220. /// </summary>
  221. Normal = 1,
  222. /// <summary>
  223. /// SQLite database engine will use the xSync method of the VFS
  224. /// to ensure that all content is safely written to the disk surface prior to continuing.
  225. /// </summary>
  226. Full = 2,
  227. /// <summary>
  228. /// EXTRA synchronous is like FULL with the addition that the directory containing a rollback journal
  229. /// is synced after that journal is unlinked to commit a transaction in DELETE mode.
  230. /// </summary>
  231. Extra = 3
  232. }
  233. /// <summary>
  234. /// Storage mode used by temporary database files.
  235. /// </summary>
  236. public enum TempStoreMode
  237. {
  238. /// <summary>
  239. /// The compile-time C preprocessor macro SQLITE_TEMP_STORE
  240. /// is used to determine where temporary tables and indices are stored.
  241. /// </summary>
  242. Default = 0,
  243. /// <summary>
  244. /// Temporary tables and indices are stored in a file.
  245. /// </summary>
  246. File = 1,
  247. /// <summary>
  248. /// Temporary tables and indices are kept in as if they were pure in-memory databases memory.
  249. /// </summary>
  250. Memory = 2
  251. }
  252. }