BaseSqliteRepository.cs 9.1 KB

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