BaseSqliteRepository.cs 12 KB

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