Пример #1
0
        public void PerformUpgrade_ShouldUseCustomVersionsTable_IfCustomJournalIsPassed()
        {
            upgradeEngineBuilder.Some <UpgradeEngineBuilder, Error>()
            .SelectJournal(
                new Journal("test_scheme", "test_SchemaVersion").Some()
                );

            upgradeEngineBuilder.Build().PerformUpgrade();

            logger.InfoMessages.Should().Contain("Creating the [test_scheme].[test_SchemaVersion] table");
        }
Пример #2
0
            public override UpgradeEngine Given()
            {
                scriptProvider = Substitute.For <IScriptProvider>();
                scriptProvider.GetScripts(Arg.Any <IConnectionManager>()).Returns(new List <SqlScript> {
                    new SqlScript("1234", "foo")
                });
                versionTracker = Substitute.For <IJournal>();
                dbConnection   = Substitute.For <IDbConnection>();
                dbCommand      = Substitute.For <IDbCommand>();
                dbConnection.CreateCommand().Returns(dbCommand);
                var connectionManager = new TestConnectionManager(dbConnection);

                scriptExecutor = new SqlScriptExecutor(() => connectionManager, () => Substitute.For <IUpgradeLog>(), null, () => true, null, () => versionTracker);

                var builder = new UpgradeEngineBuilder()
                              .WithScript(new SqlScript("1234", "create table $var$ (Id int)"))
                              .JournalTo(versionTracker)
                              .WithVariable("var", "sub");

                builder.Configure(c => c.ScriptExecutor    = scriptExecutor);
                builder.Configure(c => c.ConnectionManager = connectionManager);

                var upgrader = builder.Build();

                return(upgrader);
            }
        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));
        }
Пример #4
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 DowngradeEnabledUpgradeEngine(UpgradeEngineBuilder builder, bool autoDowngradeEnabled)
        {
            _autoDowngradeEnabled = autoDowngradeEnabled;

            builder.Configure(c =>
            {
                if (!(c.Journal is DowngradeEnabledTableJournal))
                {
                    throw new NotSupportedException("Can't build 'DowngradeEnabledUpgradeEngine', journal table not inherits 'DowngradeEnabledTableJournal'");
                }

                _journal           = c.Journal as DowngradeEnabledTableJournal;
                _scriptProviders   = c.ScriptProviders;
                _connectionManager = c.ConnectionManager;
                _log = c.Log;
            });

            UpgradeEngine = builder.Build();
        }
Пример #6
0
        private static bool PerformUpgrade(UpgradeEngineBuilder upgraderBuilder)
        {
            var upgrader = upgraderBuilder.Build();

            var result = upgrader.PerformUpgrade();

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

                return(false);
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Success!");
            Console.ResetColor();

            return(true);
        }
Пример #7
0
        RunTest(UpgradeEngineBuilder builder)
        {
            var executor    = new Mock <IScriptExecutor>();
            var connections = new Mock <IConnectionManager>();

            builder.Configure(c =>
            {
                c.ScriptExecutor    = executor.Object;
                c.ConnectionManager = connections.Object;
            });

            var scripts = new List <SqlScript>();

            executor.Setup(x => x.Execute(It.IsAny <SqlScript>()))
            .Callback(new Action <SqlScript>(s => scripts.Add(s)));

            executor.Setup(x => x.Execute(It.IsAny <SqlScript>(), It.IsAny <IDictionary <string, string> >()))
            .Callback(new Action <SqlScript, IDictionary <string, string> >((s, a) => scripts.Add(s)));

            builder.Build().PerformUpgrade();

            return(scripts, executor, connections);
        }
Пример #8
0
 private void UpgradeIsPerformed()
 {
     result = upgradeEngineBuilder.Build().PerformUpgrade();
 }
Пример #9
0
        public static void Main(string[] args)
        {
            //FhirSearchParamters test = new FhirSearchParamters();
            //string SQL = test.GetMSSQLQuerySearchParameterTargetResources();

            Dictionary <string, string> Arguments = ProcessArguments(args);
            bool UnattendedMode = false;

            if (Arguments.ContainsKey("-unattendedmode"))
            {
                if (Arguments["-unattendedmode"] == "true")
                {
                    UnattendedMode = true;
                }
            }


            WebConfigReader  WebConfigReader = new WebConfigReader();
            DbConnectionInfo ConnectionInfo  = WebConfigReader.Read("PyroConnectionString");

            //string connectionString = string.Empty;
            if (ConnectionInfo != null)
            {
                string            TargetScriptFolder = string.Empty;
                Tools.SynchToDbUp SynchToDbUp        = new Tools.SynchToDbUp();

                UpgradeEngineBuilder UpgradeEngineBuilder = null;
                if (ConnectionInfo.ProviderName == ResourceStore.MsSQLProviderName)
                {
                    SynchToDbUp.RunMsSQL(ConnectionInfo.ConnectionString);

                    EnsureDatabase.For.SqlDatabase(ConnectionInfo.ConnectionString);

                    TargetScriptFolder   = $"{ResourceStore.BaseSqlScriptFolder}.{ResourceStore.MsSQLScriptFolder}";
                    UpgradeEngineBuilder = DeployChanges.To
                                           .SqlDatabase(ConnectionInfo.ConnectionString, null) //null or "" for default schema for user
                                           .JournalToSqlTable("dbo", ResourceStore.DbUpSchemaVersionsTableName)
                                           .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly(), (string s) => s.StartsWith(TargetScriptFolder));
                }
                else if (ConnectionInfo.ProviderName == ResourceStore.PostgreSQLProviderName)
                {
                    SynchToDbUp.RunPostgreSQL(ConnectionInfo.ConnectionString);
                    EnsureDatabase.For.PostgresqlDatabase(ConnectionInfo.ConnectionString);

                    TargetScriptFolder   = $"{ResourceStore.BaseSqlScriptFolder}.{ResourceStore.PostgreSqlScriptFolder}";
                    UpgradeEngineBuilder = DeployChanges.To
                                           .PostgresqlDatabase(ConnectionInfo.ConnectionString, null) //null or "" for default schema for user
                                           .JournalToPostgresqlTable("public", ResourceStore.DbUpSchemaVersionsTableName)
                                           .WithScriptsAndCodeEmbeddedInAssembly(Assembly.GetExecutingAssembly(), (string s) => s.StartsWith(TargetScriptFolder));
                }
                else
                {
                    throw new ApplicationException($"The ProviderName from the Connection information in the Web.Config file is not supported. Name was {ConnectionInfo.ProviderName}, supported are '{ResourceStore.MsSQLProviderName}' and '{ResourceStore.PostgreSQLProviderName}'.");
                }

                //Common to both SQL Server and PostgreSQL
                UpgradeEngineBuilder.WithTransactionPerScript()
                .WithVariablesDisabled()
                .LogToConsole()
                .WithExecutionTimeout(TimeSpan.FromSeconds(180));

                var upgrader = UpgradeEngineBuilder.Build();

                Console.WriteLine("Building upgrade knowledge, please wait...");
                System.Threading.Thread.Sleep(1000 * 10);
                bool UpgradeRequired = upgrader.IsUpgradeRequired();
                Console.WriteLine("Database upgrade required: " + UpgradeRequired.ToString());
                if (UpgradeRequired)
                {
                    var ScriptsToExecute = upgrader.GetScriptsToExecute();
                    Console.WriteLine("Scripts to execute:");
                    foreach (var Script in ScriptsToExecute)
                    {
                        Console.ForegroundColor = ConsoleColor.Cyan;

                        Console.WriteLine($"  {Script.Name.Substring(TargetScriptFolder.Count() + 1, Script.Name.Count() - (TargetScriptFolder.Count() + 1))}");
                    }



                    Console.ForegroundColor = ConsoleColor.Magenta;
                    Console.WriteLine("");
                    bool OutputComplted = false;
                    while (!OutputComplted)
                    {
                        Console.WriteLine();
                        Console.WriteLine("Would you like the SQL scripts output to a folder");
                        Console.WriteLine("before they are applied to the database?");
                        Console.Write("Answer (Y/N)?: ");
                        bool OutputSqlScripts = false;
                        if (UnattendedMode)
                        {
                            OutputSqlScripts = false;
                            OutputComplted   = true;
                        }
                        else
                        {
                            ConsoleKeyInfo Input = Console.ReadKey();
                            if (Input.Key == ConsoleKey.Y)
                            {
                                OutputSqlScripts = true;
                            }
                            else
                            {
                                OutputComplted = true;
                            }
                        }

                        if (OutputSqlScripts)
                        {
                            Console.Clear();
                            Console.WriteLine();
                            Console.WriteLine("Please type the directory name where you would like the SQL scripts writen to?");
                            Console.WriteLine("e.g 'C:\\Temp\\PyroSqlScripts' and hit [Enter]");
                            Console.Write("Directory: ");
                            string UserPath = Console.ReadLine();
                            UserPath = UserPath.TrimEnd('\\');
                            Tools.ScriptFileDrop ScriptFileDrop = new Tools.ScriptFileDrop(UserPath, ScriptsToExecute);
                            string ScriptFileDropResult         = ScriptFileDrop.Output(TargetScriptFolder);
                            if (string.IsNullOrWhiteSpace(ScriptFileDropResult))
                            {
                                OutputComplted = true;
                                foreach (var Script in ScriptsToExecute)
                                {
                                    Console.ForegroundColor = ConsoleColor.Cyan;
                                    Console.WriteLine($"  {Script.Name.Substring(TargetScriptFolder.Count() + 1, Script.Name.Count() - (TargetScriptFolder.Count() + 1))}");
                                }

                                Console.WriteLine();
                                Console.ForegroundColor = ConsoleColor.Magenta;
                                Console.WriteLine($"All Sql Scripts where output to : '{UserPath}'");
                            }
                            else
                            {
                                Console.WriteLine();
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine(ScriptFileDropResult);
                                Console.ForegroundColor = ConsoleColor.Magenta;
                                OutputComplted          = false;
                            }
                        }
                    }


                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("");
                    Console.WriteLine("");
                    Console.WriteLine("###############################################################################");
                    Console.WriteLine("################### Have you backed up your database? #########################");
                    Console.WriteLine("###############################################################################");
                    Console.WriteLine("");
                    Console.ForegroundColor = ConsoleColor.Magenta;
                    Console.WriteLine("Do you wish to perform the upgrade against the database ?");
                    Console.Write("Answer (Y/N)?: ");
                    bool Run = false;
                    if (UnattendedMode)
                    {
                        Run = true;
                    }
                    else
                    {
                        ConsoleKeyInfo Input = Console.ReadKey();
                        if (Input.Key == ConsoleKey.Y)
                        {
                            Run = true;
                        }
                    }

                    if (Run)
                    {
                        DateTime StartTime = DateTime.Now;
                        Console.ResetColor();
                        Console.WriteLine();
                        Console.WriteLine($"Start Time: {StartTime.ToShortDateString()} {StartTime.ToShortTimeString()}");
                        var result = upgrader.PerformUpgrade();

                        // Display the result
                        if (result.Successful)
                        {
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine("Success!");
                            DateTime EndTime = DateTime.Now;
                            var      Timer   = EndTime.Subtract(StartTime);
                            Console.ResetColor();
                            Console.WriteLine($"TimeTaken: {Timer.Hours}:Hrs, {Timer.Minutes}:Mins, {Timer.Seconds}: Secs");
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine(result.Error);
                            Console.WriteLine("Failed!");
                            DateTime EndTime = DateTime.Now;
                            var      Timer   = EndTime.Subtract(StartTime);
                            Console.ResetColor();
                            Console.WriteLine($"TimeTaken: {Timer.Hours}:Hrs, {Timer.Minutes}:Mins, {Timer.Seconds}: Secs");
                        }
                    }
                    else
                    {
                        Console.Clear();
                        Console.WriteLine("Upgrade aborted, press any key to end.");
                    }
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("");
                    Console.WriteLine("No upgrades are required!");
                }

                Console.ResetColor();
                Console.WriteLine("");
                Console.Write("Hit any key to end.");
                Console.ReadKey();
            }
        }