BaseSqliteRepository.cs 7.9 KB

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