public MigrationRunner(ConnectionInfo connection, Config config)
 {
     this.connection = connection;
     this.force = config.Force;
     var migrationPath = config.MigrationPath.IsNullOrEmptyReturn(Environment.CurrentDirectory);
     this.migrations = GetPaths(migrationPath).Select(p => new Migration(p)).ToArray();
 }
Example #2
0
        public void Migrate(ConnectionInfo connection, bool force)
        {
            // ensure migration has not already run
            if (connection.Exists("select 1 from Migrations where [Hash] = {0}", Hash))
            {
                logger.Info("Skipping Migration " + Filename);
                if (!connection.Exists("select 1 from Migrations where [Hash] = {0} and Filename = {1}", Hash, Filename))
                {
                    logger.Info("Filename has changed in the database; updating");
                    connection.Execute("update Migrations set Filename = {0} where [Hash] = {1}", Filename, Hash);
                }
                return;
            }

            logger.Info("Running Migration " + Filename);

            bool exists = false;

            if (connection.Exists("select 1 from Migrations where [Filename] = {0}", Filename))
            {
                if (!force)
                {
                    throw new ApplicationException("Failed to migrate: " + Filename + " - the file was already migrated in the past, to force migration use the --force command");
                }

                exists = true;
            }

            var watch = new System.Diagnostics.Stopwatch();
            try
            {
                watch.Start();
                connection.BeginTran();

                foreach (var sqlCommand in SqlCommands)
                {
                    connection.Execute(sqlCommand);
                }

                watch.Stop();

                if (exists)
                {
                    connection.Execute("UPDATE Migrations SET [Hash] = {0}, [ExecutionDate] = {1}, [Duration] = {2} WHERE [Filename] = {3}",
                        Hash,
                        DateTime.UtcNow,
                        watch.ElapsedMilliseconds,
                        Filename
                        );
                }
                else
                {
                    connection.Execute("INSERT Migrations([Filename], [Hash], [ExecutionDate], [Duration]) VALUES({0}, {1}, {2}, {3})",
                        Filename,
                        Hash,
                        DateTime.UtcNow,
                        watch.ElapsedMilliseconds
                        );
                }

                connection.CommitTran();
            }
            catch (Exception e)
            {
                connection.RollbackTran();
                throw new ApplicationException("Failed to run migration: " + Filename + " " + e.Message);
            }
        }