public static Migrator Create(string targetName, Migrator migrator) { migrator.Guard = new Guard(); switch (targetName) { case "mysql": migrator.DbInterface = new DbInterface(); migrator.DbInterface.Executor = new Executor(); migrator.Applier = new MySQL.Applier(); break; case "mssql": migrator.DbInterface = new MSSQL.DbInterface(); migrator.DbInterface.Executor = new MSSQL.Executor(); migrator.Applier = new MSSQL.Applier(); break; case "postgresql": migrator.DbInterface = new PostgreSQL.DbInterface(); migrator.DbInterface.Executor = new PostgreSQL.Executor(); migrator.Applier = new PostgreSQL.Applier(); break; default: throw new Exception("Target name " + targetName + " is not valid"); } return migrator; }
void SetUpCurrentVersion(long version, List<long> appliedVersions, bool assertRollbackIsCalled, bool includeBad) { var providerMock = new DynamicMock(typeof (ITransformationProvider)); providerMock.SetReturnValue("get_MaxVersion", version); providerMock.SetReturnValue("get_AppliedMigrations", appliedVersions); providerMock.SetReturnValue("get_Logger", new Logger(false)); if (assertRollbackIsCalled) providerMock.Expect("Rollback"); else providerMock.ExpectNoCall("Rollback"); _migrator = new Migrator((ITransformationProvider) providerMock.MockInstance, Assembly.GetExecutingAssembly(), false); // Enlève toutes les migrations trouvée automatiquement _migrator.MigrationsTypes.Clear(); _upCalled.Clear(); _downCalled.Clear(); _migrator.MigrationsTypes.Add(typeof (FirstMigration)); _migrator.MigrationsTypes.Add(typeof (SecondMigration)); _migrator.MigrationsTypes.Add(typeof (ThirdMigration)); _migrator.MigrationsTypes.Add(typeof (FourthMigration)); _migrator.MigrationsTypes.Add(typeof (SixthMigration)); if (includeBad) _migrator.MigrationsTypes.Add(typeof (BadMigration)); }
public ActionResult Get(string id) { var migrator = new Migrator(RavenSessionManager.DocumentStore, typeof(MigrationClass).Assembly); var status = migrator.GetMigrationStatus(); return View(status); }
public bool Migrate(string connectionString, string providerName, IEnumerable<Type> entities, Action<MigratorResult, Type> callbackOnChanges) { var bResult = false; var provider = ProviderFactory.GetProvider(connectionString, providerName); foreach (var entity in entities) { var batch = new BatchQuery(provider); var m = new Migrator(Assembly.GetExecutingAssembly()); var commands = m.MigrateFromModel(entity, provider); bResult |= commands.Length > 0; try { foreach (var s in commands) batch.QueueForTransaction(new QueryCommand(PrepareCommand(s), provider)); batch.ExecuteTransaction(); } catch(Exception ex) { var sb = new StringBuilder(ex.Message); sb.Append(": "); foreach (var command in commands) sb.Append(command); throw new Exception(sb.ToString(), ex); } if (callbackOnChanges == null) continue; callbackOnChanges(commands.Length > 0 ? MigratorResult.ChangesMadeToEntity : MigratorResult.NoChanges, entity); } if (callbackOnChanges != null) callbackOnChanges(MigratorResult.ChangesMadeToAllEntities, null); return bResult; }
public override bool Execute() { using (var store = new DocumentStore()) { store.ConfigureUsingConnectionString(ConnectionString); store.Initialize(); var migrator = new Migrator(); foreach (var item in Migrations) { var assembly = Assembly.LoadFrom(item.GetMetadata("FullPath")); migrator.Migrate(store, assembly, ToVersion); } } if (ToVersion > 0) { Log.LogMessage("Migrated to version " + ToVersion + "."); } else { Log.LogMessage("Migrated to maximum version."); } return true; }
public void SetUp() { _migrator = new Migrator(TransformationProvider, MigrationAssembly, true); Assert.IsTrue(_migrator.MigrationsTypes.Count > 0, "No migrations in assembly " + MigrationAssembly.Location); _migrator.MigrateTo(0); }
public void SetUp() { _migrator = new Migrator(TransformationProvider); Assert.IsTrue(_migrator.MigrationsTypes.Count > 0); _migrator.MigrateTo(0); }
public override bool Execute() { log4net.Config.BasicConfigurator.Configure(new Log4NetMsBuildAppender(this.Log, new log4net.Layout.PatternLayout("%-5p %x %m"))); var migrator = new Migrator(); migrator.Run(this); return true; }
public static async Task Main() { var serilogLogger = new LoggerConfiguration().WriteTo.Console().CreateLogger(); var logger = new LoggerFactory().AddSerilog(serilogLogger).CreateLogger("Logging"); var dotenvPath = Path.Combine(Directory.GetCurrentDirectory(), ".env"); if (File.Exists(dotenvPath)) { logger.LogInformation(".env added"); DotEnv.Config(false, dotenvPath); } var configuration = new ConfigurationBuilder() .AddEnvironmentVariables() .Build(); var autofacBuilder = new ContainerBuilder(); autofacBuilder.RegisterInstance(configuration).As <IConfiguration>(); autofacBuilder.RegisterInstance(logger).As <ILogger>(); autofacBuilder.RegisterType <PeskybirdBot>(); autofacBuilder.RegisterType <PeskybirdContext>() .InstancePerLifetimeScope(); autofacBuilder.RegisterType <DiscordSocketClient>() .OwnedByLifetimeScope() .AsSelf() .AsImplementedInterfaces(); var assembly = typeof(Program).Assembly; autofacBuilder.RegisterAssemblyTypes(assembly) .Where(type => type.IsAssignableTo(typeof(ICommand)) && type.GetCustomAttribute <CommandAttribute>() != null) .Named <ICommand>(type => type.GetCustomAttribute <CommandAttribute>() !.Key.ToLower()); autofacBuilder.RegisterAssemblyTypes(assembly) .Where(type => type.IsAssignableTo(typeof(IVoiceStateUpdate))) .As <IVoiceStateUpdate>(); autofacBuilder.RegisterAssemblyTypes(assembly) .Where(t => t.Name.EndsWith("Service")) .AsImplementedInterfaces(); await using var container = autofacBuilder.Build(); var wasSuccessful = Migrator.Migrate(); if (!wasSuccessful) { logger.LogError("migration failed"); return; } var bot = container.Resolve <PeskybirdBot>(); await bot.RunBot(); await Task.Delay(-1); }
public static async Task <DbConnection> OpenDb() { var db = new SqliteConnection("Data Source=:memory:"); await db.OpenAsync(); await Migrator.Run(db); return(db); }
private Migrator GetMigrator() { Assembly asm = Assembly.LoadFrom(ConfigurationManager.AppSettings["MigrationAsembly"]); string provider = ConfigurationManager.AppSettings["MigrationProvider"]; string connectString = ConfigurationManager.AppSettings["ConnectionString"]; Migrator migrator = new Migrator(provider, connectString, asm, false); return migrator; }
protected void btnInstallAndMigrate_Click(object sender, EventArgs e) { ExecuteWithErrorHandling(() => { ShowResults(Migrator.UpgradeAndMigrate()); }); status = null; Installer.UpdateStatus(Status.Level); }
public ConcreteMigrationsEnabledDatabase( DbContextService <IModel> model, DataStoreCreator dataStoreCreator, DataStoreConnection connection, Migrator migrator, ILoggerFactory loggerFactory) : base(model, dataStoreCreator, connection, migrator, loggerFactory) { }
public SqlServerDatabase( [NotNull] DbContext context, [NotNull] ISqlServerDataStoreCreator dataStoreCreator, [NotNull] ISqlServerConnection connection, [NotNull] Migrator migrator, [NotNull] ILoggerFactory loggerFactory) : base(context, dataStoreCreator, connection, migrator, loggerFactory) { }
public void TestIrreversibleMigrationExceptionIsThrown() { long timestamp2 = typeof(Migration2).GetTimestamp(); IVersioning versioning = GetVersioning(true, true, true); Migrator migrator = new Migrator("", ProviderNames.SqlServer2008); migrator.UseCustomVersioning(versioning); migrator.FetchMigrationsTo(typeof(Migration1).Assembly, timestamp2); // should throw an IrreversibleMigrationException as Migration3 is irreversible }
public void EnsureJournal_ShouldCallCreateJournal() { var mockJournal = new FakeJournal(); var subject = new Migrator(mockJournal, Mock.Of <IMigrationsProvider>(), Mock.Of <IProgressReporter>()); subject.EnsureJournal(); Assert.That(mockJournal.IsCreated); }
public ConcreteRelationalDatabase( DbContext context, IRelationalDataStoreCreator dataStoreCreator, IRelationalConnection connection, Migrator migrator, ILoggerFactory loggerFactory) : base(context, dataStoreCreator, connection, migrator, loggerFactory) { }
public void LiftVersion_Was0Point12_IsSetTo0Point13() { using (TempFile f = new TempFile("<lift version='0.12' producer='testing'/>")) { string path = Migrator.MigrateToLatestVersion(f.Path); Assert.AreEqual(Validator.LiftVersion, Validator.GetLiftVersion(path)); AssertXPathAtLeastOne("//lift[@producer='testing']", path); } }
public NpgsqlDatabase( [NotNull] DbContext context, [NotNull] INpgsqlDataStoreCreator dataStoreCreator, [NotNull] INpgsqlEFConnection connection, [NotNull] Migrator migrator, [NotNull] ILoggerFactory loggerFactory) : base(context, dataStoreCreator, connection, migrator, loggerFactory) { }
private static void InitialiseDatabase() { var connectionStringSettings = ConfigurationManager.ConnectionStrings["DDDEastAnglia"]; var databaseMigrator = new Migrator(connectionStringSettings.ConnectionString); databaseMigrator.MigrateToLatestSchema(); WebSecurity.InitializeDatabaseConnection("DDDEastAnglia", "UserProfiles", "UserId", "UserName", autoCreateTables: false); }
/// <summary> /// Выполнить заданные действия над БД /// </summary> protected override void ExecuteTask() { ConfigureLogging(); using (Migrator migrator = MigratorFactory.CreateMigrator(this)) { migrator.Migrate(to); } }
static Command TryParseArgs(string[] args, out Options options) { var showHelp = false; var showVersion = false; var getCount = false; var optionsTmp = options = new Options(); var optionSet = new OptionSet() { { "h|help", "Shows this help message.", v => showHelp = v != null }, { "c|connection=", "A SQL Server connection string. For integrated auth, you can use --database and --server instead.", v => optionsTmp.ConnectionString = v }, { "n|name=", "A conections string from the config file.", v => optionsTmp.ConnectionStringName = v }, { "d|database=", "Generates an integrated auth connection string for the specified database.", v => optionsTmp.Database = v }, { "s|server=", "Generates an integrated auth connection string with the specified server (default: localhost).", v => optionsTmp.Server = v }, { "f|folder=", "The folder containing your .sql migration files (defaults to current working directory).", v => optionsTmp.MigrationsFolder = v }, { "timeout=", "Command timeout duration in seconds (default: 30)", v => optionsTmp.CommandTimeout = int.Parse(v) }, { "preview", "Run outstanding migrations, but roll them back.", v => optionsTmp.IsPreview = v != null }, { "global", "Run all outstanding migrations in a single transaction, if possible.", v => optionsTmp.UseGlobalTransaction = v != null }, { "table=", "Name of the table used to track migrations (default: Migrations)", v => optionsTmp.MigrationsTable = v }, { "force", "Will rerun modified migrations.", v => optionsTmp.Force = v != null }, { "version", "Print version number.", v => showVersion = v != null }, { "count", "Print the number of outstanding migrations.", v => getCount = v != null }, }; try { optionSet.Parse(args); options.Output = Console.Out; if (!showHelp && !showVersion) { optionsTmp.AssertValid(); } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(); showHelp = true; } if (showVersion) { Console.WriteLine("Mayflower.NET - Version " + Migrator.GetVersion()); Console.WriteLine(); return(Command.None); } if (showHelp) { ShowHelpMessage(optionSet); return(Command.None); } return(getCount ? Command.GetCount : Command.RunMigrations); }
private BindingSource LoadGridTable(string pTableName) { try { // Obtenemos la configuracion del origen SettingsModel model = SettingsManager.GetXml(); if (model == null) { return(null); } // Obtenemos la configuracion del destino SettingsModel modelDest = SettingsManager.GetXml(true); if (modelDest == null) { return(null); } // Inicializamos el manager de origen DatabaseManage manager = new DatabaseManage(model); // Inicializamos el manager de destino DatabaseManage managerDest = new DatabaseManage(modelDest); List <ColumnData> listColumns = new List <ColumnData>(); // Obtenemos las columnas de la tabla de origen IEnumerable <ColumnData> columns = manager.GetColumnsTypesInfoForTable(pTableName); foreach (ColumnData column in columns) { // Buscamos la columna en la base de datos de destino, // si no existe, no la guardaremos if (!managerDest.GetColumnWithNameForTable(pTableName, column.ColumnName)) { continue; } // Agregamos la columna al listado listColumns.Add(column); } // Enviamos la tabla, y la lista de columnas validas, para que nos genere las querys List <FieldResult> listFields = Migrator.GenerateInserts(pTableName, listColumns, manager, managerDest, progressBarResult); // Asignamos los datos al grid var bindingList = new BindingList <FieldResult>(listFields); var source = new BindingSource(bindingList, null); return(source); } catch (Exception ex) { DisplayMessage(ex.Message); } return(null); }
private Migrator GetMigrator() { Assembly asm = Assembly.LoadFrom(_migrationsAssembly); Migrator migrator = new Migrator(_provider, _connectionString, asm, _trace); migrator.args = args; migrator.DryRun = _dryrun; return(migrator); }
private Migrator CreateMigrator() { var migrator = new Migrator(ConnectionString, DbPlatform, _options); if (CustomConnection != null) { migrator.UseCustomConnection(CustomConnection); } return(migrator); }
protected MigratedDatabaseTest() { Migrator dbMigrator = new Migrator(ConfigurationManager.ConnectionStrings[CONNECTIONSTRING_NAME].ConnectionString); // reset the database to its initial state dbMigrator.Migrate(Assembly.Load("Entree.Migrations"), runner => runner.RollbackToVersion(0)); // run all of the migrations to get the database to the current version dbMigrator.Migrate(Assembly.Load("Entree.Migrations"), runner => runner.MigrateUp()); }
public void Execute_WithSingleValue_TakesValue() { var migrator = new Migrator(); string json = @"{execute: 'SELECT current_timestamp' }"; string command = migrator.GetCommandFromJson(json); Assert.AreEqual("SELECT current_timestamp", command); }
public async Task RunMigrationTaskAsync() { await ReplyAsync("Running migration."); var _ = Task.Run(async() => { Migrator.RunMigration(Local); await ReplyAsync("Done."); }); }
public void VerifyPendingMigrationsAreFoundForSpecificModule() { IVersioning versioning = GetVersioning(false, false, false); Migrator migrator = new Migrator("", ProviderNames.SqlServer2008, new MigrationOptions { ModuleSelector = m => m == Migration2.Module }); migrator.UseCustomVersioning(versioning); IMigrationBatch batch = migrator.FetchMigrations(typeof(Migration1).Assembly); Assert.AreEqual(1, batch.Count, string.Format(CultureInfo.CurrentCulture, "Only one migration for the module named '{0}' exists.", Migration2.Module)); }
public async Task RunClearMigrationTaskAsync() { await ReplyAsync("Running migration clear."); var _ = Task.Run(async() => { Migrator.RunClear(Context); await ReplyAsync("Done clearing."); }); }
public void CallsUpdate(DbAuthType authType) { TestConstants.ConfigureRequest(Request, authType); var underTest = new UpdateMigrationAction(MigratorFactory.Object); underTest.Migrate(Request, Result); Migrator.Verify(m => m.Update(), Times.Once); }
public void Can_Export_Database_Into_Export_File() { var migrator = new Migrator(); migrator.Migrate(); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, BlogMLExportWorker.ExportFileName); var exportFile = new FileInfo(path); Assert.True(exportFile.Exists); }
private Migrator GetMigrator() { Assembly asm = Assembly.LoadFrom(ConfigurationManager.AppSettings["MigrationAsembly"]); string provider = ConfigurationManager.AppSettings["MigrationProvider"]; string connectString = ConfigurationManager.AppSettings["ConnectionString"]; Migrator migrator = new Migrator(provider, connectString, asm, false); return(migrator); }
public void StartMigration() { var provider = "Postgres"; var assembly = typeof(DbMigration).Assembly; using (var migrator = new Migrator(provider, settings.ConnectionString, assembly)) { migrator.Migrate(); } }
static void Main(string[] args) { var migrationDir = LocateMigrations(); _args = args; _development = new Migrator(migrationDir, "development"); _test = new Migrator(migrationDir, "test", silent: true); _production = new Migrator(migrationDir, "production"); SayHello(); }
public void Initialize(IDatabaseInitializer <DbContext> databaseInitializer = null) { this.log($"DbContext Instance {this.instanceId} - Initializing Database"); Database.SetInitializer(databaseInitializer == null ? new DataSeedingInitializer() : databaseInitializer as IDatabaseInitializer <AppUsageDbContext>); Migrator.RunMigrations(); this.Database.Initialize(force: true); this.log($"DbContext Instance {this.instanceId} - Initialized Database"); }
private void SetVersionToLastAppliedMigration(Migrator migrator) { if (migrator.AppliedMigrations.Count > 0) { VersionField.Text = Convert.ToInt32(migrator.AppliedMigrations.Max()).ToString(); } else { VersionField.Text = "0"; } }
public static void MigrateDatabase() { string connectionString = ConfigurationManager.ConnectionStrings["Simple.Data.Properties.Settings.DefaultConnectionString"].ConnectionString; var migrator = new Migrator(connectionString); #if DEBUG migrator.Migrate(runner => runner.MigrateDown(3)); #endif migrator.Migrate(runner => runner.MigrateUp()); }
public int VerifyPendingMigrationsAreFound(bool migration1IsContained, bool migration2IsContained, bool migration3IsContained) { IVersioning versioning = GetVersioning(migration1IsContained, migration2IsContained, migration3IsContained); Migrator migrator = new Migrator("", ProviderNames.SqlServer2008); migrator.UseCustomVersioning(versioning); IMigrationBatch batch = migrator.FetchMigrations(typeof(Migration1).Assembly); versioning.VerifyAllExpectations(); return batch.Count; }
public static void CreateDatabase(string dbName, string relativePath) { string dbFilePath = GetAbsoluteDatabaseFilePath(dbName, relativePath); string connectionString = ConnectionString(dbFilePath); Migrator migrator = new Migrator(connectionString); #if DEBUG migrator.Migrate(runner => runner.MigrateDown(0)); #endif migrator.Migrate(runner => runner.MigrateUp()); DapperExtensions.DapperExtensions.DefaultMapper = typeof(PluralizedAutoClassMapper<>); }
public void HasEtymologyInSense_EtymologyMovedToEntry() { using (TempFile f = new TempFile("<lift version='0.11'><entry><sense><etymology/></sense></entry></lift>")) { string path = Migrator.MigrateToLatestVersion(f.Path); using (TempFile.TrackExisting(path)) { AssertXPathAtLeastOne("//entry/etymology", path); } } }
public void Setup() { _migrator = new Migrator(); var cloudStorage = CloudStorageAccount.Parse( ConfigurationManager.AppSettings["StorageConnectionString"]); _tableClient = cloudStorage.CreateCloudTableClient(); _tableClient.GetTableReference("versionData").DeleteIfExists(); }
public void MigrationConnection(string cnnStrng) { Npgsql.NpgsqlConnection conn = new NpgsqlConnection(cnnStrng); conn.Open(); //"Server=localhost;Port=5432;Database=test_migration;UserId=postgres;Password=postgres" Console.WriteLine(conn.FullState); var assembly = typeof(Program).Assembly; var migrator = new Migrator("postgres", conn, assembly); migrator.Migrate(); }
public void Migrator_get_version() { //Arrange const string version = "0.10.0"; //Act string result = Migrator.GetVersion(); //Assert Assert.Equal(version, result); }
private List<MigrationInfo> GetMigrationsList(Migrator mig) { List<System.Type> migrations = mig.MigrationsTypes; migrations.Reverse(); List<MigrationInfo> list = new List<MigrationInfo>(); List<System.Type>.Enumerator en = migrations.GetEnumerator(); while(en.MoveNext()){ MigrationInfo info = new MigrationInfo(en.Current); list.Add(info); } return list; }
public Program(IApplicationEnvironment appEnv, ILoggerProvider logProvider) { _logger = logProvider?.CreateLogger(this.GetType().ToString()) ?? new ConsoleLogger(this.GetType().ToString(), (catgory,level) => { return true; }, true); Configuration = new ConfigurationBuilder() .SetBasePath(appEnv.ApplicationBasePath) .AddJsonFile("config.json", true) .Build(); _migrator = new Migrator(Configuration, appEnv.ApplicationName); }
public void create_database_and_apply_all_migrations() { Mock<ISupplyMigrations> source = SetupSource(); Mock<ICommandDatabases> handler = SetupHandler(new DatabaseVersion {Type = DatabaseVersionType.NotCreated}); Mock<ICompareMigrations> comparer = SetupComparer(); var migrator = new Migrator(source.Object, comparer.Object, handler.Object); migrator.Migrate(); handler.Verify(h => h.Create(), Times.Once); handler.Verify(h => h.CreateMigrationHistoryTable(), Times.Never); handler.Verify(h => h.ExecuteMigration(It.IsAny<Migration>()), Times.Exactly(2)); }
public Migrator Parse(string[] args, Migrator migrator) { CurrentOptions = Options.Factory.Create(args); migrator = InitMigrator(migrator); SetDefaultOptionsForMigrator(migrator); SetCustomOptionsForMigrator(migrator); migrator.Strategy = Strategy.Factory.Create(CurrentOptions.Strategy); return migrator; }
public void apply_no_migrations() { Mock<ISupplyMigrations> source = SetupSource(); Mock<ICommandDatabases> handler = SetupHandler(new DatabaseVersion {Type = DatabaseVersionType.VersionNumber, Number = "1"}); Mock<ICompareMigrations> comparer = SetupComparer(); var migrator = new Migrator(source.Object, comparer.Object, handler.Object); migrator.Migrate(); handler.Verify(h => h.Create(), Times.Never); handler.Verify(h => h.CreateMigrationHistoryTable(), Times.Never); handler.Verify(h => h.ExecuteMigration(It.IsAny<Migration>()), Times.Never); }
public void Can_Deserialize_Exported_File() { var migrator = new Migrator(); migrator.Migrate(); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, BlogMLExportWorker.ExportFileName); var file = new FileStream(path, FileMode.Open); var blog = BlogMLSerializer.Deserialize(file); Assert.NotNull(blog); Assert.NotEqual(0, blog.Posts.Count); Assert.NotEqual(0, blog.Categories.Count); }
public void Execute() { var connection = ConfigurationManager.ConnectionStrings["database"]; var options = new MigrationOptions(); options.SupportedProviders.Clear(); options.SupportedProviders.Add(ProviderNames.SQLite); options.SupportedProviders.Add(ProviderNames.SqlServer2005); options.SupportedProviders.Add(ProviderNames.SqlServer2008); var m = new Migrator(connection.ConnectionString, connection.ProviderName, options); m.MigrateAll(typeof(MeasuresController).Assembly); }
public void CanMoveDownWithoutTransaction() { var provider = new Mock<ITransformationProvider>(); Assembly asm = Assembly.Load("ECM7.Migrator.TestAssembly"); using (var migrator = new Migrator(provider.Object, asm)) { migrator.ExecuteMigration(4, 4); provider.Verify(db => db.ExecuteNonQuery("down4")); provider.Verify(db => db.MigrationUnApplied(4, "test-key111")); } }
public void Execute_WithArray_ConcatenesValues() { var migrator = new Migrator(); string json = @"{execute: [ 'SELECT current_timestamp, ', 'system_user' ]}"; string command = migrator.GetCommandFromJson(json); Assert.AreEqual(string.Format(@"SELECT current_timestamp, {0}system_user{0}", Environment.NewLine), command); }
static int DetermineVersion(InputParameters parameters, Migrator m) { switch(parameters.GotoMode) { default: case GotoMode.Specific: return parameters.DesitinationVersion.GetValueOrDefault(0); case GotoMode.Previous: return Math.Max(m.Migrations.Count - 1, 0); case GotoMode.Last: return m.Migrations.Count; } }
public void Initialise(IConfigSource configSource) { IConfig config = configSource.Configs["EventRecorder"]; m_connectionString = config.GetString("ConnectionString"); if (m_connectionString == null) throw new Exception("No ConnectionString parameter found in [EventRecorder] config for MySQLRecorder"); // m_log.DebugFormat("[MYSQL EVENT RECORDER]: Got connection string '{0}'", m_connectionString); Migrator migrator = new Migrator(m_connectionString); migrator.Migrate(runner => runner.MigrateUp()); }
public override void AddForeignKey(string name, string primaryTable, string[] primaryColumns, string refTable, string[] refColumns, Migrator.Framework.ForeignKeyConstraint constraint) { if (ConstraintExists(primaryTable, name)) { Logger.Warn("Constraint {0} already exists", name); return; } ExecuteNonQuery( String.Format( "ALTER TABLE {0} ADD CONSTRAINT {1} FOREIGN KEY ({2}) REFERENCES {3} ({4})", primaryTable, name, String.Join(",", primaryColumns), refTable, String.Join(",", refColumns))); }
public void Exports_Post_Category_Relations() { var migrator = new Migrator(); migrator.Migrate(); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, BlogMLExportWorker.ExportFileName); var file = new FileStream(path, FileMode.Open); var blog = BlogMLSerializer.Deserialize(file); var post = blog.Posts[0]; var categories = post.Categories; Assert.NotNull(categories); Assert.NotEmpty(categories); }
public void CanMoveUp() { var provider = new Mock<ITransformationProvider>(); Assembly asm = Assembly.Load("ECM7.Migrator.TestAssembly"); using (var migrator = new Migrator(provider.Object, asm)) { migrator.ExecuteMigration(2, 1); provider.Verify(db => db.BeginTransaction()); provider.Verify(db => db.ExecuteNonQuery("up")); provider.Verify(db => db.MigrationApplied(2, "test-key111")); provider.Verify(db => db.Commit()); } }
public override Migrator SetCustomOptionsForMigrator(Migrator migrator) { if (_useWindowsAuth) { migrator.DbInterface.Executor.Username = string.Empty; migrator.DbInterface.Executor.Password = string.Empty; } if (!string.IsNullOrWhiteSpace(migrator.DbInterface.Executor.Username) && string.IsNullOrWhiteSpace(migrator.DbInterface.Executor.Password)) { throw new Exception("You must apply a password for your database username!"); } return migrator; }