SqliteExtensions.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Data;
  3. using System.Data.SQLite;
  4. using System.Threading.Tasks;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Server.Implementations.Persistence;
  7. namespace MediaBrowser.ServerApplication.Native
  8. {
  9. /// <summary>
  10. /// Class SQLiteExtensions
  11. /// </summary>
  12. static class SqliteExtensions
  13. {
  14. /// <summary>
  15. /// Connects to db.
  16. /// </summary>
  17. /// <param name="dbPath">The db path.</param>
  18. /// <param name="logger">The logger.</param>
  19. /// <returns>Task{IDbConnection}.</returns>
  20. /// <exception cref="System.ArgumentNullException">dbPath</exception>
  21. public static async Task<IDbConnection> ConnectToDb(string dbPath, ILogger logger)
  22. {
  23. if (string.IsNullOrEmpty(dbPath))
  24. {
  25. throw new ArgumentNullException("dbPath");
  26. }
  27. logger.Info("Sqlite {0} opening {1}", SQLiteConnection.SQLiteVersion, dbPath);
  28. var connectionstr = new SQLiteConnectionStringBuilder
  29. {
  30. PageSize = 4096,
  31. CacheSize = 2000,
  32. SyncMode = SynchronizationModes.Full,
  33. DataSource = dbPath,
  34. JournalMode = SQLiteJournalModeEnum.Wal
  35. };
  36. var connection = new SQLiteConnection(connectionstr.ConnectionString);
  37. await connection.OpenAsync().ConfigureAwait(false);
  38. return connection;
  39. }
  40. }
  41. public class DbConnector : IDbConnector
  42. {
  43. private readonly ILogger _logger;
  44. public DbConnector(ILogger logger)
  45. {
  46. _logger = logger;
  47. }
  48. public async Task<IDbConnection> Connect(string dbPath)
  49. {
  50. try
  51. {
  52. return await SqliteExtensions.ConnectToDb(dbPath, _logger).ConfigureAwait(false);
  53. }
  54. catch (Exception ex)
  55. {
  56. _logger.ErrorException("Error opening database {0}", ex, dbPath);
  57. throw;
  58. }
  59. }
  60. }
  61. }