DataAccess.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. );
  37. }
  38. }
  39. private DbConnection GetConnection()
  40. {
  41. var conn = new SqliteConnection("Data Source=" + _filename);
  42. conn.Open();
  43. return conn;
  44. }
  45. // --- common ---
  46. public int BulkOperation<T>(IEnumerable<T> items, Func<T, DbConnection, int> proc)
  47. {
  48. var count = 0;
  49. using (var conn = GetConnection())
  50. {
  51. using (var t = conn.BeginTransaction())
  52. {
  53. count += items.Sum(p => proc(p, conn));
  54. t.Commit();
  55. }
  56. }
  57. return count;
  58. }
  59. public Dictionary<string, string> GetConfigs()
  60. {
  61. using (var conn = GetConnection())
  62. return conn.Query<ConfigEntry>("SELECT * FROM Configs")
  63. .ToDictionary(p => p.Key, p => p.Value);
  64. }
  65. }
  66. }