BaseSqliteRepository.cs 9.9 KB

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