BaseSqliteRepository.cs 12 KB

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