OpenSource » Database Migrator » Migrator2
Clone URL:  
Pushed to one repository · View In Graph Contained in tip

Migrator Case 50595
Work on redesigned migrator

Changeset 14345fa44ab1

Parent 756c45455cdb

by Profile picture of Daniel PupekDaniel Pupek

Changes to 5 files · Browse files at 14345fa44ab1 Showing diff from parent 756c45455cdb Diff from another changeset...

 
116
117
118
119
 
120
121
122
 
243
244
245
246
 
247
248
 
249
250
251
 
116
117
118
 
119
120
121
122
 
243
244
245
 
246
247
 
248
249
250
251
@@ -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
185
186
187
 
188
189
 
190
191
192
 
213
214
215
216
 
217
218
 
219
220
221
 
398
399
400
401
 
 
 
 
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
 
420
421
422
423
424
425
426
427
 
 
 
428
429
 
430
431
432
433
434
435
436
437
438
439
 
 
 
 
 
 
440
441
442
 
453
454
455
456
 
 
457
458
 
 
459
460
 
 
461
462
463
 
470
471
472
 
 
473
474
475
 
492
493
494
 
 
 
 
 
 
 
 
 
495
496
497
498
499
500
501
 
502
503
504
 
511
512
513
 
 
514
515
516
 
583
584
585
586
 
587
588
589
 
590
591
592
593
594
595
 
596
597
598
 
603
604
605
606
 
607
608
609
 
610
611
612
613
 
614
615
616
 
618
619
620
621
 
622
623
 
 
 
 
 
 
 
 
 
 
 
 
 
624
625
626
 
706
707
708
 
 
 
709
710
711
 
184
185
186
 
187
188
 
189
190
191
192
 
213
214
215
 
216
217
 
218
219
220
221
 
398
399
400
 
401
402
403
404
405
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
406
407
408
409
 
410
411
412
 
413
414
415
416
 
417
418
419
420
421
422
423
 
424
425
 
426
427
428
429
430
431
432
433
434
 
445
446
447
 
448
449
450
 
451
452
453
 
454
455
456
457
458
 
465
466
467
468
469
470
471
472
 
489
490
491
492
493
494
495
496
497
498
499
500
501
 
 
 
 
 
 
502
503
504
505
 
512
513
514
515
516
517
518
519
 
586
587
588
 
589
590
591
 
592
593
594
595
596
597
 
598
599
600
601
 
606
607
608
 
609
610
611
 
612
613
614
615
 
616
617
618
619
 
621
622
623
 
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
 
722
723
724
725
726
727
728
729
730
@@ -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
554
555
556
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
557
558
559
560
561
562
563
564
565
566
567
568
 
 
 
 
 
 
 
 
 
 
 
 
 
 
569
570
571
572
573
574
575
576
577
578
579
580
 
 
581
582
583
584
585
586
587
588
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
589
590
591
592
 
 
 
 
 
 
 
 
 
 
593
594
595
596
 
597
598
599
 
 
 
600
601
 
602
603
604
 
 
 
 
 
 
 
 
 
 
605
606
607
608
609
610
 
611
612
613
 
553
554
555
 
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
 
 
 
 
 
 
 
 
 
 
 
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
 
 
 
 
 
 
 
 
 
 
 
587
588
589
 
 
 
 
 
 
 
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
 
606
 
607
608
609
610
611
612
613
614
615
616
617
618
619
 
620
621
622
623
624
625
626
627
 
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
 
647
648
649
650
@@ -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
46
47
48
 
49
50
51
 
117
118
119
120
 
121
122
123
124
125
126
127
 
128
129
 
130
131
132
 
45
46
47
 
48
49
50
51
 
117
118
119
 
120
121
122
123
124
125
126
 
127
128
 
129
130
131
132
@@ -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
155
156
157
 
158
159
160
161
162
 
163
164
165
166
167
 
168
169
170
 
176
177
178
179
 
180
181
182
 
154
155
156
 
157
158
159
160
161
 
162
163
164
165
166
 
167
168
169
170
 
176
177
178
 
179
180
181
182
@@ -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();   }