CreateDbmsSyntax() public méthode

public CreateDbmsSyntax ( ) : IDbmsSyntax
Résultat IDbmsSyntax
        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 #2
0
        private void RunIntegratedTestAndConfirmOutputResults(string syntaxName, DirectoryInfo templateDirectory)
        {
            StringWriter writer = new StringWriter();

            ChangeScript changeOne = new StubChangeScript(1, "001_change.sql", "-- contents of change script 1");
            ChangeScript changeTwo = new StubChangeScript(2, "002_change.sql", "-- contents of change script 2");

            List <ChangeScript> changeScripts = new List <ChangeScript> {
                changeOne, changeTwo
            };
            ChangeScriptRepository changeScriptRepository = new ChangeScriptRepository(changeScripts);

            var factory = new DbmsFactory(syntaxName, string.Empty);

            StubSchemaManager schemaManager = new StubSchemaManager(factory.CreateDbmsSyntax());

            IChangeScriptApplier applier    = new TemplateBasedApplier(writer, syntaxName, "ChangeLog", ";", new NormalDelimiter(), templateDirectory);
            Controller           controller = new Controller(changeScriptRepository, schemaManager, applier, null, System.Console.Out);

            controller.ProcessChangeScripts(null);

            var actual = writer.ToString();

            try
            {
                Assert.AreEqual(this.ReadExpectedFileContents(this.GetExpectedFilename(syntaxName)), actual);
            }
            catch (Exception)
            {
                // Output actual template on failure.
                Console.WriteLine("\n\nActual Template ({0}):", syntaxName);
                Console.WriteLine(actual);
                throw;
            }
        }
Exemple #3
0
        protected void SetUp()
        {
            var factory = new DbmsFactory(Dbms, ConnectionString);
            var executer = new QueryExecuter(factory);

            databaseSchemaVersion = new DatabaseSchemaVersionManager(executer, factory.CreateDbmsSyntax(), TableName);
        }
        public void TestDoesNotRunSecondScriptIfFirstScriptFails()
        {
            this.EnsureTableDoesNotExist("TableWeWillUse");
            this.EnsureTableDoesNotExist(TableName);

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

            var output = new StringBuilder();

            var applier = new TemplateBasedApplier(
                new StringWriter(output),
                dbmsSyntax,
                TableName,
                ";",
                DbDeployDefaults.DelimiterType,
                DbDeployDefaults.TemplateDirectory);

            applier.Apply(new ChangeScript[]
            {
                new StubChangeScript(1, "1.test.sql", "INSERT INTO TableWeWillUse VALUES (1);"),
                new StubChangeScript(2, "2.test.sql", "CREATE TABLE dbo.TableWeWillUse (Id int NULL);"),
            }, createChangeLogTable: true);

            using (var sqlExecuter = new SqlCmdExecutor(this.ConnectionString))
            {
                var cmdOutput = new StringBuilder();
                sqlExecuter.ExecuteString(output.ToString(), cmdOutput);
            }
            this.AssertTableDoesNotExist("TableWeWillUse");
        }
        public void TestDoesNotRunSecondScriptIfFirstScriptFails()
        {
            this.EnsureTableDoesNotExist("TableWeWillUse");
            this.EnsureTableDoesNotExist(TableName);

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

            var output = new StringBuilder();
            
            var applier = new TemplateBasedApplier(
                new StringWriter(output),
                dbmsSyntax,
                TableName,
                ";",
                DbDeployDefaults.DelimiterType,
                DbDeployDefaults.TemplateDirectory);

            applier.Apply(new ChangeScript[]
            {
                new StubChangeScript(1, "1.test.sql", "INSERT INTO TableWeWillUse VALUES (1);"), 
                new StubChangeScript(2, "2.test.sql", "CREATE TABLE dbo.TableWeWillUse (Id int NULL);"), 
            }, createChangeLogTable: true);

            using (var sqlExecuter = new SqlCmdExecutor(this.ConnectionString))
            {
                var cmdOutput = new StringBuilder();
                sqlExecuter.ExecuteString(output.ToString(), cmdOutput);
            }
            this.AssertTableDoesNotExist("TableWeWillUse");
        }
        private void RunIntegratedTestAndConfirmOutputResults(string syntaxName, DirectoryInfo templateDirectory) 
        {
            StringWriter writer = new StringWriter();

            ChangeScript changeOne = new StubChangeScript(1, "001_change.sql", "-- contents of change script 1");
            ChangeScript changeTwo = new StubChangeScript(2, "002_change.sql", "-- contents of change script 2");

            List<ChangeScript> changeScripts = new List<ChangeScript> { changeOne, changeTwo };
            ChangeScriptRepository changeScriptRepository = new ChangeScriptRepository(changeScripts);

            var factory = new DbmsFactory(syntaxName, string.Empty);
            var dbmsSyntax = factory.CreateDbmsSyntax();

            var createChangeLogTable = false;
            StubSchemaManager schemaManager = new StubSchemaManager(dbmsSyntax, createChangeLogTable);

            IChangeScriptApplier applier = new TemplateBasedApplier(writer, dbmsSyntax, "ChangeLog", ";", new NormalDelimiter(), templateDirectory);
            Controller controller = new Controller(changeScriptRepository, schemaManager, applier, null, createChangeLogTable, System.Console.Out);

            controller.ProcessChangeScripts(null);

            var actual = writer.ToString();

            try
            {
                Assert.AreEqual(this.ReadExpectedFileContents(this.GetExpectedFilename(syntaxName)), actual);
            }
            catch (Exception)
            {
                // Output actual template on failure.
                Console.WriteLine("\n\nActual Template ({0}):", syntaxName);
                Console.WriteLine(actual);
                throw;
            }
        }
        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);
        }
Exemple #8
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);
        }
Exemple #9
0
        public void criar_instancia_de_mysql_syntax()
        {
            dbmsFactory = new DbmsFactory(SupportedDbms.MYSQL, connectionStringMySql);
            var dbmsSyntax = dbmsFactory.CreateDbmsSyntax();

            dbmsSyntax.Should().NotBeNull();
            dbmsSyntax.Should().BeOfType <MySqlDbmsSyntax>();
        }
Exemple #10
0
        public void criar_instancia_de_sybase()
        {
            dbmsFactory = new DbmsFactory(SupportedDbms.SYBASE, connectionStringSybase);
            var dbmsSyntax = dbmsFactory.CreateDbmsSyntax();

            dbmsSyntax.Should().NotBeNull();
            dbmsSyntax.Should().BeOfType <SybaseDbmsSyntax>();
        }
        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 #12
0
        public void criar_instancia_de_oracle()
        {
            dbmsFactory = new DbmsFactory(SupportedDbms.ORACLE, connectionStringOracleTns);

            var dbmsSyntax = dbmsFactory.CreateDbmsSyntax();

            dbmsSyntax.Should().NotBeNull();
            dbmsSyntax.Should().BeOfType <OracleDbmsSyntax>();
        }
Exemple #13
0
        public void criar_instancia_de_firebird_sintaxe()
        {
            dbmsFactory = new DbmsFactory(SupportedDbms.FIREBIRD, "connectionString");

            var dbmsSyntax = dbmsFactory.CreateDbmsSyntax();

            dbmsSyntax.Should().NotBeNull();
            dbmsSyntax.Should().BeOfType <FirebirdDbmsSyntax>();
        }
Exemple #14
0
        public void instanciar_factory_mssql()
        {
            dbmsFactory = new DbmsFactory(SupportedDbms.MSSQL, connectionStringMySql);

            var dbmsSyntax = dbmsFactory.CreateDbmsSyntax();

            dbmsSyntax.Should().NotBeNull();
            dbmsSyntax.Should().BeOfType <MsSqlDbmsSyntax>();
        }
Exemple #15
0
        public void criar_instancia_de_postgre_sintaxe()
        {
            dbmsFactory = new DbmsFactory(SupportedDbms.POSTGRE, "connectionString");

            var dbmsSyntax = dbmsFactory.CreateDbmsSyntax();

            dbmsSyntax.Should().NotBeNull();
            dbmsSyntax.Should().BeOfType <PostgreDbmsSyntax>();
        }
        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);
        }
        private void RunIntegratedTestAndConfirmOutputResults(string syntaxName, DirectoryInfo templateDirectory) 
        {
            var writer = new StringWriter();
            var listReplaces = new List<string>() { "$script.Guid", "$script.Folder", "$script.ScriptNumber", "$script.ScriptName" };
            var listExpecteds = new List<string>()
                {
                    "START CHANGE SCRIPT v1.0/001_change.sql",
                    "END CHANGE SCRIPT v1.0/001_change.sql",
                    "START CHANGE SCRIPT v1.0/002_change.sql",
                    "END CHANGE SCRIPT v1.0/002_change.sql",
                    "INSERT INTO ChangeLog (ChangeId, Folder, ScriptNumber, ScriptName, StartDate, AppliedBy, ScriptStatus, ScriptOutput)",
                    "UPDATE ChangeLog"
                };

            ChangeScript changeOne = new StubChangeScript(1, "001_change.sql", "-- contents of change script 1");
            ChangeScript changeTwo = new StubChangeScript(2, "002_change.sql", "-- contents of change script 2");

            var changeScripts = new List<ChangeScript> { changeOne, changeTwo };
            var changeScriptRepository = new ChangeScriptRepository(changeScripts);

            var factory = new DbmsFactory(syntaxName, string.Empty);
            var dbmsSyntax = factory.CreateDbmsSyntax();

            const bool createChangeLogTable = false;
            var schemaManager = new StubSchemaManager(dbmsSyntax, createChangeLogTable);

            IChangeScriptApplier applier = new TemplateBasedApplier(writer, dbmsSyntax, "ChangeLog", ";", new NormalDelimiter(), templateDirectory);
            var controller = new Controller(new RepositorioScripts(schemaManager,changeScriptRepository), schemaManager, applier, null, createChangeLogTable, Console.Out);

            controller.ProcessChangeScripts(null);

            var actual = writer.ToString();

            try
            {
                var expected = ReadExpectedFileContents(GetExpectedFilename(syntaxName));
                foreach (var currentExpected in listExpecteds)
                {
                    expected.Should().Contain(currentExpected, string.Format("The expected script does not contain {0}", currentExpected));
                }

                foreach (var replace in listReplaces)
                {
                    if (actual.Contains(replace)) 
                        Assert.Fail("A regex from template does not were replaced. \n\rRegex: {0} ", replace);
                }
            }
            catch (Exception)
            {
                // Output actual template on failure.
                Console.WriteLine("\n\nActual Template ({0}):", syntaxName);
                Console.WriteLine(actual);
                throw;
            }
        }
Exemple #18
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");
        }
        private void RunIntegratedTestAndConfirmOutputResults(string syntaxName, DirectoryInfo templateDirectory) 
        {
            StringWriter writer = new StringWriter();

            ChangeScript changeOne = new StubChangeScript(1, "001_change.sql", "-- contents of change script 1");
            ChangeScript changeTwo = new StubChangeScript(2, "002_change.sql", "-- contents of change script 2");

            List<ChangeScript> changeScripts = new List<ChangeScript> { changeOne, changeTwo };
            ChangeScriptRepository changeScriptRepository = new ChangeScriptRepository(changeScripts);

            var factory = new DbmsFactory(syntaxName, string.Empty);

            StubSchemaManager schemaManager = new StubSchemaManager(factory.CreateDbmsSyntax());

            IChangeScriptApplier applier = new TemplateBasedApplier(writer, syntaxName, "changelog", ";", new NormalDelimiter(), templateDirectory);
            Controller controller = new Controller(changeScriptRepository, schemaManager, applier, null, System.Console.Out);

            controller.ProcessChangeScripts(null);

            Assert.AreEqual(this.ReadExpectedFileContents(this.GetExpectedFilename(syntaxName)), writer.ToString());
        }
Exemple #21
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);
            }
        }
Exemple #22
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);
            }
        }
Exemple #23
0
        private void RunIntegratedTestAndConfirmOutputResults(string syntaxName, DirectoryInfo templateDirectory)
        {
            var writer       = new StringWriter();
            var listReplaces = new List <string>()
            {
                "$script.Guid", "$script.Folder", "$script.ScriptNumber", "$script.ScriptName"
            };
            var listExpecteds = new List <string>()
            {
                "START CHANGE SCRIPT v1.0/001_change.sql",
                "END CHANGE SCRIPT v1.0/001_change.sql",
                "START CHANGE SCRIPT v1.0/002_change.sql",
                "END CHANGE SCRIPT v1.0/002_change.sql",
                "INSERT INTO ChangeLog (ChangeId, Folder, ScriptNumber, ScriptName, StartDate, AppliedBy, ScriptStatus, ScriptOutput)",
                "UPDATE ChangeLog"
            };

            ChangeScript changeOne = new StubChangeScript(1, "001_change.sql", "-- contents of change script 1");
            ChangeScript changeTwo = new StubChangeScript(2, "002_change.sql", "-- contents of change script 2");

            var changeScripts = new List <ChangeScript> {
                changeOne, changeTwo
            };
            var changeScriptRepository = new ChangeScriptRepository(changeScripts);

            var factory    = new DbmsFactory(syntaxName, string.Empty);
            var dbmsSyntax = factory.CreateDbmsSyntax();

            const bool createChangeLogTable = false;
            var        schemaManager        = new StubSchemaManager(dbmsSyntax, createChangeLogTable);

            IChangeScriptApplier applier = new TemplateBasedApplier(writer, dbmsSyntax, "ChangeLog", ";", new NormalDelimiter(), templateDirectory);
            var controller = new Controller(new RepositorioScripts(schemaManager, changeScriptRepository), schemaManager, applier, null, createChangeLogTable, Console.Out);

            controller.ProcessChangeScripts(null);

            var actual = writer.ToString();

            try
            {
                var expected = ReadExpectedFileContents(GetExpectedFilename(syntaxName));
                foreach (var currentExpected in listExpecteds)
                {
                    expected.Should().Contain(currentExpected, string.Format("The expected script does not contain {0}", currentExpected));
                }

                foreach (var replace in listReplaces)
                {
                    if (actual.Contains(replace))
                    {
                        Assert.Fail("A regex from template does not were replaced. \n\rRegex: {0} ", replace);
                    }
                }
            }
            catch (Exception)
            {
                // Output actual template on failure.
                Console.WriteLine("\n\nActual Template ({0}):", syntaxName);
                Console.WriteLine(actual);
                throw;
            }
        }
Exemple #24
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();
            }
        }
Exemple #25
0
        private void Instanciar(string sgbd)
        {
            var dbmsFactory = new DbmsFactory(sgbd, "connection=string");

            dbmsSyntax = (DbmsSyntax)dbmsFactory.CreateDbmsSyntax();
        }
        /// <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 #27
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;
		}
Exemple #28
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);
            }
        }
 private void Instanciar(string sgbd)
 {
     var dbmsFactory = new DbmsFactory(sgbd, "connection=string");
     dbmsSyntax = (DbmsSyntax)dbmsFactory.CreateDbmsSyntax();
 }
        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");
        }