Example #1
0
        #pragma warning disable 0612
        public Migrator(string connectionString)
        {
            var announcer = new ConsoleAnnouncer()
            {
                ShowSql = true,
            };

            var options = new ProcessorOptions()
            {
                ConnectionString = connectionString,
            };

            var factory   = new FluentMigrator.Runner.Processors.MySql.MySql5ProcessorFactory();
            var processor = factory.Create(connectionString, announcer, options);

            var context = new RunnerContext(announcer)
            {
                AllowBreakingChange = true,
            };

            _runner = new MigrationRunner(
                typeof(Migrator).Assembly,
                context,
                processor);
        }
        private void CreateDatabaseSchemaInMemory(string connectionString)
        {
            if (connectionString == null)
            {
                throw new ArgumentNullException("connectionString");
            }

            // Enable testing profile in FluentMigrator.
            Environment.SetEnvironmentVariable("TestingProfile", "1", EnvironmentVariableTarget.Process);

            // Create migration announcer.
            var announcer = new ConsoleAnnouncer();

            // Create migration context.
            var migrationContext = new RunnerContext(announcer);

            // Create migration options, factory and runner.
            var options = new ProcessorOptions
            {
                PreviewOnly = false,
                Timeout     = 60
            };
            var factory   = new SqliteProcessorFactory();
            var processor = factory.Create(connectionString, announcer, options);
            var runner    = new MigrationRunner(Assembly.GetAssembly(typeof(MigrationExtensions)), migrationContext, processor);

            // Update database.
            runner.MigrateUp(long.MaxValue, true);
        }
Example #3
0
        private static void RunMigrations()
        {
            var announcer = new ConsoleAnnouncer()
            {
                ShowSql = true
            };
            var runner = new RunnerContext(announcer)
            {
                Connection = DatabaseSettings.Instance.BuildConnectionString(),
                Database   = Enum.GetName(typeof(DatabaseType), (DatabaseType)DatabaseSettings.Instance.Type).ToLower(),
                Targets    = new string [] { typeof(ModelHelper).Assembly.Location },
            };

            new TaskExecutor(runner).Execute();
        }
Example #4
0
        private static void MigrateDatabaseToLastestVersion(SqlConnectionStringBuilder csb)
        {
            var announcer = new ConsoleAnnouncer {
                ShowSql = true
            };
            var options          = new ProcessorOptions();
            var processorFactory = new SqlServer2016ProcessorFactory();
            var processor        = processorFactory.Create(csb.ConnectionString, announcer, options);
            var context          = new RunnerContext(announcer)
            {
                AllowBreakingChange = true
            };

            var runner = new MigrationRunner(typeof(FirstMigration).Assembly, context, processor);

            runner.MigrateUp();
        }
Example #5
0
        private static void RunMigration(SqlConnection sqlConnection)
        {
            if ((sqlConnection != null) && (String.IsNullOrEmpty(sqlConnection.ConnectionString) == false))
            {
                ConsoleAnnouncer consoleAnnouncer = new ConsoleAnnouncer {
                    ShowSql = true
                };
                RunnerContext runnerContext = new RunnerContext(consoleAnnouncer)
                {
                    Targets     = new[] { MigrationNamespace },
                    Database    = "SqlServer",
                    Connection  = sqlConnection.ConnectionString,
                    PreviewOnly = false
                };

                TaskExecutor taskExecutor = new TaskExecutor(runnerContext);
                taskExecutor.Execute();
            }
        }
        private static void RunInLegacyMode(DatabaseConfiguration dbConfig)
        {
            // Create the announcer to output the migration messages
#pragma warning disable 612
            var announcer = new ConsoleAnnouncer()
            {
                ShowSql = true,
            };
#pragma warning restore 612

            // Processor specific options (usually none are needed)
            var options = new ProcessorOptions()
            {
                ConnectionString = dbConfig.ConnectionString,
            };

            // Initialize the DB-specific processor
#pragma warning disable 612
            var processor = MigrationProcessorFactoryProvider
                            .RegisteredFactories.Single(
                x => string.Equals(x.Name, dbConfig.ProcessorId, StringComparison.OrdinalIgnoreCase))
                            .Create(dbConfig.ConnectionString, announcer, options);
#pragma warning restore 612

            // Configure the runner
#pragma warning disable 612
            var context = new RunnerContext(announcer)
            {
                AllowBreakingChange = true,
            };
#pragma warning restore 612

            // Create the migration runner
#pragma warning disable 612
            var runner = new MigrationRunner(
                typeof(AddGTDTables).Assembly,
                context,
                processor);
#pragma warning restore 612

            // Run the migrations
            runner.MigrateUp();
        }
Example #7
0
        static void Main()
        {
            // Configure the DB connection
            var dbFileName = Path.Combine(AppContext.BaseDirectory, "test.db");
            var csb        = new SqliteConnectionStringBuilder
            {
                DataSource = dbFileName,
                Mode       = SqliteOpenMode.ReadWriteCreate
            };

            // Create the announcer to output the migration messages
            var announcer = new ConsoleAnnouncer()
            {
                ShowSql = true,
            };

            // Processor specific options (usually none are needed)
            var options = new ProcessorOptions();

            // Initialize the DB-specific processor
            var processorFactory = new SQLiteProcessorFactory();
            var processor        = processorFactory.Create(csb.ConnectionString, announcer, options);

            // Configure the runner
            var context = new RunnerContext(announcer)
            {
                AllowBreakingChange = true,
            };

            // Create the migration runner
            var runner = new MigrationRunner(
                typeof(AddGTDTables).Assembly,
                context,
                processor);

            // Run the migrations
            runner.MigrateUp();
        }
Example #8
0
        private static void RunInLegacyMode(string connectionString)
        {
            // Create the announcer to output the migration messages
#pragma warning disable 612
            var announcer = new ConsoleAnnouncer()
            {
                ShowSql = true,
            };
#pragma warning restore 612

            // Processor specific options (usually none are needed)
            var options = new ProcessorOptions();

            // Initialize the DB-specific processor
#pragma warning disable 612
            var processorFactory = new SQLiteProcessorFactory(serviceProvider: null);
            var processor        = processorFactory.Create(connectionString, announcer, options);
#pragma warning restore 612

            // Configure the runner
#pragma warning disable 612
            var context = new RunnerContext(announcer)
            {
                AllowBreakingChange = true,
            };
#pragma warning restore 612

            // Create the migration runner
#pragma warning disable 612
            var runner = new MigrationRunner(
                typeof(AddGTDTables).Assembly,
                context,
                processor);
#pragma warning restore 612

            // Run the migrations
            runner.MigrateUp();
        }
Example #9
0
        public override bool Execute()
        {
            if (string.IsNullOrEmpty(databaseType))
            {
                Log.LogError("You must specific a database type. i.e. mysql or sqlserver");
                return(false);
            }

            if (string.IsNullOrEmpty(migrationAssembly))
            {
                Log.LogError("You must specific a migration assembly");
                return(false);
            }

            IAnnouncer announcer = new ConsoleAnnouncer
            {
                ShowElapsedTime = Verbose,
                ShowSql         = Verbose
            };

            StreamWriter outputWriter = null;

            if (Output)
            {
                if (string.IsNullOrEmpty(OutputFilename))
                {
                    OutputFilename = Path.GetFileName(Target) + ".sql";
                }

                outputWriter = new StreamWriter(OutputFilename);
                var fileAnnouncer = new TextWriterAnnouncer(outputWriter)
                {
                    ShowElapsedTime = false,
                    ShowSql         = true
                };

                announcer = new CompositeAnnouncer(announcer, fileAnnouncer);
            }

            Log.LogMessage(MessageImportance.Low, "Creating Context");

            var runnerContext = new RunnerContext(announcer)
            {
                ApplicationContext         = ApplicationContext,
                Database                   = databaseType,
                Connection                 = Connection,
                ConnectionStringConfigPath = ConnectionStringConfigPath,
                Target           = Target,
                PreviewOnly      = PreviewOnly,
                Namespace        = Namespace,
                Task             = Task,
                Version          = Version,
                Steps            = Steps,
                WorkingDirectory = WorkingDirectory,
                Profile          = Profile,
                Tags             = Tags.ToTags(),
                Timeout          = Timeout
            };

            Log.LogMessage(MessageImportance.Low, "Executing Migration Runner");
            try
            {
                new TaskExecutor(runnerContext).Execute();
            }
            catch (ProcessorFactoryNotFoundException ex)
            {
                Log.LogError("While executing migrations the following error was encountered: {0}", ex.Message);
                return(false);
            }
            catch (Exception ex)
            {
                Log.LogError("While executing migrations the following error was encountered: {0}, {1}", ex.Message, ex.StackTrace);
                return(false);
            }
            finally
            {
                if (outputWriter != null)
                {
                    outputWriter.Dispose();
                }
            }

            return(true);
        }
Example #10
0
 public MigratorContext()
 {
     // Default values
     Announcer = new ConsoleAnnouncer();
     Timeout   = 30;
 }
Example #11
0
        protected override void ExecuteTask()
        {
            IAnnouncer announcer = new ConsoleAnnouncer
            {
                ShowElapsedTime = Verbose,
                ShowSql         = Verbose
            };

            StreamWriter outputWriter = null;

            if (Output)
            {
                if (string.IsNullOrEmpty(OutputFilename))
                {
                    OutputFilename = Path.GetFileName(Target) + ".sql";
                }

                outputWriter = new StreamWriter(OutputFilename);
                var fileAnnouncer = new TextWriterAnnouncer(outputWriter)
                {
                    ShowElapsedTime = false,
                    ShowSql         = true
                };

                announcer = new CompositeAnnouncer(announcer, fileAnnouncer);
            }

            var runnerContext = new RunnerContext(announcer)
            {
                ApplicationContext = ApplicationContext,
                Database           = Database,
                Connection         = Connection,
                Targets            = new string[] { Target },
                PreviewOnly        = Preview,
                Namespace          = Namespace,
                NestedNamespaces   = NestedNamespaces,
                Task                  = Task,
                Version               = Version,
                Steps                 = Steps,
                WorkingDirectory      = WorkingDirectory,
                Profile               = Profile,
                Tags                  = Tags.ToTags(),
                Timeout               = Timeout,
                TransactionPerSession = TransactionPerSession
            };

            try
            {
                new TaskExecutor(runnerContext).Execute();
            }
            catch (ProcessorFactoryNotFoundException ex)
            {
                announcer.Error("While executing migrations the following error was encountered: {0}", ex.Message);
                throw;
            }
            catch (Exception e)
            {
                announcer.Error("While executing migrations the following error was encountered: {0}, {1}", e.Message, e.StackTrace);
                throw;
            }
            finally
            {
                if (outputWriter != null)
                {
                    outputWriter.Dispose();
                }
            }
        }
Example #12
0
 public MigratorContext()
 {
     // Default values
     Announcer = new ConsoleAnnouncer();
     Timeout = 30;
 }
Example #13
0
        static void Main(string[] args)
        {
            _config = new ConfigurationBuilder()
                      .SetBasePath(Directory.GetCurrentDirectory())
                      .AddJsonFile("appsettings.json", false, true)
                      .AddEnvironmentVariables()
                      .Build();

            _provider = new ServiceCollection()
                        .AddSingleton <CancellationTokenSource>()
                        .AddOptions()
                        .Configure <DatabaseOptions>(_config.GetSection("database"))
                        .AddLogging(cfg =>
            {
                cfg.AddConfiguration(_config);
                cfg.AddConsole();
            })
                        .BuildServiceProvider();

            _logger = _provider.GetRequiredService <ILogger <Program> >();

            IOptionsSnapshot <DatabaseOptions> dbSettings = _provider.GetService <IOptionsSnapshot <DatabaseOptions> >();

            CreateDatabaseIfNotExists(dbSettings);

            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();

            builder.UserID     = dbSettings.Value.User;
            builder.Password   = dbSettings.Value.Password;
            builder.DataSource = dbSettings.Value.Server;
            if (dbSettings.Value.Name != null)
            {
                builder.InitialCatalog = dbSettings.Value.Name;
            }

            _logger.LogInformation("Using connection string {0} for migrations.", builder);


            // Create the announcer to output the migration messages
            ConsoleAnnouncer announcer = new ConsoleAnnouncer()
            {
                ShowSql         = true,
                ShowElapsedTime = true
            };

            // Processor specific options (usually none are needed)
            ProcessorOptions options = new ProcessorOptions();

            // Initialize the DB-specific processor
            SqlServerProcessorFactory processorFactory = new SqlServerProcessorFactory();
            IMigrationProcessor       processor        = processorFactory.Create(builder.ToString(), announcer, options);

            // Configure the runner
            RunnerContext context = new RunnerContext(announcer)
            {
                AllowBreakingChange = true,
            };

            // Create the migration runner
            MigrationRunner runner = new MigrationRunner(
                typeof(Program).Assembly,
                context,
                processor);

            // Run the migrations
            runner.MigrateUp();
            Console.WriteLine("Hello World!");
        }
Example #14
0
        static void Main(string[] args)
        {
            const string usage = @"Fluent Migrator Schema Dumper
  Usage:
    SchemaDumper.exe --connection CONNECTION [--file FILE] [--verbose] [--show] [--open]
    SchemaDumper.exe --version
    SchemaDumper.exe --help

  Options:
    --connection CONNECTION -c CONNECTION    The connection string. Required.
    --file FILE -f FILE                      File to output. Optional. [default: schemaDump.cs]
    --show -s                                Show output. Optional.
    --open -o                                Open file. Optional.
    --verbose                                Verbose. Optional.
    --help -h                                Show this screen.
    --version -v                             Show version.
";

            var arguments = new Docopt().Apply(usage, args, version: Assembly.GetExecutingAssembly().GetName().Version, exit: true);
            var file      = arguments["--file"].ToString();
            var verbose   = arguments["--verbose"].IsTrue;
            var open      = arguments["--open"].IsTrue;
            var show      = arguments["--show"].IsTrue;

            if (!Path.IsPathRooted(file))
            {
                file = Path.Combine(Environment.CurrentDirectory, file);
            }
            var connectionString = arguments["--connection"].ToString();

            if (verbose)
            {
                WriteLine($"Saving to {file}.");
            }
            try { var builder = new SqlConnectionStringBuilder(connectionString); }
            catch (ArgumentException)
            {
                WriteLine("Connection string is in incorrect format.");
                return;
            }
            using (var connection = new SqlConnection(connectionString))
            {
                try { connection.Open(); }
                catch (SqlException ex)
                {
                    WriteLine($"Connection couldn't be established:\n{ex.Message}");
                    return;
                }
                var consoleAnnouncer = new ConsoleAnnouncer();
                var dumper           = new SqlServerSchemaDumper(new SqlServerProcessor(connection, new SqlServer2000Generator(), consoleAnnouncer, new ProcessorOptions(), new SqlServerDbFactory()), consoleAnnouncer);
                var tables           = dumper.ReadDbSchema();
                var writer           = new RCDumpWriter();
                writer.WriteToFile(tables, file);
            }
            if (show)
            {
                WriteLine(File.ReadAllText(file));
            }
            if (open)
            {
                try { Process.Start(file); } catch { }
            }
            if (verbose)
            {
                WriteLine("Done.");
            }
        }