Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

78 řádky
2.5 KiB

  1. using System;
  2. using System.Data;
  3. using System.Data.SqlClient;
  4. using Dapper;
  5. using DotNetCore.CAP.SqlServer.Diagnostics;
  6. using Microsoft.Extensions.Logging;
  7. using Moq;
  8. namespace DotNetCore.CAP.SqlServer.Test
  9. {
  10. public abstract class DatabaseTestHost : IDisposable
  11. {
  12. protected ILogger<SqlServerStorage> Logger;
  13. protected CapOptions CapOptions;
  14. protected SqlServerOptions SqlSeverOptions;
  15. protected DiagnosticProcessorObserver DiagnosticProcessorObserver;
  16. public bool SqlObjectInstalled;
  17. protected DatabaseTestHost()
  18. {
  19. Logger = new Mock<ILogger<SqlServerStorage>>().Object;
  20. CapOptions = new Mock<CapOptions>().Object;
  21. SqlSeverOptions = new SqlServerOptions()
  22. {
  23. ConnectionString = ConnectionUtil.GetConnectionString()
  24. };
  25. DiagnosticProcessorObserver = new DiagnosticProcessorObserver(new Mock<IDispatcher>().Object);
  26. InitializeDatabase();
  27. }
  28. public void Dispose()
  29. {
  30. DeleteAllData();
  31. }
  32. private void InitializeDatabase()
  33. {
  34. var masterConn = ConnectionUtil.GetMasterConnectionString();
  35. var databaseName = ConnectionUtil.GetDatabaseName();
  36. using (var connection = ConnectionUtil.CreateConnection(masterConn))
  37. {
  38. connection.Execute($@"
  39. IF NOT EXISTS (SELECT * FROM sysdatabases WHERE name = N'{databaseName}')
  40. CREATE DATABASE [{databaseName}];");
  41. }
  42. new SqlServerStorage(Logger, CapOptions, SqlSeverOptions, DiagnosticProcessorObserver).InitializeAsync().GetAwaiter().GetResult();
  43. SqlObjectInstalled = true;
  44. }
  45. private void DeleteAllData()
  46. {
  47. var conn = ConnectionUtil.GetConnectionString();
  48. using (var connection = new SqlConnection(conn))
  49. {
  50. var commands = new[] {
  51. "DISABLE TRIGGER ALL ON ?",
  52. "ALTER TABLE ? NOCHECK CONSTRAINT ALL",
  53. "DELETE FROM ?",
  54. "ALTER TABLE ? CHECK CONSTRAINT ALL",
  55. "ENABLE TRIGGER ALL ON ?"
  56. };
  57. foreach (var command in commands)
  58. {
  59. connection.Execute(
  60. "sp_MSforeachtable",
  61. new { command1 = command },
  62. commandType: CommandType.StoredProcedure);
  63. }
  64. }
  65. }
  66. }
  67. }