public static IMigrationInfo GetMigrationInfoFor(IMigration migration)
        {
            var migrationAttribute = migration.GetType().GetOneAttribute<MigrationAttribute>();
            var migrationInfo = new MigrationInfo(migrationAttribute.Version, migrationAttribute.Description, migrationAttribute.TransactionBehavior, migration);

            foreach (MigrationTraitAttribute traitAttribute in migration.GetType().GetAllAttributes<MigrationTraitAttribute>())
                migrationInfo.AddTrait(traitAttribute.Name, traitAttribute.Value);

            return migrationInfo;
        }
示例#2
0
        private async Task RunTheUpdate(IMigration migrateInitialize, IMongoDatabase db)
        {
            _log.Info($"Starting {migrateInitialize.GetType().Name} db update");
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            await migrateInitialize.Update(db);

            stopwatch.Stop();
            _log.Info($"Done {migrateInitialize.GetType().Name} in {stopwatch.ElapsedMilliseconds}ms");
        }
示例#3
0
        private async Task EnsureThatVersionDoesNotExistThenUpdate(IEnumerable <DbVersion> versions, int i, IMigration migrateInitialize, MongoRepository <DbVersion> repository, IMongoDatabase db)
        {
            DbVersion version = versions.FirstOrDefault(x => x.Id == i);

            if (version == null)
            {
                _log.Info($"Running version update {migrateInitialize.GetType().Name}");
                await RunTheUpdate(migrateInitialize, db);

                var dbVersion1 = new DbVersion {
                    Id = i, Name = migrateInitialize.GetType().Name
                };
                await repository.Add(dbVersion1);
            }
        }
示例#4
0
        private static IMigrationInfo GetMigrationInfoForMigrationImpl(IMigration migration)
        {
            if (typeof(DbSchemaItem).IsAssignableFrom(migration.GetType()))
            {
                var migrationType      = migration.GetType();
                var migrationAttribute = migrationType.GetCustomAttribute <MigrationAttribute>() ?? new MigrationAttribute(number++, "");
                var migrationInfo      = new MigrationInfo(migrationAttribute.Version, migrationAttribute.Description, migrationAttribute.TransactionBehavior, migrationAttribute.BreakingChange, () => migration);

                foreach (var traitAttribute in migrationType.GetCustomAttributes <MigrationTraitAttribute>(true))
                {
                    migrationInfo.AddTrait(traitAttribute.Name, traitAttribute.Value);
                }

                return(migrationInfo);
            }
            return(DefaultMigrationRunnerConventions.Instance.GetMigrationInfoForMigration(migration));
        }
示例#5
0
 private long ExtractTimestamp(string moduleName, IMigration migration)
 {
     var timestampProvider = _timestampProviders.ContainsKey(moduleName)
         ? _timestampProviders[moduleName]
         : _timestampProviders[MigrationExportAttribute.DefaultModuleName];
     long timestamp = timestampProvider.GetTimestamp(migration.GetType());
     return timestamp;
 }
示例#6
0
        public override void Migrate(IMigration migration)
        {
            _provider.BeginTransaction();
#if NETSTANDARD
            var attr = migration.GetType().GetTypeInfo().GetCustomAttribute <MigrationAttribute>();
#else
            var attr = (MigrationAttribute)Attribute.GetCustomAttribute(migration.GetType(), typeof(MigrationAttribute));
#endif

            if (_provider.AppliedMigrations.Contains(attr.Version))
            {
                RemoveMigration(migration, attr);
            }
            else
            {
                ApplyMigration(migration, attr);
            }
        }
示例#7
0
        private long ExtractTimestamp(string moduleName, IMigration migration)
        {
            var timestampProvider = _timestampProviders.ContainsKey(moduleName)
                ? _timestampProviders[moduleName]
                : _timestampProviders[MigrationExportAttribute.DefaultModuleName];
            long timestamp = timestampProvider.GetTimestamp(migration.GetType());

            return(timestamp);
        }
示例#8
0
        public static string GetName(this IMigration migration)
        {
            if (migration == null)
            {
                throw new ArgumentNullException("migration");
            }

            return(migration.GetType().FullName);
        }
示例#9
0
        private string GetMigrationName(IMigration migration)
        {
            if (migration == null)
            {
                throw new ArgumentNullException("migration");
            }

            return(string.Format("{0}", migration.GetType().Name));
        }
        /// <summary>
        /// Gets the name of the specified <paramref name="migration"/> which is
        /// the class' name without the 'Migration' suffix.
        /// </summary>
        /// <param name="migration">The migration.</param>
        /// <returns>The migration's name.</returns>
        public static string GetName(this IMigration migration)
        {
            string name = migration.GetType().Name;

            if (name.EndsWith("Migration"))
            {
                name = name.Substring(0, name.Length - "Migration".Length);
            }
            return(name);
        }
示例#11
0
 public override void Migrate(IMigration migration)
 {
     _provider.BeginTransaction();
     MigrationAttribute attr = (MigrationAttribute)Attribute.GetCustomAttribute(migration.GetType(), typeof(MigrationAttribute));
     
     if (_provider.AppliedMigrations.Contains(attr.Version)) {
     	RemoveMigration(migration, attr);
     } else {
     	ApplyMigration(migration, attr);
     }
 }
        /// <inheritdoc />
        public override bool Exclude(IMigration migration)
        {
            if (migration == null)
            {
                return(false);
            }

            return(migration.GetType()
                   .GetCustomAttributes(true)
                   .OfType <ExperimentalMigrationAttribute>()
                   .Any());
        }
示例#13
0
        public override void Migrate(IMigration migration)
        {
            _provider.BeginTransaction();
            MigrationAttribute attr = (MigrationAttribute)Attribute.GetCustomAttribute(migration.GetType(), typeof(MigrationAttribute));

            var v = attr.GetVersion(migration.GetType());
            var contains = false;

            foreach (var appliedMigration in _provider.AppliedMigrations)
            {
                if (appliedMigration.Key != v.Key || appliedMigration.Value != v.Value) continue;
                contains = true;
                break;
            }

            if (contains)
            {
            	RemoveMigration(migration, attr);
            } else {
            	ApplyMigration(migration, attr);
            }
        }
        private static IMigrationInfo GetMigrationInfoForMigrationImpl(IMigration migration)
        {
            var migrationType      = migration.GetType();
            var migrationAttribute = migrationType.GetCustomAttribute <MigrationAttribute>();
            var migrationInfo      = new MigrationInfo(migrationAttribute.Version, migrationAttribute.Description, migrationAttribute.TransactionBehavior, migrationAttribute.BreakingChange, () => migration);

            foreach (var traitAttribute in migrationType.GetCustomAttributes <MigrationTraitAttribute>(true))
            {
                migrationInfo.AddTrait(traitAttribute.Name, traitAttribute.Value);
            }

            return(migrationInfo);
        }
示例#15
0
        public override void Migrate(IMigration migration)
        {
            _provider.BeginTransaction();
            var attr = (MigrationAttribute)Attribute.GetCustomAttribute(migration.GetType(), typeof(MigrationAttribute));

            if (_provider.AppliedMigrations.Contains(attr.Version))
            {
                RemoveMigration(migration, attr);
            }
            else
            {
                ApplyMigration(migration, attr);
            }
        }
        /// <inheritdoc />
        protected override async Task InsertMigrationAsync(IMigration migration, string name)
        {
            await _connection.OpenAsync();

            using (NpgsqlCommand command = this._connection.CreateCommand())
            {
                command.CommandText = Sql.InsertMigration;
                command.Parameters.AddWithValue("key", NpgsqlDbType.Bigint, migration.Key);
                command.Parameters.AddWithValue("date", NpgsqlDbType.Timestamp, DateTime.UtcNow);
                command.Parameters.AddWithValue("type", NpgsqlDbType.Text, name ?? migration.GetType().Name);
                await command.ExecuteNonQueryAsync();
            }
            _connection.Close();
        }
        /// <summary>
        /// Called when a migration exception occurs.
        /// </summary>
        /// <param name="migration">The migration.</param>
        /// <param name="exception">The exception.</param>
        protected virtual void OnMigrationException(IMigration migration, Exception exception)
        {
            var message = new
            {
                Message = $"Migration failed to be applied: {exception.Message}",
                migration.Version,
                Name = migration.GetType(),
                migration.Description,
                DatabaseName = _migrationTarget.DatabaseName
            };

            _logger.LogError(exception, $"Migration version {migration.Version} \"{migration.Description}\" from type \"{migration.GetType().FullName}\" to database {_migrationTarget.DatabaseName} failed to be applied");
            throw new MigrationException(message.ToString(), exception);
        }
示例#18
0
        private string GetMigrationName(IMigration migration)
        {
            if (migration == null)
            {
                throw new ArgumentNullException("migration");
            }

            IMigrationMetadata metadata = migration as IMigrationMetadata;

            if (metadata != null)
            {
                return(string.Format("{0}: {1}", metadata.Version, metadata.Type.Name));
            }
            return(migration.GetType().Name);
        }
示例#19
0
        public void Down(IMigration migration)
        {
            var name = migration.GetType().Name;
            _announcer.Heading(name + ": reverting");

            CaughtExceptions = new List<Exception>();

            var context = new MigrationContext(Conventions, Processor);
            migration.GetDownExpressions(context);

            _stopWatch.Start();
            ExecuteExpressions(context.Expressions);
            _stopWatch.Stop();

            _announcer.Say(name + ": reverted");
            _announcer.ElapsedTime(_stopWatch.ElapsedTime());
        }
示例#20
0
        public void Down(IMigration migration)
        {
            var name = migration.GetType().Name;

            _announcer.Heading(name + ": reverting");

            CaughtExceptions = new List <Exception>();

            var context = new MigrationContext(Conventions, Processor, MigrationAssembly);

            migration.GetDownExpressions(context);

            _stopWatch.Start();
            ExecuteExpressions(context.Expressions);
            _stopWatch.Stop();

            _announcer.Say(name + ": reverted");
            _announcer.ElapsedTime(_stopWatch.ElapsedTime());
        }
 private Task <bool> RunMigration(IMigration migration)
 {
     try
     {
         connection.RunInTransaction(() =>
         {
             migration.PreMigrate(connection);
             migration.Migrate(connection);
             migration.PostMigrate(connection);
             migration.Seed(connection);
         });
     }
     catch (Exception exc)
     {
         string migrationName = migration.GetType().Name;
         throw new DbInitialiserException($"Migration {migrationName} could not be run. See inner exception for details", exc);
     }
     return(Task.FromResult <bool>(true));
 }
示例#22
0
        private Dictionary <int, MethodInfo> GetMigrationSteps(IMigration migration)
        {
            Dictionary <int, MethodInfo> steps = new Dictionary <int, MethodInfo>();

            foreach (MethodInfo method in migration.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public))
            {
                Match match = mUpgradeMethodNameRegex.Match(method.Name);
                if (match.Success && method.ReturnType == typeof(int))
                {
                    int version = 0;
                    if (int.TryParse(match.Groups["Version"].Value, out version))
                    {
                        steps.Add(version, method);
                    }
                }
            }

            return(steps);
        }
示例#23
0
        public void Down(IMigration migration)
        {
            var name = migration.GetType().Name;
            _announcer.Announce(name + ": reverting");

            CaughtExceptions = new List<Exception>();

            var context = new MigrationContext(Conventions,Processor);
            migration.GetDownExpressions(context);

            _stopWatch.Start();

            ExecuteExpressions(context.Expressions);

            _stopWatch.Stop();

            var elapsed = _stopWatch.ElapsedTime().TotalSeconds;

            _announcer.Announce(name + ": reverted (" + elapsed + "s" + ")");
        }
        /// <summary>
        /// Validates each migration expression that has implemented the ICanBeValidated interface.
        /// It throws an InvalidMigrationException exception if validation fails.
        /// </summary>
        /// <param name="migration">The current migration being run</param>
        /// <param name="expressions">All the expressions contained in the up or down action</param>
        public void ApplyConventionsToAndValidateExpressions(IMigration migration, IEnumerable<IMigrationExpression> expressions)
        {
            var errorMessageBuilder = new StringBuilder();

            foreach (var expression in expressions)
            {
                expression.ApplyConventions(_conventions);

                var errors = new Collection<string>();
                expression.CollectValidationErrors(errors);

                if (errors.Count > 0)
                    AppendError(errorMessageBuilder, expression.GetType().Name, string.Join(" ", errors.ToArray()));
            }

            if (errorMessageBuilder.Length > 0)
            {
                var errorMessage = errorMessageBuilder.ToString();
                _announcer.Error("The migration {0} contained the following Validation Error(s): {1}", migration.GetType().Name, errorMessage);
                throw new InvalidMigrationException(migration, errorMessage);
            }
        }
示例#25
0
        public TimeSpan Up(IMigration migration)
        {
            var name = migration.GetType().Name;
            _announcer.Heading(name + ": migrating");

            CaughtExceptions = new List<Exception>();

            var context = new MigrationContext(Conventions, Processor,MigrationAssembly);
            migration.GetUpExpressions(context);

            _stopWatch.Start();
            ExecuteExpressions(context.Expressions);
            _stopWatch.Stop();

            _announcer.Say(name + ": migrated");
            _announcer.ElapsedTime(_stopWatch.ElapsedTime());

            return _stopWatch.ElapsedTime();
        }
        private string GetMigrationName(IMigration migration)
        {
            if (migration == null) throw new ArgumentNullException("migration");

            IMigrationMetadata metadata = migration as IMigrationMetadata;
            if (metadata != null)
            {
                return string.Format("{0}: {1}", metadata.Version, metadata.Type.Name);
            }
            return migration.GetType().Name;
        }
示例#27
0
 private void RemoveMigration(IMigration migration, MigrationAttribute attr)
 {
     // we're removing this one
     _logger.MigrateDown(Current, migration.Name);
     if (! DryRun)
     {
         migration.Down();
         var v = attr.GetVersion(migration.GetType());
         _provider.MigrationUnApplied(v.Value, v.Key);
         _provider.Commit();
         migration.AfterDown();
     }
 }
示例#28
0
 private void ApplyMigration(IMigration migration, MigrationAttribute attr)
 {
     // we're adding this one
     _logger.MigrateUp(Current, migration.Name);
     if(! DryRun)
     {
         migration.Up();
         var v = attr.GetVersion(migration.GetType());
         _provider.MigrationApplied(v.Value, v.Key);
         _provider.Commit();
         migration.AfterUp();
     }
 }
示例#29
0
        /// <summary>
        /// Validates each migration expression that has implemented the ICanBeValidated interface.
        /// It throws an InvalidMigrationException exception if validation fails.
        /// </summary>
        /// <param name="migration">The current migration being run</param>
        /// <param name="expressions">All the expressions contained in the up or down action</param>
        protected void ApplyConventionsToAndValidateExpressions(IMigration migration, IEnumerable <IMigrationExpression> expressions)
        {
            var invalidExpressions = new Dictionary <string, string>();

            foreach (var expression in expressions)
            {
                expression.ApplyConventions(Conventions);

                var errors = new Collection <string>();
                expression.CollectValidationErrors(errors);

                if (errors.Count > 0)
                {
                    invalidExpressions.Add(expression.GetType().Name, string.Join(" ", errors.ToArray()));
                }
            }

            if (invalidExpressions.Count > 0)
            {
                var errorMessage = DictToString(invalidExpressions, "{0}: {1}");
                _announcer.Error("The migration {0} contained the following Validation Error(s): {1}", migration.GetType().Name, errorMessage);
                throw new InvalidMigrationException(migration, errorMessage);
            }
        }
        /// <summary>
        /// Gets the version of the specified <paramref name="migration"/>.
        /// </summary>
        /// <param name="migration">The migration.</param>
        /// <returns>The version.</returns>
        public static long GetVersion(this IMigration migration)
        {
            var attribute = migration.GetType().GetCustomAttributes(typeof(MigrationAttribute), false).First() as MigrationAttribute;

            return(attribute.Version);
        }
示例#31
0
        public void Up(IMigration migration)
        {
            var name = GetMigrationName(migration);
            _announcer.Heading(string.Format("{0} migrating", name));

            CaughtExceptions = new List<Exception>();

            var context = new MigrationContext(Conventions, Processor, Assembly.GetAssembly(migration.GetType()), ApplicationContext);
            migration.GetUpExpressions(context);

            _stopWatch.Start();
            ExecuteExpressions(context.Expressions);
            _stopWatch.Stop();

            _announcer.Say(string.Format("{0} migrated", name));
            _announcer.ElapsedTime(_stopWatch.ElapsedTime());
        }
        public static IMigrationInfo GetMigrationInfoFor(IMigration migration)
        {
            var migrationAttribute = migration.GetType().GetOneAttribute<MigrationAttribute>();
            var migrationInfo = new MigrationInfo(migrationAttribute.Version, migrationAttribute.TransactionBehavior, migration);

            foreach (MigrationTraitAttribute traitAttribute in migration.GetType().GetAllAttributes<MigrationTraitAttribute>())
                migrationInfo.AddTrait(traitAttribute.Name, traitAttribute.Value);

            return migrationInfo;
        }
示例#33
0
 private string GetName(IMigration migration) => migration.GetType().Name;
示例#34
0
        internal static int Number(this IMigration migration)
        {
            var typeName = migration.GetType().Name;

            return(int.Parse(numberPattern.Match(typeName).Captures[0].Value));
        }
 public static string GetId(this IMigration migration)
 {
     return(migration.MigrationType != MigrationType.Repeatable ? migration.Version.ToString() : migration.GetType().FullName);
 }
示例#36
0
        /// <summary>
        /// Validates each migration expression that has implemented the ICanBeValidated interface.
        /// It throws an InvalidMigrationException exception if validation fails.
        /// </summary>
        /// <param name="migration">The current migration being run</param>
        /// <param name="expressions">All the expressions contained in the up or down action</param>
        public void ApplyConventionsToAndValidateExpressions(IMigration migration, IEnumerable <IMigrationExpression> expressions)
        {
            var errorMessageBuilder = new StringBuilder();

            foreach (var expression in expressions)
            {
                expression.ApplyConventions(_conventions);

                var errors = new Collection <string>();
                expression.CollectValidationErrors(errors);

                if (errors.Count > 0)
                {
                    AppendError(errorMessageBuilder, expression.GetType().Name, string.Join(" ", errors.ToArray()));
                }
            }

            if (errorMessageBuilder.Length > 0)
            {
                var errorMessage = errorMessageBuilder.ToString();
                _announcer.Error("The migration {0} contained the following Validation Error(s): {1}", migration.GetType().Name, errorMessage);
                throw new InvalidMigrationException(migration, errorMessage);
            }
        }
示例#37
0
        public static MigrationAttribute GetMigrationsAttributes(IMigration migration)
        {
            Trace.WriteLineIf(ts.TraceInfo, "MigrationService - GetMigrationsAttributes() - Start");
            Attribute[] attrs = Attribute.GetCustomAttributes(migration.GetType());
            MigrationAttribute results = null;

            foreach (var attr in attrs)
            {
                if (attr is MigrationAttribute)
                {
                    MigrationAttribute atr = attr as MigrationAttribute;
                    results = atr;
                    break;
                }
            }

            Trace.WriteLineIf(ts.TraceInfo, "MigrationService - GetMigrationsAttributes() - End");
            return results;
        }