BaseSqliteRepository.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using MediaBrowser.Model.Logging;
  7. using SQLitePCL.pretty;
  8. using System.Linq;
  9. using SQLitePCL;
  10. namespace Emby.Server.Implementations.Data
  11. {
  12. public abstract class BaseSqliteRepository : IDisposable
  13. {
  14. protected string DbFilePath { get; set; }
  15. protected ReaderWriterLockSlim WriteLock;
  16. protected ILogger Logger { get; private set; }
  17. protected BaseSqliteRepository(ILogger logger)
  18. {
  19. Logger = logger;
  20. WriteLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
  21. }
  22. protected TransactionMode TransactionMode
  23. {
  24. get { return TransactionMode.Deferred; }
  25. }
  26. protected TransactionMode ReadTransactionMode
  27. {
  28. get { return TransactionMode.Deferred; }
  29. }
  30. internal static int ThreadSafeMode { get; set; }
  31. static BaseSqliteRepository()
  32. {
  33. SQLite3.EnableSharedCache = false;
  34. int rc = raw.sqlite3_config(raw.SQLITE_CONFIG_MEMSTATUS, 0);
  35. //CheckOk(rc);
  36. rc = raw.sqlite3_config(raw.SQLITE_CONFIG_MULTITHREAD, 1);
  37. //rc = raw.sqlite3_config(raw.SQLITE_CONFIG_SINGLETHREAD, 1);
  38. //rc = raw.sqlite3_config(raw.SQLITE_CONFIG_SERIALIZED, 1);
  39. //CheckOk(rc);
  40. rc = raw.sqlite3_enable_shared_cache(1);
  41. ThreadSafeMode = raw.sqlite3_threadsafe();
  42. }
  43. private static bool _versionLogged;
  44. private string _defaultWal;
  45. protected ManagedConnection _connection;
  46. protected virtual bool EnableSingleConnection
  47. {
  48. get { return true; }
  49. }
  50. protected ManagedConnection CreateConnection(bool isReadOnly = false)
  51. {
  52. if (_connection != null)
  53. {
  54. return _connection;
  55. }
  56. lock (WriteLock)
  57. {
  58. if (!_versionLogged)
  59. {
  60. _versionLogged = true;
  61. Logger.Info("Sqlite version: " + SQLite3.Version);
  62. Logger.Info("Sqlite compiler options: " + string.Join(",", SQLite3.CompilerOptions.ToArray()));
  63. }
  64. ConnectionFlags connectionFlags;
  65. if (isReadOnly)
  66. {
  67. //Logger.Info("Opening read connection");
  68. //connectionFlags = ConnectionFlags.ReadOnly;
  69. connectionFlags = ConnectionFlags.Create;
  70. connectionFlags |= ConnectionFlags.ReadWrite;
  71. }
  72. else
  73. {
  74. //Logger.Info("Opening write connection");
  75. connectionFlags = ConnectionFlags.Create;
  76. connectionFlags |= ConnectionFlags.ReadWrite;
  77. }
  78. if (EnableSingleConnection)
  79. {
  80. connectionFlags |= ConnectionFlags.PrivateCache;
  81. }
  82. else
  83. {
  84. connectionFlags |= ConnectionFlags.SharedCached;
  85. }
  86. connectionFlags |= ConnectionFlags.NoMutex;
  87. var db = SQLite3.Open(DbFilePath, connectionFlags, null);
  88. if (string.IsNullOrWhiteSpace(_defaultWal))
  89. {
  90. _defaultWal = db.Query("PRAGMA journal_mode").SelectScalarString().First();
  91. Logger.Info("Default journal_mode for {0} is {1}", DbFilePath, _defaultWal);
  92. }
  93. var queries = new List<string>
  94. {
  95. //"PRAGMA cache size=-10000"
  96. //"PRAGMA read_uncommitted = true",
  97. "PRAGMA synchronous=Normal"
  98. };
  99. if (CacheSize.HasValue)
  100. {
  101. queries.Add("PRAGMA cache_size=" + CacheSize.Value.ToString(CultureInfo.InvariantCulture));
  102. }
  103. if (EnableTempStoreMemory)
  104. {
  105. queries.Add("PRAGMA temp_store = memory");
  106. }
  107. else
  108. {
  109. queries.Add("PRAGMA temp_store = file");
  110. }
  111. foreach (var query in queries)
  112. {
  113. db.Execute(query);
  114. }
  115. _connection = new ManagedConnection(db, false);
  116. return _connection;
  117. }
  118. }
  119. public IStatement PrepareStatement(ManagedConnection connection, string sql)
  120. {
  121. return connection.PrepareStatement(sql);
  122. }
  123. public IStatement PrepareStatementSafe(ManagedConnection connection, string sql)
  124. {
  125. return connection.PrepareStatement(sql);
  126. }
  127. public IStatement PrepareStatement(IDatabaseConnection connection, string sql)
  128. {
  129. return connection.PrepareStatement(sql);
  130. }
  131. public IStatement PrepareStatementSafe(IDatabaseConnection connection, string sql)
  132. {
  133. return connection.PrepareStatement(sql);
  134. }
  135. public List<IStatement> PrepareAll(IDatabaseConnection connection, IEnumerable<string> sql)
  136. {
  137. return PrepareAllSafe(connection, sql);
  138. }
  139. public List<IStatement> PrepareAllSafe(IDatabaseConnection connection, IEnumerable<string> sql)
  140. {
  141. return sql.Select(connection.PrepareStatement).ToList();
  142. }
  143. protected void RunDefaultInitialization(ManagedConnection db)
  144. {
  145. var queries = new List<string>
  146. {
  147. "PRAGMA journal_mode=WAL",
  148. "PRAGMA page_size=4096",
  149. "PRAGMA synchronous=Normal"
  150. };
  151. if (EnableTempStoreMemory)
  152. {
  153. queries.AddRange(new List<string>
  154. {
  155. "pragma default_temp_store = memory",
  156. "pragma temp_store = memory"
  157. });
  158. }
  159. else
  160. {
  161. queries.AddRange(new List<string>
  162. {
  163. "pragma temp_store = file"
  164. });
  165. }
  166. db.ExecuteAll(string.Join(";", queries.ToArray()));
  167. Logger.Info("PRAGMA synchronous=" + db.Query("PRAGMA synchronous").SelectScalarString().First());
  168. }
  169. protected virtual bool EnableTempStoreMemory
  170. {
  171. get
  172. {
  173. return false;
  174. }
  175. }
  176. protected virtual int? CacheSize
  177. {
  178. get
  179. {
  180. return null;
  181. }
  182. }
  183. internal static void CheckOk(int rc)
  184. {
  185. string msg = "";
  186. if (raw.SQLITE_OK != rc)
  187. {
  188. throw CreateException((ErrorCode)rc, msg);
  189. }
  190. }
  191. internal static Exception CreateException(ErrorCode rc, string msg)
  192. {
  193. var exp = new Exception(msg);
  194. return exp;
  195. }
  196. private bool _disposed;
  197. protected void CheckDisposed()
  198. {
  199. if (_disposed)
  200. {
  201. throw new ObjectDisposedException(GetType().Name + " has been disposed and cannot be accessed.");
  202. }
  203. }
  204. public void Dispose()
  205. {
  206. _disposed = true;
  207. Dispose(true);
  208. GC.SuppressFinalize(this);
  209. }
  210. private readonly object _disposeLock = new object();
  211. /// <summary>
  212. /// Releases unmanaged and - optionally - managed resources.
  213. /// </summary>
  214. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  215. protected virtual void Dispose(bool dispose)
  216. {
  217. if (dispose)
  218. {
  219. try
  220. {
  221. lock (_disposeLock)
  222. {
  223. using (WriteLock.Write())
  224. {
  225. if (_connection != null)
  226. {
  227. using (_connection)
  228. {
  229. }
  230. _connection = null;
  231. }
  232. CloseConnection();
  233. }
  234. }
  235. }
  236. catch (Exception ex)
  237. {
  238. Logger.ErrorException("Error disposing database", ex);
  239. }
  240. }
  241. }
  242. protected virtual void CloseConnection()
  243. {
  244. }
  245. protected List<string> GetColumnNames(IDatabaseConnection connection, string table)
  246. {
  247. var list = new List<string>();
  248. foreach (var row in connection.Query("PRAGMA table_info(" + table + ")"))
  249. {
  250. if (row[1].SQLiteType != SQLiteType.Null)
  251. {
  252. var name = row[1].ToString();
  253. list.Add(name);
  254. }
  255. }
  256. return list;
  257. }
  258. protected void AddColumn(IDatabaseConnection connection, string table, string columnName, string type, List<string> existingColumnNames)
  259. {
  260. if (existingColumnNames.Contains(columnName, StringComparer.OrdinalIgnoreCase))
  261. {
  262. return;
  263. }
  264. connection.Execute("alter table " + table + " add column " + columnName + " " + type + " NULL");
  265. }
  266. }
  267. public static class ReaderWriterLockSlimExtensions
  268. {
  269. private sealed class ReadLockToken : IDisposable
  270. {
  271. private ReaderWriterLockSlim _sync;
  272. public ReadLockToken(ReaderWriterLockSlim sync)
  273. {
  274. _sync = sync;
  275. sync.EnterReadLock();
  276. }
  277. public void Dispose()
  278. {
  279. if (_sync != null)
  280. {
  281. _sync.ExitReadLock();
  282. _sync = null;
  283. }
  284. }
  285. }
  286. private sealed class WriteLockToken : IDisposable
  287. {
  288. private ReaderWriterLockSlim _sync;
  289. public WriteLockToken(ReaderWriterLockSlim sync)
  290. {
  291. _sync = sync;
  292. sync.EnterWriteLock();
  293. }
  294. public void Dispose()
  295. {
  296. if (_sync != null)
  297. {
  298. _sync.ExitWriteLock();
  299. _sync = null;
  300. }
  301. }
  302. }
  303. public class DummyToken : IDisposable
  304. {
  305. public void Dispose()
  306. {
  307. }
  308. }
  309. public static IDisposable Read(this ReaderWriterLockSlim obj)
  310. {
  311. //if (BaseSqliteRepository.ThreadSafeMode > 0)
  312. //{
  313. // return new DummyToken();
  314. //}
  315. return new WriteLockToken(obj);
  316. }
  317. public static IDisposable Write(this ReaderWriterLockSlim obj)
  318. {
  319. //if (BaseSqliteRepository.ThreadSafeMode > 0)
  320. //{
  321. // return new DummyToken();
  322. //}
  323. return new WriteLockToken(obj);
  324. }
  325. }
  326. }