BaseSqliteRepository.cs 7.7 KB

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