2
0

BaseSqliteRepository.cs 12 KB

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