Changeset 5f8dc566ecdd…
Parent 49ae302c31c2…
by
Changes to 12 files · Browse files at 5f8dc566ecdd Showing diff from parent 49ae302c31c2 Diff from another changeset...
Change 1 of 3
Show Entire File
app/console/Migrator.Console.csproj
Stacked
renamed from app/console/Migrator.Console_2005.csproj
|
||
---|---|---|
@@ -1,4 +1,5 @@ - <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
@@ -19,9 +20,11 @@ </SccProvider>
<FileUpgradeFlags>
</FileUpgradeFlags>
- <OldToolsVersion>2.0</OldToolsVersion>
+ <OldToolsVersion>3.5</OldToolsVersion>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
+ <TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -55,5 +58,10 @@ <Name>Migrator</Name>
</ProjectReference>
</ItemGroup>
+ <ItemGroup>
+ <None Include="app.config">
+ <SubType>Designer</SubType>
+ </None>
+ </ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>
\ No newline at end of file |
|
|
@@ -12,6 +12,9 @@ using System.Reflection;
using System.IO;
using Migrator.Tools;
+using System.Collections.Generic;
+using System.Collections;
+using System.Runtime.InteropServices;
namespace Migrator.MigratorConsole
{
@@ -28,14 +31,28 @@ private bool _trace = false;
private string _dumpTo;
private int _migrateTo = -1;
-
+ private bool _migrateUp = false;
+ private bool _migrateDown = false;
+
+ private bool allParamsSpecified = true;
+
/// <summary>
/// Builds a new console
/// </summary>
/// <param name="argv">Command line arguments</param>
public MigratorConsole(string[] argv)
{
- ParseArguments(argv);
+ System.Threading.Thread.Sleep(1000);
+ Console.Out.WriteLine("Migrator.Console.exe started....");
+ try
+ {
+ ParseArguments(argv);
+ }
+ catch (ArgumentException ex)
+ {
+ Console.Out.Write(ex.Message);
+ allParamsSpecified = false;
+ }
}
/// <summary>
@@ -44,6 +61,8 @@ /// <returns>-1 if error, else 0</returns>
public int Run()
{
+ if (!allParamsSpecified)
+ return 1;
try
{
if (_list)
@@ -76,7 +95,12 @@ CheckArguments();
Migrator mig = GetMigrator();
- if (_migrateTo == -1)
+
+ if(_migrateUp)
+ mig.MigrateUp();
+ else if (_migrateDown)
+ mig.MigrateDown();
+ else if (_migrateTo == -1)
mig.MigrateToLastVersion();
else
mig.MigrateTo(_migrateTo);
@@ -129,14 +153,73 @@ Console.WriteLine("\t{0} {1}", "connectionString".PadRight(tab), "Connection string to the database");
Console.WriteLine("\t{0} {1}", "migrationAssembly".PadRight(tab), "Path to the assembly containing the migrations");
Console.WriteLine("Options:");
- Console.WriteLine("\t-{0}{1}", "version NO".PadRight(tab), "To specific version to migrate the database to");
+ Console.WriteLine("\t-{0}{1}", "to=<version>".PadRight(tab), "Migrats to specified version");
+ Console.WriteLine("\t-{0}{1}", "up".PadRight(tab), "Migrates up a version");
+ Console.WriteLine("\t-{0}{1}", "down".PadRight(tab), "Migrates down a version");
Console.WriteLine("\t-{0}{1}", "list".PadRight(tab), "List migrations");
Console.WriteLine("\t-{0}{1}", "trace".PadRight(tab), "Show debug informations");
- Console.WriteLine("\t-{0}{1}", "dump FILE".PadRight(tab), "Dump the database schema as migration code");
Console.WriteLine();
+ Console.WriteLine("-up, -down, and -to options are mutually exclusive");
}
#region Private helper methods
+ private Assembly GetAssembly()
+ {
+ return Assembly.LoadFrom(_migrationsAssembly);;
+ }
+
+ private Migration GetBeginMigration()
+ {
+ foreach (Type t in GetAssembly().GetTypes())
+ {
+ MigrationBeginAttribute attrib = (MigrationBeginAttribute)
+ Attribute.GetCustomAttribute(t, typeof(MigrationBeginAttribute));
+ if (attrib != null && typeof(Migration).IsAssignableFrom(t))
+ {
+ return (Migration)Activator.CreateInstance(t);
+ }
+ }
+
+ return new NullMigration();
+ }
+
+ private Migration GetEndMigration()
+ {
+ foreach (Type t in GetAssembly().GetTypes())
+ {
+ MigrationEndAttribute attrib = (MigrationEndAttribute)
+ Attribute.GetCustomAttribute(t, typeof(MigrationEndAttribute));
+ if (attrib != null && typeof(Migration).IsAssignableFrom(t))
+ {
+ return (Migration)Activator.CreateInstance(t);
+ }
+ }
+
+ return new NullMigration();
+
+ }
+
+ private ArrayList GetGeneralMigrations()
+ {
+ ArrayList migrations = new ArrayList();
+
+ foreach (Type t in GetAssembly().GetTypes())
+ {
+ MigrationAttribute attrib = (MigrationAttribute)
+ Attribute.GetCustomAttribute(t, typeof(MigrationAttribute));
+ if (attrib != null && typeof(Migration).IsAssignableFrom(t))
+ {
+ if (!attrib.Ignore)
+ {
+ migrations.Add(t);
+ }
+ }
+ }
+
+ migrations.Sort(new MigrationTypeComparer(true));
+ return migrations;
+ }
+
private void CheckArguments()
{
if (_connectionString == null)
@@ -147,32 +230,36 @@
private Migrator GetMigrator()
{
- Assembly asm = Assembly.LoadFrom(_migrationsAssembly);
-
- return new Migrator(_provider, _connectionString, asm, _trace);
+ GuidAttribute guidAttribute = (GuidAttribute)Attribute.GetCustomAttribute(GetAssembly(), typeof(GuidAttribute));
+ // This is done incase we are scanning a 4.0 dll, the console is compiled against 4.0 so it can do all the assembly scanning
+ var logger = new Loggers.ConsoleLogger(_trace);
+ return new Migrator(_provider, _connectionString, GetGeneralMigrations(), GetBeginMigration(), GetEndMigration(), guidAttribute, logger);
}
private void ParseArguments(string[] argv)
{
for (int i = 0; i < argv.Length; i++)
{
- if (argv[i].Equals("-list"))
+ if (argv[i].ToLower().Equals("-list"))
{
_list = true;
}
- else if (argv[i].Equals("-trace"))
+ else if (argv[i].ToLower().Equals("-trace"))
{
_trace = true;
}
- else if (argv[i].Equals("-version"))
+ else if (argv[i].ToLower().StartsWith("-to="))
{
- _migrateTo = int.Parse(argv[i+1]);
- i++;
+ if (!int.TryParse(argv[i].ToLower().Replace("-to=", ""), out _migrateTo))
+ throw new ArgumentException("migrate to values must be integers");
}
- else if (argv[i].Equals("-dump"))
+ else if (argv[i].ToLower().Equals("-up"))
{
- _dumpTo = argv[i+1];
- i++;
+ _migrateUp = true;
+ }
+ else if (argv[i].ToLower().Equals("-down"))
+ {
+ _migrateDown = true;
}
else
{
@@ -181,6 +268,16 @@ if (i == 2) _migrationsAssembly = argv[i];
}
}
+ List<String> messages = new List<String>();
+ if (!_list && argv.Length > 0)
+ {
+ if (!(_migrateUp ^ _migrateDown ^ _migrateTo > 0) && !(_migrateTo < 0)) messages.Add("You must specify only one up, down, or to command.");
+ if (_provider == null) messages.Add("Provider not specified (SqlServer, MySql, Postgre).");
+ if (_connectionString == null) messages.Add("Connection string not specified.");
+ if (_migrationsAssembly == null) messages.Add("Migration assembly not specified");
+ if (messages.Count > 0)
+ throw new ArgumentException("\n\n" + String.Join(" \n", messages.ToArray()) + "\n\n");
+ }
}
#endregion
}
|
|
@@ -0,0 +1,3 @@ + <?xml version="1.0"?>
+<configuration>
+<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
|
@@ -19,43 +19,38 @@ {
private int _widthFirstColumn = 5;
private bool _trace = false;
-
+
public ConsoleLogger(bool trace)
{
_trace = trace;
}
-
+
public void Started(int currentVersion, int finalVersion)
{
- if (_trace)
- Console.WriteLine("Migrating from Current Version: {0} to version {1}", currentVersion, finalVersion);
- else
- Console.Write("Migrating from {0} to {1}: ", currentVersion, finalVersion);
+ Console.WriteLine("Migrating from {0} to {1}: ", currentVersion, finalVersion);
}
-
+
public void MigrateUp(int version, string migrationName)
{
if (this._trace)
Console.WriteLine("{0} {1}", version.ToString().PadLeft(_widthFirstColumn), migrationName);
- else
- Console.Write("..{0}");
}
-
+
public void MigrateDown(int version, string migrationName)
{
MigrateUp(version, migrationName);
}
-
+
public void Skipping(int version)
{
Console.WriteLine("{0} {1}", version.ToString().PadLeft(_widthFirstColumn), "<Migration not found>");
}
-
+
public void RollingBack(int originalVersion)
{
Console.WriteLine("Rolling back to migration {0}", originalVersion);
}
-
+
public void Exception(int version, string migrationName, Exception ex)
{
Console.WriteLine("{0} Error in migration {1} : {2}", "".PadLeft(_widthFirstColumn), version, ex.Message);
@@ -68,27 +63,27 @@ Console.WriteLine(format, args);
this.TraceException(ex);
}
-
+
public void Finished(int originalVersion, int currentVersion)
{
if (_trace)
Console.WriteLine("Finished migrating to version {0}", currentVersion);
else
- Console.Write(".. Done.");
+ Console.WriteLine(".. Done.");
}
-
+
public void Log(string format, params object[] args)
{
Console.Write("{0} ", "".PadLeft(_widthFirstColumn));
Console.WriteLine(format, args);
}
-
+
public void Warn(string format, params object[] args)
{
Console.Write("{0} Warning! : ", "".PadLeft(_widthFirstColumn));
Console.WriteLine(format, args);
- }
-
+ }
+
public void Trace(string format, params object[] args)
{
if (_trace)
@@ -114,6 +109,6 @@ Console.WriteLine("======================================");
}
}
-
+
}
}
|
|
|
@@ -36,6 +36,7 @@ /// </summary>
public class Migrator
{
+ #region Fields
private TransformationProvider _provider;
private ArrayList _migrationsTypes = new ArrayList();
private ILogger _logger = new NullLogger();
@@ -43,7 +44,9 @@ private Dictionary<string, string> _parameters;
private Dictionary<string, TransformationProvider> _additionalProviders = new Dictionary<string, TransformationProvider>();
private List<TransformationProvider> _allProviders = new List<TransformationProvider>(); // used internally for transaction managment
+ #endregion
+ #region Constructors
public Migrator(TransformationProvider defaultProvider, Dictionary<string, TransformationProvider> additionalProviders, Assembly migrationAssembly, ILogger logger)
: this(defaultProvider, migrationAssembly, logger)
{
@@ -72,23 +75,24 @@ public Migrator(string provider, string connectionString)
: this(CreateProvider(provider, connectionString), Assembly.GetExecutingAssembly(), new Log4NetLogger())
{ }
-
+
public Migrator(TransformationProvider provider, Assembly migrationAssembly, ILogger logger)
{
_provider = provider;
_logger = logger;
_provider.Logger = _logger;
+ if (provider == null)
+ throw new ArgumentNullException("provider");
+
if (migrationAssembly == null)
{
_logger.Exception("Migration assembly not provided.", new ArgumentNullException("migrationAssembly"));
- throw new ArgumentNullException("migrationAssembly");
+ throw new Exception("Assembly not found");
}
- if (provider == null)
- throw new ArgumentNullException("provider");
-
- _logger.Log("Performing migrations for {0}", migrationAssembly.FullName);
+ if(migrationAssembly != null)
+ _logger.Log("Performing migrations for {0}", migrationAssembly.FullName);
// add all providers to the "all providers" list
if (this._additionalProviders != null)
@@ -100,39 +104,106 @@ }
this._allProviders.Add(_provider);
+ GuidAttribute guid = (GuidAttribute)Attribute.GetCustomAttribute(migrationAssembly, typeof(GuidAttribute));
+
// only load the migrations for the given assembly
- _migrationsTypes.AddRange(GetMigrationTypes(migrationAssembly));
+ if (migrationAssembly != null)
+ {
+ _migrationsTypes.AddRange(GetMigrationTypes(migrationAssembly));
- // Load the begin and end migrations
- this.BeginMigration = GetBeginMigration(migrationAssembly);
- this.EndMigration = GetEndMigration(migrationAssembly);
+ this.BeginMigration = GetBeginMigration(migrationAssembly);
+ this.EndMigration = GetEndMigration(migrationAssembly);
+ }
+ CheckForDuplicatedVersion();
+ }
- CheckForDuplicatedVersion();
+ public Migrator(string provider, string connectionString, ArrayList migrations, Migration beginMigration, Migration endMigration, GuidAttribute assemblyAttribute, ILogger logger)
+ : this(CreateProvider(provider, connectionString), migrations, beginMigration, endMigration, assemblyAttribute, logger ?? new Log4NetLogger())
+ { }
- // Enshure that the Schema Info table is created
- GuidAttribute guid = (GuidAttribute)Attribute.GetCustomAttribute(migrationAssembly, typeof(GuidAttribute));
- if (guid != null)
- _provider.CreateSchemaInfoTable(guid.Value);
- else
- _provider.CreateSchemaInfoTable();
+ public Migrator(TransformationProvider provider, ArrayList migrations, Migration beginMigration, Migration endMigration, GuidAttribute assemblyAttribute, ILogger logger)
+ {
+ _provider = provider;
+ _logger = logger;
+ _provider.Logger = _logger;
+ AssemblyGuid = assemblyAttribute;
+ BeginMigration = beginMigration ?? new NullMigration();
+ EndMigration = endMigration ?? new NullMigration();
+ MigrationsTypes.AddRange(migrations);
+ }
+ #endregion
- // Print a list of loaded Migrations
- _logger.Trace("Loaded migrations:");
- foreach (Type t in _migrationsTypes)
+ #region Properties
+ /// <summary>
+ /// The id of the assembly that migrations are being run
+ /// </summary>
+ public GuidAttribute AssemblyGuid { get; set; }
+ /// <summary>
+ /// The migration that will be run before all others...everytime
+ /// </summary>
+ public Migration BeginMigration { get; set; }
+ /// <summary>
+ /// The migration that will be run after all others...everytime
+ /// </summary>
+ public Migration EndMigration { get; set; }
+
+ /// <summary>
+ /// Returns the last version of the migrations.
+ /// </summary>
+ public int LastVersion
+ {
+ get
{
- _logger.Trace("{0} {1}", GetMigrationVersion(t).ToString().PadLeft(5), GetMigrationDescription(t));
+ if (_migrationsTypes.Count == 0)
+ return 0;
+ return GetMigrationVersion((Type)_migrationsTypes[_migrationsTypes.Count - 1]);
}
}
+ public Dictionary<string, string> MigrationParameters
+ {
+ get { return this._parameters; }
+ set { this._parameters = value; }
+ }
+
/// <summary>
- /// The migration that will be run before all others...everytime
+ /// Returns the current version of the database.
/// </summary>
- public Migration BeginMigration { get; private set; }
+ public int CurrentVersion
+ {
+ get { return _provider.CurrentVersion; }
+ }
+
/// <summary>
- /// The migration that will be run after all others...everytime
+ /// Returns registered migration <see cref="System.Type">types</see>.
/// </summary>
- public Migration EndMigration { get; private set; }
- /// <summary>
+ public ArrayList MigrationsTypes
+ {
+ get { return _migrationsTypes; }
+ }
+
+ /// <summary>
+ /// Get or set the event logger.
+ /// </summary>
+ public ILogger Logger
+ {
+ get { return _logger; }
+ set { _logger = value; }
+ }
+
+ public string ConnectionString
+ {
+ get
+ {
+ if (_provider != null)
+ return _provider.ConnectionString;
+ return null;
+ }
+ }
+ #endregion
+
+ #region Static Methods
+ /// <summary>
/// Allow a migration to create a TransformationProvider to another database so it can migrate data from that database
/// </summary>
/// <param name="providerName"></param>
@@ -143,8 +214,116 @@ return new ProviderFactory().Create(providerName, constr);
}
-
- /// <summary>
+ /// <summary>
+ /// Returns the version of the migration
+ /// <see cref="MigrationAttribute">MigrationAttribute</see>.
+ /// </summary>
+ /// <param name="t">Migration type.</param>
+ /// <returns>Version number sepcified in the attribute</returns>
+ public static int GetMigrationVersion(Type t)
+ {
+ MigrationAttribute attrib = (MigrationAttribute)
+ Attribute.GetCustomAttribute(t, typeof(MigrationAttribute));
+
+ return attrib.Version;
+ }
+
+ /// <summary>
+ /// Returns the Description of the migration
+ /// <see cref="MigrationAttribute">MigrationAttribute</see>.
+ /// </summary>
+ /// <param name="t">Migration type.</param>
+ /// <returns>Long form Description sepcified in the attribute</returns>
+ public static String GetMigrationDescription(Type t)
+ {
+ MigrationAttribute attrib = (MigrationAttribute)
+ Attribute.GetCustomAttribute(t, typeof(MigrationAttribute));
+
+ return attrib.Description == null ? t.Name : attrib.Description;
+ }
+
+ /// <summary>
+ /// Collect migrations in one <c>Assembly</c>.
+ /// </summary>
+ /// <param name="asm">The <c>Assembly</c> to browse.</param>
+ /// <returns>The migrations collection</returns>
+ public static Migration GetBeginMigration(Assembly asm)
+ {
+ foreach (Type t in asm.GetTypes())
+ {
+ MigrationBeginAttribute attrib = (MigrationBeginAttribute)
+ Attribute.GetCustomAttribute(t, typeof(MigrationBeginAttribute));
+ if (attrib != null && typeof(Migration).IsAssignableFrom(t))
+ {
+ return (Migration)Activator.CreateInstance(t);
+ }
+ }
+
+ return new NullMigration();
+ }
+
+ public static Migration GetEndMigration(Assembly asm)
+ {
+ foreach (Type t in asm.GetTypes())
+ {
+ MigrationEndAttribute attrib = (MigrationEndAttribute)
+ Attribute.GetCustomAttribute(t, typeof(MigrationEndAttribute));
+ if (attrib != null && typeof(Migration).IsAssignableFrom(t))
+ {
+ return (Migration)Activator.CreateInstance(t);
+ }
+ }
+
+ return new NullMigration();
+ }
+
+ /// <summary>
+ /// Return a new migrator initialized from an active record/NHibernate config file
+ /// </summary>
+ /// <param name="configFilePath">Full path to the Active Record Config File</param>
+ /// <returns>TransformationProvider</returns>
+ public static TransformationProvider CreateProvider(string arConfigPath)
+ {
+ System.Xml.XmlDocument source = new System.Xml.XmlDocument();
+ source.Load(arConfigPath);
+
+ //Pulling a connection string out of the ActiveRecord config file
+ string driver = (source.SelectSingleNode("//add[@key='connection.driver_class']/@value")).Value;
+ string connString = (source.SelectSingleNode("//add[@key='connection.connection_string']/@value")).Value;
+
+ return CreateProvider(driver, connString);
+ }
+
+ /// <summary>
+ /// Collect migrations in one <c>Assembly</c>.
+ /// </summary>
+ /// <param name="asm">The <c>Assembly</c> to browse.</param>
+ /// <returns>The migrations collection</returns>
+ public static ArrayList GetMigrationTypes(Assembly asm)
+ {
+ ArrayList migrations = new ArrayList();
+
+ foreach (Type t in asm.GetTypes())
+ {
+ MigrationAttribute attrib = (MigrationAttribute)
+ Attribute.GetCustomAttribute(t, typeof(MigrationAttribute));
+ if (attrib != null && typeof(Migration).IsAssignableFrom(t))
+ {
+ if (!attrib.Ignore)
+ {
+ migrations.Add(t);
+ }
+ }
+ }
+
+ migrations.Sort(new MigrationTypeComparer(true));
+ return migrations;
+ }
+
+ #endregion
+
+ #region Migration Methods
+ /// <summary>
/// Migrate the database to a specific version.
/// Runs all migration between the actual version and the
/// specified version.
@@ -220,6 +399,44 @@ }
/// <summary>
+ /// Migrate Up to the next version, if it exists
+ /// </summary>
+ public void MigrateUp()
+ {
+ GetReady();
+
+ if (this.CurrentVersion < this.LastVersion)
+ this.MigrateTo(this.CurrentVersion + 1);
+ else
+ this.MigrateTo(this.CurrentVersion);
+ }
+
+ /// <summary>
+ /// Migrate Down to the previous version, if it exists
+ /// </summary>
+ public void MigrateDown()
+ {
+ GetReady();
+
+ if (this.CurrentVersion > 0)
+ this.MigrateTo(this.CurrentVersion - 1);
+ else
+ this.MigrateTo(this.CurrentVersion);
+ }
+
+ /// <summary>
+ /// Run all migrations up to the latest.
+ /// </summary>
+ public void MigrateToLastVersion()
+ {
+ GetReady();
+ MigrateTo(LastVersion);
+ }
+
+ #endregion
+
+ #region Private Methods
+ /// <summary>
/// Start transactions for all databases
/// </summary>
private void BeginTransactions()
@@ -286,6 +503,8 @@ /// </summary>
private void Down()
{
+ GetReady();
+
Migration migration = GetMigration(CurrentVersion);
this._logger.MigrateDown(this.CurrentVersion - 1, GetMigrationDescription(migration.GetType()));
migration.Down();
@@ -293,215 +512,33 @@ }
/// <summary>
- /// Migrate Up to the next version, if it exists
+ ///
/// </summary>
- public void MigrateUp()
+ /// <returns></returns>
+ private void GetReady()
{
- if (this.CurrentVersion < this.LastVersion)
- this.MigrateTo(this.CurrentVersion + 1);
+ if (MigrationsTypes.Count < 1)
+ {
+ _logger.Exception("Migration assembly not provided.", new ArgumentNullException("migrationAssembly"));
+ throw new Exception("No migrations found");
+ }
+
+ // Enshure that the Schema Info table is created
+ GuidAttribute guid = AssemblyGuid;
+ if (guid != null)
+ _provider.CreateSchemaInfoTable(guid.Value);
else
- this.MigrateTo(this.CurrentVersion);
+ _provider.CreateSchemaInfoTable();
+
+ // Print a list of loaded Migrations
+ _logger.Trace("Loaded migrations:");
+ foreach (Type t in _migrationsTypes)
+ {
+ _logger.Trace("{0} {1}", GetMigrationVersion(t).ToString().PadLeft(5), GetMigrationDescription(t));
+ }
+
}
- /// <summary>
- /// Migrate Down to the previous version, if it exists
- /// </summary>
- public void MigrateDown()
- {
- if (this.CurrentVersion > 0)
- this.MigrateTo(this.CurrentVersion - 1);
- else
- this.MigrateTo(this.CurrentVersion);
- }
-
- /// <summary>
- /// Run all migrations up to the latest.
- /// </summary>
- public void MigrateToLastVersion()
- {
- MigrateTo(LastVersion);
- }
-
- /// <summary>
- /// Returns the last version of the migrations.
- /// </summary>
- public int LastVersion
- {
- get
- {
- if (_migrationsTypes.Count == 0)
- return 0;
- return GetMigrationVersion((Type)_migrationsTypes[_migrationsTypes.Count - 1]);
- }
- }
-
- public Dictionary<string, string> MigrationParameters
- {
- get
- {
- return this._parameters;
- }
- set
- {
- this._parameters = value;
- }
- }
-
- /// <summary>
- /// Returns the current version of the database.
- /// </summary>
- public int CurrentVersion
- {
- get
- {
- return _provider.CurrentVersion;
- }
- }
-
- /// <summary>
- /// Returns registered migration <see cref="System.Type">types</see>.
- /// </summary>
- public ArrayList MigrationsTypes
- {
- get { return _migrationsTypes; }
- }
-
- /// <summary>
- /// Get or set the event logger.
- /// </summary>
- public ILogger Logger
- {
- get { return _logger; }
- set { _logger = value; }
- }
-
- public string ConnectionString
- {
- get
- {
- if (_provider != null)
- return _provider.ConnectionString;
- return null;
- }
- }
-
- /// <summary>
- /// Returns the version of the migration
- /// <see cref="MigrationAttribute">MigrationAttribute</see>.
- /// </summary>
- /// <param name="t">Migration type.</param>
- /// <returns>Version number sepcified in the attribute</returns>
- public static int GetMigrationVersion(Type t)
- {
- MigrationAttribute attrib = (MigrationAttribute)
- Attribute.GetCustomAttribute(t, typeof(MigrationAttribute));
-
- return attrib.Version;
- }
-
- /// <summary>
- /// Returns the Description of the migration
- /// <see cref="MigrationAttribute">MigrationAttribute</see>.
- /// </summary>
- /// <param name="t">Migration type.</param>
- /// <returns>Long form Description sepcified in the attribute</returns>
- public static String GetMigrationDescription(Type t)
- {
- MigrationAttribute attrib = (MigrationAttribute)
- Attribute.GetCustomAttribute(t, typeof(MigrationAttribute));
-
- return attrib.Description == null ? t.Name : attrib.Description;
- }
-
- /// <summary>
- /// Check for duplicated version in migrations.
- /// </summary>
- /// <exception cref="CheckForDuplicatedVersion">CheckForDuplicatedVersion</exception>
- public void CheckForDuplicatedVersion()
- {
- ArrayList versions = new ArrayList();
-
- foreach (Type t in _migrationsTypes)
- {
- int version = GetMigrationVersion(t);
- if (versions.Contains(version))
- throw new DuplicatedVersionException(version);
-
- versions.Add(version);
- }
-
- // check that the versions of the migrations are contiguous from 1 to n:
- versions.Sort();
- if(versions.Count > 0)
- {
- int maxVersion = (int)versions[versions.Count - 1];
- if (versions.Count != maxVersion)
- throw new ArgumentOutOfRangeException(String.Format("There are {0} Migrations but the highest version is {1}. The Migrations are not contiguous.", versions.Count, maxVersion));
- }
- }
-
- /// <summary>
- /// Collect migrations in one <c>Assembly</c>.
- /// </summary>
- /// <param name="asm">The <c>Assembly</c> to browse.</param>
- /// <returns>The migrations collection</returns>
- public static ArrayList GetMigrationTypes(Assembly asm)
- {
- ArrayList migrations = new ArrayList();
-
- foreach (Type t in asm.GetTypes())
- {
- MigrationAttribute attrib = (MigrationAttribute)
- Attribute.GetCustomAttribute(t, typeof(MigrationAttribute));
- if (attrib != null && typeof(Migration).IsAssignableFrom(t))
- {
- if (!attrib.Ignore)
- {
- migrations.Add(t);
- }
- }
- }
-
- migrations.Sort(new MigrationTypeComparer(true));
- return migrations;
- }
-
- /// <summary>
- /// Collect migrations in one <c>Assembly</c>.
- /// </summary>
- /// <param name="asm">The <c>Assembly</c> to browse.</param>
- /// <returns>The migrations collection</returns>
- public static Migration GetBeginMigration(Assembly asm)
- {
-
- foreach (Type t in asm.GetTypes())
- {
- MigrationBeginAttribute attrib = (MigrationBeginAttribute)
- Attribute.GetCustomAttribute(t, typeof(MigrationBeginAttribute));
- if (attrib != null && typeof(Migration).IsAssignableFrom(t))
- {
- return (Migration)Activator.CreateInstance(t);
- }
- }
-
- return new NullMigration();
- }
-
- private Migration GetEndMigration(Assembly asm)
- {
- foreach (Type t in asm.GetTypes())
- {
- MigrationEndAttribute attrib = (MigrationEndAttribute)
- Attribute.GetCustomAttribute(t, typeof(MigrationEndAttribute));
- if (attrib != null && typeof(Migration).IsAssignableFrom(t))
- {
- return (Migration)Activator.CreateInstance(t);
- }
- }
-
- return new NullMigration();
- }
- #region Helper methods
private Type GetMigrationType(int version)
{
// since the list is sorted and contiguous getting an item is simple:
@@ -529,23 +566,35 @@ migration.Parameters = this._parameters;
return migration;
}
+ #endregion
+
+ #region Helper methods
/// <summary>
- /// Return a new migrator initialized from an active record/NHibernate config file
+ /// Check for duplicated version in migrations.
/// </summary>
- /// <param name="configFilePath">Full path to the Active Record Config File</param>
- /// <returns>TransformationProvider</returns>
- public static TransformationProvider CreateProvider(string arConfigPath)
+ /// <exception cref="CheckForDuplicatedVersion">CheckForDuplicatedVersion</exception>
+ public void CheckForDuplicatedVersion()
{
- System.Xml.XmlDocument source = new System.Xml.XmlDocument();
- source.Load(arConfigPath);
+ ArrayList versions = new ArrayList();
- //Pulling a connection string out of the ActiveRecord config file
- string driver = (source.SelectSingleNode("//add[@key='connection.driver_class']/@value")).Value;
- string connString = (source.SelectSingleNode("//add[@key='connection.connection_string']/@value")).Value;
+ foreach (Type t in _migrationsTypes)
+ {
+ int version = GetMigrationVersion(t);
+ if (versions.Contains(version))
+ throw new DuplicatedVersionException(version);
- return CreateProvider(driver, connString);
+ versions.Add(version);
+ }
+
+ // check that the versions of the migrations are contiguous from 1 to n:
+ versions.Sort();
+ if (versions.Count > 0)
+ {
+ int maxVersion = (int)versions[versions.Count - 1];
+ if (versions.Count != maxVersion)
+ throw new ArgumentOutOfRangeException(String.Format("There are {0} Migrations but the highest version is {1}. The Migrations are not contiguous.", versions.Count, maxVersion));
+ }
}
-
#endregion
}
}
|
@@ -1,4 +1,5 @@ - <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
@@ -19,12 +20,11 @@ </SccProvider>
<FileUpgradeFlags>
</FileUpgradeFlags>
- <OldToolsVersion>2.0</OldToolsVersion>
+ <OldToolsVersion>3.5</OldToolsVersion>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
- <TargetFrameworkSubset>
- </TargetFrameworkSubset>
+ <TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
|
@@ -1,3 +1,3 @@ - <?xml version="1.0"?>
+<?xml version="1.0"?>
<configuration>
-<startup><supportedRuntime version="v2.0.50727"/></startup></configuration>
+ <startup><supportedRuntime version="v2.0.50727"/></startup></configuration>
|
|
|
@@ -22,6 +22,7 @@ using System.Collections.Generic;
using NAnt.Core.Tasks;
using Migrator.Providers;
+using System.Diagnostics;
namespace Migrator.NAnt
{
@@ -31,6 +32,7 @@ [TaskName("migrate")]
public class MigrateTask : Task
{
+ private string _executable;
private string _provider;
private string _connectionString;
private string _configFile;
@@ -40,150 +42,88 @@ private bool _down = false;
private List<PropertyTask> _params = new List<PropertyTask>();
private List<ProviderTask> _providers = new List<ProviderTask>();
-
+
#region Attribute properties
+ [TaskAttribute("executable", Required = false)]
+ public string Executable
+ {
+ get { return _executable; }
+ set { _executable = value; }
+ }
+
[TaskAttribute("provider", Required = false)]
public string Provider
{
- get
- {
- return _provider;
- }
- set
- {
- _provider = value;
- }
-
+ get { return _provider; }
+ set { _provider = value; }
+
}
-
+
[TaskAttribute("connectionstring", Required = false)]
public string ConnectionString
{
- get
- {
- return _connectionString;
- }
- set
- {
- _connectionString = StringUtils.ConvertEmptyToNull(value);
- }
+ get { return _connectionString; }
+ set { _connectionString = StringUtils.ConvertEmptyToNull(value); }
}
[TaskAttribute("config-file", Required = false)]
[StringValidator(AllowEmpty = false)]
public string ConfigFile
{
- get
- {
- return _configFile;
- }
- set
- {
- _configFile = StringUtils.ConvertEmptyToNull(value);
- }
+ get { return _configFile; }
+ set { _configFile = StringUtils.ConvertEmptyToNull(value); }
}
-
+
[TaskAttribute("migrations", Required = true)]
public FileInfo MigrationsAssembly
{
- set
- {
- _migrationsAssembly = value;
- }
- get
- {
- return _migrationsAssembly;
- }
+ set { _migrationsAssembly = value; }
+ get { return _migrationsAssembly; }
}
[TaskAttribute("to", Required = false)]
public int To
{
- set
- {
- _to = value;
- }
- get
- {
- return _to;
- }
+ set { _to = value; }
+ get { return _to; }
}
[TaskAttribute("up", Required = false)]
[BooleanValidator()]
public bool Up
{
- get
- {
- return _up;
- }
- set
- {
- _up = value;
- }
+ get { return _up; }
+ set { _up = value; }
}
[TaskAttribute("down", Required = false)]
[BooleanValidator()]
public bool Down
{
- get
- {
- return _down;
- }
- set
- {
- _down = value;
- }
+ get { return _down; }
+ set { _down = value; }
}
- [BuildElementCollection("properties", "property", ElementType = typeof(PropertyTask), ProcessXml=true, Required=false)]
+ [BuildElementCollection("properties", "property", ElementType = typeof(PropertyTask), ProcessXml = true, Required = false)]
public List<PropertyTask> Params
{
- get
- {
- return _params;
- }
+ get { return _params; }
}
- [BuildElementCollection("providers", "provider", ElementType=typeof(ProviderTask), ProcessXml=true, Required=false)]
+ [BuildElementCollection("providers", "provider", ElementType = typeof(ProviderTask), ProcessXml = true, Required = false)]
public List<ProviderTask> Providers
{
- get
- {
- return _providers;
- }
+ get { return _providers; }
}
-
+
#endregion
-
+
protected override void ExecuteTask()
{
- Assembly asm = Assembly.LoadFrom(_migrationsAssembly.FullName);
-
- Migrator migrator = this.GetMigrator();
- migrator.Logger = new TaskLogger(this);
- migrator.MigrationParameters = PropertyTasksToGenericDisctionary(this._params);
-
- if (this.Up)
- {
- migrator.MigrateUp();
- }
- else if (this.Down)
- {
- migrator.MigrateDown();
- }
- else if (this._to > -1)
- {
- migrator.MigrateTo(this._to);
- }
- else
- {
- migrator.MigrateToLastVersion();
- }
+ Migrate();
}
- private Migrator GetMigrator()
+ private void Migrate()
{
// determin the default provider
TransformationProvider defaultProvider;
@@ -191,12 +131,12 @@ {
defaultProvider = Migrator.CreateProvider(this.ConfigFile);
}
- else
+ else
{
if (this.ConnectionString == null || this.Provider == null)
{
this.Log(Level.Error, "Not enough information to make a DB connection.");
- return null;
+ return;
}
defaultProvider = Migrator.CreateProvider(this.Provider, this.ConnectionString);
@@ -204,15 +144,106 @@
// load any additional providers:
Dictionary<string, TransformationProvider> additionalProviders = new Dictionary<string, TransformationProvider>();
- if (this.Providers != null && this.Providers.Count > 0)
+ if (this.Providers != null && this.Providers.Count > 0)
{
foreach (ProviderTask providerTask in this.Providers)
{
additionalProviders.Add(providerTask.ProviderName, Migrator.CreateProvider(providerTask.ConfigFile));
}
}
+ if (Executable != null)
+ {
+ CallMigratorExecutable(defaultProvider);
+ }
+ else
+ {
+ var migrator = new Migrator(defaultProvider, additionalProviders, Assembly.LoadFrom(this.MigrationsAssembly.FullName), new TaskLogger(this));
+ migrator.Logger = new TaskLogger(this);
+ migrator.MigrationParameters = PropertyTasksToGenericDisctionary(this._params);
- return new Migrator(defaultProvider, additionalProviders, Assembly.LoadFrom(this.MigrationsAssembly.FullName), new TaskLogger(this));
+ if (this.Up)
+ {
+ migrator.MigrateUp();
+ }
+ else if (this.Down)
+ {
+ migrator.MigrateDown();
+ }
+ else if (this._to > -1)
+ {
+ migrator.MigrateTo(this._to);
+ }
+ else
+ {
+ migrator.MigrateToLastVersion();
+ }
+ }
+ }
+
+ private int CallMigratorExecutable(TransformationProvider defaultProvider)
+ {
+ // Migrator.Console.exe SqlServer "Data Source=localhost;Initial Catalog=Nexport;User Id=;Password=;Integrated Security=True" Nexport.Models.dll -up
+
+ // Defaults to SqlServer provider
+ string provider = defaultProvider is MySqlTransformationProvider ? "MySql" :
+ defaultProvider is PostgreSQLTransformationProvider ? "Postgre" :
+ "SqlServer";
+ String databaseConnection = defaultProvider.ConnectionString;
+
+ string assemblyLocation = this.MigrationsAssembly.FullName;
+
+ string command = "";
+ if (this.Up)
+ command = "-up";
+ else if (this.Down)
+ command = "-down";
+ else if (this._to > -1)
+ command = "-to="+this._to;
+ else
+ command = "";
+
+ string exeArgs = String.Format(" {0} \"{1}\" \"{2}\" {3}", provider, databaseConnection, assemblyLocation, command);
+
+ ProcessStartInfo processStartInfo = new ProcessStartInfo();
+ Process migratorProcess = null;
+ int exitCode = 0;
+ Console.Out.WriteLine("");
+ try
+ {
+ processStartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
+ processStartInfo.FileName = Executable;
+ processStartInfo.Arguments = exeArgs;
+ processStartInfo.ErrorDialog = false;
+ processStartInfo.CreateNoWindow = true;
+ processStartInfo.UseShellExecute = false;
+ processStartInfo.RedirectStandardError = true;
+ processStartInfo.RedirectStandardOutput = true;
+
+ migratorProcess = Process.Start(processStartInfo);
+ var outReader = migratorProcess.StandardOutput;
+ var errorReader = migratorProcess.StandardError;
+ while (!migratorProcess.HasExited)
+ {
+ var outLine = outReader.ReadToEnd();
+ Console.Out.Write(outLine);
+ var error = errorReader.ReadToEnd();
+ if(error != null && error.Length > 0)
+ Console.Out.Write("*** {0}", error);
+ }
+ migratorProcess.WaitForExit();
+ Console.Out.WriteLine("Process error code : " + migratorProcess.ExitCode);
+ exitCode = migratorProcess.ExitCode;
+ }
+ finally
+ {
+ if(migratorProcess != null)
+ migratorProcess.Close();
+ }
+ return exitCode;
+ }
+
+ public void OutputRecievedHandler (object sender, DataReceivedEventArgs e){
+ Console.Out.Write(e.Data);
}
private TransformationProvider GetProvider(ProviderTask providerTask)
@@ -224,12 +255,13 @@ {
Dictionary<string, string> result = new Dictionary<string, string>();
- foreach (PropertyTask prop in propertyTasks) {
+ foreach (PropertyTask prop in propertyTasks)
+ {
// parse the ${stuff} out of the value
prop.Value = Project.ExpandProperties(prop.Value, Location);
result[prop.PropertyName] = prop.Value;
}
-
+
return result;
}
}
|
Change 1 of 4
Show Entire File
app/nant/Migrator.NAnt.csproj
Stacked
renamed from app/nant/Migrator.NAnt_2005.csproj
|
||
---|---|---|
@@ -1,4 +1,5 @@ - <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
@@ -19,9 +20,26 @@ </SccProvider>
<FileUpgradeFlags>
</FileUpgradeFlags>
- <OldToolsVersion>2.0</OldToolsVersion>
+ <OldToolsVersion>3.5</OldToolsVersion>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
+ <TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
+ <TargetFrameworkProfile />
+ <PublishUrl>publish\</PublishUrl>
+ <Install>true</Install>
+ <InstallFrom>Disk</InstallFrom>
+ <UpdateEnabled>false</UpdateEnabled>
+ <UpdateMode>Foreground</UpdateMode>
+ <UpdateInterval>7</UpdateInterval>
+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>
+ <UpdatePeriodically>false</UpdatePeriodically>
+ <UpdateRequired>false</UpdateRequired>
+ <MapFileExtensions>true</MapFileExtensions>
+ <ApplicationRevision>0</ApplicationRevision>
+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>
+ <IsWebBootstrapper>false</IsWebBootstrapper>
+ <UseApplicationTrust>false</UseApplicationTrust>
+ <BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -44,7 +62,7 @@ <Reference Include="log4net, Version=1.2.9.0, Culture=neutral, PublicKeyToken=b32731d11ce58905">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\log4net.dll</HintPath>
- <Private>False</Private>
+ <Private>True</Private>
</Reference>
<Reference Include="NAnt.Core, Version=0.85.2344.0, Culture=neutral">
<SpecificVersion>False</SpecificVersion>
@@ -65,5 +83,22 @@ <Name>Migrator</Name>
</ProjectReference>
</ItemGroup>
+ <ItemGroup>
+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">
+ <Visible>False</Visible>
+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
+ <Install>false</Install>
+ </BootstrapperPackage>
+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
+ <Visible>False</Visible>
+ <ProductName>.NET Framework 3.5 SP1</ProductName>
+ <Install>true</Install>
+ </BootstrapperPackage>
+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
+ <Visible>False</Visible>
+ <ProductName>Windows Installer 3.1</ProductName>
+ <Install>true</Install>
+ </BootstrapperPackage>
+ </ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>
\ No newline at end of file |
@@ -8,8 +8,6 @@ <property name="defines" value="MONO2" if="${framework::get-target-framework() == 'mono-2.0'}" />
<target name="build" description="Builds the app" >
- <msbuild project="migrator_2008.sln" >
- </msbuild>
<copy todir="build" >
<fileset basedir="app\core\bin\Migrator\Debug" >
@@ -19,7 +17,12 @@
<copy todir="build" >
<fileset basedir="app\nant\bin\Migrator.NAnt\Debug" >
- <include name="Migrator.NantTasks.dll"/>
+ <include name="*.dll"/>
+ </fileset>
+ </copy>
+ <copy todir="build" >
+ <fileset basedir="app\console\bin\Migrator.Console\Debug" >
+ <include name="*.*"/>
</fileset>
</copy>
|
@@ -1,12 +1,12 @@ - Microsoft Visual Studio Solution File, Format Version 10.00
-# Visual Studio 2008
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Migrator.Console_2005", "app\console\Migrator.Console_2005.csproj", "{FBE3A83A-D0F8-4D72-AF8D-9EF772569A31}"
+Microsoft Visual Studio Solution File, Format Version 11.00
+# Visual Studio 2010
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Migrator.Console", "app\console\Migrator.Console.csproj", "{FBE3A83A-D0F8-4D72-AF8D-9EF772569A31}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Migrator.Tests_2005", "test\Migrator.Tests_2005.csproj", "{882B6A93-67B8-45BF-8636-5796B1B1CBF8}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Migrator.Tests", "test\Migrator.Tests.csproj", "{882B6A93-67B8-45BF-8636-5796B1B1CBF8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Migrator", "app\core\Migrator.csproj", "{1FEE70A4-AAD7-4C60-BE60-3F7DC03A8C4D}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Migrator.NAnt_2005", "app\nant\Migrator.NAnt_2005.csproj", "{CDD39DB7-C9C0-4ECA-AD36-1B4D0BF59101}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Migrator.NAnt", "app\nant\Migrator.NAnt.csproj", "{CDD39DB7-C9C0-4ECA-AD36-1B4D0BF59101}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
Change 1 of 2
Show Entire File
test/Migrator.Tests.csproj
Stacked
renamed from test/Migrator.Tests_2005.csproj
|
||
---|---|---|
@@ -1,4 +1,5 @@ - <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
@@ -19,9 +20,11 @@ </SccProvider>
<FileUpgradeFlags>
</FileUpgradeFlags>
- <OldToolsVersion>2.0</OldToolsVersion>
+ <OldToolsVersion>3.5</OldToolsVersion>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
+ <TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
|
Loading...