BaseSqliteRepository.cs 6.9 KB

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