BaseSqliteRepository.cs 9.7 KB

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