Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 

79 rader
2.3 KiB

  1. using System.Data;
  2. using System.Data.SqlClient;
  3. using System.Threading;
  4. using Dapper;
  5. using Microsoft.EntityFrameworkCore;
  6. namespace DotNetCore.CAP.PostgreSql.Test
  7. {
  8. public abstract class DatabaseTestHost : TestHost
  9. {
  10. private static bool _sqlObjectInstalled;
  11. public static object _lock = new object();
  12. protected override void PostBuildServices()
  13. {
  14. base.PostBuildServices();
  15. lock (_lock)
  16. {
  17. if (!_sqlObjectInstalled)
  18. {
  19. InitializeDatabase();
  20. }
  21. }
  22. }
  23. public override void Dispose()
  24. {
  25. DeleteAllData();
  26. base.Dispose();
  27. }
  28. private void InitializeDatabase()
  29. {
  30. using (CreateScope())
  31. {
  32. var storage = GetService<PostgreSqlStorage>();
  33. var token = new CancellationTokenSource().Token;
  34. CreateDatabase();
  35. storage.InitializeAsync(token).GetAwaiter().GetResult();
  36. _sqlObjectInstalled = true;
  37. }
  38. }
  39. private void CreateDatabase()
  40. {
  41. var masterConn = ConnectionUtil.GetMasterConnectionString();
  42. var databaseName = ConnectionUtil.GetDatabaseName();
  43. using (var connection = ConnectionUtil.CreateConnection(masterConn))
  44. {
  45. connection.Execute($@"
  46. IF NOT EXISTS (SELECT * FROM sysdatabases WHERE name = N'{databaseName}')
  47. CREATE DATABASE [{databaseName}];");
  48. }
  49. }
  50. private void DeleteAllData()
  51. {
  52. var conn = ConnectionUtil.GetConnectionString();
  53. using (var connection = new SqlConnection(conn))
  54. {
  55. var commands = new[] {
  56. "DISABLE TRIGGER ALL ON ?",
  57. "ALTER TABLE ? NOCHECK CONSTRAINT ALL",
  58. "DELETE FROM ?",
  59. "ALTER TABLE ? CHECK CONSTRAINT ALL",
  60. "ENABLE TRIGGER ALL ON ?"
  61. };
  62. foreach (var command in commands)
  63. {
  64. connection.Execute(
  65. "sp_MSforeachtable",
  66. new { command1 = command },
  67. commandType: CommandType.StoredProcedure);
  68. }
  69. }
  70. }
  71. }
  72. }