Represents DbDeploy configuration settings.
        public void DbDebployCanExecuteBothEmbeddedScriptsAndScriptsInDirectories()
        {
            var assembly = Assembly.LoadFrom("Test.Net.Sf.DbDeploy.EmbeddedScripts.dll");
            
            using (var tw = File.CreateText("database_" + DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss") + ".txt"))
            {
                var dbDeployer = new DbDeployer();
                var config = new DbDeployConfig
                    {
                        ConnectionString = ConnectionString,
                        Dbms = SupportedDbms.MSSQL,
                        Delimiter = "GO",
                        ScriptDirectory = new List<DirectoryInfo> { new DirectoryInfo(@"Mocks\Versioned\2.0.0.0") },
                        ScriptAssemblies = new List<Assembly> {assembly},
                        DelimiterType = Parser.ParseDelimiterType("row"),
                        UseSqlCmd = false,
                        AssemblyResourceNameFilter = resourceName => resourceName.Contains("db.MsSql.")
                    };
                dbDeployer.Execute(config, tw);
            }

            AssertTableExists(ChangeLogTableName);
            AssertTableExists("Product");
            AssertTableExists("Customer");
        }
示例#2
0
        /// <summary>
        /// Reads the config element into a configuration.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="rootPath">The root path to resolve relative paths to.</param>
        /// <returns>
        /// Configuration read.
        /// </returns>
        public DbDeployConfig ReadConfigElement(XElement element, string rootPath)
        {
            var config = new DbDeployConfig();

            config.Dbms                     = GetAttribute(element, "dbms", DbDeployDefaults.Dbms);
            config.ConnectionString         = GetAttribute(element, "connectionString", DbDeployDefaults.ConnectionString);
            config.ScriptDirectory          = GetAttribute(element, "scriptDirectory", DbDeployDefaults.ScriptDirectory, v => Parser.ParseDirectory(rootPath, v));
            config.OutputFile               = GetAttribute(element, "outputFile", DbDeployDefaults.OutputFile, v => new FileInfo(ResolveRelativePath(rootPath, v)));
            config.ChangeLogTableName       = GetAttribute(element, "changeLogTableName", DbDeployDefaults.ChangeLogTableName);
            config.AutoCreateChangeLogTable = GetAttribute(element, "autoCreateChangeLogTable", DbDeployDefaults.AutoCreateChangeLogTable, bool.Parse);
            config.ForceUpdate              = GetAttribute(element, "forceUpdate", DbDeployDefaults.ForceUpdate, bool.Parse);
            config.UseSqlCmd                = GetAttribute(element, "useSqlCmd", DbDeployDefaults.UseSqlCmd, bool.Parse);
            config.LastChangeToApply        = GetAttribute(element, "lastChangeToApply", DbDeployDefaults.LastChangeToApply, v => new UniqueChange(v));
            config.Encoding                 = GetAttribute(element, "encoding", DbDeployDefaults.Encoding, v => new OutputFileEncoding(v).AsEncoding());
            config.TemplateDirectory        = GetAttribute(element, "templateDirectory", DbDeployDefaults.TemplateDirectory, v => new DirectoryInfo(ResolveRelativePath(rootPath, v)));
            config.Delimiter                = GetAttribute(element, "delimiter", DbDeployDefaults.Delimiter);
            config.DelimiterType            = GetAttribute(element, "delimiterType", DbDeployDefaults.DelimiterType, Parser.ParseDelimiterType);
            config.LineEnding               = GetAttribute(element, "lineEnding", DbDeployDefaults.LineEnding, Parser.ParseLineEnding);

            config.ScriptAssemblies           = GetAttribute(element, "assembly", DbDeployDefaults.ScriptAssemblies, Parser.ParseAssembly);
            config.AssemblyResourceNameFilter = GetAttribute(element, "assemblyFilterByName", DbDeployDefaults.AssemblyResourceNameFilter, Parser.ParseAssemblyFilterByName);
            //config.AssemblyOnly = GetAttribute(element, "assemblyOnly", DbDeployDefaults.AssemblyOnly, Parser.ParseAssemblyOnly);

            return(config);
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            if (string.IsNullOrEmpty(this.OutputFile))
            {
                this.WriteError(new ErrorRecord(new PSInvalidOperationException(
                    "Missing a file for output"),
                    "NoOutputFile",
                    ErrorCategory.MetadataError,
                    null));

                return;
            }

            var config = new DbDeployConfig
                             {
                                 Dbms = this.DatabaseType,
                                 ConnectionString = this.ConnectionString,
                                 ChangeLogTableName = this.TableName,
                                 ScriptDirectory = Parser.ParseDirectory(this.deltasDirectory),
                                 AutoCreateChangeLogTable = this.AutoCreateChangeLogTable,
                                 ForceUpdate = this.ForceUpdate,
                                 UseSqlCmd = this.UseSqlCmd,
                                 OutputFile = new FileInfo(this.ToAbsolutePath(this.OutputFile))
                             };

            if (!string.IsNullOrEmpty(this.UndoOutputFile))
            {
                config.OutputFile = new FileInfo(this.ToAbsolutePath(UndoOutputFile));
            }

            var deployer = new DbDeployer();
            deployer.Execute(config, new LambdaTextWriter(WriteVerbose));
        }
        protected override void ProcessRecord()
        {
            var configurationFile = this.ToAbsolutePath(ConfigurationFile);
            this.deltasDirectory = this.ToAbsolutePath(DeltasDirectory);

            if (!string.IsNullOrEmpty(configurationFile) && File.Exists(configurationFile))
            {
                var configurationManager = new DbDeployConfigurationManager();
                this.config = configurationManager.ReadConfiguration(configurationFile).Deployments.FirstOrDefault();

                if (string.IsNullOrEmpty(this.DatabaseType) || this.DatabaseType == DbDeployDefaults.Dbms)
                    this.DatabaseType = this.config.Dbms;

                if (string.IsNullOrEmpty(this.ConnectionString))
                    this.ConnectionString = this.config.ConnectionString;

                if (string.IsNullOrEmpty(this.TableName) || this.TableName == DbDeployDefaults.ChangeLogTableName)
                    this.TableName = this.config.ChangeLogTableName;
            }

            if (string.IsNullOrEmpty(this.ConnectionString))
            {
                throw new InvalidDataException(
                    "Missing connection string. It must either be in the config file or passed as a parameter");
            }
        }
        public void SetUp()
        {
            EnsureTableDoesNotExist(ChangeLogTableName);
            EnsureTableDoesNotExist("Product");
            EnsureTableDoesNotExist("Customer");
            EnsureTableDoesNotExist("Teste");
            EnsureTableDoesNotExist("Teste2");
            EnsureTableDoesNotExist("tabelaTeste");

            dbDeployConfig = new DbDeployConfig { ConnectionString = @"Server=.\SQLEXPRESS;Initial Catalog=dbdeploy;User Id=sa;Password=sa" };

            executorScriptsIndividuais = new ExecutorScriptsIndividuais(dbDeployConfig, new StringWriter());
        }
        public void retornar_change_script_repository()
        {
            var dbDeployConfig = new DbDeployConfig
            {
                ScriptDirectory = new List<DirectoryInfo>{new DirectoryInfo(@"Mocks\Versioned")},
            };
            var changeScriptRepositoryFactory = new ChangeScriptRepositoryFactory(dbDeployConfig, new StringWriter());

            var changeScriptRepository = changeScriptRepositoryFactory.Obter();

            changeScriptRepository.Should().NotBeNull();
            changeScriptRepository.Should().BeOfType<ChangeScriptRepository>();
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            var config = new DbDeployConfig
            {
                Dbms = DatabaseType,
                ConnectionString = ConnectionString,
                ChangeLogTableName = TableName,
                ScriptDirectory = Parser.ParseDirectory(deltasDirectory),
            };

            var deployer = new DbDeployer();
            deployer.Execute(config, new LambdaTextWriter(WriteVerbose));
        }
        public void LineEndingWorksOk()
        {
            var config = new DbDeployConfig();
            Assert.AreEqual(DbDeployDefaults.LineEnding, config.LineEnding);

            config = OptionsManager.ParseOptions("--lineending cr".Split(' ')).Deployments.First();
            Assert.AreEqual(LineEnding.Cr, config.LineEnding);

            config = OptionsManager.ParseOptions("--lineending crlf".Split(' ')).Deployments.First();
            Assert.AreEqual(LineEnding.CrLf, config.LineEnding);

            config = OptionsManager.ParseOptions("--lineending lf".Split(' ')).Deployments.First();
            Assert.AreEqual(LineEnding.Lf, config.LineEnding);

            config = OptionsManager.ParseOptions("--lineending platform".Split(' ')).Deployments.First();
            Assert.AreEqual(LineEnding.Platform, config.LineEnding);

        }
        public void buscar_scripts_dos_diretorios()
        {
            var dbDeployConfig = new DbDeployConfig
            {
                ScriptDirectory = new List<DirectoryInfo> { new DirectoryInfo(@"Mocks\Versioned") },
            };

            var changeScriptRepositoryFactory = new ChangeScriptRepositoryFactory(dbDeployConfig, new StringWriter());

            var changeScriptRepository = changeScriptRepositoryFactory.Obter();

            var availableChangeScripts = changeScriptRepository.GetAvailableChangeScripts();

            availableChangeScripts.Should().NotBeEmpty();
            availableChangeScripts.Count.Should().BeGreaterOrEqualTo(6);
            availableChangeScripts.Should().Contain(x => x.ScriptName == "10.Add Sold Column.sql" && x.Folder == "2.0.0.0");
            availableChangeScripts.Should().Contain(x => x.ScriptName == "2.SQLCMD Add Email Column Table.sql" && x.Folder == "v2.0.10.0");
        }
示例#10
0
        /// <summary>
        /// Parses the specified args into a deployments configuration.
        /// </summary>
        /// <param name="args">The args.</param>
        /// <returns>
        /// Configuration set.
        /// </returns>
        /// <exception cref="UsageException">Throws when unknown or invalid parameters are found.</exception>
        public static DbDeploymentsConfig ParseOptions(string[] args)
        {
            // Initialize configuration with a single deployment.
            var deploymentsConfig = new DbDeploymentsConfig();
            try
            {
                var configFile = new ConfigFileInfo();
                var config = new DbDeployConfig();
                OptionSet options = Initialize(config, configFile);
                deploymentsConfig.Deployments.Add(config);

                List<string> unknown = options.Parse(args);

                if (unknown != null && unknown.Count != 0)
                {
                    foreach (var s in unknown)
                    {
                        // empty "unkown" parameters are allowed
                        if (s != null && !string.IsNullOrEmpty(s.Trim()))
                        {
                            throw new UsageException("Unkown parameter(s): " + string.Join(", ", unknown.ToArray()));
                        }
                    }
                }

                // If a configuration file was specified in the command, use that instead of options.
                if (configFile.FileInfo != null)
                {
                    var configurationManager = new DbDeployConfigurationManager();
                    deploymentsConfig = configurationManager.ReadConfiguration(configFile.FileInfo.FullName);
                }
            }
            catch (OptionException e)
            {
                throw new UsageException(e.Message, e);
            }

            return deploymentsConfig;
        }
 public ChangeScriptRepositoryFactory(DbDeployConfig dbDeployConfig, TextWriter infoWriter)
 {
     this.dbDeployConfig = dbDeployConfig;
     this.infoWriter = infoWriter;
 }
示例#12
0
        /// <summary>
        /// Validates the specified config.
        /// </summary>
        /// <param name="config">The config.</param>
        /// <param name="infoWriter">The info writer.</param>
        /// <exception cref="UsageException">Script directory must point to a valid directory</exception>
        private void Validate(DbDeployConfig config, TextWriter infoWriter)
        {
            this.CheckForRequiredParameter(config.Dbms, "dbms");
            this.CheckForRequiredParameter(config.ConnectionString, "connectionString");
            this.CheckForRequiredParameter(config.ScriptDirectory, "dir");
            this.CheckForRequiredParameter(infoWriter, "infoWriter");

            if (config.ScriptDirectory == null || !config.ScriptDirectory.Exists) 
            {
                throw new UsageException(string.Format("The directory '{0}' does not exist.\nScript directory must point to a valid directory", config.ScriptDirectory));
            }
        }
示例#13
0
        /// <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();
                }
            }
        }
示例#14
0
 public Dbdeploy()
 {
     this.config = new DbDeployConfig();
 }
示例#15
0
 public NAntTask()
 {
     this.config = new DbDeployConfig();
 }
        public void DbDebployCanExecuteDirectoryScripts()
        {
            using (var tw = File.CreateText("database_" + DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss") + ".txt"))
            {
                var dbDeployer = new DbDeployer();
                var config = new DbDeployConfig
                {
                    ConnectionString = ConnectionString,
                    Dbms = SupportedDbms.MSSQL,
                    Delimiter = "GO",
                    ScriptDirectory = new List<DirectoryInfo> { new DirectoryInfo(@"Mocks\Versioned\2.0.0.0") },
                    DelimiterType = Parser.ParseDelimiterType("row"),
                    UseSqlCmd = false
                };
                dbDeployer.Execute(config, tw);
            }

            AssertTableExists(ChangeLogTableName);
            AssertTableExists("Product");
        }
 public ExecutorScriptsIndividuais(DbDeployConfig dbDeployConfig, TextWriter textWriter)
 {
     this.dbDeployConfig = dbDeployConfig;
     this.textWriter = textWriter;
 }
示例#18
0
        /// <summary>
        /// Initializes the specified config.
        /// </summary>
        /// <param name="config">The config.</param>
        /// <param name="configFile">The config file to read if found.</param>
        /// <returns>
        /// Option set for the config.
        /// </returns>
        private static OptionSet Initialize(DbDeployConfig config, ConfigFileInfo configFile) 
        {
            var options = new OptionSet();

            options
                .Add(
                    "d|dbms=",
                    "DBMS type ('mssql', 'mysql' or 'ora')",
                    s => config.Dbms = s)

                .Add(
                    "c|connectionstring=",
                    "connection string for database",
                    s => config.ConnectionString = StripQuotes(s))

                .Add(
                    "s|scriptdirectory=",
                    "directory containing change scripts (default: .)",
                    s => config.ScriptDirectory = new DirectoryInfo(StripQuotes(s)))

                .Add(
                    "o|outputfile=",
                    "output file",
                    s => config.OutputFile = new FileInfo(StripQuotes(s)))

                .Add(
                    "t|changelogtablename=",
                    "name of change log table to use (default: ChangeLog)",
                    s => config.ChangeLogTableName = StripQuotes(s))

                .Add(
                    "a|autocreatechangelogtable=",
                    "automatically creates the change log table if it does not exist (true or false).  Defaults to true.",
                    s => config.AutoCreateChangeLogTable = s.ToLowerInvariant() != "false")

                .Add(
                    "f|forceupdate=",
                    "forces previously failed scripts to be run again (true or false).  Defaults to false.",
                    s => config.ForceUpdate = s.ToLowerInvariant() == "true")

                .Add(
                    "u|usesqlcmd=",
                    "runs scripts in SQLCMD mode (true or false).  Defaults to false.",
                    s => config.UseSqlCmd = s.ToLowerInvariant() == "true")

                .Add(
                    "l|lastchangetoapply=",
                    "sets the last change to apply in the form of folder/scriptnumber (v1.0.0/4).",
                    s => config.LastChangeToApply = !string.IsNullOrWhiteSpace(s) ? new UniqueChange(s) : null)

                .Add(
                    "e|encoding=",
                    "encoding for input and output files (default: UTF-8)",
                    s => config.Encoding = new OutputFileEncoding(StripQuotes(s)).AsEncoding())

                .Add(
                    "templatedirectory=",
                    "template directory",
                    s => config.TemplateDirectory = new DirectoryInfo(StripQuotes(s)))

                .Add(
                    "delimiter=",
                    "delimiter to separate sql statements",
                    s => config.Delimiter = s)

                .Add(
                    "delimitertype=",
                    "delimiter type to separate sql statements (row or normal)",
                    s => config.DelimiterType = Parser.ParseDelimiterType(s))

                .Add(
                    "lineending=",
                    "line ending to use when applying scripts direct to db (platform, cr, crlf, lf)",
                    s => config.LineEnding = Parser.ParseLineEnding(s))

                .Add(
                    "config=",
                    "configuration file to use for all settings.",
                    s => configFile.FileInfo = !string.IsNullOrWhiteSpace(s) ? new FileInfo(StripQuotes(s)) : null);
            
            return options;
        }