BaseSqliteRepository.cs 8.0 KB

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