/// <summary>
        /// When overridden in a derived class, executes the task.
        /// </summary>
        /// <returns>
        /// true if the task successfully executed; otherwise, false.
        /// </returns>
        public override bool Execute()
        {
            //
            // Load DbPlatform
            Type platformType = Type.GetType(DbPlatformType);
            IDbPlatform dbPlatform = (IDbPlatform)Activator.CreateInstance(platformType, null);

            DbMigrationVersionInfoManager migrationVersionInfoManager = 
                new DbMigrationVersionInfoManager(dbPlatform, new DbCommandExecutionStrategy(), "SchemaInfo");
            long currentMigrationVersion = 
                MigrationVersionInfoManagerUtil.GetCurrentMigrationVersion(migrationVersionInfoManager, dbPlatform, ConnectionString);
            if(targetVersion.HasValue && targetVersion.Value < currentMigrationVersion && !AllowDowngrade)
            {
                if(BuildEngine != null)
                    Log.LogError("Could not downgrade from version {0} to version {1}. Review your migration definition or " +
                        "set 'AllowDowngrade' property to 'true'.", currentMigrationVersion, targetVersion.Value);
                return false;
            } // if

            IMigrationService migrationService = new MigrationService(dbPlatform,
                migrationVersionInfoManager,
                new DbMigrationScriptExecutive(new DbCommandExecutionStrategy()),
                new FileSystemNativeSqlResourceProvider(Directory.GetCurrentDirectory()));
            migrationService.Migrated += delegate(object sender, MigrationEventArgs args)
                {
                    if(BuildEngine != null)
                        Log.LogMessage(MessageImportance.Normal, "Migrated to version {0}", args.Version);
                };
            
            using(StreamReader streamReader = new StreamReader(MigrationDefinitionPath))
                migrationService.Migrate(ConnectionString, TargetVersion, streamReader);
            
            return true;
        }
        /// <summary>
        /// When overridden in a derived class, executes the task.
        /// </summary>
        /// <returns>
        /// true if the task successfully executed; otherwise, false.
        /// </returns>
        public override bool Execute()
        {
            //
            // Load IDbPlatforms
            Type sourcePlatformType = Type.GetType(SourceDbPlatformType);
            Type targetPlatformType = String.IsNullOrEmpty(TargetDbPlatformType) ?
                sourcePlatformType :
                Type.GetType(TargetDbPlatformType);

            IDbPlatform sourceDbPlatform = (IDbPlatform)Activator.CreateInstance(sourcePlatformType, null);
            IDbPlatform targetDbPlatform = (IDbPlatform)Activator.CreateInstance(targetPlatformType, null);

            IMigrationVersionInfoManager sourceDbMigrationVersionInfoManager =
                new DbMigrationVersionInfoManager(sourceDbPlatform, new DbCommandExecutionStrategy(), "SchemaInfo");
            IMigrationVersionInfoManager targetDbMigrationVersionInfoManager =
                new DbMigrationVersionInfoManager(targetDbPlatform, new DbCommandExecutionStrategy(), "SchemaInfo");
            
            //
            // Source database version
            long sourceMigrationVersion = MigrationVersionInfoManagerUtil.GetCurrentMigrationVersion(
                sourceDbMigrationVersionInfoManager, sourceDbPlatform, SourceConnectionString);
            long targetMigrationVersion = MigrationVersionInfoManagerUtil.GetCurrentMigrationVersion(
                targetDbMigrationVersionInfoManager, targetDbPlatform, TargetConnectionString);

            if(targetMigrationVersion > sourceMigrationVersion && !AllowDowngrade)
            {
                if(BuildEngine != null)
                    Log.LogError("Could not downgrade from version {0} to version {1}. Review your migration definition or " +
                        "set 'AllowDowngrade' property to 'true'.", sourceMigrationVersion, targetMigrationVersion);
                return false;
            } // if

            IMigrationService migrationService =
                new MigrationService(targetDbPlatform, targetDbMigrationVersionInfoManager,
                    new DbMigrationScriptExecutive(new DbCommandExecutionStrategy()),
                    new FileSystemNativeSqlResourceProvider(Directory.GetCurrentDirectory()));
            migrationService.Migrated += delegate(object sender, MigrationEventArgs args)
                {
                    if(BuildEngine != null)
                        Log.LogMessage(MessageImportance.Normal, "Migrated to version {0}", args.Version);
                };

            using(StreamReader streamReader = new StreamReader(MigrationDefinitionPath))
                migrationService.Migrate(TargetConnectionString, sourceMigrationVersion, streamReader);

            return true;
        }
Ejemplo n.º 3
0
        static int Main(string[] args)
        {
            System.Console.WriteLine(Resources.CopyrightInformation, 
                Assembly.GetExecutingAssembly().GetName().Version.ToString(4),
                ApplicationInfo.Milestone);

            if(args.Length == 0 || (args.Length == 1 && args[0] == "/?"))
            {
                System.Console.WriteLine();
                System.Console.WriteLine(Resources.UsageInformation);

                return 1;
            } // if

            serviceProvider = new ServiceProvider();
            serviceProvider.RegisterService(BuildDbPlatformRegistry());
            serviceProvider.RegisterService<IMigrationService>(delegate(IServiceProvider sp)
                {
                    MigrationService migrationService = new MigrationService(
                        sp.GetService<IDbPlatform>(),
                        sp.GetService<IMigrationVersionInfoManager>(),
                        sp.GetService<IMigrationScriptExecutive>(),
                        sp.GetService<INativeSqlResourceProvider>());

                    migrationService.Migrating += MigrationServiceMigrating;
                    migrationService.Migrated += MigrationServiceMigrated;
                
                    return migrationService;
                });
            serviceProvider.RegisterService<IMigrationVersionInfoManager>(delegate(IServiceProvider sp)
                {
                    return new DbMigrationVersionInfoManager(
                        sp.GetService<IDbPlatform>(), 
                        sp.GetService<IDbCommandExecutionStrategy>(),
                        "SchemaInfo");
                });
            serviceProvider.RegisterService<IMigrationScriptExecutive>(delegate(IServiceProvider sp)
                {
                    return new DbMigrationScriptExecutive(
                        sp.GetService<IDbCommandExecutionStrategy>());
                });
            serviceProvider.RegisterService(new DeploymentService());
            serviceProvider.RegisterService(new ReverseEngineeringService());
            serviceProvider.RegisterService(new UtcDateTimeTimestampProvider());
            serviceProvider.RegisterService(new FileSystemNativeSqlResourceProvider(Directory.GetCurrentDirectory()));
            
            //
            // Prepare Migration Command Registry...
            MigrationCommandRegistry migrationCommandRegistry = new MigrationCommandRegistry();
            migrationCommandRegistry.RegisterAssembly(typeof(Program).Assembly);

            try
            {
                //
                // Parse parameters
                MigrationParametersParser parametersParser = new MigrationParametersParser();
                parameters = parametersParser.ParseMigrationParameters(args);

                //
                // If we have an output file name specified, use special IDbCommandExecutionStrategy
                if(!string.IsNullOrEmpty(parameters.OutputFileName))
                    serviceProvider.RegisterService(new FileDbCommandExecutionStrategy(parameters.OutputFileName));
                else
                    serviceProvider.RegisterService(new DbCommandExecutionStrategy());

                //
                // ...and execute whatever command we need
                IMigrationCommand migrationCommand = migrationCommandRegistry.ResolveCommand(parameters.Command);
                migrationCommand.ServiceProvider = serviceProvider;
                
                migrationCommand.Execute(parameters);
            } // try

            catch(MdlParserException e)
            {
                using(new ConsoleStylingScope(ConsoleColor.Red))
                    System.Console.WriteLine(System.Environment.NewLine + "Compilation Exception: {0}", e.Message);

                return 2;
            } // catch

            catch(MdlCompilerException e)
            {
                using(new ConsoleStylingScope(ConsoleColor.Red))
                    System.Console.WriteLine(System.Environment.NewLine + "Compilation Exception: {0} ({1})", e.Message,
                        e.Location);

                return 3;
            } // catch

            catch(MigrationException e)
            {
                using(new ConsoleStylingScope(ConsoleColor.Red))
                    System.Console.WriteLine(System.Environment.NewLine + "Migration Exception: {0} ({1})", e.Message, e.SqlStatement);

                return 4;
            } // catch

            catch(DbPlatformException e)
            {
                IDbPlatform dbPlatform = serviceProvider.GetService<DbPlatformRegistry>().ResolvePlatform(parameters.PlatformAlias);
                using(new ConsoleStylingScope(ConsoleColor.Red))
                    System.Console.WriteLine(System.Environment.NewLine + "{0} Exception: {1}", 
                        serviceProvider.GetService<DbPlatformRegistry>().GetPlatformName(dbPlatform), e.Message + e.StackTrace.ToString());
                
                return 5;
            } // catch

            catch(DbException e)
            {
                IDbPlatform dbPlatform = serviceProvider.GetService<DbPlatformRegistry>().ResolvePlatform(parameters.PlatformAlias);
                using (new ConsoleStylingScope(ConsoleColor.Red))
                    System.Console.WriteLine(System.Environment.NewLine + "{0} Exception: {1}",
                        serviceProvider.GetService<DbPlatformRegistry>().GetPlatformName(dbPlatform), e.Message + e.StackTrace.ToString());

                return 6;
            } // catch

            catch(Exception e)
            {
                using(new ConsoleStylingScope(ConsoleColor.Red))
                    System.Console.WriteLine(System.Environment.NewLine + "Unknown Exception: {0}", e.ToString());

                return 100;
            } // catch

            return 0;
        }