BaseSqliteRepository.cs 11 KB

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