Migrations support
A simple migrations mechanism. Leverage the existing querying features to do migrations also.
So to define a migration:
[Migration(20190127135100, "A sample migration")]
public class SampleMigration : Migration
{
public override void Up()
{
// Some queries here
}
public override void Down()
{
// Some queries here
}
}
And to start a migration flow:
var migrationController = new MigrationController();
migrationController.LoadMigrationsFromAssembly(this.GetType().Assembly);
migrationController.VersionQueryHandler = () =>
{
try
{
var version = Query.New<SchemaGlobals>()
.Select(SchemaGlobals.Columns.Data)
.Where(SchemaGlobals.Columns.Key, "version")
.LimitRows(1)
.ExecuteScalar() as string;
if (version == null) return 0;
return Convert.ToInt64(version);
}
catch
{
Query.New<SchemaGlobals>().CreateTable().Execute();
return 0;
}
};
migrationController.MigrationVersionEvent += (sender, args) =>
{
Query.New<SchemaGlobals>()
.Insert(SchemaGlobals.Columns.Key, "version")
.Insert(SchemaGlobals.Columns.Data, args.Version)
.InsertOrUpdate()
.Execute();
};
migrationController.ItemStartEvent += (sender, args) =>
{
logger.Info($"Migrating db to version {args.Version}: {args.Description ?? args.Type.Name}...");
};
migrationController.ItemEndEvent += (sender, args) =>
{
logger.Info($"Migrating db to version {args.Version}: {args.Description ?? args.Type.Name} - Done.");
};
try
{
var count = migrationController.MigrateUp();
if (count > 0)
{
logger.Info($"Successfully ran {count} migrations.");
}
}
catch (Exception ex)
{
logger.Error(ex, "Migration failed.");
try
{
migrationController.Rollback();
}
catch (Exception rex)
{
logger.Error(rex, "Migration rollback failed.");
}
}