Exemple #1
0
        internal int GetExitCode(DatabaseUpgradeResult result)
        {
            if (!result.Successful)
            {
                logger.Error("An exception occurred while upgrading the database.", result.Error);

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(result.Error);
                Console.ResetColor();
                return(-1);
            }
            else
            {
                int count = result.Scripts.Count();

                stopwatch.Stop();
                TimeSpan elapsed  = stopwatch.Elapsed;
                string   duration = elapsed.ToString("mm':'ss");

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("{0} scripts executed successfully. Done in {1}!", count, duration);
                Console.ResetColor();
                return(0);
            }
        }
        public static int Main(string[] args)
        {
            string connectionString = Configuration["ConnectionStrings:PrimarySchoolDB"];

            EnsureDatabase.For.SqlDatabase(connectionString);

            UpgradeEngine upgrader =
                DeployChanges.To
                .SqlDatabase(connectionString)
                .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
                .LogToConsole()
                .Build();

            DatabaseUpgradeResult result = upgrader.PerformUpgrade();

            if (!result.Successful)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(result.Error);
                Console.ResetColor();

                return(-1);
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Success!");
            Console.ResetColor();
            return(0);
        }
Exemple #3
0
        public RunGroupOrderScenarios()
        {
            upgradeResult = null;
            scripts       = new List <SqlScript>
            {
                new SqlScript("ZZZScript1.sql", "create table Foo (Id int identity)", new SqlScriptOptions {
                    ScriptType = ScriptType.RunOnce, RunGroupOrder = DbUpDefaults.DefaultRunGroupOrder
                }),
                new SqlScript("ZZZScript2.sql", "alter table Foo add column Name varchar(255)", new SqlScriptOptions {
                    ScriptType = ScriptType.RunOnce, RunGroupOrder = DbUpDefaults.DefaultRunGroupOrder
                }),
                new SqlScript("AAAScript3.sql", "insert into Foo (Name) values ('test')", new SqlScriptOptions {
                    ScriptType = ScriptType.RunOnce, RunGroupOrder = DbUpDefaults.DefaultRunGroupOrder + 1
                })
            };

            logger = new CaptureLogsLogger();
            recordingConnection   = new RecordingDbConnection(logger, "SchemaVersions");
            testConnectionFactory = new DelegateConnectionFactory(_ => recordingConnection);

            upgradeEngineBuilder = DeployChanges.To
                                   .SqlDatabase("testconn")
                                   .WithScripts(new TestScriptProvider(scripts))
                                   .OverrideConnectionFactory(testConnectionFactory)
                                   .LogTo(logger);
        }
        protected virtual DatabaseUpgradeResult ExecuteAlways(string connectionString, string scriptsPath, string configurationSpecificScriptsPath, IDictionary <string, string> variables)
        {
            DatabaseUpgradeResult result = new DatabaseUpgradeResult(new SqlScript[0], true, null);

            if (Directory.Exists(scriptsPath))
            {
                UpgradeEngineBuilder engineBuilder = DeployChanges.To
                                                     .SqlDatabase(connectionString)
                                                     .WithScriptsFromFileSystem(scriptsPath);

                if (configurationSpecificScriptsPath != null)
                {
                    engineBuilder = engineBuilder.WithScriptsFromFileSystem(configurationSpecificScriptsPath);
                }

                var engine = engineBuilder.JournalTo(new NullJournal())
                             .WithVariables(variables)
                             .LogToConsole()
                             .Build();

                result = engine.PerformUpgrade();
            }

            return(result);
        }
Exemple #5
0
        public Task <int> Undo()
        {
            Console.WriteLine($"Starting: {nameof(this.Undo)}");
            EnsureDatabase();

            DatabaseUpgradeResult result = null;

            result = _runner.Run(_callbacks.beforeUndo);

            // Collect
            var before   = _callbacks.beforeEachUndo;
            var after    = _callbacks.afterEachUndo;
            var afterErr = _callbacks.afterEachUndoError;

            result = _runner.Run(_provider.GetUndoScripts(), before, after, afterErr);

            if (!result.Successful)
            {
                _runner.Run(_callbacks.afterUndoError);
            }
            else
            {
                _runner.Run(_callbacks.afterUndo);
            }

            return(ParseReturn(result));
        }
Exemple #6
0
        public Task <int> Migrate()
        {
            Console.WriteLine($"Starting: {nameof(this.Migrate)}");
            EnsureDatabase();

            DatabaseUpgradeResult result = null;

            result = _runner.Run(_callbacks.beforeMigrate);
            if (!result.Successful)
            {
                return(ParseReturn(result));
            }

            // Collect
            var before   = _callbacks.beforeEachMigrate;
            var after    = _callbacks.afterEachMigrate;
            var afterErr = _callbacks.afterEachMigrateError;

            result = _runner.Run(_provider.GetVersionScripts(), before, after, afterErr);
            result = _runner.RunHashed(_provider.GetRepeatableScripts(), before, after, afterErr);

            if (!result.Successful)
            {
                _runner.Run(_callbacks.afterMigrateError);
            }
            else
            {
                _runner.Run(_callbacks.afterMigrate);
            }

            return(ParseReturn(result));
        }
Exemple #7
0
        public Task <int> Test()
        {
            Console.WriteLine($"Starting: {nameof(this.Test)}");
            EnsureDatabase();

            DatabaseUpgradeResult result = null;

            result = _runner.Run(_callbacks.beforeTest);

            // Collect
            var before   = _callbacks.beforeEachTest;
            var after    = _callbacks.afterEachTest;
            var afterErr = _callbacks.afterEachTestError;

            result = _runner.RunHashed(_provider.GetTestScripts(), before, after, afterErr);

            if (!result.Successful)
            {
                _runner.Run(_callbacks.afterTestError);
            }
            else
            {
                _runner.Run(_callbacks.afterTest);
                if (_testRunner != null)
                {
                    _testRunner.RunTests();
                }
            }

            return(ParseReturn(result));
        }
        public UpgradeDatabaseScenarios()
        {
            upgradeResult = null;
            scripts       = new List <SqlScript>
            {
                new SqlScript("Script1.sql", "create table Foo (Id int identity)"),
                new SqlScript("Script2.sql", "alter table Foo add column Name varchar(255)"),
                new SqlScript("Script3.sql", "insert into Foo (Name) values ('test')")
            };

            executedScripts = new List <ExecutedSqlScript>
            {
                new ExecutedSqlScript {
                    Name = "Script1.sql", Hash = "a"
                },
                new ExecutedSqlScript {
                    Name = "Script2.sql", Hash = "b"
                },
                new ExecutedSqlScript {
                    Name = "Script3.sql", Hash = "c"
                }
            };

            logger = new CaptureLogsLogger();
            recordingConnection   = new RecordingDbConnection(logger, "SchemaVersions");
            testConnectionFactory = new DelegateConnectionFactory(_ => recordingConnection);

            upgradeEngineBuilder = DeployChanges.To
                                   .SqlDatabase("testconn")
                                   .WithScripts(new TestScriptProvider(scripts))
                                   .OverrideConnectionFactory(testConnectionFactory)
                                   .LogTo(logger);
        }
Exemple #9
0
 private static int ReportFailure(DatabaseUpgradeResult result)
 {
     Console.ForegroundColor = ConsoleColor.Red;
     Console.WriteLine(result.Error);
     Console.ResetColor();
     return(FailureResult);
 }
        public DatabaseUpgradeResult UpgradeDatabase(string connectionString, string pathToChangelog, bool runRollbacks = true)
        {
            EnsureDatabase.For.SqlDatabase(connectionString);

            DatabaseUpgradeResult upgradeResult = PerformUpgrade(connectionString, Path.Combine(pathToChangelog, "schema\\1.0.X"),
                                                                 script => !script.Contains("_rollback"));

            if (!upgradeResult.Successful)
            {
                return(new DatabaseUpgradeResult(allExecutedScripts, upgradeResult.Successful, upgradeResult.Error));
            }

            //upgradeResult = PerformUpgrade(connectionString, Path.Combine(pathToChangelog, "procedures"),
            //    script => !script.Contains("_rollback"));
            //if (!upgradeResult.Successful)
            //    return new DatabaseUpgradeResult(allExecutedScripts, upgradeResult.Successful, upgradeResult.Error);

            if (runRollbacks)
            {
                //upgradeResult = PerformUpgrade(connectionString, Path.Combine(pathToChangelog, "procedures"),
                //    script => script.Contains("_rollback"));
                //if (!upgradeResult.Successful)
                //    return new DatabaseUpgradeResult(allExecutedScripts, upgradeResult.Successful, upgradeResult.Error);

                upgradeResult = PerformUpgrade(connectionString, Path.Combine(pathToChangelog, "schema\\1.0.X"),
                                               script => script.Contains("_rollback"));
                if (!upgradeResult.Successful)
                {
                    return(new DatabaseUpgradeResult(allExecutedScripts, upgradeResult.Successful, upgradeResult.Error));
                }
            }

            return(new DatabaseUpgradeResult(allExecutedScripts, upgradeResult.Successful, upgradeResult.Error));
        }
        public Task <int> Handle(UpgradeDatabaseCommand request, CancellationToken cancellationToken)
        {
            _logger.LogDebug("Running with Options={@DbUpOptions}", request);

            var connectionStringBuilder = new SqlConnectionStringBuilder(request.ConnectionString);

            var variables = new Dictionary <string, string>
            {
                { "environment", request.Environment },
                { "login_name", connectionStringBuilder.UserID },
                { "database_name", connectionStringBuilder.InitialCatalog },
            };

            UpgradeEngineBuilder builder = DeployChanges.To.SqlDatabase(request.ConnectionString)
                                           .WithScriptsFromFileSystem(request.ScriptsDirectory)
                                           .WithTransaction()
                                           .LogToLogger(_logger)
                                           .WithVariables(variables);

            if (!request.EnableJournaling)
            {
                builder = builder.JournalTo(new NullJournal());
            }

            DatabaseUpgradeResult result = builder
                                           .Build()
                                           .PerformUpgrade();

            return(Task.FromResult(result.Successful ? 0 : 1));
        }
        internal static int Main(string[] args)
        {
            string connectionString      = args.FirstOrDefault();
            bool   dropDatabase          = Convert.ToBoolean(args[1]);
            DatabaseUpgradeResult result = RunDatabaseUpdate(connectionString, dropDatabase);

            return(!result.Successful ? ShowError(result.Error) : ShowSuccess());
        }
 private void PrintResult(string resultType, DatabaseUpgradeResult executionResult)
 {
     Console.WriteLine($"Database {resultType} Result: {(executionResult.Successful ? "Success" : "Error")}");
     if (!executionResult.Successful)
     {
         Console.WriteLine(executionResult.Error);
     }
 }
Exemple #14
0
        private static void WriteResultErrorToConsole(DatabaseUpgradeResult result)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(result.Error);
            Console.ResetColor();
#if DEBUG
            Console.ReadLine();
#endif
        }
Exemple #15
0
 public static void WriteExecutedScriptsToOctopusTaskSummary(this DatabaseUpgradeResult result)
 {
     Console.WriteLine("##octopus[stdout-highlight]");
     Console.WriteLine($"Ran {result.Scripts.Count()} script{(result.Scripts.Count() == 1 ? "" : "s")}");
     foreach (var script in result.Scripts)
     {
         Console.WriteLine(script.Name);
     }
     Console.WriteLine("##octopus[stdout-default]");
 }
        protected virtual DatabaseUpgradeResult ExecuteAlways(AlwaysScriptType alwaysScriptType, string migrationsDirectory, string connectionString, string configuration, string configurationDefault, IDictionary <string, string> variables)
        {
            EnsureDatabase.For.SqlDatabase(connectionString);

            string scriptsPath = Path.Combine(migrationsDirectory, alwaysScriptType.ToString());
            string configurationSpecificScriptsPath = GetConfigurationSpecificScriptsPath(scriptsPath, configuration, configurationDefault);
            DatabaseUpgradeResult result            = ExecuteAlways(connectionString, scriptsPath, configurationSpecificScriptsPath, variables);

            return(result);
        }
        private bool HandleResult(DatabaseUpgradeResult result)
        {
            if (!result.Successful)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(result.Error);
                Console.ResetColor();
            }

            return(result.Successful);
        }
Exemple #18
0
        private static bool IsError(DatabaseUpgradeResult result)
        {
            if (!result.Successful)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(result.Error);
                Console.ResetColor();
                Console.ReadLine();
                return(true);
            }

            return(false);
        }
Exemple #19
0
        private bool RunNonIdempotentMigrationScripts()
        {
            builder = DeployChanges.To.PostgresqlDatabase(connectionString);
            var upgrader = builder
                           .WithScriptsEmbeddedInAssembly(
                Assembly.GetExecutingAssembly(),
                fileName => !fileName.ContainsKeyword(IdempotentScriptIndicator))
                           .Build();

            DatabaseUpgradeResult upgradeResult = upgrader.PerformUpgrade();

            return(upgradeResult.Successful);
        }
Exemple #20
0
        internal void ReportResult_WhenFailure_ReturnFailureResponse(
            Mock <IEnumerable <SqlScript> > scripts,
            Mock <SqlScript> script,
            Mock <Exception> exception)
        {
            // Arrange
            var upgradeResult = new DatabaseUpgradeResult(scripts.Object, false, exception.Object, script.Object);

            // Act
            var result = ResultReporter.ReportResult(upgradeResult);

            // Assert
            Assert.Equal(FailureResult, result);
        }
Exemple #21
0
 private static void DisplayResult(DatabaseUpgradeResult result)
 {
     if (result.Successful)
     {
         Console.ForegroundColor = ConsoleColor.Green;
         Console.WriteLine("Success.");
     }
     else
     {
         Console.ForegroundColor = ConsoleColor.Red;
         Console.WriteLine(result.Error);
     }
     Console.ResetColor();
 }
Exemple #22
0
        public static DatabaseUpgradeResult DeployTestSeedData(string connectionString)
        {
            EnsureDatabase.For.SqlDatabase(connectionString);
            UpgradeEngine upgrader = DeployChanges.To
                                     .SqlDatabase(connectionString)
                                     .WithTransactionPerScript()
                                     .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly(), (s) => { return(s.Contains("SeedData")); })
                                     .LogToConsole()
                                     .Build();

            DatabaseUpgradeResult result = upgrader.PerformUpgrade();

            return(result);
        }
Exemple #23
0
 private Task <int> ParseReturn(DatabaseUpgradeResult result,
                                [System.Runtime.CompilerServices.CallerMemberName] string caller = null)
 {
     if (result.Successful)
     {
         Console.WriteLine($"Finished Successful: {caller}");
         return(Task.FromResult(0));
     }
     else
     {
         Console.WriteLine($"Finished Failed: {caller}");
         return(Task.FromResult(1));
     }
 }
Exemple #24
0
        private static void HandleMigrationResults(DatabaseUpgradeResult result, bool reset = false)
        {
            if (!result.Successful && (!reset || result.Error.Message != "Invalid object name 'SchemaVersions'."))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(result.Error);
                Console.ResetColor();
                Environment.Exit(-1);
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Success!");
            Console.ResetColor();
        }
        private static string WriteExecutedScriptsToOctopusTaskSummary(DatabaseUpgradeResult result)
        {
            var sb = new StringBuilder();

            sb.AppendLine("##octopus[stdout-highlight]");
            sb.AppendLine($"Ran {result.Scripts.Count()} script{(result.Scripts.Count() == 1 ? "" : "s")}");
            foreach (var script in result.Scripts)
            {
                sb.AppendLine(script.Name);
                sb.AppendLine(script.Contents);
            }

            sb.AppendLine("##octopus[stdout-default]");
            return(sb.ToString());
        }
Exemple #26
0
        public static void UseMigration(this IApplicationBuilder app, string connectionString)
        {
            DropDatabase.For.SqlDatabase(connectionString);
            EnsureDatabase.For.SqlDatabase(connectionString);

            UpgradeEngine upgrader = DeployChanges.To
                                     .SqlDatabase(connectionString)
                                     .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
                                     .LogToConsole()
                                     .Build();

            DatabaseUpgradeResult result = upgrader.PerformUpgrade();

            ShowMessage(result);
        }
Exemple #27
0
        private static int InstallTests(string connectionString)
        {
            UpgradeEngine upgradeEngine = DeployChanges
                                          .To
                                          .SqlDatabase(connectionString)
                                          .WithScriptsFromFileSystem(TESTS_PATH, new FileSystemScriptOptions {
                IncludeSubDirectories = true
            })
                                          .JournalTo(new NullJournal())
                                          .Build();

            DatabaseUpgradeResult databaseUpgradeResult = upgradeEngine.PerformUpgrade();

            return(!databaseUpgradeResult.Successful ? ShowError(databaseUpgradeResult.Error) : ShowSuccess());
        }
Exemple #28
0
        private static void SetupDatabase()
        {
            EnsureDatabase.For.SqlDatabase(DataContext.GetDatabaseConnectionString());
            UpgradeEngine dbUpgradeEngine = DeployChanges.To.SqlDatabase(DataContext.GetDatabaseConnectionString())
                                            .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
                                            .LogToConsole()
                                            .Build();

            DatabaseUpgradeResult dbUpgradeResult = dbUpgradeEngine.PerformUpgrade();

            if (!dbUpgradeResult.Successful)
            {
                throw new ApplicationException("Database setup failed", dbUpgradeResult.Error);
            }
        }
        static int Main(string[] args)
        {
            var connectionName = "dissertation";

            var connectionString = Environment.GetEnvironmentVariable($"SQLAZURECONNSTR_{connectionName}");

            if (string.IsNullOrEmpty(connectionString))
            {
                connectionString = args.FirstOrDefault()
                                   ?? ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
            }

            Console.WriteLine($"Connection string: {connectionString}");

            DatabaseUpgradeResult result = null;

            try
            {
                var upgrader =
                    DeployChanges.To
                    .SqlDatabase(connectionString)
                    .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
                    .LogToConsole()
                    .Build();

                result = upgrader.PerformUpgrade();
            }
            catch (Exception)
            {
                Console.WriteLine($"Connection string: {connectionString}");
            }

            if (result == null || !result.Successful)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(result == null ? "result is null" : $"{result.Error}");
                Console.ResetColor();
#if DEBUG
                Console.ReadLine();
#endif
                return(-1);
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Success!");
            Console.ResetColor();
            return(0);
        }
        private DatabaseUpgradeResult PerformUpgrade(string connectionString, string filesInPath, Func <string, bool> fileNameFilter)
        {
            UpgradeEngineBuilder builder = DeployChanges
                                           .To
                                           .SqlDatabase(connectionString)
                                           .WithTransaction()
                                           //.WithTransactionAlwaysRollback()
                                           .WithVariablesDisabled()
                                           .WithScriptsFromFileSystem(filesInPath, fileNameFilter);

            DatabaseUpgradeResult result = builder.Build().PerformUpgrade();

            allExecutedScripts.AddRange(result.Scripts);

            return(result);
        }
 public UpgradeModel(DatabaseUpgradeResult[] results, string log)
 {
     Results = results;
     Log = log;
 }