Changeset 14345fa44ab1…
Parent 756c45455cdb…
by Daniel Pupek
Changes to 5 files · Browse files at 14345fa44ab1 Showing diff from parent 756c45455cdb Diff from another changeset...
@@ -116,7 +116,7 @@ CheckArguments();
Migrator mig = GetMigrator();
- int currentVersion = mig.LatestVersion;
+ int currentVersion = mig.HighestDatabaseVersion;
bool isLegacy = mig.IsLegacyAssembly();
if(isLegacy)
@@ -243,9 +243,9 @@ {
_trace = true;
}
- else if (argv[i].ToLower().StartsWith("-to="))
+ else if (argv[i].ToLower().StartsWith("-to=") || argv[i].ToLower().StartsWith("-to:"))
{
- if (!int.TryParse(argv[i].ToLower().Replace("-to=", ""), out _migrateTo))
+ if (!int.TryParse(argv[i].ToLower().Replace("-to=", "").Replace("-to:", ""), out _migrateTo))
throw new ArgumentException("migrate to values must be integers");
}
else if (argv[i].ToLower().Equals("-up"))
|
|
|
@@ -184,9 +184,9 @@ public Migration EndMigration { get; set; }
/// <summary>
- /// Returns the last version of the migrations.
+ /// Returns the last version of the migrations in the actual assembly.
/// </summary>
- public int LastVersion
+ public int LastVersionInAssembly
{
get
{
@@ -213,9 +213,9 @@ /// <summary>
/// Returns the current version of the database.
/// </summary>
- public int LatestVersion
+ public int HighestDatabaseVersion
{
- get { return _provider.GetLatestVersion(_provider.AssemblyId); }
+ get { return _provider.GetHighestDatabaseVersion(_provider.AssemblyId); }
}
@@ -398,45 +398,37 @@ {
GetReady();
- int originalVersion = this.LatestVersion;
+ // Ensure Schema is updated
+ _provider.CreateMigrationTrackingTable();
+
+ int originalVersion = this.HighestDatabaseVersion;
- // check for cases where migration is unnecessary or impossible
- if (toVersion == this.LatestVersion)
- {
- this._logger.Log(string.Format("Current Version is v.{0}, no migration necessary.", this.LatestVersion));
- return;
- }
- else if (
- toVersion > 0 && (
- (this.LatestVersion > toVersion && this.GetMigration(toVersion + 1) == null) ||
- (this.LatestVersion < toVersion && this.GetMigration(toVersion) == null)
- )
- )
- {
- this._logger.Warn(string.Format("Cannot Migrate from version {0}, to {1}. Migration for version {1} does not exist", this.LatestVersion, toVersion));
- return;
- }
-
+
// Perform necessary migrations
try
{
- var goingUp = this.LatestVersion < toVersion;
// start transactions on all databases
this.BeginTransactions();
- this._logger.Started(LatestVersion, toVersion);
+ var goingUp = this.HighestDatabaseVersion <= toVersion;
+
+ this._logger.Started(HighestDatabaseVersion, toVersion);
IEnumerable<int> migratedVersions = new List<int>();
- _provider.CreateMigrationTrackingTable();
+
if (goingUp)
migratedVersions = InternalMigrateUpTo(toVersion);
else
migratedVersions = InternalMigrateDownTo(toVersion);
-
this.CommitTransactions();
- this._logger.Finished(originalVersion, this.LatestVersion);
+ _logger.Log("{0} migrations were run {1}", migratedVersions.Count(), goingUp ? "UP":"DOWN");
+
+ foreach(var migVer in migratedVersions)
+ _logger.Log("Migration {0} was run {1}", migVer, goingUp ? "UP" : "DOWN");
+
+ this._logger.Finished(originalVersion, this.HighestDatabaseVersion);
}
catch (Exception exception)
{
@@ -453,11 +445,14 @@ /// <param name="toVersion"></param>
private IEnumerable<int> InternalMigrateDownTo(int toVersion)
{
- InitializeMigration(EndMigration).Down();
+ Queue<Migration> migrations = GetMigrationsToBeRunDown(toVersion);
+ var migratedVersions = new List<int>();
- Queue<Migration> migrations = GetMigrationsToBeRunDown(toVersion);
+ if (migrations.Count == 0)
+ return migratedVersions;
- var migratedVersions = new List<int>();
+ InitializeMigration(EndMigration).Down();
+
int migratingVersion = -1;
try
{
@@ -470,6 +465,8 @@ this._logger.MigrateDown(migratingVersion, GetMigrationDescription(currentMigration.GetType()));
currentMigration.Down();
+ _provider.RemoveMigrationRecord(migratingVersion);
+
migratedVersions.Add(migratingVersion);
}
}
@@ -492,13 +489,17 @@ /// <param name="toVersion"></param>
private IEnumerable<int> InternalMigrateUpTo(int toVersion)
{
+
+ Queue<Migration> migrations = GetMigrationsToBeRunUP(toVersion);
+ _logger.Log("Found {0} migrations to migrate up.", migrations.Count);
+
+ var migratedVersions = new List<int>();
+
+ if (migrations.Count == 0)
+ return migratedVersions;
+
// Execute the Begin Migration
-
- InitializeMigration(BeginMigration).Up();
-
-
- Queue<Migration> migrations = GetMigrationsToBeRunUP(toVersion);
- var migratedVersions = new List<int>();
+ InitializeMigration(BeginMigration).Up();
int migratingVersion = -1;
try
@@ -511,6 +512,8 @@ this._logger.MigrateUp(migratingVersion, GetMigrationDescription(currentMigration.GetType()));
currentMigration.Up();
migratedVersions.Add(migratingVersion);
+
+ _provider.RecordMigration(migratingVersion);
}
}
catch (Exception e)
@@ -583,16 +586,16 @@ {
GetReady();
- if (this.LatestVersion < this.LastVersion)
+ if (this.HighestDatabaseVersion < this.LastVersionInAssembly)
{
// Find the next version
- var nextVersion = GetMigrationVersion(MigrationsTypes.Where(m=>GetMigrationVersion(m) > LatestVersion).OrderBy(GetMigrationVersion).First());
+ var nextVersion = GetMigrationVersion(MigrationsTypes.Where(m=>GetMigrationVersion(m) > HighestDatabaseVersion).OrderBy(GetMigrationVersion).First());
this.MigrateTo(nextVersion);
}
else
{
- this.MigrateTo(this.LatestVersion);
+ this.MigrateTo(this.HighestDatabaseVersion);
}
}
@@ -603,14 +606,14 @@ {
GetReady();
- if (this.LatestVersion > 0)
+ if (this.HighestDatabaseVersion > 0)
{
// Find the next version
- var nextVersion = GetMigrationVersion(MigrationsTypes.Where(m => GetMigrationVersion(m) < LatestVersion).OrderByDescending(GetMigrationVersion).First());
+ var nextVersion = GetMigrationVersion(MigrationsTypes.Where(m => GetMigrationVersion(m) < HighestDatabaseVersion).OrderByDescending(GetMigrationVersion).First());
this.MigrateTo(nextVersion);
}
else
- this.MigrateTo(this.LatestVersion);
+ this.MigrateTo(this.HighestDatabaseVersion);
}
/// <summary>
@@ -618,9 +621,22 @@ /// </summary>
public void MigrateToLastVersion()
{
- MigrateTo(LastVersion);
+ MigrateTo(Math.Max(LastVersionInAssembly, _provider.GetHighestDatabaseVersion()));
}
+ /// <summary>
+ /// Determine if this assembly needs to be migrated
+ /// </summary>
+ /// <returns></returns>
+ public bool NeedsMigration()
+ {
+ if (IsLegacyAssembly())
+ return true;
+
+ return GetMigrationsToBeRunUP(LastVersionInAssembly).Count > 0;
+
+ }
+
#endregion
#region Private Methods
@@ -706,6 +722,9 @@ private Migration GetMigration(int version)
{
Type t = GetMigrationType(version);
+ if (t == null)
+ return null;
+
Migration m = (Migration)Activator.CreateInstance(t);
InitializeMigration(m);
return m;
|
|
@@ -553,61 +553,98 @@ /// <param name="assemblyId"></param>
public virtual void CreateMigrationTrackingTable()
{
- EnsureHasConnection();
+
+ try
+ {
+ BeginTransaction();
+ // Does the old style schema info (without the assembly id column) table exist?
+ // We'll migrate the old info to the new format
+ int oldVersion = 0;
+ if (this.TableExists(OldSchemaInfoTable) )
+ {
+
+ oldVersion = (int?)ExecuteScalar(String.Format("SELECT Version FROM {1} WHERE AssemblyId='{0}'", AssemblyId, OldSchemaInfoTable)) ?? 0;
+ // We have what we needed
+ ExecuteNonQuery("DELETE from {0} WHERE AssemblyId = '{1}'", OldSchemaInfoTable, AssemblyId);
+
+ }
- // Does the old style schema info (without the assembly id column) table exist?
- // We'll migrate the old info to the new format
- int oldVersion = 0;
- if (this.TableExists(OldSchemaInfoTable) )
- {
-
- oldVersion = (int?)ExecuteScalar(String.Format("SELECT Version FROM {1} WHERE AssemblyId='{0}'", AssemblyId, OldSchemaInfoTable)) ?? 0;
- // We have what we needed
- ExecuteNonQuery("DELETE from {0} WHERE AssemblyId = '{1}'", OldSchemaInfoTable, AssemblyId);
-
- }
+ // create the Schema Info table to store the latest migration version
+ if (!this.TableExists(MigrationsTrackingTable))
+ {
+ _logger.Log("Creating Version 2 tracking tables.");
+ Column[] columns = new Column[] {
+ new Column(VersionColumn, typeof(int), ColumnProperties.NotNull),
+ new Column(AssemblyIdColumn, typeof(string), 255,ColumnProperties.NotNull),
+ new Column("UtcDateMigratedColumn", typeof(DateTime), 255,ColumnProperties.NotNull)
+ };
+
+ this.AddTable(MigrationsTrackingTable, columns);
+ this.AddPrimaryKey("MigrationTracking_PK", MigrationsTrackingTable, AssemblyIdColumn, VersionColumn);
+
+ }
- // create the Schema Info table to store the latest migration version
- if (!this.TableExists(MigrationsTrackingTable))
- {
- Column[] columns = new Column[] {
- new Column(VersionColumn, typeof(int), ColumnProperties.NotNull),
- new Column(AssemblyIdColumn, typeof(string), 255,ColumnProperties.NotNull),
- new Column("UtcDateMigratedColumn", typeof(DateTime), 255,ColumnProperties.NotNull)
- };
-
- this.AddTable(MigrationsTrackingTable, columns);
- this.AddPrimaryKey("MigrationTracking_PK", MigrationsTrackingTable, AssemblyIdColumn, VersionColumn);
+ if(oldVersion > 0)
+ _logger.Log("Moving old migration tracking records to the new tracking schema.");
- for (var i = 1; i <= oldVersion; i++)
- {
- this.RecordMigration(i); // bring over any previous verion
- }
-
- }
-
+ for (var i = 1; i <= oldVersion; i++)
+ {
+ this.RecordMigration(i); // bring over any previous verion
+ }
+
+ Commit();
+ }
+ catch (Exception e)
+ {
+ Rollback();
+ _logger.Exception("Error occured while ensuring tracking schema was up to date.",e);
+
+ throw;
+ }
+
}
-
- /// <summary>
+ /// <summary>
+ /// Get the version from the SchemaInfo Table
+ /// </summary>
+ /// <returns>The current version</returns>
+ public int GetHighestDatabaseVersion()
+ {
+ return GetHighestDatabaseVersion(AssemblyId);
+ }
+
+ /// <summary>
/// Get the version from the SchemaInfo Table
/// </summary>
/// <returns>The current version</returns>
- public virtual int GetLatestVersion(String assemblyId)
+ public virtual int GetHighestDatabaseVersion(String assemblyId)
{
if (assemblyId == null) return 0; // No schema info.
if (!TableExists(MigrationsTrackingTable)) return 0;
+ object ret = ExecuteScalar(String.Format("SELECT Top 1 Version FROM {1} WHERE AssemblyId='{0}' Order By Version Desc", assemblyId, MigrationsTrackingTable));
+ if(ret == null)
+ return 0;
- return (int)ExecuteScalar(String.Format("SELECT Top 1 Version FROM {1} WHERE AssemblyId='{0}' Order By Version Desc", assemblyId, MigrationsTrackingTable));
+ return (int) ret;
}
/// <summary>
+ /// rEMOVES RECORD OF A MIGRATION FROM THE TRACKING TABLE. USED AFTER A MIGRATION DOWN.
+ /// </summary>
+ /// <param name="version"></param>
+ internal void RemoveMigrationRecord(int version)
+ {
+ ExecuteNonQuery("DELETE FROM {0} WHERE ASSEMBLYID = '{1}' AND VERSION = '{2}'", MigrationsTrackingTable,
+ AssemblyId, version);
+ }
+
+ /// <summary>
/// Record the current version in the Migration Tracking Table
/// USING UTCNOW
/// </summary>
/// <param name="version">the new version to set</param>
/// <param name="date"></param>
- protected virtual void RecordMigration(int version)
+ internal virtual void RecordMigration(int version)
{
RecordMigration(version, DateTime.UtcNow);
}
|
@@ -45,7 +45,7 @@ SetUpCurrentVersion(1);
_migrator.MigrateTo(3);
- Assert.AreEqual(3, _migrator.LatestVersion);
+ Assert.AreEqual(3, _migrator.HighestDatabaseVersion);
Assert.AreEqual(2, _upCalled.Count);
Assert.AreEqual(0, _downCalled.Count);
@@ -117,16 +117,16 @@ [Test]
public void LastVersion()
{
- Assert.AreEqual(6, _migrator.LastVersion);
+ Assert.AreEqual(6, _migrator.LastVersionInAssembly);
}
[Test]
public void CurrentVersion()
{
SetUpCurrentVersion(4);
- Assert.AreEqual(4, _migrator.LatestVersion);
+ Assert.AreEqual(4, _migrator.HighestDatabaseVersion);
SetUpCurrentVersion(1);
- Assert.AreEqual(1, _migrator.LatestVersion);
+ Assert.AreEqual(1, _migrator.HighestDatabaseVersion);
}
[Test]
|
@@ -154,17 +154,17 @@ Assert.IsFalse(_provider.TableExists("SchemaInfo"));
// Check that a "get" call works on the first run.
- Assert.AreEqual(0, _provider.GetLatestVersion(_provider.AssemblyId));
+ Assert.AreEqual(0, _provider.GetHighestDatabaseVersion(_provider.AssemblyId));
// Check that a "set" called after the first run works.
// _provider.CurrentVersion = 1;
Assert.IsTrue(_provider.TableExists("SchemaInfo"), "No SchemaInfo table created"); // Setting a version should have caused the table to be created.
- Assert.AreEqual(1, _provider.GetLatestVersion(_provider.AssemblyId));
+ Assert.AreEqual(1, _provider.GetHighestDatabaseVersion(_provider.AssemblyId));
_provider.RemoveTable("SchemaInfo");
// Check that a "set" call works on the first run.
//_provider.CurrentVersion = 1;
- Assert.AreEqual(1, _provider.GetLatestVersion(_provider.AssemblyId));
+ Assert.AreEqual(1, _provider.GetHighestDatabaseVersion(_provider.AssemblyId));
Assert.IsTrue(_provider.TableExists("SchemaInfo"), "No SchemaInfo table created");
}
@@ -176,7 +176,7 @@ public void CommitTwice()
{
_provider.Commit();
- Assert.AreEqual(0, _provider.GetLatestVersion(_provider.AssemblyId));
+ Assert.AreEqual(0, _provider.GetHighestDatabaseVersion(_provider.AssemblyId));
_provider.Commit();
}
|
Loading...