Пример #1
0
 private void ScriptDefinition(ScriptObject dbObject, string outputDirectory, Func <StringCollection> scripter)
 {
     try
     {
         StringCollection script = scripter();
         SaveScript(dbObject, script, outputDirectory);
     }
     catch (Exception ex)
     {
         m_log.WriteError(string.Format("Error when scripting definition for {0}: {1}", dbObject.ObjectName, ex.Message));
     }
 }
Пример #2
0
    /// <summary>
    ///     Ensures that the database specified in the connection string exists.
    /// </summary>
    /// <param name="supported">Fluent helper type.</param>
    /// <param name="connectionString">The connection string.</param>
    /// <param name="logger">The <see cref="T:DbUp.Engine.Output.IUpgradeLog" /> used to record actions.</param>
    /// <param name="timeout">
    ///     Use this to set the command time out for creating a database in case you're encountering a time
    ///     out in this operation.
    /// </param>
    /// <returns />
    public static void MySqlDatabase(this SupportedDatabasesForEnsureDatabase supported, string connectionString, IUpgradeLog logger, int timeout = -1)
    {
        if (supported == null)
        {
            throw new ArgumentNullException(nameof(supported));
        }
        if (string.IsNullOrEmpty(connectionString) || connectionString.Trim() == string.Empty)
        {
            throw new ArgumentNullException(nameof(connectionString));
        }
        if (logger == null)
        {
            throw new ArgumentNullException(nameof(logger));
        }

        var connectionStringBuilder = new MySqlConnectionStringBuilder(connectionString);
        var initialCatalog          = connectionStringBuilder.Database;

        if (string.IsNullOrEmpty(initialCatalog) || initialCatalog.Trim() == string.Empty)
        {
            throw new InvalidOperationException("The connection string does not specify a database name.");
        }
        connectionStringBuilder.Database = "sys";

        var maskedConnectionStringBuilder = new MySqlConnectionStringBuilder(connectionStringBuilder.ConnectionString)
        {
            Password = string.Empty.PadRight(connectionStringBuilder.Password.Length, '*')
        };

        logger.WriteInformation("Using connection string {0}", maskedConnectionStringBuilder.ConnectionString);

        using (var connection = new MySqlConnection(connectionStringBuilder.ConnectionString))
        {
            try
            {
                connection.Open();
            }
            catch (Exception ex)
            {
                logger.WriteError("Unable to open database connection to {0}: {1}",
                                  connection.ConnectionString, connection.Database, ex);
                throw;
            }
            using (var mySqlCommand = new MySqlCommand($"CREATE DATABASE IF NOT EXISTS {initialCatalog}", connection)
            {
                CommandType = CommandType.Text
            })
            {
                if (timeout >= 0)
                {
                    mySqlCommand.CommandTimeout = timeout;
                }
                mySqlCommand.ExecuteNonQuery();
            }

            logger.WriteInformation("Ensured database {0} exists", initialCatalog);
        }
    }
Пример #3
0
        public bool Run()
        {
            try
            {
                if (IsNew())
                {
                    _upgradeLog.WriteInformation("No '{0}' database found. One will be created.", DatabaseName);
                    CreateDatabase();
                }

                _upgradeLog.WriteInformation("Performing beforeMigrations for '{0}' database.", DatabaseName);
                BeforeMigration();

                _upgradeLog.WriteInformation("Performing migrations for '{0}' database.", DatabaseName);
                MigrateDatabase();

                _upgradeLog.WriteInformation("Executing hashed scripts for '{0}' database.", DatabaseName);
                HashedScripts();

                _upgradeLog.WriteInformation("Executing always run scripts for '{0}' database.", DatabaseName);
                AlwaysRun();

                _upgradeLog.WriteInformation("Executing test scripts for '{0}' database. These are run every time.", DatabaseName);
                UpdateTests();

                if (_seedData)
                {
                    _upgradeLog.WriteInformation("Executing seed scripts for '{0}' database.", DatabaseName);
                    SeedDatabase();
                }
            }
            catch (Exception e)
            {
                _upgradeLog.WriteError(e.Message);

                return(false);
            }

            return(true);
        }
Пример #4
0
        /// <summary>
        /// Executes the specified script against a database at a given connection string.
        /// </summary>
        /// <param name="script">The script.</param>
        /// <param name="variables">Variables to replace in the script</param>
        public virtual void Execute(SqlScript script, string connectionString, IUpgradeLog log, IDictionary<string, string> variables = null, IEnumerable<IScriptPreprocessor> scriptPreprocessors = null)
        {
            log.WriteInformation("Executing SQL Server script '{0}'", script.Name);

            if (script.IsAdminScript)
            {
                //need the databaseName variable for the add/drop scripts
                variables["databaseName"] = this.GetDatabaseName(connectionString);

                //now set the connection string to point to the master database
                connectionString = this.GetMasterConnectionString(connectionString);
            }

            //run all the pre processors/variable replacements
            string scriptContents = this.RunPreProcessors(script, variables, scriptPreprocessors);

            //figure out if we should use transactions or not
            bool useTransactions = true;
            if (scriptContents.Contains("<DisableTransaction>true</DisableTransaction>")) useTransactions = false;

            //break the script into its parts
            IEnumerable<string> scriptStatements = this.SplitByGoStatements(scriptContents);

            //this is used for logging which block is being executed
            int currentBlockNumber = -1;

            //open the connection and execute
            try
            {
                using (IDbConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    //use a transaction if we're supposed to
                    if (useTransactions)
                    {
                        using (IDbTransaction transaction = connection.BeginTransaction())
                        {
                            this.ExecuteScriptStatements(scriptStatements, connection, out currentBlockNumber, transaction);

                            transaction.Commit();
                        }
                    }
                    else
                    {
                        ExecuteScriptStatements(scriptStatements, connection, out currentBlockNumber);
                    }
                }
            }
            catch (SqlException sqlException)
            {
                log.WriteInformation("SQL exception has occured in script: '{0}'", script.Name);
                log.WriteError("Script block number: {0}; Block line {1}; Message: {2}", currentBlockNumber, sqlException.LineNumber, sqlException.Procedure, sqlException.Number, sqlException.Message);
                log.WriteError(sqlException.ToString());
                throw;
            }
            catch (DbException dbException)
            {
                log.WriteInformation("DB exception has occured in script: '{0}'", script.Name);
                log.WriteError("Script block number: {0}; Error code {1}; Message: {2}", currentBlockNumber, dbException.ErrorCode, dbException.Message);
                log.WriteError(dbException.ToString());
                throw;
            }
            catch (Exception ex)
            {
                log.WriteInformation("Exception has occured in script: '{0}'", script.Name);
                log.WriteError(ex.ToString());
                throw;
            }
        }