public async Task Migrate_AllScriptOk_NoRollback()
        {
            var config           = ConfigProvider.GetConfig();
            var connectionString = String.Format(config.ConnectionStringMask, "test_ok");


            var builder = new MigratorBuilder();

            builder.UseCodeMigrations().FromAssembly(Assembly.GetExecutingAssembly());
            builder.UseScriptMigrations().FromDirectory(Path.Combine(Directory.GetCurrentDirectory(), "ScriptMigrations"));
            builder.UsePostgreSQL(connectionString);

            builder.UseUpgradeMigrationPolicy(MigrationPolicy.All);
            builder.UseDowngradeMigrationPolicy(MigrationPolicy.All);
            builder.SetUpTargetVersion(new DbVersion(3, 0));

            var migrator = builder.Build();

            await migrator.MigrateAsync();

            var migrationProvider = new PostgreDbProvider(new PostgreDbProviderOptions(connectionString));
            await migrationProvider.OpenConnectionAsync();

            var currentDbVersion = await migrationProvider.GetDbVersionSafeAsync();

            await migrationProvider.CloseConnectionAsync();

            Assert.Equal(new DbVersion(3, 0), currentDbVersion);
        }
        public void OverrideDefaultVariablesFromProvider()
        {
            // arrange
            var builder = new MigratorBuilder();

            var providerMock = new Mock <IDbProvider>();

            providerMock
            .Setup(x => x.GetDefaultVariables())
            .Returns(() => new Dictionary <string, string>
            {
                { DefaultVariables.User, ProviderUserName },
                { DefaultVariables.DbName, ProviderDbName }
            });
            var factoryMock = new Mock <IDbProviderFactory>();

            factoryMock
            .Setup(x => x.CreateDbProvider())
            .Returns(() => providerMock.Object);

            IReadOnlyDictionary <string, string> scriptVariables = null;
            var migrationsProviderMock = new Mock <IMigrationsProvider>();

            migrationsProviderMock
            .Setup(x => x.GetMigrations(
                       It.IsAny <IDbProvider>(),
                       It.IsAny <Dictionary <string, string> >(),
                       It.IsAny <ILogger>()))
            .Callback <IDbProvider, IReadOnlyDictionary <string, string>, ILogger>((provider, variables, logger) => { scriptVariables = variables; })
            .Returns <IDbProvider, IReadOnlyDictionary <string, string>, ILogger>((provider, variables, logger) => new List <IMigration>(0));

            builder.UseCustomMigrationsProvider(migrationsProviderMock.Object);
            builder.UserDbProviderFactory(factoryMock.Object);
            builder.UseVariable(DefaultVariables.User, ManualUserName);

            // act
            var migrator = builder.Build();

            // assert
            migrator.Should().NotBeNull("because we've create migrator");

            scriptVariables.Should().NotBeNull("because provider returns 2 variables");
            scriptVariables.Count.Should().Be(2, "because provider returns variable with user and db names");
            scriptVariables.ContainsKey(DefaultVariables.User).Should().BeTrue("because user name is default variable");
            scriptVariables[DefaultVariables.User].Should().BeEquivalentTo(ManualUserName, "because we set it manually to builder");
            scriptVariables.ContainsKey(DefaultVariables.DbName).Should().BeTrue("because db name is default variable");
            scriptVariables[DefaultVariables.DbName].Should().BeEquivalentTo(ProviderDbName, "because we set it manually to mock");
        }
        public async Task Migrate_AllScriptOk_Rollback()
        {
            var config           = ConfigProvider.GetConfig();
            var connectionString = String.Format(config.ConnectionStringMask, "test_rollback");


            var builder = new MigratorBuilder();

            builder.UseCodeMigrations().FromAssembly(Assembly.GetExecutingAssembly());
            builder.UseScriptMigrations().FromDirectory(Path.Combine(Directory.GetCurrentDirectory(), "ScriptMigrations"));
            builder.UsePostgreSQL(connectionString);

            builder.UseUpgradeMigrationPolicy(MigrationPolicy.Allowed);
            builder.UseDowngradeMigrationPolicy(MigrationPolicy.Allowed);
            builder.SetUpTargetVersion(new DbVersion(6, 0));

            var migrator = builder.Build();

            try
            {
                await migrator.MigrateAsync();

                // last migration is incorrect, can not go here
                Assert.False(true);
            }
            catch
            {
                // ignored
            }

            var migrationProvider = new PostgreDbProvider(new PostgreDbProviderOptions(connectionString));
            await migrationProvider.OpenConnectionAsync();

            var actualAppliedMigrations = await migrationProvider.GetAppliedMigrationVersionAsync();

            await migrationProvider.CloseConnectionAsync();

            var expectedAppliedMigrations = new HashSet <DbVersion>
            {
                new DbVersion(1, 0),
                new DbVersion(2, 0),
                new DbVersion(3, 0),
                new DbVersion(4, 0),
                new DbVersion(5, 0)
            };

            Assert.Equal(expectedAppliedMigrations, actualAppliedMigrations);
        }
        public async Task Migrate_AllScriptOk_SwitchedOffTransaction()
        {
            var config           = ConfigProvider.GetConfig();
            var connectionString = String.Format(config.ConnectionStringMask, "test_without_transactions");


            var builder = new MigratorBuilder();

            builder.UseCodeMigrations().FromAssembly(Assembly.GetExecutingAssembly());
            builder.UseScriptMigrations().FromDirectory(Path.Combine(Directory.GetCurrentDirectory(), "ScriptMigrations"));
            builder.UsePostgreSQL(connectionString);

            builder.UseUpgradeMigrationPolicy(MigrationPolicy.Allowed);
            builder.UseDowngradeMigrationPolicy(MigrationPolicy.Allowed);
            builder.SetUpTargetVersion(new DbVersion(5, 0));

            var migrator = builder.Build();

            await migrator.MigrateAsync();

            var migrationProvider = new PostgreDbProvider(new PostgreDbProviderOptions(connectionString));
            await migrationProvider.OpenConnectionAsync();

            var actualAppliedMigrations = await migrationProvider.GetAppliedMigrationVersionAsync();

            await migrationProvider.CloseConnectionAsync();

            var expectedAppliedMigrations = new HashSet <DbVersion>
            {
                new DbVersion(1, 0),
                new DbVersion(2, 0),
                new DbVersion(3, 0),
                new DbVersion(4, 0),
                new DbVersion(5, 0)
            };

            Assert.Equal(expectedAppliedMigrations, actualAppliedMigrations);
        }
Example #5
0
        /// <summary>
        /// Use provider to make migration on Postgre database.
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="connectionString">Connection string to Postgre</param>
        /// <param name="migrationTableHistoryName">Migration history table name. If param <see langword="null"/> default value from DB will be used </param>
        /// <param name="databaseEncoding">Text presentation of database encoding for Postgre. If <see langword="null"/> default value from DB will be used </param>
        /// <param name="lcCollate"> String sort order for Postgre. If param <see langword="null"/> default value from DB will be used </param>
        /// <param name="lcCtype">Character classification for Postgre. If param <see langword="null"/> default value from DB will be used</param>
        /// <param name="connectionLimit">Limit of connections to Postgre. If param <see langword="null"/> default value from DB will be used </param>
        /// <param name="template">The name of the template from which to create the new database. If param <see langword="null"/> default value from DB will be used</param>
        /// <param name="tableSpace">The name of the tablespace that will be associated with the new database. If param <see langword="null"/> default value from DB will be used </param>
        /// <remarks>
        /// For detailed params description look at <see cref="PostgreDbProviderOptions"/>
        /// </remarks>
        // ReSharper disable once InconsistentNaming
        public static MigratorBuilder UsePostgreSQL(
            this MigratorBuilder builder,
            string connectionString,
            string migrationTableHistoryName = null,
            string databaseEncoding          = null,
            string lcCollate    = null,
            string lcCtype      = null,
            int?connectionLimit = null,
            string template     = null,
            string tableSpace   = null)
        {
            var options = new PostgreDbProviderOptions(
                connectionString,
                migrationTableHistoryName,
                databaseEncoding,
                lcCollate,
                lcCtype,
                connectionLimit,
                template,
                tableSpace);

            builder.UserDbProviderFactory(new PostgreDbProviderFactory(options));
            return(builder);
        }
Example #6
0
        public async Task StartAsync(CancellationToken cToken)
        {
            _logger.LogInformation("Мигратор запущен");

            var builder = new MigratorBuilder(_services);

            builder.UsePostgreSQL(
                _configuration.MigrationOptions.ConnectionString,
                lcCollate: _configuration.MigrationOptions.LC_Collate,
                lcCtype: _configuration.MigrationOptions.LC_Type,
                databaseEncoding: _configuration.MigrationOptions.DataBaseEncoding,
                migrationTableHistoryName: "migration_history");
            builder.UseScriptMigrations()
            .FromAssembly(typeof(MigrationService).Assembly, "Migrations.Scripts.");
            builder.UseCodeMigrations()
            .FromAssembly <IMigration>(typeof(MigrationService).Assembly);
            builder.UseUpgradeMigrationPolicy(MigrationPolicy.Allowed);
            builder.UserLogger(_logger);

            if (_configuration.MigrationOptions.LogSql)
            {
                builder.UseLoggerForSql(_logger);
            }

            if (!String.IsNullOrWhiteSpace(_configuration.MigrationOptions.GrantUser))
            {
                builder.UseVariable(DefaultVariables.User, _configuration.MigrationOptions.GrantUser);
            }

            var migrator = builder.Build();
            var result   = await migrator.MigrateSafeAsync(cToken);

            _logger.LogInformation(result.IsSuccessfully
                ? "Миграции успешно выполнены"
                : $"Ошибка миграции: {result.ErrorMessage}");
        }