BaseSqliteRepository.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. db.ExecuteAll(string.Join(";", queries.ToArray()));
  184. Logger.LogInformation("PRAGMA synchronous=" + db.Query("PRAGMA synchronous").SelectScalarString().First());
  185. }
  186. protected virtual bool EnableTempStoreMemory => false;
  187. protected virtual int? CacheSize => null;
  188. internal static void CheckOk(int rc)
  189. {
  190. string msg = "";
  191. if (raw.SQLITE_OK != rc)
  192. {
  193. throw CreateException((ErrorCode)rc, msg);
  194. }
  195. }
  196. internal static Exception CreateException(ErrorCode rc, string msg)
  197. {
  198. var exp = new Exception(msg);
  199. return exp;
  200. }
  201. private bool _disposed;
  202. protected void CheckDisposed()
  203. {
  204. if (_disposed)
  205. {
  206. throw new ObjectDisposedException(GetType().Name, "Object has been disposed and cannot be accessed.");
  207. }
  208. }
  209. public void Dispose()
  210. {
  211. _disposed = true;
  212. Dispose(true);
  213. }
  214. private readonly object _disposeLock = new object();
  215. /// <summary>
  216. /// Releases unmanaged and - optionally - managed resources.
  217. /// </summary>
  218. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  219. protected virtual void Dispose(bool dispose)
  220. {
  221. if (dispose)
  222. {
  223. DisposeConnection();
  224. }
  225. }
  226. private void DisposeConnection()
  227. {
  228. try
  229. {
  230. lock (_disposeLock)
  231. {
  232. using (WriteLock.Write())
  233. {
  234. if (_connection != null)
  235. {
  236. using (_connection)
  237. {
  238. _connection.Close();
  239. }
  240. _connection = null;
  241. }
  242. CloseConnection();
  243. }
  244. }
  245. }
  246. catch (Exception ex)
  247. {
  248. Logger.LogError(ex, "Error disposing database");
  249. }
  250. }
  251. protected virtual void CloseConnection()
  252. {
  253. }
  254. protected List<string> GetColumnNames(IDatabaseConnection connection, string table)
  255. {
  256. var list = new List<string>();
  257. foreach (var row in connection.Query("PRAGMA table_info(" + table + ")"))
  258. {
  259. if (row[1].SQLiteType != SQLiteType.Null)
  260. {
  261. var name = row[1].ToString();
  262. list.Add(name);
  263. }
  264. }
  265. return list;
  266. }
  267. protected void AddColumn(IDatabaseConnection connection, string table, string columnName, string type, List<string> existingColumnNames)
  268. {
  269. if (existingColumnNames.Contains(columnName, StringComparer.OrdinalIgnoreCase))
  270. {
  271. return;
  272. }
  273. connection.Execute("alter table " + table + " add column " + columnName + " " + type + " NULL");
  274. }
  275. }
  276. public static class ReaderWriterLockSlimExtensions
  277. {
  278. private sealed class ReadLockToken : IDisposable
  279. {
  280. private ReaderWriterLockSlim _sync;
  281. public ReadLockToken(ReaderWriterLockSlim sync)
  282. {
  283. _sync = sync;
  284. sync.EnterReadLock();
  285. }
  286. public void Dispose()
  287. {
  288. if (_sync != null)
  289. {
  290. _sync.ExitReadLock();
  291. _sync = null;
  292. }
  293. }
  294. }
  295. private sealed class WriteLockToken : IDisposable
  296. {
  297. private ReaderWriterLockSlim _sync;
  298. public WriteLockToken(ReaderWriterLockSlim sync)
  299. {
  300. _sync = sync;
  301. sync.EnterWriteLock();
  302. }
  303. public void Dispose()
  304. {
  305. if (_sync != null)
  306. {
  307. _sync.ExitWriteLock();
  308. _sync = null;
  309. }
  310. }
  311. }
  312. public class DummyToken : IDisposable
  313. {
  314. public void Dispose()
  315. {
  316. }
  317. }
  318. public static IDisposable Read(this ReaderWriterLockSlim obj)
  319. {
  320. //if (BaseSqliteRepository.ThreadSafeMode > 0)
  321. //{
  322. // return new DummyToken();
  323. //}
  324. return new WriteLockToken(obj);
  325. }
  326. public static IDisposable Write(this ReaderWriterLockSlim obj)
  327. {
  328. //if (BaseSqliteRepository.ThreadSafeMode > 0)
  329. //{
  330. // return new DummyToken();
  331. //}
  332. return new WriteLockToken(obj);
  333. }
  334. }
  335. }