2
0

BaseSqliteRepository.cs 12 KB

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