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; }
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"); }
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); } }
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)); }
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; }
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); } }
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); }
public static string GetName(this IMigration migration) { if (migration == null) { throw new ArgumentNullException("migration"); } return(migration.GetType().FullName); }
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); }
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()); }
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); }
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); }
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); }
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()); }
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)); }
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); }
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); } }
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; }
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(); } }
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(); } }
/// <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); }
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; }
private string GetName(IMigration migration) => migration.GetType().Name;
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); }
/// <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); } }
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; }