DataAccess.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using D3NsCore.Entities;
  2. using Dapper;
  3. using Mono.Data.Sqlite;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Data.Common;
  7. using System.IO;
  8. using System.Linq;
  9. namespace D3NsCore.Tools
  10. {
  11. internal class DataAccess
  12. {
  13. private readonly string _filename;
  14. public DataAccess(string filename)
  15. {
  16. _filename = filename;
  17. CreateDatabaseIfNotExist();
  18. }
  19. private void CreateDatabaseIfNotExist()
  20. {
  21. if (File.Exists(_filename)) return;
  22. using (var conn = GetConnection())
  23. {
  24. conn.Execute(
  25. //Create table:Config
  26. "CREATE TABLE Configs("
  27. + $"{nameof(ConfigEntry.Key)} VARCHAR(32) PRIMARY KEY,"
  28. + $"{nameof(ConfigEntry.Value)} VARCHAR(512)"
  29. + ");" +
  30. //Init Data
  31. $"INSERT INTO Configs ({nameof(ConfigEntry.Key)}) VALUES ('{nameof(ConfigAdapter.Key)}');"
  32. + $"INSERT INTO Configs ({nameof(ConfigEntry.Key)}) VALUES ('{nameof(ConfigAdapter.Secret)}');"
  33. + $"INSERT INTO Configs ({nameof(ConfigEntry.Key)}) VALUES ('{nameof(ConfigAdapter.GetMyIp)}');"
  34. + $"INSERT INTO Configs ({nameof(ConfigEntry.Key)}) VALUES ('{nameof(ConfigAdapter.Domain)}');"
  35. + $"INSERT INTO Configs ({nameof(ConfigEntry.Key)}) VALUES ('{nameof(ConfigAdapter.DnsRecordName)}');"
  36. + $"INSERT INTO Configs ({nameof(ConfigEntry.Key)}) VALUES ('{nameof(ConfigAdapter.WebProxy)}');"
  37. );
  38. }
  39. }
  40. private DbConnection GetConnection()
  41. {
  42. var conn = new SqliteConnection("Data Source=" + _filename);
  43. conn.Open();
  44. return conn;
  45. }
  46. // --- common ---
  47. public int BulkOperation<T>(IEnumerable<T> items, Func<T, DbConnection, int> proc)
  48. {
  49. var count = 0;
  50. using (var conn = GetConnection())
  51. {
  52. using (var t = conn.BeginTransaction())
  53. {
  54. count += items.Sum(p => proc(p, conn));
  55. t.Commit();
  56. }
  57. }
  58. return count;
  59. }
  60. public Dictionary<string, string> GetConfigs()
  61. {
  62. using (var conn = GetConnection())
  63. return conn.Query<ConfigEntry>("SELECT * FROM Configs")
  64. .ToDictionary(p => p.Key, p => p.Value);
  65. }
  66. }
  67. }