BaseSqliteRepository.cs 8.3 KB

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