public DirectToDbApplier(
            QueryExecuter queryExecuter,
            DatabaseSchemaVersionManager schemaVersionManager,
            QueryStatementSplitter splitter,
            IDbmsSyntax dbmsSyntax,
            string changeLogTableName,
            TextWriter infoTextWriter)
        {
            if (queryExecuter == null)
                throw new ArgumentNullException("queryExecuter");

            if (schemaVersionManager == null)
                throw new ArgumentNullException("schemaVersionManager");

            if (splitter == null)
                throw new ArgumentNullException("splitter");

            if (infoTextWriter == null)
                throw new ArgumentNullException("infoTextWriter");

            this.queryExecuter = queryExecuter;
            this.schemaVersionManager = schemaVersionManager;
            this.splitter = splitter;
            this.dbmsSyntax = dbmsSyntax;
            this.changeLogTableName = changeLogTableName;
            this.infoTextWriter = infoTextWriter;
        }
 public void IfCurrentDbVersionIsSpecifiedShouldGenerateAppliedChangesUpToAndIncludingCurrentDbVersion()
 {
     List<int> appliedChanges = new DatabaseSchemaVersionManager(null, "Main", 10).GetAppliedChangeNumbers();
     Assert.AreEqual(10, appliedChanges.Count);
     Assert.AreEqual(1, appliedChanges[0]);
     Assert.AreEqual(10, appliedChanges[9]);
 }
Exemple #3
0
        protected void SetUp()
        {
            var factory = new DbmsFactory(Dbms, ConnectionString);
            var executer = new QueryExecuter(factory);

            databaseSchemaVersion = new DatabaseSchemaVersionManager(executer, factory.CreateDbmsSyntax(), TableName);
        }
Exemple #4
0
        public void SetUp()
        {
            this.changeLogTableName = "changelog";

            this.expectedResultSet = new Mock <IDataReader>();

            var connection = new Mock <IDbConnection>();

            var factory = new Mock <DbmsFactory>("mssql", string.Empty);

            factory.Setup(f => f.CreateConnection()).Returns(connection.Object);

            this.queryExecuter = new Mock <QueryExecuter>(factory.Object);

            this.syntax = new Mock <IDbmsSyntax>();

            this.queryExecuter
            .Setup(e => e.ExecuteQuery(It.IsAny <string>()))
            .Returns(this.expectedResultSet.Object);

            var checkForChangeLogDataReader = new Mock <IDataReader>();

            checkForChangeLogDataReader
            .Setup(r => r.Read())
            .Returns(true);

            this.queryExecuter
            .Setup(e => e.ExecuteQuery(It.Is <string>(v => v.Contains("INFORMATION_SCHEMA")), It.Is <string>(s => s.Equals(changeLogTableName))))
            .Returns(() => checkForChangeLogDataReader.Object);

            this.schemaVersionManager = new DatabaseSchemaVersionManager(this.queryExecuter.Object, this.syntax.Object, changeLogTableName);
        }
        protected override void ProcessRecord()
        {
            var configurationFile = ToAbsolutePath(ConfigurationFile);
            _deltasDirectory = ToAbsolutePath(DeltasDirectory);

            if (!string.IsNullOrEmpty(configurationFile) && File.Exists(configurationFile))
            {
                _config = new XmlConfiguration(configurationFile);
                if(string.IsNullOrEmpty(DatabaseType))
                    DatabaseType = _config.DbType;
                if(string.IsNullOrEmpty(ConnectionString))
                    ConnectionString = _config.DbConnectionString;
                if(string.IsNullOrEmpty(DeltaSet))
                    DeltaSet = _config.DbDeltaSet;
                if(string.IsNullOrEmpty(TableName))
                    TableName = _config.TableName;
                if(!CurrentDbVersion.HasValue)
                    CurrentDbVersion = _config.CurrentDbVersion;
            }

            if(string.IsNullOrEmpty(ConnectionString))
            {
                throw new InvalidDataException(
                    "Missing connection string. It must either be in the config file or passed as a parameter");
            }

            _dbmsFactory = new DbmsFactory(DatabaseType, ConnectionString, ForDirectExecution);
            _databaseSchemaVersion = new DatabaseSchemaVersionManager(_dbmsFactory,
                                                                     DeltaSet,
                                                                     CurrentDbVersion,
                                                                     TableName);
        }
        public void SetUp() 
        {
            this.changeLogTableName = "changelog";

            this.expectedResultSet = new Mock<IDataReader>();

            var connection = new Mock<IDbConnection>();

            var factory = new Mock<DbmsFactory>("mssql", string.Empty);
            factory.Setup(f => f.CreateConnection()).Returns(connection.Object);
        
            this.queryExecuter = new Mock<QueryExecuter>(factory.Object);

            this.syntax = new Mock<IDbmsSyntax>();

            this.queryExecuter
                .Setup(e => e.ExecuteQuery(It.IsAny<string>()))
                .Returns(this.expectedResultSet.Object);

            var checkForChangeLogDataReader = new Mock<IDataReader>();
            checkForChangeLogDataReader
                .Setup(r => r.Read())
                .Returns(true);

            this.queryExecuter
                .Setup(e => e.ExecuteQuery(It.Is<string>(v => v.Contains("INFORMATION_SCHEMA")), It.Is<string>(s => s.Equals(changeLogTableName))))
                .Returns(() => checkForChangeLogDataReader.Object);

            this.schemaVersionManager = new DatabaseSchemaVersionManager(this.queryExecuter.Object, this.syntax.Object, changeLogTableName);
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            var infoTextWriter = new LambdaTextWriter(WriteVerbose);

            List<ChangeScript> allChangeScripts = new DirectoryScanner(infoTextWriter, Encoding.UTF8, new DirectoryInfo(this.deltasDirectory))
                .GetChangeScripts();
            
            var repository = new ChangeScriptRepository(allChangeScripts);
            var changeScripts = repository.GetAvailableChangeScripts();

            DbmsFactory factory = new DbmsFactory(this.DatabaseType, this.ConnectionString);
            var queryExecuter = new QueryExecuter(factory);

            var schemaManager = new DatabaseSchemaVersionManager(queryExecuter, factory.CreateDbmsSyntax(), this.TableName);

            var appliedChanges = schemaManager.GetAppliedChanges();
            var notAppliedChangeScripts = changeScripts.Where(c => appliedChanges.All(a => a.ScriptNumber != c.ScriptNumber));

            var descriptionPrettyPrinter = new DescriptionPrettyPrinter();

            var objects = notAppliedChangeScripts
                .Select(script => new
                    {
                        Id = script.ScriptNumber,
                        Description = descriptionPrettyPrinter.Format(script.ScriptName),
                        File = script.FileInfo
                    });

            this.WriteObject(objects, true);
        }
 public DirectToDbApplierAccessor(
     QueryExecuter queryExecuter, 
     DatabaseSchemaVersionManager schemaVersionManager, 
     QueryStatementSplitter splitter, 
     TextWriter infoTextWriter) 
     : base(queryExecuter, schemaVersionManager, splitter, infoTextWriter)
 {
 }
        public void IfCurrentDbVersionIsSpecifiedShouldGenerateAppliedChangesUpToAndIncludingCurrentDbVersion()
        {
            List <Int64> appliedChanges = new DatabaseSchemaVersionManager(null, "Main", 10).GetAppliedChangeNumbers();

            Assert.AreEqual(10, appliedChanges.Count);
            Assert.AreEqual(1, appliedChanges[0]);
            Assert.AreEqual(10, appliedChanges[9]);
        }
Exemple #10
0
        public virtual void TestCanSetChangeLogTableName()
        {
            const string expectedTableName   = "FooTable";
            const string expectedChangeOwner = "FooOwner";
            DatabaseSchemaVersionManager databaseSchemaVersionManager = new DatabaseSchemaVersionManager(new DbmsFactory(Dbms, ConnectionString), DeltaSet, null, expectedTableName, expectedChangeOwner);

            Assert.AreEqual(expectedTableName, databaseSchemaVersionManager.TableName);
        }
Exemple #11
0
 public Controller(DatabaseSchemaVersionManager schemaManager,
                   ChangeScriptRepository changeScriptRepository,
                   ChangeScriptExecuter changeScriptExecuter)
 {
     this.schemaManager = schemaManager;
     this.changeScriptRepository = changeScriptRepository;
     this.changeScriptExecuter = changeScriptExecuter;
 }
Exemple #12
0
        protected override void SetUp()
        {
            var factory  = new DbmsFactory(Dbms, ConnectionString, postGreDataDll);
            var executer = new QueryExecuter(factory);

            this.syntax           = factory.CreateDbmsSyntax();
            databaseSchemaVersion = new DatabaseSchemaVersionManager(executer, this.syntax, TableName);
        }
        protected override void SetUp()
        {
            var factory = new DbmsFactory(Dbms, firebirdConnectionString, firebirdSqlDataFirebirdClient);
            var executer = new QueryExecuter(factory);

            this.syntax = factory.CreateDbmsSyntax();

            databaseSchemaVersion = new DatabaseSchemaVersionManager(executer, this.syntax, TableName);
        }
Exemple #14
0
        public void ShouldGenerateSqlStringContainingSpecifiedChangelogTableNameOnDelete()
        {
            var schemaVersionManagerWithDifferentTableName =
                new DatabaseSchemaVersionManager(this.queryExecuter.Object, this.syntax.Object, "user_specified_changelog");

            string updateSql = schemaVersionManagerWithDifferentTableName.GetChangelogDeleteSql(this.script);

            Assert.IsTrue(updateSql.StartsWith("DELETE FROM user_specified_changelog "));
        }
 public DirectToDbApplierAccessor(
     QueryExecuter queryExecuter, 
     DatabaseSchemaVersionManager schemaVersionManager, 
     QueryStatementSplitter splitter, 
     IDbmsSyntax dbmsSyntax,
     string changeLogTableName,
     TextWriter infoTextWriter)
     : base(queryExecuter, schemaVersionManager, splitter, dbmsSyntax, changeLogTableName, infoTextWriter)
 {
 }
        protected override void SetUp()
        {
            var factory = new DbmsFactory(Dbms, ConnectionString, mySqlDataDll);
            var executer = new QueryExecuter(factory);

            this.syntax = factory.CreateDbmsSyntax();
            syntax.SetDefaultDatabaseName(connectionString);

            databaseSchemaVersion = new DatabaseSchemaVersionManager(executer, this.syntax, TableName);
        }
Exemple #17
0
        public void ShouldGetAppliedChangesFromSpecifiedChangelogTableName()
        {
            changeLogTableName = "user_specified_changelog";

            var schemaVersionManagerWithDifferentTableName =
                new DatabaseSchemaVersionManager(this.queryExecuter.Object, this.syntax.Object, changeLogTableName);

            schemaVersionManagerWithDifferentTableName.GetAppliedChanges();

            this.queryExecuter.Verify(e => e.ExecuteQuery(It.Is <string>(s => s.StartsWith("SELECT change_number FROM user_specified_changelog "))));
        }
 	public ToPrintStreamDeployer(DatabaseSchemaVersionManager schemaManager, DirectoryInfo dir,
                                  TextWriter outputPrintStream,
                                  IDbmsSyntax dbmsSyntax, bool useTransaction, TextWriter undoOutputPrintStream)
     {
         this.schemaManager = schemaManager;
         this.dir = dir;
         doOutputPrintStream = outputPrintStream;
         this.dbmsSyntax = dbmsSyntax;
     	this.useTransaction = useTransaction;
     	this.undoOutputPrintStream = undoOutputPrintStream;
     }
Exemple #19
0
        public void TestShouldHandleCreatingChangeLogTableWithSchema()
        {
            this.EnsureTableDoesNotExist("log.Installs");

            var factory  = new DbmsFactory(this.Dbms, this.ConnectionString);
            var executer = new QueryExecuter(factory);
            var databaseSchemaManager = new DatabaseSchemaVersionManager(executer, factory.CreateDbmsSyntax(), "log.Installs", true);

            // Table should be created when attempted now; if table does not exist.
            databaseSchemaManager.GetAppliedChanges();

            this.AssertTableExists("log.Installs");
        }
        public void SetUp()
        {
            var dbmsFactory = new DbmsFactory(Dbms, ConnectionString);
            var queryExecuter = new QueryExecuter(dbmsFactory);
            var dbmsSyntax = dbmsFactory.CreateDbmsSyntax();

            var schemaVersionManager = new DatabaseSchemaVersionManager(queryExecuter, dbmsSyntax, ChangeLogTableName);
            this.sqlCmdApplier = new SqlCmdApplier(ConnectionString, schemaVersionManager, dbmsSyntax, ChangeLogTableName, System.Console.Out);
            

            // Remove any existing changelog and customers test table.
            this.EnsureTableDoesNotExist(ChangeLogTableName);
            this.EnsureTableDoesNotExist("Customer");
        }
        public void TestCanGenerateVersionCheck()
        {
            databaseSchemaVersion = new DatabaseSchemaVersionManager(new DbmsFactory(DBMS, CONNECTION_STRING), "Main", 5);
            Assert.AreEqual(@"DECLARE @currentDatabaseVersion INTEGER, @errMsg VARCHAR(1000)
            SELECT @currentDatabaseVersion = MAX(ChangeNumber) FROM changelog WHERE Project = 'Main'
            IF (@currentDatabaseVersion <> 5)
            BEGIN
            SET @errMsg = 'Error: current database version on Project <Main> is not 5, but ' + CONVERT(VARCHAR, @currentDatabaseVersion)
            RAISERROR (@errMsg, 16, 1)
            END

            GO

            ", databaseSchemaVersion.GenerateVersionCheck());
        }
        public void TestCanGenerateVersionCheck()
        {
            databaseSchemaVersion = new DatabaseSchemaVersionManager(new DbmsFactory(DBMS, CONNECTION_STRING), "Main", 5);
            Assert.AreEqual(@"DECLARE @currentDatabaseVersion INTEGER, @errMsg VARCHAR(1000)
SELECT @currentDatabaseVersion = MAX(ChangeNumber) FROM changelog WHERE Project = 'Main'
IF (@currentDatabaseVersion <> 5)
BEGIN
    SET @errMsg = 'Error: current database version on Project <Main> is not 5, but ' + CONVERT(VARCHAR, @currentDatabaseVersion)
    RAISERROR (@errMsg, 16, 1)
END

GO

", databaseSchemaVersion.GenerateVersionCheck());
        }
        public PowershellPrintStreamDeployer(DatabaseSchemaVersionManager schemaManager, ChangeScriptRepository repository,
                                             TextWriter outputPrintStream,
                                             IDbmsSyntax dbmsSyntax, bool useTransaction,
                                             TextWriter undoOutputPrintStream,
                                             TextWriter infoPrintStream)
        {   
            this.schemaManager = schemaManager;
            this.doOutputPrintStream = outputPrintStream;
            this.dbmsSyntax = dbmsSyntax;
            this.useTransaction = useTransaction;
            this.undoOutputPrintStream = undoOutputPrintStream;
            this.infoPrintStream = infoPrintStream;
            this.repository = repository;

        }
        public void TestShouldHandleCreatingChangeLogTableWithSchema()
        {
            this.EnsureTableDoesNotExist("log.Installs");

            var factory  = new DbmsFactory(this.Dbms, this.ConnectionString);
            var executer = new QueryExecuter(factory);
            var databaseSchemaManager = new DatabaseSchemaVersionManager(executer, factory.CreateDbmsSyntax(), "log.Installs");

            var applier = new DirectToDbApplier(executer, databaseSchemaManager, new QueryStatementSplitter(),
                                                factory.CreateDbmsSyntax(), "log.Installs", new NullWriter());

            applier.Apply(new ChangeScript[] {}, createChangeLogTable: true);

            this.AssertTableExists("log.Installs");
        }
Exemple #25
0
        public void SetUp()
        {
            this.changeLogTableName = "ChangeLog";

            this.expectedResultSet = new Mock <IDataReader>();

            var connection = new Mock <IDbConnection>();

            var factory = new Mock <DbmsFactory>("mssql", string.Empty, null);

            factory.Setup(f => f.CreateConnection()).Returns(connection.Object);

            this.queryExecuter = new Mock <QueryExecuter>(factory.Object);

            this.syntax = new Mock <IDbmsSyntax>();
            this.syntax.Setup(s => s.TableExists(It.IsAny <string>()))
            .Returns <string>(t => string.Format(CultureInfo.InvariantCulture,
                                                 @"SELECT table_schema 
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_NAME = '{0}'", t));

            this.executedQueries = new List <string>();

            var checkForChangeLogDataReader = new Mock <IDataReader>();

            checkForChangeLogDataReader
            .Setup(r => r.Read())
            .Returns(true);

            this.queryExecuter
            .Setup(e => e.ExecuteQuery(It.Is <string>(v => v.Contains("INFORMATION_SCHEMA"))))
            .Returns(() => checkForChangeLogDataReader.Object);

            this.queryExecuter
            .Setup(e => e.ExecuteQuery(It.Is <string>(v => !v.Contains("INFORMATION_SCHEMA")), It.IsAny <object[]>()))
            .Returns(this.expectedResultSet.Object)
            .Callback <string, object[]>((query, args) => this.executedQueries.Add(query));

            this.schemaVersionManager = new DatabaseSchemaVersionManager(this.queryExecuter.Object, this.syntax.Object, changeLogTableName);
        }
Exemple #26
0
        public static void Main(string[] args)
        {
            try
            {
                var commandLineArgumentsParser = new CommandLineArgumentsParser();
                ParsedArguments parsedArguments = commandLineArgumentsParser.ParseArgs(args);

                var printScreenFactory = new PrintScreenFactory();

                var config = new CommandLineArgsConfiguration(parsedArguments);
                var factory = new DbmsFactory(config.DbType, config.DbConnectionString);
                var databaseSchemaVersion = new DatabaseSchemaVersionManager(factory, config.DbDeltaSet, config.CurrentDbVersion, config.TableName, config.ChangeOwner);

                var directoryInfo = new DirectoryInfo(parsedArguments.GetScriptFilesFolderOrDefaultFolder());
                TextWriter outputPrintStream = printScreenFactory.GetDoPrintStream(parsedArguments);
                var dbmsSyntax = factory.CreateDbmsSyntax(config.ChangeOwner);
                var useTransaction = config.UseTransaction;
                TextWriter undoOutputPrintStream = printScreenFactory.GetUndoPrintStream(parsedArguments);

                var toPrintStreamDeployer = new ToPrintStreamDeployer(databaseSchemaVersion, directoryInfo, outputPrintStream, dbmsSyntax, useTransaction, undoOutputPrintStream);

                toPrintStreamDeployer.DoDeploy(LastVersionChangeToApply);

                printScreenFactory.ClosePrintStream(outputPrintStream);
                printScreenFactory.ClosePrintStream(undoOutputPrintStream);
            }
            catch (DbDeployException ex)
            {
                Console.Error.WriteLine(ex.Message);
                Environment.Exit(1);
            }

            catch (Exception ex)
            {
                Console.Error.WriteLine("Failed to apply changes: " + ex);
                Console.Error.WriteLine(ex.StackTrace);
                Environment.Exit(2);
            }
        }
        public void SetUp() 
        {
            this.changeLogTableName = "ChangeLog";

            this.expectedResultSet = new Mock<IDataReader>();

            var connection = new Mock<IDbConnection>();

            var factory = new Mock<DbmsFactory>("mssql", string.Empty, null);
            factory.Setup(f => f.CreateConnection()).Returns(connection.Object);
        
            this.queryExecuter = new Mock<QueryExecuter>(factory.Object);

            this.syntax = new Mock<IDbmsSyntax>();
            this.syntax.Setup(s => s.TableExists(It.IsAny<string>()))
                .Returns<string>(t => string.Format(CultureInfo.InvariantCulture,
@"SELECT table_schema 
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_NAME = '{0}'", t));

            this.executedQueries = new List<string>();

            var checkForChangeLogDataReader = new Mock<IDataReader>();
            checkForChangeLogDataReader
                .Setup(r => r.Read())
                .Returns(true);

            this.queryExecuter
                .Setup(e => e.ExecuteQuery(It.Is<string>(v => v.Contains("INFORMATION_SCHEMA"))))
                .Returns(() => checkForChangeLogDataReader.Object);

            this.queryExecuter
                .Setup(e => e.ExecuteQuery(It.Is<string>(v => !v.Contains("INFORMATION_SCHEMA")), It.IsAny<object[]>()))
                .Returns(this.expectedResultSet.Object)
                .Callback<string, object[]>((query, args) => this.executedQueries.Add(query));

            this.schemaVersionManager = new DatabaseSchemaVersionManager(this.queryExecuter.Object, this.syntax.Object, changeLogTableName);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SqlCmdApplier" /> class.
        /// </summary>
        /// <param name="connectionString">The database connection string.</param>
        /// <param name="schemaVersionManager">The schema version manager.</param>
        /// <param name="dbmsSyntax">Database syntax</param>
        /// <param name="changeLogTableName">ChangeLog table name</param>
        /// <param name="infoTextWriter">The info text writer.</param>
        public SqlCmdApplier(
            string connectionString,
            DatabaseSchemaVersionManager schemaVersionManager,
            IDbmsSyntax dbmsSyntax,
            string changeLogTableName,
            TextWriter infoTextWriter)
        {
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new ArgumentNullException("connectionString");
            }

            if (schemaVersionManager == null)
            {
                throw new ArgumentNullException("schemaVersionManager");
            }

            if (dbmsSyntax == null)
            {
                throw new ArgumentNullException("dbmsSyntax");
            }

            if (changeLogTableName == null)
            {
                throw new ArgumentNullException("changeLogTableName");
            }

            if (infoTextWriter == null)
            {
                throw new ArgumentNullException("infoTextWriter");
            }

            this.schemaVersionManager = schemaVersionManager;
            this.dbmsSyntax = dbmsSyntax;
            this.changeLogTableName = changeLogTableName;
            this.infoTextWriter = infoTextWriter;
            this.connectionString = connectionString;
        }
Exemple #29
0
        public static void Main(string[] args)
        {
            try
            {
                IConfiguration config = new ConfigurationFile();
                DbmsFactory factory = new DbmsFactory(config.DbType, config.DbConnectionString);
                DatabaseSchemaVersionManager databaseSchemaVersion = new DatabaseSchemaVersionManager(factory, config.DbDeltaSet, config.CurrentDbVersion, config.TableName);

                new ToPrintStreamDeployer(databaseSchemaVersion, new DirectoryInfo("."), Console.Out, factory.CreateDbmsSyntax(), config.UseTransaction, null).DoDeploy(Int32.MaxValue);
            }
            catch (DbDeployException ex)
            {
                Console.Error.WriteLine(ex.Message);
                Environment.Exit(1);
            }

            catch (Exception ex)
            {
                Console.Error.WriteLine("Failed to apply changes: " + ex);
                Console.Error.WriteLine(ex.StackTrace);
                Environment.Exit(2);
            }
        }
        public DirectToDbApplier(
            QueryExecuter queryExecuter,
            DatabaseSchemaVersionManager schemaVersionManager,
            QueryStatementSplitter splitter,
            TextWriter infoTextWriter)
        {
            if (queryExecuter == null)
                throw new ArgumentNullException("queryExecuter");

            if (schemaVersionManager == null)
                throw new ArgumentNullException("schemaVersionManager");

            if (splitter == null)
                throw new ArgumentNullException("splitter");

            if (infoTextWriter == null)
                throw new ArgumentNullException("infoTextWriter");

            this.queryExecuter = queryExecuter;
            this.schemaVersionManager = schemaVersionManager;
            this.splitter = splitter;
            this.infoTextWriter = infoTextWriter;
        }
Exemple #31
0
		public override bool Execute()
		{
			bool result = false;
			try
			{
				LogTaskProperties();

			    using (TextWriter outputPrintStream = new StreamWriter(outputfile.FullName))
				{
					TextWriter undoOutputPrintStream = null;
					if (undoOutputfile != null)
					{
						undoOutputPrintStream = new StreamWriter(undoOutputfile.FullName);
					}
					DbmsFactory factory = new DbmsFactory(dbType, dbConnection);
					IDbmsSyntax dbmsSyntax = factory.CreateDbmsSyntax();
					DatabaseSchemaVersionManager databaseSchemaVersion = new DatabaseSchemaVersionManager(factory, deltaSet, null);

					ToPrintStreamDeployer toPrintSteamDeployer = new ToPrintStreamDeployer(databaseSchemaVersion, dir, outputPrintStream, dbmsSyntax, useTransaction, undoOutputPrintStream);
					toPrintSteamDeployer.DoDeploy(lastChangeToApply);

					if (undoOutputPrintStream != null)
					{
						undoOutputPrintStream.Close();
					}
				}
				result = true;
			}
			catch (DbDeployException ex)
			{
				Log.LogErrorFromException(ex, true);
				Console.Error.WriteLine(ex.Message);
			}
			catch (Exception ex)
			{
				Log.LogErrorFromException(ex, true);
				Console.Error.WriteLine("Failed to apply changes: " + ex.Message);
				Console.Error.WriteLine("Stack Trace:");
				Console.Error.Write(ex.StackTrace);
			}
			return result;
		}
        public void ShouldGenerateSqlStringContainingSpecifiedChangelogTableNameOnDelete() 
        {
            var schemaVersionManagerWithDifferentTableName =
                new DatabaseSchemaVersionManager(this.queryExecuter.Object, this.syntax.Object, "user_specified_changelog");

            string updateSql = schemaVersionManagerWithDifferentTableName.GetChangelogDeleteSql(this.script);

            Assert.IsTrue(updateSql.StartsWith("DELETE FROM user_specified_changelog "));
        }
        public void ShouldGetAppliedChangesFromSpecifiedChangelogTableName()
        {
            changeLogTableName = "user_specified_changelog";

            var schemaVersionManagerWithDifferentTableName =
                new DatabaseSchemaVersionManager(this.queryExecuter.Object, this.syntax.Object, changeLogTableName);

            schemaVersionManagerWithDifferentTableName.GetAppliedChanges();

            this.queryExecuter.Verify(e => e.ExecuteQuery(It.Is<string>(s => s.StartsWith("SELECT ChangeId, Folder, ScriptNumber, ScriptName, ScriptStatus, ScriptOutput FROM user_specified_changelog"))));
        }
		public virtual void TestCanSetChangeLogTableName()
		{
			const string expectedTableName = "FooTable";
			DatabaseSchemaVersionManager databaseSchemaVersionManager = new DatabaseSchemaVersionManager(new DbmsFactory(Dbms, ConnectionString), DeltaSet, null, expectedTableName);
			Assert.AreEqual(expectedTableName, databaseSchemaVersionManager.TableName);
		}
        protected void SetUp()
        {
			databaseSchemaVersion = new DatabaseSchemaVersionManager(new DbmsFactory(Dbms, ConnectionString), DeltaSet, null);
        }
        public void TestShouldHandleCreatingChangeLogTableWithSchema()
        {
            this.EnsureTableDoesNotExist("log.Installs");

            var factory = new DbmsFactory(this.Dbms, this.ConnectionString);
            var executer = new QueryExecuter(factory);
            var databaseSchemaManager = new DatabaseSchemaVersionManager(executer, factory.CreateDbmsSyntax(), "log.Installs");

            var applier = new DirectToDbApplier(executer, databaseSchemaManager, new QueryStatementSplitter(),
                factory.CreateDbmsSyntax(), "log.Installs", new NullWriter());
            
            applier.Apply(new ChangeScript[] {}, createChangeLogTable: true);

            this.AssertTableExists("log.Installs");
        }
Exemple #37
0
 protected void SetUp()
 {
     databaseSchemaVersion = new DatabaseSchemaVersionManager(new DbmsFactory(Dbms, ConnectionString), DeltaSet, null);
 }
 public void TestCanGenerateVersionCheck()
 {
     databaseSchemaVersion = new DatabaseSchemaVersionManager(new DbmsFactory(DBMS, CONNECTION_STRING), "Main", 5);
     Assert.AreEqual(@"execute versionCheck('Main', 5, 'changelog');"
     , databaseSchemaVersion.GenerateVersionCheck());
 }
 public void TestCanGenerateVersionCheck()
 {
     databaseSchemaVersion = new DatabaseSchemaVersionManager(new DbmsFactory(DBMS, CONNECTION_STRING), "Main", 5);
     Assert.AreEqual(@"execute versionCheck('Main', 5, 'changelog');"
                     , databaseSchemaVersion.GenerateVersionCheck());
 }
Exemple #40
0
        public void Go()
        {
            this.Validate();

            this.InfoWriter.WriteLine(this.GenerateWelcomeString());
            
            var factory = new DbmsFactory(this.Dbms, this.ConnectionString);
            
            var dbmsSyntax = factory.CreateDbmsSyntax();

            QueryExecuter queryExecuter = new QueryExecuter(factory);

            var databaseSchemaVersionManager =
                    new DatabaseSchemaVersionManager(queryExecuter, dbmsSyntax, this.ChangeLogTableName);

            var scanner = new DirectoryScanner(this.InfoWriter, this.Encoding);

            var changeScriptRepository =
                    new ChangeScriptRepository(scanner.GetChangeScriptsForDirectory(this.ScriptDirectory));

            IChangeScriptApplier doScriptApplier;
            TextWriter doWriter = null;

            if (this.OutputFile != null) 
            {
                doWriter = new StreamWriter(this.OutputFile.OpenWrite(), this.Encoding);

                doScriptApplier = new TemplateBasedApplier(
                    doWriter, 
                    this.Dbms, 
                    this.ChangeLogTableName, 
                    this.Delimiter, 
                    this.DelimiterType, 
                    this.TemplateDir);
            } 
            else 
            {
                QueryStatementSplitter splitter = new QueryStatementSplitter
                {
                    Delimiter = this.Delimiter,
                    DelimiterType = this.DelimiterType,
                    LineEnding = this.LineEnding,
                };

                doScriptApplier = new DirectToDbApplier(
                    queryExecuter, 
                    databaseSchemaVersionManager, 
                    splitter, 
                    this.InfoWriter);
            }

            IChangeScriptApplier undoScriptApplier = null;
            TextWriter undoWriter = null;

            if (this.UndoOutputFile != null) 
            {
                undoWriter = new StreamWriter(this.UndoOutputFile.OpenWrite(), this.Encoding);

                undoScriptApplier = new UndoTemplateBasedApplier(
                    undoWriter, 
                    this.Dbms, 
                    this.ChangeLogTableName, 
                    this.Delimiter, 
                    this.DelimiterType, 
                    this.TemplateDir);
            }

            try
            {
                Controller controller = new Controller(
                    changeScriptRepository, 
                    databaseSchemaVersionManager, 
                    doScriptApplier, 
                    undoScriptApplier, 
                    this.InfoWriter);

                controller.ProcessChangeScripts(this.LastChangeToApply);

                queryExecuter.Close();
            }
            finally
            {
                if (doWriter != null)
                    doWriter.Dispose();

                if (undoWriter != null)
                    undoWriter.Dispose();
            }
        }
        /// <summary>
        /// Executes the a database deployment with the specified config.
        /// </summary>
        /// <param name="config">The config.</param>
        /// <param name="infoWriter">The info writer.</param>
        /// <exception cref="System.InvalidOperationException">SQLCMD mode can only be applied against an mssql database.</exception>
        public void Execute(DbDeployConfig config, TextWriter infoWriter)
        {
            this.Validate(config, infoWriter);

            infoWriter.WriteLine();
            infoWriter.WriteLine("==========================================================");
            infoWriter.WriteLine(this.GenerateWelcomeString());

            var factory = new DbmsFactory(config.Dbms, config.ConnectionString);
            
            var dbmsSyntax = factory.CreateDbmsSyntax();

            var queryExecuter = new QueryExecuter(factory);

            var databaseSchemaVersionManager = new DatabaseSchemaVersionManager(queryExecuter, dbmsSyntax, config.ChangeLogTableName);

            var scanner = new DirectoryScanner(infoWriter, config.Encoding);

            var changeScriptRepository = new ChangeScriptRepository(scanner.GetChangeScriptsForDirectory(config.ScriptDirectory));

            IChangeScriptApplier doScriptApplier;
            TextWriter doWriter = null;
            QueryExecuter applierExecutor = null;

            if (config.OutputFile != null) 
            {
                doWriter = new StreamWriter(config.OutputFile.OpenWrite(), config.Encoding);

                doScriptApplier = new TemplateBasedApplier(
                    doWriter,
                    dbmsSyntax,
                    config.ChangeLogTableName,
                    config.Delimiter,
                    config.DelimiterType,
                    config.TemplateDirectory);
            }
            else if (config.UseSqlCmd)
            {
                // Verify database is MSSQL.
                if (!string.Equals(config.Dbms, "mssql", StringComparison.InvariantCultureIgnoreCase))
                {
                    throw new InvalidOperationException("SQLCMD mode can only be applied against an mssql database.");
                }

                doScriptApplier = new SqlCmdApplier(
                    config.ConnectionString,
                    databaseSchemaVersionManager,
                    dbmsSyntax,
                    config.ChangeLogTableName,
                    infoWriter);
            }
            else 
            {
                var splitter = new QueryStatementSplitter
                {
                    Delimiter = config.Delimiter,
                    DelimiterType = config.DelimiterType,
                    LineEnding = config.LineEnding,
                };

                // Do not share query executor between schema manager and applier, since a failure in one will effect the other.
                applierExecutor = new QueryExecuter(factory);
                doScriptApplier = new DirectToDbApplier(
                    applierExecutor, 
                    databaseSchemaVersionManager, 
                    splitter, 
                    dbmsSyntax, 
                    config.ChangeLogTableName,
                    infoWriter);
            }

            IChangeScriptApplier undoScriptApplier = null;
            TextWriter undoWriter = null;

            if (config.UndoOutputFile != null) 
            {
                undoWriter = new StreamWriter(config.UndoOutputFile.OpenWrite(), config.Encoding);

                undoScriptApplier = new UndoTemplateBasedApplier(
                    undoWriter,
                    dbmsSyntax,
                    config.ChangeLogTableName,
                    config.Delimiter,
                    config.DelimiterType,
                    config.TemplateDirectory);
            }

            try
            {
                var controller = new Controller(
                    changeScriptRepository, 
                    databaseSchemaVersionManager, 
                    doScriptApplier, 
                    undoScriptApplier, 
                    config.AutoCreateChangeLogTable,
                    infoWriter);

                controller.ProcessChangeScripts(config.LastChangeToApply, config.ForceUpdate);

                queryExecuter.Close();

                if (applierExecutor != null)
                {
                    applierExecutor.Close();
                }
            }
            finally
            {
                if (doWriter != null)
                {
                    doWriter.Dispose();
                }

                if (undoWriter != null)
                {
                    undoWriter.Dispose();
                }
            }
        }
Exemple #42
0
        protected override void ExecuteTask()
        {
            try
            {
                using (TextWriter outputPrintStream = this.GetOutputStream(outputfile.FullName))
                {
                    TextWriter undoOutputPrintStream = null;
                    if (undoOutputfile != null)
                        undoOutputPrintStream = this.GetOutputStream(undoOutputfile.FullName);

                    DbmsFactory factory = new DbmsFactory(dbType, dbConnection);
                    IDbmsSyntax dbmsSyntax = factory.CreateDbmsSyntax();
                    DatabaseSchemaVersionManager databaseSchemaVersion = new DatabaseSchemaVersionManager(factory, deltaSet, GetCurrentDbVersion(), changeLogTable);

                    ToPrintStreamDeployer toPrintSteamDeployer = new ToPrintStreamDeployer(databaseSchemaVersion, dir, outputPrintStream, dbmsSyntax, useTransaction, undoOutputPrintStream);
                    toPrintSteamDeployer.DoDeploy(lastChangeToApply);

                    if (undoOutputPrintStream != null)
                        undoOutputPrintStream.Close();
                }
            }
            catch (DbDeployException ex)
            {
                Console.Error.WriteLine(ex.Message);
                throw new BuildException(ex.Message);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Failed to apply changes: " + ex);
                Console.Error.WriteLine("Stack Trace:");
                Console.Error.Write(ex.StackTrace);
                throw new BuildException(ex.Message);
            }
        }