Example #1
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jObject = JObject.Load(reader);

            for (var v = (int?)jObject["Version"] ?? 0; v < Migrations.Count; v = (int)jObject["Version"])
            {
                Migrations[v](jObject);
            }


            var result = existingValue as ProjectConfig ?? new ProjectConfig();

            serializer.Populate(jObject.CreateReader(), result);
            return(result);
        }
Example #2
0
        static void Main(string[] args)
        {
            Migrations.UpdateDatabase();
            Console.Clear();

            Console.ReadLine();
        }
Example #3
0
        /// <summary>
        /// Creates droptable
        /// </summary>
        /// <param name="migrationBuilder">builder</param>
        protected override void Down(Migrations migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "AspNetRoleClaims");

            migrationBuilder.DropTable(
                name: "AspNetUserClaims");

            migrationBuilder.DropTable(
                name: "AspNetUserLogins");

            migrationBuilder.DropTable(
                name: "AspNetUserRoles");

            migrationBuilder.DropTable(
                name: "AspNetUserTokens");

            migrationBuilder.DropTable(
                name: "Employee");

            migrationBuilder.DropTable(
                name: "TechnicianTicketTime");

            migrationBuilder.DropTable(
                name: "Ticket");

            migrationBuilder.DropTable(
                name: "AspNetRoles");

            migrationBuilder.DropTable(
                name: "AspNetUsers");
        }
Example #4
0
        public void TryItWithMoreComplexScenario()
        {
            var firstBatch = new[]
            {
                new TestMigration(1, "master", ""),
                new TestMigration(2, "branch-A", ""),
                new TestMigration(3, "branch-A", ""),

                new TestMigration(3, "branch-B", ""),
            };

            Database.Migrate(TestConfig.ConnectionString, new Migrations(firstBatch));

            var secondBatchWhereSomeoneSwoopedInANewMigration = new[]
            {
                new TestMigration(1, "master", ""),
                new TestMigration(2, "branch-A", ""),
                new TestMigration(3, "branch-A", ""),

                new TestMigration(2, "branch-B", ""),
                new TestMigration(3, "branch-B", ""),
            };

            var ex = Assert.Throws <MigrationException>(() =>
            {
                var migrations = new Migrations(secondBatchWhereSomeoneSwoopedInANewMigration);

                Database.Migrate(TestConfig.ConnectionString, migrations);
            });

            Console.WriteLine(ex);

            Assert.That(ex.Message, Contains.Substring("2-branch-B"));
        }
Example #5
0
        public async Task <IActionResult> PutMigrations(int id, Migrations migrations)
        {
            if (id != migrations.Id)
            {
                return(BadRequest());
            }

            _context.Entry(migrations).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!MigrationsExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Example #6
0
        public async Task <ActionResult <Migrations> > PostMigrations(Migrations migrations)
        {
            _context.Migrations.Add(migrations);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetMigrations", new { id = migrations.Id }, migrations));
        }
Example #7
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Migration,Batch")] Migrations migrations)
        {
            if (id != migrations.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(migrations);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!MigrationsExists(migrations.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(migrations));
        }
Example #8
0
 void ThrowIfAnyDowngradeNotSupported()
 {
     if (Migrations.Any(m => !m.CanDowngrade))
     {
         throw new NotSupportedException("One or more migrations do not support downgrading.");
     }
 }
Example #9
0
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            Migrations.Migrate(host.Services);
            Migrations.AddConfigToDb(host.Services);
            host.Run();
        }
Example #10
0
        public void ItWorks()
        {
            Database.Migrate(TestConfig.ConnectionString, Migrations.FromAssemblyOf <CheckApiWorks>(), new Options(logAction: text => Console.WriteLine("LOG: {0}", text)));

            var tableNames = GetTableNames();

            Assert.That(tableNames, Is.EqualTo(new[] { "MyFirstTable", "MySecondTable" }));
        }
Example #11
0
        public void ItWorks()
        {
            Database.Migrate(TestConfig.ConnectionString, Migrations.FromAssemblyOf <CheckFiltering>().Where(m => m.SequenceNumber < 2));

            var tableNames = GetTableNames();

            Assert.That(tableNames, Is.EqualTo(new[] { "MyFirstTable" }));
        }
        public void ExecuteMigrationWithTimeout()
        {
            var migrations = Migrations.FromFilesIn(Path.Combine(AppContext.BaseDirectory, "hints", "scripts"));

            var options = new Options(sqlCommandTimeout: TimeSpan.FromSeconds(10));

            Database.Migrate(TestConfig.MysqlConnectionString, migrations, options);
        }
Example #13
0
 /// <summary>
 /// Finds all valid implementations of <see cref="IMigration"/> in the
 /// specified <paramref name="assembly"/> and adds them to the migration process.
 /// </summary>
 /// <param name="assembly">The assembly to scan.</param>
 protected virtual void FindMigrations(Assembly assembly)
 {
     foreach (var type in assembly.GetTypes().Where(t => IsMigration(t)))
     {
         var attr = type.GetCustomAttributes(typeof(MigrationAttribute), false)[0] as MigrationAttribute;
         Migrations.Add(attr.Version, type);
     }
 }
        public void ExecuteMigrationsFromCode()
        {
            var migrations = Migrations.FromAssemblyOf <TestSqlCommandTimeoutHint>();

            var options = new Options(sqlCommandTimeout: TimeSpan.FromSeconds(10));

            Database.Migrate(TestConfig.MysqlConnectionString, migrations, options);
        }
Example #15
0
        public void CanPickUpMigrationsFromFiles()
        {
            Database.Migrate(TestConfig.ConnectionString, Migrations.FromFilesIn(_directory));

            var tableNames = GetTableNames().ToList();

            Assert.That(tableNames, Is.EqualTo(new[] { "Tabelle1", "Tabelle2", "Tabelle3" }));
        }
Example #16
0
        public ActionResult Index()
        {
            var connection = new OrmLiteConnectionFactory(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString,
                                                          SqlServerDialect.Provider);
            var migrations = new Migrations(connection);

            // migrations.Up();
            return(View());
        }
Example #17
0
        /// <summary>
        /// Run all migrations with a tag that has been specified on this project, or no tags at all
        /// </summary>
        public async Task RunApplicableMigrationsAsync()
        {
            foreach (var migration in Migrations.Where(m => m.IsToBeRun).OrderBy(m => m.Version))
            {
                await migration.UpAsync(false);
            }

            _log.Info("Ran all applicable migrations for project '{0}'", Name);
        }
Example #18
0
        private static string ConfigureTestDatabase()
        {
            var database         = CreateDatabase();
            var connectionString = string.Format("Data Source=localhost;Initial Catalog={0};Integrated Security=true", database);

            Database.Install <SqlServerConnectionFactory>(connectionString, ConnectionScope.ByThread);
            Migrations.MigrateToLatest(DatabaseType.SqlServer, connectionString, "AB");
            return(database.ToString());
        }
Example #19
0
        /// <summary>
        /// Run all migrations up until and including the specified version
        /// </summary>
        public async Task MigrateToVersion(long version)
        {
            foreach (var migration in Migrations.Where(m => m.Version <= version && m.IsToBeRun).OrderBy(m => m.Version))
            {
                await migration.UpAsync(false);
            }

            _log.Info("Ran all applicable migrations up until version {0} for project '{1}'", version, Name);
        }
Example #20
0
        public void CanPickUpMigrationsFromFiles()
        {
            var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Api");

            Database.Migrate(TestConfig.ConnectionString, Migrations.FromFilesIn(dir));

            var tableNames = GetTableNames().ToList();

            Assert.That(tableNames, Is.EqualTo(new[] { "Tabelle1", "Tabelle2", "Tabelle3" }));
        }
Example #21
0
        public async Task <IActionResult> Create([Bind("Id,Migration,Batch")] Migrations migrations)
        {
            if (ModelState.IsValid)
            {
                _context.Add(migrations);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(migrations));
        }
 /// <summary>
 ///   Creates a new instance of the <see cref="MigrationManager"/> class
 ///   for the specifed <see cref="IpfsEngine"/>.
 /// </summary>
 public MigrationManager(IpfsEngine ipfs)
 {
     this.ipfs  = ipfs;
     Migrations = typeof(MigrationManager).Assembly
                  .GetTypes()
                  .Where(x => typeof(IMigration).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)
                  .Select(x => (IMigration)Activator.CreateInstance(x))
                  .OrderBy(x => x.Version)
                  .ToList();
     log.Debug("Checking and assigning default Migration1 to avoid exceptions if none other migrations found");
     Migrations = Migrations.DefaultIfEmpty(new MigrateTo1()).ToList();
 }
Example #23
0
        public void ItWorks()
        {
            Database.Migrate(
                connectionString: TestConfig.ConnectionString,
                migrations: Migrations.FromAssemblyOf <CheckFiltering>().Where(m => m.SequenceNumber < 2),
                options: new Options(sqlCommandTimeout: TimeSpan.FromMinutes(20))
                );

            var tableNames = GetTableNames();

            Assert.That(tableNames, Is.EqualTo(new[] { "MyFirstTable" }));
        }
Example #24
0
        static void MigrationsFuck()
        {
            Migrations miggy = Migrations.Instance;

            //the simple case
            miggy.RegisterMigration(new TestMigration()
            {
                SourceTypeVersionId = new Guid("00000000-5B32-4980-9B09-F6A28A52BF86"),
                TargetTypeVersionId = new Guid("90000000-5B32-4980-9B09-F6A28A52BF86")
            });
            //add an 'infinite loop' to migrations...
            miggy.RegisterMigration(new TestMigration()
            {
                SourceTypeVersionId = new Guid("10000000-5B32-4980-9B09-F6A28A52BF86"),
                TargetTypeVersionId = new Guid("00000000-5B32-4980-9B09-F6A28A52BF86")
            });
            miggy.RegisterMigration(new TestMigration()
            {
                SourceTypeVersionId = new Guid("00000000-5B32-4980-9B09-F6A28A52BF86"),
                TargetTypeVersionId = new Guid("10000000-5B32-4980-9B09-F6A28A52BF86")
            });
            miggy.RegisterMigration(new TestMigration()
            {
                SourceTypeVersionId = new Guid("10000000-5B32-4980-9B09-F6A28A52BF86"),
                TargetTypeVersionId = new Guid("20000000-5B32-4980-9B09-F6A28A52BF86")
            });
            miggy.RegisterMigration(new TestMigration()
            {
                SourceTypeVersionId = new Guid("20000000-5B32-4980-9B09-F6A28A52BF86"),
                TargetTypeVersionId = new Guid("30000000-5B32-4980-9B09-F6A28A52BF86")
            });
            miggy.RegisterMigration(new TestMigration()
            {
                SourceTypeVersionId = new Guid("30000000-5B32-4980-9B09-F6A28A52BF86"),
                TargetTypeVersionId = new Guid("40000000-5B32-4980-9B09-F6A28A52BF86")
            });


            var noPath = miggy.FindMigrationPath(
                new Guid("11000000-5B32-4980-9B09-F6A28A52BF86"),
                new Guid("30000000-5B32-4980-9B09-F6A28A52BF86"));

            var simplePath = miggy.FindMigrationPath(
                new Guid("00000000-5B32-4980-9B09-F6A28A52BF86"),
                new Guid("30000000-5B32-4980-9B09-F6A28A52BF86"));



            var noInfiniteLoopPath = miggy.FindMigrationPath(
                new Guid("00000000-5B32-4980-9B09-F6A28A52BF86"),
                new Guid("30000000-5B32-4980-9B09-F6A28A52BF86"));
        }
Example #25
0
        /// <summary>
        /// Scan for implementations of the IMigration interface in the provided assembly and order by name
        /// </summary>
        public void ReadAssemblyMigrations(Assembly migrationAssembly)
        {
            //
            foreach (var exportedType in migrationAssembly.ExportedTypes)
            {
                if (exportedType.GetTypeInfo().GetInterfaces().Contains(typeof(IMigration)))
                {
                    var previousMigration = (IMigration)Activator.CreateInstance(exportedType);
                    Migrations.Add(previousMigration);
                }
            }

            Migrations = Migrations.OrderBy(m => m.Name).ToList();
        }
Example #26
0
        private async Task Migrate()
        {
            var currentVersion = await GetSchemaVersion();

            var migrations = Migrations.Where(m => m.VersionNumber > currentVersion).ToList();

            if (migrations.IsNotEmpty())
            {
                foreach (var migration in migrations)
                {
                    await _asyncConnection.RunInTransactionAsync(c => migration.Run(c));
                    await SetSchemaVersion(migration.VersionNumber);
                }
            }
        }
Example #27
0
        public void UseMigrations(IReadOnlyList <Migration> migrations)
        {
            Migrations = migrations.OrderBy(x => x.Version).Where((x, i) =>
            {
                var expectedVersion = i + 1;

                if (x.Version == expectedVersion)
                {
                    return(true);
                }

                throw new ArgumentException($"Missing migration for version {expectedVersion}.");
            }).ToList();

            ConfiguredVersion = Migrations.Any() ? Migrations.Last().Version : 0;
        }
Example #28
0
        /// <summary>
        /// Attempts to load a migrations assembly from the specified path and populate this object
        /// </summary>
        public async Task InitializeMigrationsAsync(string pathToMigrations)
        {
            Requires.NotNull(pathToMigrations, "pathToMigrations");

            // Find files based on the specified glob
            var file = await _filesRepository.GetMostRecentMatchingFile(pathToMigrations);

            if (file == null)
            {
                throw new ProjectException("Path to migrations dll does not exist", null, this);
            }

            // Load migrations assembly
            MigrationsAssembly = await _assemblyRepository.LoadFromFile(file.FullName);

            if (MigrationsAssembly == null)
            {
                throw new ProjectException("Could not load any migrations from the specified file", null, this);
            }

            // Load referenced Fluent Migrator assembly
            FluentMigratorAssemblyName = await _assemblyRepository.GetReferenceByName(MigrationsAssembly, "FluentMigrator");

            if (FluentMigratorAssemblyName == null)
            {
                throw new ProjectException("Could not find a reference to the FluentMigrator assembly", null, this);
            }

            // Find migration classes
            var migrationTypes = await _migrationsRepository.GetMigrationTypes(MigrationsAssembly);

            Migrations = migrationTypes.Select(m => new MigrationInfo(_migrationsRepository, _log, this, m)).ToList();

            // Find profile classes
            var profileTypes = await _migrationsRepository.GetProfileTypes(MigrationsAssembly);

            Profiles = profileTypes.Select(p => new ProfileInfo(_migrationsRepository, _log, this, p)).ToList();

            await Task.WhenAll(Migrations.Select(m => m.InitializeAsync()));

            await Task.WhenAll(Profiles.Select(p => p.InitializeAsync()));

            PathToMigrationsDll = pathToMigrations;

            _log.Info("Loaded {0} migrations and {1} profiles for project '{2}' from assembly {3}, which uses FluentMigrator {4}",
                      Migrations.Count, Profiles.Count, Name, MigrationsAssembly.GetName().Name, FluentMigratorAssemblyName.Version.ToString());
        }
Example #29
0
        protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            // run our own migrations
            var migrations = new Migrations(applicationContext);

            migrations.Run();

            UmbracoDefaultOwinStartup.MiddlewareConfigured += (sender, args) =>
            {
                args.AppBuilder.ConfigureBearerTokenAuthentication();
            };

            // somehow if we restrict ourselves to BackgroundTaskRunner<CaptureProgress> the RecurringTaskBase
            // constructor is not happy - probably some generic variance issue in Core - ok with IBackgroundTask
            _runner = new BackgroundTaskRunner <IBackgroundTask>("CaptureProgress", applicationContext.ProfilingLogger.Logger);
            _runner.TryAdd(new CaptureProgress(_runner));
        }
Example #30
0
        public static void MigrateProjectData(Project project, int fromControlFileVersion)
        {
            Logger.WriteEvent("Migrating project " + project.ProjectFilePath);

            if (s_lastProjectMigrated != project)
            {
                s_migrationsRun = 0;
            }

            if (fromControlFileVersion < 90 && (project != s_lastProjectMigrated || (s_migrationsRun & Migrations.SetBookIdForChapterBlocks) == 0))
            {
                SetBookIdForChapterBlocks(project.Books);
                s_migrationsRun |= Migrations.SetBookIdForChapterBlocks;
            }

            // We don't need to track runs of Migrations which only occur for FullyInitialized projects
            // because we shouldn't call MigrateProjectData again.
            if (project.ProjectState == ProjectState.FullyInitialized)
            {
                if (fromControlFileVersion < 96)
                {
                    MigrateInvalidMultiBlockQuoteData(project.Books);
                }
                if (fromControlFileVersion < 127)
                {
                    // This method was originally called for the < 96 case above, but we found a new case
                    // for which it is needed. Therefore, we call it here to keep it in the same order
                    // as it was before (though, technically, we aren't sure we care).
                    CleanUpOrphanedMultiBlockQuoteStati(project.Books);
                }
                if (fromControlFileVersion < 102)
                {
                    MigrateInvalidCharacterIdForScriptData(project.Books);
                }
                if (fromControlFileVersion == 104)
                {
                    MigrateInvalidCharacterIdsWithoutCharacterIdInScriptOverrides(project);
                }

                MigrateDeprecatedCharacterIds(project);
            }

            s_lastProjectMigrated = project;
        }
Example #31
0
        /// <summary>
        /// Executes the given migrations on the specified database.
        /// </summary>
        /// <param name="connectionStringOrConnectionStringName">Specifies a connection string or the name of a connection string in the current application configuration file to use.</param>
        /// <param name="migrations">Supplies the migrations to be executed.</param>
        /// <param name="options">Optionally specifies some custom options to use.</param>
        public static void Migrate(string connectionStringOrConnectionStringName, Migrations migrations, Options options = null)
        {
            options = options ?? new Options();

            var connectionString = ConfigurationManager.ConnectionStrings[connectionStringOrConnectionStringName]?.ConnectionString
                                ?? connectionStringOrConnectionStringName;

            var writer = options.GetWriter();

            var migrator = new DatabaseMigratorCore(
                db: GetDatabase(),
                migrationTableName: options.MigrationTableName,
                writer: writer,
                connectionString: connectionString);

            var executableSqlMigrations = migrations.GetMigrations();

            migrator.Execute(executableSqlMigrations);
        }
        public void TryIt()
        {
            var migrations = new Migrations(new[]
            {
                new TestMigration(1, "master", ""),
                new TestMigration(2, "feature-a", ""),
                new TestMigration(2, "feature-b", ""),
                new TestMigration(3, "feature-c", ""),
                new TestMigration(3, "feature-c", ""),
                new TestMigration(4, "master", ""),
            });

            var ex = Assert.Throws<MigrationException>(() =>
            {
                Database.Migrate(TestConfig.ConnectionString, migrations);
            });

            Console.WriteLine(ex);

            Assert.That(ex.Message, Contains.Substring("feature-c"));
        }
        public void TryIt()
        {
            var firstBatch = new[] {new TestMigration(1, "test", "")};

            Database.Migrate(TestConfig.ConnectionString, new Migrations(firstBatch));

            var secondBatchWhereSomeoneSwoopedInANewMigration = new[]
            {
                new TestMigration(0, "test", ""),
                new TestMigration(1, "test", "")
            };

            var ex = Assert.Throws<MigrationException>(() =>
            {
                var migrations = new Migrations(secondBatchWhereSomeoneSwoopedInANewMigration);

                Database.Migrate(TestConfig.ConnectionString, migrations);
            });

            Console.WriteLine(ex);

            Assert.That(ex.Message, Contains.Substring("0-test"));
        }
        public void StillWorksWithParallelDevelopmentThough()
        {
            var firstBatch = new[]
            {
                new TestMigration(1, "test", Create("test1")),
                new TestMigration(2, "feature-A", Create("A2")),
                new TestMigration(3, "feature-A", Create("A3")),
                new TestMigration(4, "feature-A", Create("A4")),
                new TestMigration(5, "test", Create("test5")),
            };

            Database.Migrate(TestConfig.ConnectionString, new Migrations(firstBatch));

            var secondBatchAfterMerge = new[]
            {
                new TestMigration(1, "test", Create("test1")),

                new TestMigration(2, "feature-A", Create("A2")),
                new TestMigration(3, "feature-A", Create("A3")),
                new TestMigration(4, "feature-A", Create("A4")),

                new TestMigration(2, "feature-B", Create("B2")),
                new TestMigration(3, "feature-B", Create("B3")),
                new TestMigration(4, "feature-B", Create("B4")),

                new TestMigration(5, "test", Create("test5")),
            };

            var migrations = new Migrations(secondBatchAfterMerge);

            Database.Migrate(TestConfig.ConnectionString, migrations);

            var tableNames = GetTableNames();

            Assert.That(tableNames, Is.EqualTo(new[] {"A2", "A3", "A4", "B2", "B3", "B4", "test1", "test5"}));
        }
        public void TryItWithMoreComplexScenario()
        {
            var firstBatch = new[]
            {
                new TestMigration(1, "master", ""),
                new TestMigration(2, "branch-A", ""),
                new TestMigration(3, "branch-A", ""),

                new TestMigration(3, "branch-B", ""),
            };

            Database.Migrate(TestConfig.ConnectionString, new Migrations(firstBatch));

            var secondBatchWhereSomeoneSwoopedInANewMigration = new[]
            {
                new TestMigration(1, "master", ""),
                new TestMigration(2, "branch-A", ""),
                new TestMigration(3, "branch-A", ""),

                new TestMigration(2, "branch-B", ""),
                new TestMigration(3, "branch-B", ""),
            };

            var ex = Assert.Throws<MigrationException>(() =>
            {
                var migrations = new Migrations(secondBatchWhereSomeoneSwoopedInANewMigration);

                Database.Migrate(TestConfig.ConnectionString, migrations);
            });

            Console.WriteLine(ex);

            Assert.That(ex.Message, Contains.Substring("2-branch-B"));
        }