BaseSqliteRepository.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Threading;
  6. using Microsoft.Extensions.Logging;
  7. using SQLitePCL;
  8. using SQLitePCL.pretty;
  9. namespace Emby.Server.Implementations.Data
  10. {
  11. public abstract class BaseSqliteRepository : IDisposable
  12. {
  13. protected string DbFilePath { get; set; }
  14. protected ReaderWriterLockSlim WriteLock;
  15. protected ILogger Logger { get; private set; }
  16. protected BaseSqliteRepository(ILogger logger)
  17. {
  18. Logger = logger;
  19. WriteLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
  20. }
  21. protected TransactionMode TransactionMode => TransactionMode.Deferred;
  22. protected TransactionMode ReadTransactionMode => TransactionMode.Deferred;
  23. internal static int ThreadSafeMode { get; set; }
  24. static BaseSqliteRepository()
  25. {
  26. SQLite3.EnableSharedCache = false;
  27. int rc = raw.sqlite3_config(raw.SQLITE_CONFIG_MEMSTATUS, 0);
  28. //CheckOk(rc);
  29. rc = raw.sqlite3_config(raw.SQLITE_CONFIG_MULTITHREAD, 1);
  30. //rc = raw.sqlite3_config(raw.SQLITE_CONFIG_SINGLETHREAD, 1);
  31. //rc = raw.sqlite3_config(raw.SQLITE_CONFIG_SERIALIZED, 1);
  32. //CheckOk(rc);
  33. rc = raw.sqlite3_enable_shared_cache(1);
  34. ThreadSafeMode = raw.sqlite3_threadsafe();
  35. }
  36. private static bool _versionLogged;
  37. private string _defaultWal;
  38. protected ManagedConnection _connection;
  39. protected virtual bool EnableSingleConnection => true;
  40. protected ManagedConnection CreateConnection(bool isReadOnly = false)
  41. {
  42. if (_connection != null)
  43. {
  44. return _connection;
  45. }
  46. lock (WriteLock)
  47. {
  48. if (!_versionLogged)
  49. {
  50. _versionLogged = true;
  51. Logger.LogInformation("Sqlite version: " + SQLite3.Version);
  52. Logger.LogInformation("Sqlite compiler options: " + string.Join(",", SQLite3.CompilerOptions.ToArray()));
  53. }
  54. ConnectionFlags connectionFlags;
  55. if (isReadOnly)
  56. {
  57. //Logger.LogInformation("Opening read connection");
  58. //connectionFlags = ConnectionFlags.ReadOnly;
  59. connectionFlags = ConnectionFlags.Create;
  60. connectionFlags |= ConnectionFlags.ReadWrite;
  61. }
  62. else
  63. {
  64. //Logger.LogInformation("Opening write connection");
  65. connectionFlags = ConnectionFlags.Create;
  66. connectionFlags |= ConnectionFlags.ReadWrite;
  67. }
  68. if (EnableSingleConnection)
  69. {
  70. connectionFlags |= ConnectionFlags.PrivateCache;
  71. }
  72. else
  73. {
  74. connectionFlags |= ConnectionFlags.SharedCached;
  75. }
  76. connectionFlags |= ConnectionFlags.NoMutex;
  77. var db = SQLite3.Open(DbFilePath, connectionFlags, null);
  78. try
  79. {
  80. if (string.IsNullOrWhiteSpace(_defaultWal))
  81. {
  82. _defaultWal = db.Query("PRAGMA journal_mode").SelectScalarString().First();
  83. Logger.LogInformation("Default journal_mode for {0} is {1}", DbFilePath, _defaultWal);
  84. }
  85. var queries = new List<string>
  86. {
  87. //"PRAGMA cache size=-10000"
  88. //"PRAGMA read_uncommitted = true",
  89. "PRAGMA synchronous=Normal"
  90. };
  91. if (CacheSize.HasValue)
  92. {
  93. queries.Add("PRAGMA cache_size=" + CacheSize.Value.ToString(CultureInfo.InvariantCulture));
  94. }
  95. if (EnableTempStoreMemory)
  96. {
  97. queries.Add("PRAGMA temp_store = memory");
  98. }
  99. else
  100. {
  101. queries.Add("PRAGMA temp_store = file");
  102. }
  103. foreach (var query in queries)
  104. {
  105. db.Execute(query);
  106. }
  107. }
  108. catch
  109. {
  110. using (db)
  111. {
  112. }
  113. throw;
  114. }
  115. _connection = new ManagedConnection(db, false);
  116. return _connection;
  117. }
  118. }
  119. public IStatement PrepareStatement(ManagedConnection connection, string sql)
  120. {
  121. return connection.PrepareStatement(sql);
  122. }
  123. public IStatement PrepareStatementSafe(ManagedConnection connection, string sql)
  124. {
  125. return connection.PrepareStatement(sql);
  126. }
  127. public IStatement PrepareStatement(IDatabaseConnection connection, string sql)
  128. {
  129. return connection.PrepareStatement(sql);
  130. }
  131. public IStatement PrepareStatementSafe(IDatabaseConnection connection, string sql)
  132. {
  133. return connection.PrepareStatement(sql);
  134. }
  135. public List<IStatement> PrepareAll(IDatabaseConnection connection, IEnumerable<string> sql)
  136. {
  137. return PrepareAllSafe(connection, sql);
  138. }
  139. public List<IStatement> PrepareAllSafe(IDatabaseConnection connection, IEnumerable<string> sql)
  140. {
  141. return sql.Select(connection.PrepareStatement).ToList();
  142. }
  143. protected bool TableExists(ManagedConnection connection, string name)
  144. {
  145. return connection.RunInTransaction(db =>
  146. {
  147. using (var statement = PrepareStatement(db, "select DISTINCT tbl_name from sqlite_master"))
  148. {
  149. foreach (var row in statement.ExecuteQuery())
  150. {
  151. if (string.Equals(name, row.GetString(0), StringComparison.OrdinalIgnoreCase))
  152. {
  153. return true;
  154. }
  155. }
  156. }
  157. return false;
  158. }, ReadTransactionMode);
  159. }
  160. protected void RunDefaultInitialization(ManagedConnection db)
  161. {
  162. var queries = new List<string>
  163. {
  164. "PRAGMA journal_mode=WAL",
  165. "PRAGMA page_size=4096",
  166. "PRAGMA synchronous=Normal"
  167. };
  168. if (EnableTempStoreMemory)
  169. {
  170. queries.AddRange(new List<string>
  171. {
  172. "pragma default_temp_store = memory",
  173. "pragma temp_store = memory"
  174. });
  175. }
  176. else
  177. {
  178. queries.AddRange(new List<string>
  179. {
  180. "pragma temp_store = file"
  181. });
  182. }
  183. // Configuration and pragmas can affect VACUUM so it needs to be last.
  184. queries.Add("VACUUM");
  185. db.ExecuteAll(string.Join(";", queries));
  186. Logger.LogInformation("PRAGMA synchronous=" + db.Query("PRAGMA synchronous").SelectScalarString().First());
  187. }
  188. protected virtual bool EnableTempStoreMemory => false;
  189. protected virtual int? CacheSize => null;
  190. private bool _disposed;
  191. protected void CheckDisposed()
  192. {
  193. if (_disposed)
  194. {
  195. throw new ObjectDisposedException(GetType().Name, "Object has been disposed and cannot be accessed.");
  196. }
  197. }
  198. public void Dispose()
  199. {
  200. _disposed = true;
  201. Dispose(true);
  202. }
  203. private readonly object _disposeLock = new object();
  204. /// <summary>
  205. /// Releases unmanaged and - optionally - managed resources.
  206. /// </summary>
  207. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  208. protected virtual void Dispose(bool dispose)
  209. {
  210. if (dispose)
  211. {
  212. DisposeConnection();
  213. }
  214. }
  215. private void DisposeConnection()
  216. {
  217. try
  218. {
  219. lock (_disposeLock)
  220. {
  221. using (WriteLock.Write())
  222. {
  223. if (_connection != null)
  224. {
  225. using (_connection)
  226. {
  227. _connection.Close();
  228. }
  229. _connection = null;
  230. }
  231. CloseConnection();
  232. }
  233. }
  234. }
  235. catch (Exception ex)
  236. {
  237. Logger.LogError(ex, "Error disposing database");
  238. }
  239. }
  240. protected virtual void CloseConnection()
  241. {
  242. }
  243. protected List<string> GetColumnNames(IDatabaseConnection connection, string table)
  244. {
  245. var list = new List<string>();
  246. foreach (var row in connection.Query("PRAGMA table_info(" + table + ")"))
  247. {
  248. if (row[1].SQLiteType != SQLiteType.Null)
  249. {
  250. var name = row[1].ToString();
  251. list.Add(name);
  252. }
  253. }
  254. return list;
  255. }
  256. protected void AddColumn(IDatabaseConnection connection, string table, string columnName, string type, List<string> existingColumnNames)
  257. {
  258. if (existingColumnNames.Contains(columnName, StringComparer.OrdinalIgnoreCase))
  259. {
  260. return;
  261. }
  262. connection.Execute("alter table " + table + " add column " + columnName + " " + type + " NULL");
  263. }
  264. }
  265. public static class ReaderWriterLockSlimExtensions
  266. {
  267. private sealed class ReadLockToken : IDisposable
  268. {
  269. private ReaderWriterLockSlim _sync;
  270. public ReadLockToken(ReaderWriterLockSlim sync)
  271. {
  272. _sync = sync;
  273. sync.EnterReadLock();
  274. }
  275. public void Dispose()
  276. {
  277. if (_sync != null)
  278. {
  279. _sync.ExitReadLock();
  280. _sync = null;
  281. }
  282. }
  283. }
  284. private sealed class WriteLockToken : IDisposable
  285. {
  286. private ReaderWriterLockSlim _sync;
  287. public WriteLockToken(ReaderWriterLockSlim sync)
  288. {
  289. _sync = sync;
  290. sync.EnterWriteLock();
  291. }
  292. public void Dispose()
  293. {
  294. if (_sync != null)
  295. {
  296. _sync.ExitWriteLock();
  297. _sync = null;
  298. }
  299. }
  300. }
  301. public static IDisposable Read(this ReaderWriterLockSlim obj)
  302. {
  303. //if (BaseSqliteRepository.ThreadSafeMode > 0)
  304. //{
  305. // return new DummyToken();
  306. //}
  307. return new WriteLockToken(obj);
  308. }
  309. public static IDisposable Write(this ReaderWriterLockSlim obj)
  310. {
  311. //if (BaseSqliteRepository.ThreadSafeMode > 0)
  312. //{
  313. // return new DummyToken();
  314. //}
  315. return new WriteLockToken(obj);
  316. }
  317. }
  318. }