BaseSqliteRepository.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. try
  89. {
  90. if (string.IsNullOrWhiteSpace(_defaultWal))
  91. {
  92. _defaultWal = db.Query("PRAGMA journal_mode").SelectScalarString().First();
  93. Logger.Info("Default journal_mode for {0} is {1}", DbFilePath, _defaultWal);
  94. }
  95. var queries = new List<string>
  96. {
  97. //"PRAGMA cache size=-10000"
  98. //"PRAGMA read_uncommitted = true",
  99. "PRAGMA synchronous=Normal"
  100. };
  101. if (CacheSize.HasValue)
  102. {
  103. queries.Add("PRAGMA cache_size=" + CacheSize.Value.ToString(CultureInfo.InvariantCulture));
  104. }
  105. if (EnableTempStoreMemory)
  106. {
  107. queries.Add("PRAGMA temp_store = memory");
  108. }
  109. else
  110. {
  111. queries.Add("PRAGMA temp_store = file");
  112. }
  113. foreach (var query in queries)
  114. {
  115. db.Execute(query);
  116. }
  117. }
  118. catch
  119. {
  120. using (db)
  121. {
  122. }
  123. throw;
  124. }
  125. _connection = new ManagedConnection(db, false);
  126. return _connection;
  127. }
  128. }
  129. public IStatement PrepareStatement(ManagedConnection connection, string sql)
  130. {
  131. return connection.PrepareStatement(sql);
  132. }
  133. public IStatement PrepareStatementSafe(ManagedConnection connection, string sql)
  134. {
  135. return connection.PrepareStatement(sql);
  136. }
  137. public IStatement PrepareStatement(IDatabaseConnection connection, string sql)
  138. {
  139. return connection.PrepareStatement(sql);
  140. }
  141. public IStatement PrepareStatementSafe(IDatabaseConnection connection, string sql)
  142. {
  143. return connection.PrepareStatement(sql);
  144. }
  145. public List<IStatement> PrepareAll(IDatabaseConnection connection, IEnumerable<string> sql)
  146. {
  147. return PrepareAllSafe(connection, sql);
  148. }
  149. public List<IStatement> PrepareAllSafe(IDatabaseConnection connection, IEnumerable<string> sql)
  150. {
  151. return sql.Select(connection.PrepareStatement).ToList();
  152. }
  153. protected void RunDefaultInitialization(ManagedConnection db)
  154. {
  155. var queries = new List<string>
  156. {
  157. "PRAGMA journal_mode=WAL",
  158. "PRAGMA page_size=4096",
  159. "PRAGMA synchronous=Normal"
  160. };
  161. if (EnableTempStoreMemory)
  162. {
  163. queries.AddRange(new List<string>
  164. {
  165. "pragma default_temp_store = memory",
  166. "pragma temp_store = memory"
  167. });
  168. }
  169. else
  170. {
  171. queries.AddRange(new List<string>
  172. {
  173. "pragma temp_store = file"
  174. });
  175. }
  176. db.ExecuteAll(string.Join(";", queries.ToArray()));
  177. Logger.Info("PRAGMA synchronous=" + db.Query("PRAGMA synchronous").SelectScalarString().First());
  178. }
  179. protected virtual bool EnableTempStoreMemory
  180. {
  181. get
  182. {
  183. return false;
  184. }
  185. }
  186. protected virtual int? CacheSize
  187. {
  188. get
  189. {
  190. return null;
  191. }
  192. }
  193. internal static void CheckOk(int rc)
  194. {
  195. string msg = "";
  196. if (raw.SQLITE_OK != rc)
  197. {
  198. throw CreateException((ErrorCode)rc, msg);
  199. }
  200. }
  201. internal static Exception CreateException(ErrorCode rc, string msg)
  202. {
  203. var exp = new Exception(msg);
  204. return exp;
  205. }
  206. private bool _disposed;
  207. protected void CheckDisposed()
  208. {
  209. if (_disposed)
  210. {
  211. throw new ObjectDisposedException(GetType().Name + " has been disposed and cannot be accessed.");
  212. }
  213. }
  214. public void Dispose()
  215. {
  216. _disposed = true;
  217. Dispose(true);
  218. GC.SuppressFinalize(this);
  219. }
  220. private readonly object _disposeLock = new object();
  221. /// <summary>
  222. /// Releases unmanaged and - optionally - managed resources.
  223. /// </summary>
  224. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  225. protected virtual void Dispose(bool dispose)
  226. {
  227. if (dispose)
  228. {
  229. DisposeConnection();
  230. }
  231. }
  232. private void DisposeConnection()
  233. {
  234. try
  235. {
  236. lock (_disposeLock)
  237. {
  238. using (WriteLock.Write())
  239. {
  240. if (_connection != null)
  241. {
  242. using (_connection)
  243. {
  244. _connection.Close();
  245. }
  246. _connection = null;
  247. }
  248. CloseConnection();
  249. }
  250. }
  251. }
  252. catch (Exception ex)
  253. {
  254. Logger.ErrorException("Error disposing database", ex);
  255. }
  256. }
  257. protected virtual void CloseConnection()
  258. {
  259. }
  260. protected List<string> GetColumnNames(IDatabaseConnection connection, string table)
  261. {
  262. var list = new List<string>();
  263. foreach (var row in connection.Query("PRAGMA table_info(" + table + ")"))
  264. {
  265. if (row[1].SQLiteType != SQLiteType.Null)
  266. {
  267. var name = row[1].ToString();
  268. list.Add(name);
  269. }
  270. }
  271. return list;
  272. }
  273. protected void AddColumn(IDatabaseConnection connection, string table, string columnName, string type, List<string> existingColumnNames)
  274. {
  275. if (existingColumnNames.Contains(columnName, StringComparer.OrdinalIgnoreCase))
  276. {
  277. return;
  278. }
  279. connection.Execute("alter table " + table + " add column " + columnName + " " + type + " NULL");
  280. }
  281. }
  282. public static class ReaderWriterLockSlimExtensions
  283. {
  284. private sealed class ReadLockToken : IDisposable
  285. {
  286. private ReaderWriterLockSlim _sync;
  287. public ReadLockToken(ReaderWriterLockSlim sync)
  288. {
  289. _sync = sync;
  290. sync.EnterReadLock();
  291. }
  292. public void Dispose()
  293. {
  294. if (_sync != null)
  295. {
  296. _sync.ExitReadLock();
  297. _sync = null;
  298. }
  299. }
  300. }
  301. private sealed class WriteLockToken : IDisposable
  302. {
  303. private ReaderWriterLockSlim _sync;
  304. public WriteLockToken(ReaderWriterLockSlim sync)
  305. {
  306. _sync = sync;
  307. sync.EnterWriteLock();
  308. }
  309. public void Dispose()
  310. {
  311. if (_sync != null)
  312. {
  313. _sync.ExitWriteLock();
  314. _sync = null;
  315. }
  316. }
  317. }
  318. public class DummyToken : IDisposable
  319. {
  320. public void Dispose()
  321. {
  322. }
  323. }
  324. public static IDisposable Read(this ReaderWriterLockSlim obj)
  325. {
  326. //if (BaseSqliteRepository.ThreadSafeMode > 0)
  327. //{
  328. // return new DummyToken();
  329. //}
  330. return new WriteLockToken(obj);
  331. }
  332. public static IDisposable Write(this ReaderWriterLockSlim obj)
  333. {
  334. //if (BaseSqliteRepository.ThreadSafeMode > 0)
  335. //{
  336. // return new DummyToken();
  337. //}
  338. return new WriteLockToken(obj);
  339. }
  340. }
  341. }