Esempio n. 1
0
 /// <summary>
 /// Runs the migrations.
 /// </summary>
 public static void Migrate(CommandLineParams parameters)
 {
     using (Migrator migrator = MigratorFactory.CreateMigrator(parameters.config))
     {
         migrator.Migrate(parameters.version);
     }
 }
Esempio n. 2
0
        private void btnOpen_Click(object sender, RoutedEventArgs e)
        {
            //var dialog = new System.Windows.Forms.FolderBrowserDialog();

            //System.Windows.Forms.DialogResult result = dialog.ShowDialog();

            ////store the path to local storage

            //pathToMigrations = dialog.SelectedPath;
            pathToMigrations = @"d:\working\connect\scripts";
            migrator         = MigratorFactory.GetMigrator(pathToMigrations);

            btnUp.DataContext   = migrator.Tracker;
            btnDown.DataContext = migrator.Tracker;

            migrations = migrator.Tracker.Migrations;
            var version = migrator.Tracker.Version;

            stackPanel1.Children.Clear();
            foreach (var mig in migrations)
            {
                var rbl = new RadioButton();
                rbl.GroupName = "RBLMigration";
                rbl.Content   = mig.Version;
                if (version == mig.Version)
                {
                    rbl.IsChecked = true;
                }
                rbl.Checked += new RoutedEventHandler(rbl_Checked);
                stackPanel1.Children.Add(rbl);
            }

            lblVersion.Content = version;
        }
Esempio n. 3
0
 public void CanInitByConfig()
 {
     using (Migrator migrator = MigratorFactory.InitByConfigFile())
     {
         Assert.IsNotNull(migrator);
     }
 }
Esempio n. 4
0
 public static void Initialize(CommandLineParams parameters)
 {
     using (Migrator migrator = MigratorFactory.CreateMigrator(parameters.config))
     {
         migrator.Initialize();
     }
 }
Esempio n. 5
0
        public static void EnsureDaContext(DbConnectionConfig SystemConConfig, params Assembly[] assemblies)
        {
            var dbtype = (DbType)SystemConConfig.DBType;

            var fuType = FlunentDBType.Sqlite;

            switch (dbtype)
            {
            case DbType.Sqlite:
                fuType = FlunentDBType.Sqlite;
                break;

            case DbType.SqlServer:
                fuType = FlunentDBType.MsSql;
                break;

            case DbType.MySql:
                fuType = FlunentDBType.MySql4;
                break;

            case DbType.PostgreSQL:
                fuType = FlunentDBType.Postgre;
                break;
            }
            MigratorFactory.CreateServices(fuType, SystemConConfig.Connectionstring, MigrationOperation.MigrateUp, 0, assemblies);
        }
Esempio n. 6
0
        public static void EnsureDaContext(string connString, int dbtype, params Assembly[] assemblies)
        {
            if (dbtype >= 0 && dbtype <= 4)
            {
                var fuType = FlunentDBType.Sqlite;

                switch (dbtype)
                {
                case 0:
                    fuType = FlunentDBType.MySql5;
                    break;

                case 1:
                    fuType = FlunentDBType.MsSql;
                    break;

                case 2:
                    fuType = FlunentDBType.Sqlite;
                    break;

                case 4:
                    fuType = FlunentDBType.Postgre;
                    break;
                }
                MigratorFactory.CreateServices(fuType, connString, MigrationOperation.MigrateUp, 0, assemblies);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Выполнить заданные действия над БД
        /// </summary>
        protected override void ExecuteTask()
        {
            ConfigureLogging();

            using (Migrator migrator = MigratorFactory.CreateMigrator(this))
            {
                migrator.Migrate(to);
            }
        }
                public void RetrievesLastMigration(DbAuthType authType, string connString)
                {
                    TestConstants.ConfigureRequest(Request, authType);

                    var underTest = new UpdateMigrationAction(MigratorFactory.Object);

                    underTest.Migrate(Request, Result);

                    MigratorFactory.Verify(m => m.CreateMigrator(connString), Times.Once);
                    Migrator.Verify(m => m.GetLocalMigrations(), Times.Once);
                }
Esempio n. 9
0
        /// <summary>
        /// Executes a task.
        /// </summary>
        /// <returns>
        /// true if the task executed successfully; otherwise, false.
        /// </returns>
        public override bool Execute()
        {
            ConfigureLogging();

            using (Migrator migrator = MigratorFactory.CreateMigrator(this))
            {
                migrator.Migrate(to);
            }

            return(true);
        }
                public void EnsuresMigrationRecordExistsForNewVersion(DbAuthType authType, string connString)
                {
                    TestConstants.ConfigureRequest(Request, authType);

                    var underTest = new UpdateMigrationAction(MigratorFactory.Object);

                    underTest.Migrate(Request, Result);

                    MigratorFactory.Verify(m => m.CreateDbContext(connString), Times.Once);
                    Repo.Verify(m => m.AddOrUpdate(TestConstants.VerAlias, lastMigration), Times.Once);
                    Context.Verify(m => m.SaveChanges());
                }
Esempio n. 11
0
 public override bool Execute()
 {
     Log.LogMessage("Directory: " + ScriptsDirectory);
     try {
         var migrator = MigratorFactory.GetMigrator(ScriptsDirectory);
         var result   = migrator.Update();
         var message  = "Success: " + result.PriorToMigration + " to " + result.AfterMigration;
         Log.LogMessage(MessageImportance.High, message, new object[] {});
         return(true);
     } catch (Exception ex) {
         Log.LogError(ex.Message);
         return(false);
     }
 }
                public void MovesMigrationForward(DbAuthType authType, string connString)
                {
                    TestConstants.ConfigureRequest(Request, authType);
                    MigratorFactory.Setup(m => m.CreateMigrator(connString)).Returns(Migrator.Object);

                    var underTest = new UpdateMigrationAction(MigratorFactory.Object);

                    underTest.Migrate(Request, Result);

                    MigratorFactory.Verify(m => m.CreateDbContext(connString), Times.Once);
                    MigratorFactory.Verify(m => m.CreateMigrationRepository(Context.Object), Times.Once);
                    Repo.Verify(m => m.Copy(It.IsAny <string>(), It.IsAny <string>()), Times.Once);
                    Repo.Verify(m => m.Copy(TestConstants.PreviousVersion, TestConstants.VerAlias), Times.Once);
                    Migrator.Verify(m => m.GetLocalMigrations(), Times.Once);
                }
Esempio n. 13
0
        private void DoImport(TCObject objectToExecuteOn)
        {
            foreach (XModule wseModule in objectToExecuteOn.GetWseModules())
            {
                try {
                    IMigrator migrator = MigratorFactory.GetMigrator(wseModule);
                    migrator.Migrate(objectToExecuteOn);
                }
                catch (Exception e) {
                    FileLogger.Instance.Error(
                        $"Migration of WSE Module 'migration for WSE Module :'{wseModule.DisplayedName}' failed due an error. This might leave the module in a inconsistent state.",
                        e);
                }
            }

            CommonUtilities.ReplaceResourceWithLastResponseResource(objectToExecuteOn);
        }
Esempio n. 14
0
        /// <summary>
        /// Выводит текущий список миграций
        /// </summary>
        public static void List(CommandLineParams parameters)
        {
            using (Migrator mig = MigratorFactory.CreateMigrator(parameters.config))
            {
                IList <long> appliedMigrations = mig.GetAppliedMigrations();

                Console.WriteLine("Available migrations:");
                foreach (var info in mig.AvailableMigrations)
                {
                    long v = info.Version;
                    Console.WriteLine(
                        "{0} {1} {2}",
                        appliedMigrations.Contains(v) ? "=>" : "  ",
                        v.ToString().PadLeft(3),
                        StringUtils.ToHumanName(info.Type.Name));
                }
            }
        }
Esempio n. 15
0
        public override bool Execute()
        {
            Log.LogMessage("Directory: " + ScriptsDirectory);
            var migrator = MigratorFactory.GetMigrator(ScriptsDirectory);
            var result   = migrator.Tracker.IsValidState();

            if (result)
            {
                Log.LogMessage("Mite database status is good.");
            }
            else
            {
                Log.LogError("Mite status is not clean");
                foreach (var migration in migrator.Tracker.InvalidMigrations())
                {
                    Log.LogError("Mismatch checksum on: " + migration.Version + "[" + migration.Hash + "]");
                }
            }
            return(result);
        }
Esempio n. 16
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("You must specify an option.  See /? for details");
                return;
            }
#if DEBUG
            Console.WriteLine("Stopped in order to attach debugger. Press any key to continue...");
            Console.ReadLine();
#endif
            if (args[0] == "/?")
            {
                Console.WriteLine("Mite - Simple and painless SQL migrations.\n\n");
                Console.WriteLine("Version " + Assembly.GetExecutingAssembly().GetName().Version);
                Console.WriteLine("mite.exe [-v] [init [filename]] [-c [filename]] [-d [destination]] [update/stepup/stepdown]\n\n");
                Console.WriteLine("Options are as follows:");
                Console.WriteLine("-v\t\tReturns the current version of Mite");
                Console.WriteLine(
                    "init\t\tCreates and opens the initial up file and makes.\n\t\tCreates the _migrations table and makes and entry into the \n\t\t_migrations table for the initial up.");
                Console.WriteLine("\t\tfilename(optional): desired filename of migration script");
                Console.WriteLine("-c\t\tCreates and launches the new migration files");
                Console.WriteLine("\t\tfilename(optional): desired filename of migration script");
                Console.WriteLine(
                    "-d\t\tSpecifies the destination version to migrate to.\n\t\t(can be greater than migrations available)");
                Console.WriteLine("update\t\tRuns all migrations greater than the current version");
                Console.WriteLine("stepup\t\tExecutes one migration file greater than the current version");
                Console.WriteLine("stepdown\tExecutes one migration file less than the current version");

                return;
            }

            if (args[0] == "-v")
            {
                Console.WriteLine("Mite Version " + Assembly.GetExecutingAssembly().GetName().Version);
                return;
            }
            if (args[0] == "-c")
            {
                try
                {
                    if (args.Count() > 1 && !string.IsNullOrEmpty(args[1]))
                    {
                        CreateMigration(args[1]);
                    }
                    else
                    {
                        CreateMigration();
                    }
                }
                catch (FormatException ex)
                {
                    Console.Write(ex.Message);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }


                return;
            }
            if (args[0] == "init")
            {
                if (!File.Exists(currentDirectory))
                {
                    Console.WriteLine("What provider are you using?");
                    Console.WriteLine("[1] MySqlDatabaseRepository");
                    Console.WriteLine("[2] MsSqlDatabaseRepository");
                    string repositoryName = "";
                    switch (Console.ReadLine()[0])
                    {
                    case '1':
                        repositoryName = "MySqlDatabaseRepository";
                        break;

                    case '2':
                        repositoryName = "MsSqlDatabaseRepository";
                        break;

                    default:
                        Console.WriteLine("Option not recognized");
                        return;
                    }
                    //determine the server
                    Console.WriteLine("Please enter your complete .Net connection string.");
                    string connectionString = Console.ReadLine();

                    //determine the database
                    JObject obj = new JObject();
                    obj["repositoryName"]   = repositoryName;
                    obj["connectionString"] = connectionString;
                    File.WriteAllText(Path.Combine(currentDirectory, "mite.config"), obj.ToString(Formatting.Indented));
                }

                try
                {
                    var tmpMigrator = MigratorFactory.GetMigrator(currentDirectory);
                    repo = tmpMigrator.DatabaseRepository;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }


                if (new DirectoryInfo(Environment.CurrentDirectory).GetFiles().Any(x => !x.Name.Contains("mite.config")))
                {
                    Console.WriteLine("Working directory is not clean.\nPlease ensure no existing scripts or project files exist when performing init.");
                    return;
                }


                var baseFileName = "";
                try
                {
                    if (args.Count() > 1 && !string.IsNullOrEmpty(args[1]))
                    {
                        baseFileName = GetMigrationFileName(args[1]);
                    }
                    else
                    {
                        baseFileName = GetMigrationFileName();
                    }
                }
                catch (FormatException ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.Write(ex.Message);
                    return;
                }

                var baseFilePath = Environment.CurrentDirectory + Path.DirectorySeparatorChar + baseFileName;

                if (!File.Exists(baseFilePath))
                {
                    Console.WriteLine("Would you like me to generate a migration script based on the current database? [y|N]");
                    var generateScript = Console.ReadLine();
                    if (generateScript.ToLower() == "y")
                    {
                        bool includeData = false;
                        Console.WriteLine("Would you like to include the data? [y|N]");
                        var generateData = Console.ReadLine();
                        if (generateData.ToLower() == "y")
                        {
                            includeData = true;
                        }
                        try
                        {
                            var sql = repo.GenerateSqlScript(includeData);
                            File.WriteAllText(baseFilePath + ".sql", sql);
                            Console.WriteLine(string.Format("{0} generated successfully", baseFileName));
                            repo.RecordMigration(new Migration(baseFileName, sql, ""));
                        }
                        catch (Win32Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                            Console.WriteLine("Using this feature requires that mysqldump be in your path.  Please add the path for mysqldump to your path variable and restart your cmd prompt.");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Use mite -c to create your first migration.");
                    }
                    return;
                }
                Console.WriteLine("Nothing to do.  Use mite -c to create your first migration.");
            }

            var migrator = MigratorFactory.GetMigrator(currentDirectory);
            var database = migrator.Tracker;
            repo = migrator.DatabaseRepository;

            MigrationResult resultingVersion = null;
            switch (args[0])
            {
            case "update":
                if (database.IsValidState())
                {
                    if (!database.UnexcutedMigrations.Any())
                    {
                        Console.WriteLine("No migrations to execute");
                        Console.WriteLine("Current Version: " + database.Version);
                        return;
                    }
                    foreach (var migToExe in database.UnexcutedMigrations)
                    {
                        Console.WriteLine("Executing migration " + migToExe.Version);
                        repo.ExecuteUp(migToExe);
                    }
                }
                else if (database.IsMigrationGap())
                {
                    Console.WriteLine("There is a gap in your migrations how would you like to resolve it?");
                    Resolve(migrator);
                }
                else if (database.IsHashMismatch())
                {
                    Console.WriteLine("There is a mismatched checksum in your migrations, would you like me to resolve it? y|N\n This SHOULD NOT be performed in a production environment.");
                    if (Console.Read() == 'y')
                    {
                        Resolve(migrator);
                    }
                }
                break;

            case "-d":
                var version = "";
                if (args.Count() < 2)
                {
                    Console.WriteLine("ERROR: You have failed to specify a destination version.\nPlease determine your destination version and try again.");
                    return;
                }
                version          = args[1].Replace(".sql", "");
                resultingVersion = migrator.MigrateTo(version);
                Console.WriteLine("Current Version:" + resultingVersion.AfterMigration);
                break;

            case "status":
                Console.WriteLine("Current Version:" + database.Version);
                if (database.IsValidState())
                {
                    if (!database.UnexcutedMigrations.Any())
                    {
                        Console.WriteLine("No migrations to execute");
                        return;
                    }
                }
                else
                {
                    if (database.IsHashMismatch())
                    {
                        var invalidMigrations = database.InvalidMigrations();
                        Console.WriteLine("The following migrations don't match their checksums:");
                        foreach (var mig in invalidMigrations)
                        {
                            Console.WriteLine(mig.Version);
                        }
                        return;
                    }
                    if (database.IsMigrationGap())
                    {
                        Console.WriteLine("The following migrations have not been executed:");
                        foreach (var mig in database.UnexcutedMigrations.Where(x => x.Version.CompareTo(database.Version) <= 0))
                        {
                            Console.WriteLine(mig.Version);
                        }
                    }
                }

                Console.WriteLine("Unexecuted Migrations:");
                foreach (var mig in database.UnexcutedMigrations)
                {
                    Console.WriteLine(mig.Version);
                }
                return;

            case "stepdown":
                resultingVersion = migrator.StepDown();
                break;

            case "stepup":
                resultingVersion = migrator.StepUp();
                break;

            case "verify":
                try
                {
                    migrator.Verify();
                    Console.WriteLine("All migrations have been verified and executed successfully");
                }
                catch (MigrationException ex)
                {
                    Console.WriteLine("Migrations could not be verified");
                    Console.WriteLine("The " + ex.Direction + " migration failed on: " + ex.Migration.Version);
                }
                break;

            case "version":
                Console.WriteLine("Database Version: " + database.Version);
                return;

            case "scratch":
                //drop all the tables and run all migrations
                migrator.FromScratch();
                Console.WriteLine("Database Version: " + database.Version);
                break;

            case "clean":
                Console.WriteLine("This will remove the mite.config and drop the _migrations table.  Are you sure you would like to clean (y/n)?");
                if (Console.ReadLine() == "y")
                {
                    repo.DropMigrationTable();
                    File.Delete(currentDirectory);
                    Console.WriteLine("mite cleaned successfully");
                }
                return;
            }
            if (resultingVersion != null)
            {
                Console.WriteLine(resultingVersion.Message);
            }
        }