static void GetMasterConnectionStringBuilder(string connectionString, IUpgradeLog logger, out string masterConnectionString, out string databaseName)
    {
        if (string.IsNullOrEmpty(connectionString) || connectionString.Trim() == string.Empty)
        {
            throw new ArgumentNullException("connectionString");
        }

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

        var masterConnectionStringBuilder = new SqlConnectionStringBuilder(connectionString);

        databaseName = masterConnectionStringBuilder.InitialCatalog;

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

        masterConnectionStringBuilder.InitialCatalog = "master";
        var logMasterConnectionStringBuilder = new SqlConnectionStringBuilder(masterConnectionStringBuilder.ConnectionString)
        {
            Password = string.Empty.PadRight(masterConnectionStringBuilder.Password.Length, '*')
        };

        logger.WriteInformation("Master ConnectionString => {0}", logMasterConnectionStringBuilder.ConnectionString);
        masterConnectionString = masterConnectionStringBuilder.ConnectionString;
    }
        /// <summary>
        /// Records a migration as having been run.
        /// </summary>
        /// <param name="contextManager">The ContextManager</param>
        /// <param name="log">The UpgradeLog</param>
        /// <param name="migration">Migration that has been run</param>
        public MigrationInfo StoreExecutedMigration(IContextManager contextManager, IUpgradeLog log, IMigration migration)
        {
            if (!_lastIdInitialised)
            {
                throw new InvalidOperationException("GetExecutedMigrations (to get previous migrations) is expected before StoreExecutedMigration (to store new ones)");
            }

            var clientContext = contextManager.CurrentContext;
            var rootWeb       = clientContext.Site.RootWeb;

            clientContext.Load(rootWeb);
            var properties = rootWeb.AllProperties;

            clientContext.Load(properties);
            clientContext.ExecuteQuery();

            var id            = _lastId + 1;
            var migrationInfo = new MigrationInfo(id, migration.Name, migration.Note, DateTimeOffset.UtcNow);
            var key           = _prefix + migrationInfo.Id;

            properties[key] = JsonConvert.SerializeObject(migrationInfo);

            rootWeb.Update();
            log.Verbose("Storing migration info '{0}'", key);
            clientContext.ExecuteQuery();

            _lastId = id;

            return(migrationInfo);
        }
示例#3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FunnelWebJournal"/> class.
 /// </summary>
 /// <param name="connectionFactory"></param>
 /// <param name="sourceIdentifier">The source identifier - usually the ID of the extension or FunnelWeb.DatabaseDeployer.</param>
 /// <param name="logger">The log.</param>
 /// <param name="schema">Database Schema</param>
 /// <example>
 /// var journal = new TableJournal("Server=server;Database=database;Trusted_Connection=True;");
 /// </example>
 public FunnelWebJournal(Func <IDbConnection> connectionFactory, string sourceIdentifier, IUpgradeLog logger, string schema)
 {
     schemaTableName        = string.IsNullOrEmpty(schema) ? TableName : string.Format("{0}.{1}", schema, TableName);
     this.connectionFactory = connectionFactory;
     this.sourceIdentifier  = sourceIdentifier;
     log = logger;
 }
示例#4
0
 public ToolEngine(IEnvironment environment, IUpgradeLog logger, Option <IConnectionFactory> connectionFactory)
 {
     // ConnectionFactory to override the default. Mostly used for mocking
     ConnectionFactory = connectionFactory;
     Logger            = logger ?? throw new ArgumentNullException(nameof(logger));
     Environment       = environment ?? throw new ArgumentNullException(nameof(environment));
 }
 public void Initialise(IDbConnection dbConnection, IUpgradeLog upgradeLog)
 {
     connection = dbConnection;
     log        = upgradeLog;
     upgradeLog.WriteInformation("Beginning transaction");
     transaction = connection.BeginTransaction();
 }
示例#6
0
        public static Option <bool, Error> EnsureDb(IUpgradeLog logger, Provider provider, string connectionString, int connectionTimeoutSec)
        {
            try
            {
                switch (provider)
                {
                case Provider.SqlServer:
                    EnsureDatabase.For.SqlDatabase(connectionString, logger, connectionTimeoutSec);
                    return(true.Some <bool, Error>());

                case Provider.PostgreSQL:
                    EnsureDatabase.For.PostgresqlDatabase(connectionString, logger);     // Postgres provider does not support timeout...
                    return(true.Some <bool, Error>());

                case Provider.MySQL:
                    EnsureDatabase.For.MySqlDatabase(connectionString, logger, connectionTimeoutSec);
                    return(true.Some <bool, Error>());
                }
            }
            catch (Exception ex)
            {
                return(Option.None <bool, Error>(Error.Create(ex.Message)));
            }

            return(Option.None <bool, Error>(Error.Create(Constants.ConsoleMessages.UnsupportedProvider, provider.ToString())));
        }
示例#7
0
 public UpgradeTool()
 {
     logger = LogManager.GetLogger(typeof(UpgradeEngine));
     log = new Log4NetAndConsoleUpgradeLog(logger);
     stopwatch = new Stopwatch();
     connections = new List<IDbConnection>();
 }
        }                                          // Dont't make table name uppercase. It's not required.

        /// <summary>
        /// Initializes a new instance of the <see cref="OracleTableJournal"/> class.
        /// </summary>
        /// <param name="connectionManager">The connection manager.</param>
        /// <param name="logger">The log.</param>
        /// <param name="table">The table name.</param>
        public OracleTableJournal(Func <IConnectionManager> connectionManager, Func <IUpgradeLog> logger, string table)
        {
            _connectionManager = connectionManager();
            _log = logger();

            JournalTableName = table;
        }
示例#9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MySqlTableJournal"/> class.
        /// </summary>
        /// <param name="connectionFactory">The connection factory.</param>
        /// <param name="table">The table name.</param>
        /// <param name="logger">The log.</param>
        /// <example>
        /// var journal = new TableJournal("Server=server;Database=database;Trusted_Connection=True", "dbo", "MyVersionTable");
        /// </example>
        public MySqlTableJournal(Func<IDbConnection> connectionFactory, string table, IUpgradeLog logger)
        {
            this.connectionFactory = connectionFactory;
            schemaTableName = tableName = table;

            log = logger;
        }
示例#10
0
    private static void GetMasterConnectionStringBuilder(string connectionString, IUpgradeLog logger, out string masterConnectionString, out string databaseName)
    {
        if (string.IsNullOrEmpty(connectionString) || connectionString.Trim() == string.Empty)
        {
            throw new ArgumentNullException(nameof(connectionString));
        }

        if (logger == null)
        {
            throw new ArgumentNullException(nameof(logger));
        }

        var masterConnectionStringBuilder = new NpgsqlConnectionStringBuilder(connectionString);

        databaseName = masterConnectionStringBuilder.Database;

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

        masterConnectionStringBuilder.Database = "postgres";

        var logMasterConnectionStringBuilder = new NpgsqlConnectionStringBuilder(masterConnectionStringBuilder.ConnectionString);

        if (!string.IsNullOrEmpty(masterConnectionStringBuilder.Password))
        {
            logMasterConnectionStringBuilder.Password = string.Empty.PadRight(masterConnectionStringBuilder.Password.Length, '*');
        }

        logger.WriteInformation("Master ConnectionString => {0}", logMasterConnectionStringBuilder.ConnectionString);

        masterConnectionString = masterConnectionStringBuilder.ConnectionString;
    }
示例#11
0
 public UpgradeTool()
 {
     logger      = LogManager.GetLogger(typeof(UpgradeEngine));
     log         = new Log4NetAndConsoleUpgradeLog(logger);
     stopwatch   = new Stopwatch();
     connections = new List <IDbConnection>();
 }
示例#12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FunnelWebJournal"/> class.
 /// </summary>
 /// <param name="connectionFactory"></param>
 /// <param name="sourceIdentifier">The source identifier - usually the ID of the extension or FunnelWeb.DatabaseDeployer.</param>
 /// <param name="logger">The log.</param>
 /// <param name="schema">Database Schema</param>
 /// <example>
 /// var journal = new TableJournal("Server=server;Database=database;Trusted_Connection=True;");
 /// </example>
 public FunnelWebJournal(Func<IDbConnection> connectionFactory, string sourceIdentifier, IUpgradeLog logger, string schema)
 {
     schemaTableName = string.IsNullOrEmpty(schema) ? TableName : string.Format("{0}.{1}", schema, TableName);
     this.connectionFactory = connectionFactory;
     this.sourceIdentifier = sourceIdentifier;
     log = logger;
 }
        /// <summary>
        /// Stores the hash for the specified file.
        /// </summary>
        /// <param name="contextManager">Provides the current SharePoint context</param>
        /// <param name="logger">To log messages to the migrator</param>
        /// <param name="prefixedServerRelativeUrl">Server relative URL of the file; a prefixed URL is allowed</param>
        /// <param name="hash">Hash value to store</param>
        public void StoreFileHash(IContextManager contextManager, IUpgradeLog logger, string prefixedServerRelativeUrl, byte[] hash)
        {
            if (_hashValues == null)
            {
                throw new InvalidOperationException("Must have been initialized first (by calling GetFileHash)");
            }

            var clientContext     = contextManager.CurrentContext;
            var serverRelativeUrl = SPUrlUtility.ResolveServerRelativeUrl(clientContext.Site, clientContext.Web, prefixedServerRelativeUrl);

            var webRelativeUrl = serverRelativeUrl.Substring(clientContext.Web.ServerRelativeUrl.Length);

            if (webRelativeUrl.StartsWith("/"))
            {
                webRelativeUrl = webRelativeUrl.Substring(1);
            }
            var hashString = BitConverter.ToString(hash);

            _hashValues[webRelativeUrl] = hashString;
            var propertyValue = JsonConvert.SerializeObject(_hashValues.ToList());

            clientContext.Web.AllProperties[_propertyBagKey] = propertyValue;
            clientContext.Web.Update();
            clientContext.ExecuteQuery();
        }
        /// <summary>
        /// Performs the upgrade.
        /// </summary>
        /// <returns>
        /// A container of information about the results of the database upgrade.
        /// </returns>
        public DatabaseUpgradeResult[] PerformUpgrade(IEnumerable<ScriptedExtension> scriptedExtensions, IUpgradeLog log)
        {
            var results = new List<DatabaseUpgradeResult>();
            
            var provider = providerLookup[connectionStringProvider.DatabaseProvider.ToLower()];
            var schema = provider.SupportSchema ? connectionStringProvider.Schema : null;
            var connectionFactory = provider.GetConnectionFactory(connectionStringProvider.ConnectionString);

            // Upgrade core
            var core = Upgrade(
                provider, CreateScriptProvider(connectionStringProvider.DatabaseProvider), log,
                CreateJournal(connectionFactory, CoreSourceIdentifier, schema), schema);
            results.Add(core);

            // Upgrade extensions
            var databaseUpgradeResults = scriptedExtensions
                .Select(extension =>
                        Upgrade(
                        provider, extension.ScriptProvider, log,
                            CreateJournal(connectionFactory, extension.SourceIdentifier, schema),
                            schema));
            results.AddRange(databaseUpgradeResults);

            return results.ToArray();
        }
示例#15
0
 /// <summary>
 /// Tries to connect to the database.
 /// </summary>
 public bool TryConnect(IUpgradeLog upgradeLog, out string errorMessage)
 {
     try
     {
         errorMessage      = "";
         upgradeConnection = CreateConnection(upgradeLog);
         if (upgradeConnection.State == ConnectionState.Closed)
         {
             upgradeConnection.Open();
         }
         var strategy = transactionStrategyFactory[TransactionMode.NoTransaction]();
         strategy.Initialise(upgradeConnection, upgradeLog);
         strategy.Execute(dbCommandFactory =>
         {
             using (var command = dbCommandFactory())
             {
                 command.CommandText = "select 1";
                 command.ExecuteScalar();
             }
         });
         return(true);
     }
     catch (Exception ex)
     {
         errorMessage = ex.Message;
         return(false);
     }
 }
        /// <summary>
        /// Gets the hash for the specified file.
        /// </summary>
        /// <param name="contextManager">Provides the current SharePoint context</param>
        /// <param name="logger">To log messages to the migrator</param>
        /// <param name="prefixedServerRelativeUrl">Server relative URL of the file; a prefixed URL is allowed.</param>
        /// <returns>The stored hash, or an empty array if there is no stored hash</returns>
        public byte[] GetFileHash(IContextManager contextManager, IUpgradeLog logger, string prefixedServerRelativeUrl)
        {
            if (_hashValues == null)
            {
                InitHashValues(contextManager, logger);
            }

            var clientContext     = contextManager.CurrentContext;
            var serverRelativeUrl = SPUrlUtility.ResolveServerRelativeUrl(clientContext.Site, clientContext.Web, prefixedServerRelativeUrl);

            var webRelativeUrl = serverRelativeUrl.Substring(clientContext.Web.ServerRelativeUrl.Length);

            if (webRelativeUrl.StartsWith("/"))
            {
                webRelativeUrl = webRelativeUrl.Substring(1);
            }
            var hash       = new List <byte>();
            var hashString = "";

            if (_hashValues.TryGetValue(webRelativeUrl, out hashString))
            {
                var parts = hashString.Split('-');
                foreach (var part in parts)
                {
                    hash.Add(byte.Parse(part, System.Globalization.NumberStyles.HexNumber));
                }
            }
            return(hash.ToArray());
        }
示例#17
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="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>
    /// <param name="collation">The collation name to set during database creation</param>
    /// <returns></returns>
    public static void MySqlDatabase(
        this SupportedDatabasesForEnsureDatabase supported,
        string connectionString,
        IUpgradeLog logger,
        int timeout      = -1,
        string collation = null)
    {
        GetMysqlConnectionStringBuilder(connectionString, logger, out var masterConnectionString, out var databaseName);

        try
        {
            using (var connection = new MySqlConnection(masterConnectionString))
            {
                connection.Open();
                if (DatabaseExists(connection, databaseName))
                {
                    return;
                }
            }
        }
        catch (Exception e)
        {
            logger.WriteInformation(@"Database not found on server with connection string in settings: {0}", e.Message);
        }

        using (var connection = new MySqlConnection(masterConnectionString))
        {
            connection.Open();
            if (DatabaseExists(connection, databaseName))
            {
                return;
            }

            var collationString = string.IsNullOrEmpty(collation) ? "" : string.Format(@" COLLATE {0}", collation);
            var sqlCommandText  = string.Format
                                  (
                @"create database {0}{1};",
                databaseName,
                collationString
                                  );


            // Create the database...
            using (var command = new MySqlCommand(sqlCommandText, connection)
            {
                CommandType = CommandType.Text
            })
            {
                if (timeout >= 0)
                {
                    command.CommandTimeout = timeout;
                }

                command.ExecuteNonQuery();
            }

            logger.WriteInformation(@"Created database {0}", databaseName);
        }
    }
示例#18
0
 public virtual void AfterEach()
 {
     ScriptProvider = null;
     VersionTracker = null;
     ScriptExecutor = null;
     Log = null;
     DbUpgrader = null;
 }
示例#19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SqlTableJournal"/> class.
 /// </summary>
 /// <param name="connectionFactory">The connection factory.</param>
 /// <param name="schema">The schema that contains the table.</param>
 /// <param name="table">The table name.</param>
 /// <param name="logger">The log.</param>
 /// <example>
 /// var journal = new TableJournal("Server=server;Database=database;Trusted_Connection=True", "dbo", "MyVersionTable");
 /// </example>
 public SqlTableJournal(Func<IDbConnection> connectionFactory, string schema, string table, IUpgradeLog logger)
 {
     this.connectionFactory = connectionFactory;
     schemaTableName = tableName = SqlObjectParser.QuoteSqlObjectName(table);
     if (!string.IsNullOrEmpty(schema))
         schemaTableName = SqlObjectParser.QuoteSqlObjectName(schema) + "." + tableName;
     log = logger;
 }
示例#20
0
 public void Initialise(IUpgradeLog upgradeLog)
 {
     log = upgradeLog;
     upgradeLog.WriteInformation("Beginning transaction");
     connection = connectionFactory();
     connection.Open();
     transaction = connection.BeginTransaction();
 }
示例#21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SqlTableJournal"/> class.
 /// </summary>
 /// <param name="connectionFactory">The connection factory.</param>
 /// <param name="schema">The schema that contains the table.</param>
 /// <param name="table">The table name.</param>
 /// <param name="logger">The log.</param>
 /// <example>
 /// var journal = new TableJournal("Server=server;Database=database;Trusted_Connection=True", "dbo", "MyVersionTable");
 /// </example>
 public SqlTableJournal(Func<IDbConnection> connectionFactory, string schema, string table, IUpgradeLog logger)
 {
     this.connectionFactory = connectionFactory;
     schemaTableName = tableName = table;
     if (!string.IsNullOrEmpty(schema))
         schemaTableName = schema + "." + tableName;
     log = logger;
 }
示例#22
0
 public virtual void AfterEach()
 {
     ScriptProvider = null;
     VersionTracker = null;
     ScriptExecutor = null;
     Log            = null;
     DbUpgrader     = null;
 }
示例#23
0
        protected override IDbConnection CreateConnection(IUpgradeLog log)
        {
            var conn = new SqlConnection(connectionString);

            if(this.IsScriptOutputLogged)
                conn.InfoMessage += (sender, e) => log.WriteInformation(e.Message + "\r\n");

            return conn;
        }
示例#24
0
 public void UpgradeStarting(IUpgradeLog upgradeLog)
 {
     if (transactionStrategy != null)
     {
         throw new InvalidOperationException("UpgradeStarting is meant to be called by DbUp and can only be called once");
     }
     transactionStrategy = transactionStrategyFactory[TransactionMode]();
     transactionStrategy.Initialise(upgradeLog);
 }
示例#25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UpgradeConfiguration"/> class.
        /// </summary>
        public UpgradeConfiguration()
        {
#if SUPPORTS_LIBLOG
            defaultLog = new AutodetectUpgradeLog();
#else
            defaultLog = new TraceUpgradeLog();
#endif
            VariablesEnabled = true;
        }
示例#26
0
 public void Initialise(IDbConnection dbConnection, IUpgradeLog upgradeLog, List <SqlScript> executedScripts)
 {
     executedScriptsCollection          = executedScripts;
     executedScriptsListBeforeExecution = executedScripts.ToArray();
     connection = dbConnection;
     log        = upgradeLog;
     upgradeLog.WriteInformation("Beginning transaction");
     transaction = connection.BeginTransaction();
 }
示例#27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SqlTableJournal"/> class.
 /// </summary>
 /// <param name="connectionFactory">The connection factory.</param>
 /// <param name="schema">The schema that contains the table.</param>
 /// <param name="table">The table name.</param>
 /// <param name="logger">The log.</param>
 /// <example>
 /// var journal = new TableJournal("Server=server;Database=database;Trusted_Connection=True", "dbo", "MyVersionTable");
 /// </example>
 public SqlTableJournal(Func <IDbConnection> connectionFactory, string schema, string table, IUpgradeLog logger)
 {
     this.connectionFactory = connectionFactory;
     schemaTableName        = tableName = SqlObjectParser.QuoteSqlObjectName(table);
     if (!string.IsNullOrEmpty(schema))
     {
         schemaTableName = SqlObjectParser.QuoteSqlObjectName(schema) + "." + tableName;
     }
     log = logger;
 }
        private DatabaseUpgradeResult Upgrade(IDatabaseProvider provider, IScriptProvider scriptProvider, IUpgradeLog log, IJournal journal, string schema)
        {
            var upgradeEngine = provider.GetUpgradeEngineBuilder(connectionStringProvider.ConnectionString, schema)
                .WithScripts(scriptProvider)
                .JournalTo(journal)
                .LogTo(log)
                .Build();

            return upgradeEngine.PerformUpgrade();
        }
示例#29
0
 public SqlDbProvider(IAmsLicenseManager licenseManager, IOptions <DatabaseConfigurationOptions> highAvailabilityOptions, ILogger <SqlDbProvider> logger, IUpgradeLog upgradeLogger, SqlLocalDbInstanceProvider localDbInstanceProvider, SqlServerInstanceProvider sqlServerInstanceProvider)
 {
     this.licenseManager          = licenseManager;
     this.highAvailabilityOptions = highAvailabilityOptions.Value;
     this.logger                    = logger;
     this.upgradeLogger             = upgradeLogger;
     this.localDbInstanceProvider   = localDbInstanceProvider;
     this.sqlServerInstanceProvider = sqlServerInstanceProvider;
     this.InitializeDb();
 }
示例#30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ScriptExecutingEngine"/> class.
 /// </summary>
 /// <param name="configuration">The configuration.</param>
 public ScriptExecutingEngine(DbInstallerConfiguration configuration)
 {
     _connectionString = configuration.ConnectionString;
     _journal = configuration.Journal;
     _databaseServerAdapter = configuration.DatabaseServerAdapter;
     _logger = configuration.Logger;
     _scriptProviders = configuration.ScriptProviders;
     _scriptPreProcessors = configuration.ScriptPreprocessors;
     _variables = configuration.Variables;
 }
示例#31
0
        /// <summary>
        /// Tells the context manager when it is starting, and completing, a migration context
        /// </summary>
        /// <param name="log">Log to use</param>
        public IDisposable ContextScope(IUpgradeLog log)
        {
            _log = log;
            _log.Verbose("Creating context {0}", _sharePointUrl);
            _context = new ClientContext(_sharePointUrl);
            var credentials = new SharePointOnlineCredentials(_userName, _securePassword);

            _context.Credentials = credentials;
            return(new BasicContextDisposer(this));
        }
        public DbObjectScripter(string connectionString, Options options, IUpgradeLog log)
        {
            m_connectionBuilder = new SqlConnectionStringBuilder(connectionString);
            m_options = options;
            m_log = log;

            var exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            m_definitionDirectory = Path.GetFullPath(Path.Combine(exePath, m_options.BaseFolderNameDefinitions)).Normalize();
            EnsureDirectoryExists(m_definitionDirectory);
        }
示例#33
0
        protected override IDbConnection CreateConnection(IUpgradeLog log)
        {
            var conn = new SqlConnection(connectionString);

            if (this.IsScriptOutputLogged)
            {
                conn.InfoMessage += (sender, e) => log.WriteInformation(e.Message + "\r\n");
            }

            return(conn);
        }
示例#34
0
        public override void Apply(IContextManager contextManager, IUpgradeLog logger)
        {
            logger.Information("Running migration for URL: {0}", contextManager.CurrentContext.Url);

            var clientContext = contextManager.CurrentContext;

            clientContext.Load(clientContext.Web, w => w.Title);
            clientContext.ExecuteQuery();

            logger.Warning("Site title is: {0}", clientContext.Web.Title);
        }
示例#35
0
 public static DbUpdater UsingEmbeddedScripts(Assembly migrationAssembly,
                                              string folderName,
                                              string databaseName,
                                              string connectionStringName,
                                              IDictionary <string, string> scriptVariables,
                                              bool seedData      = false,
                                              Env env            = Env.Undefined,
                                              IUpgradeLog logger = null)
 {
     return(new EmbeddedScriptsDbUpdater(migrationAssembly, folderName, databaseName, connectionStringName, scriptVariables, seedData, env, logger));
 }
示例#36
0
        public DbObjectScripter(string connectionString, Options options, IUpgradeLog log)
        {
            m_connectionBuilder = new SqlConnectionStringBuilder(connectionString);
            m_options           = options;
            m_log = log;

            var exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            m_definitionDirectory = Path.GetFullPath(Path.Combine(exePath, m_options.BaseFolderNameDefinitions)).Normalize();
            EnsureDirectoryExists(m_definitionDirectory);
        }
        public ScriptHost(IUpgradeLog logger)
        {
            _hostUI = new ScriptHostUI(logger);
            _id     = Guid.NewGuid();
            _originalCultureInfo   = Thread.CurrentThread.CurrentCulture;
            _originalUICultureInfo = Thread.CurrentThread.CurrentUICulture;

            var assembly = System.Reflection.Assembly.GetExecutingAssembly();
            var fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);

            _version = new Version(fvi.FileMajorPart, fvi.FileMinorPart, fvi.FileBuildPart, fvi.FilePrivatePart);
        }
示例#38
0
 public FileSystemScriptsDbUpdater(string folderName,
                                   FileSystemScriptOptions fileSystemScriptOptions,
                                   string databaseName,
                                   string connectionStringName,
                                   IDictionary <string, string> scriptVariables,
                                   bool seedData          = false,
                                   Env env                = Env.Undefined,
                                   IUpgradeLog upgradeLog = null)
     : base(folderName, databaseName, connectionStringName, scriptVariables, seedData, env, upgradeLog)
 {
     this._fileSystemScriptOptions = fileSystemScriptOptions;
 }
示例#39
0
 public EmbeddedScriptsDbUpdater(Assembly migrationAssembly,
                                 string folderName,
                                 string databaseName,
                                 string connectionStringName,
                                 IDictionary <string, string> scriptVariables,
                                 bool seedData      = false,
                                 Env env            = Env.Undefined,
                                 IUpgradeLog logger = null)
     : base(folderName, databaseName, connectionStringName, scriptVariables, seedData, env, logger)
 {
     _namespacePrefix   = migrationAssembly.GetName().Name;
     _migrationAssembly = migrationAssembly;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="UpgradeConfiguration"/> class.
        /// </summary>
        public UpgradeConfiguration()
        {
#if SUPPORTS_LIBLOG
            defaultLog = new AutodetectUpgradeLog();
#else
            defaultLog = new TraceUpgradeLog();
#endif
            VariablesEnabled = true;

            Hasher = new Hasher();

            ScriptDependencyOrderer = new ScriptDependencyOrderer();
        }
示例#41
0
 static UpgradeEngine CreateUpgradeEngine(Context context, IUpgradeLog upgradeLog)
 {
     var connectionString = context.ConnectionString;
     var scriptsPath = context.ScriptsPath;
     var auxScriptPath = context.AuxiliaryScriptsPath;
     var variables = context.Variables;
     return DeployChanges
         .To
         .SqlDatabase(connectionString)
         .WithScriptsFromFileSystem(scriptsPath)
         .WithScriptsFromFileSystem(auxScriptPath)
         .LogTo(upgradeLog)
         .WithVariables(variables)
         .Build();
 }
示例#42
0
 static bool DatabaseExistsIfConnectedToDirectly(IUpgradeLog logger, string connectionString, string databaseName)
 {
     try
     {
         using (var connection = new SqlConnection(connectionString))
         {
             connection.Open();
             return(DatabaseExists(connection, databaseName));
         }
     }
     catch
     {
         logger.WriteInformation("Could not connect to the database directly");
         return(false);
     }
 }
示例#43
0
 public void SetUp()
 {
     log = Substitute.For<IUpgradeLog>();
     upgradeResult = null;
     scripts = new List<SqlScript>
     {
         new SqlScript("Script1.sql", "create table Foo (Id int identity)"),
         new SqlScript("Script2.sql", "alter table Foo add column Name varchar(255)"),
         new SqlScript("Script3.sql", "insert into Foo (Name) values ('test')")
     };
     database = new TemporarySQLiteDatabase("IntegrationScenarios");
     upgradeEngineBuilder = DeployChanges.To
         .SQLiteDatabase(database.SharedConnection)
         .WithScripts(new TestScriptProvider(scripts))
         .LogTo(log);
 }
示例#44
0
        public virtual void BeforeEach()
        {
            ScriptProvider = Substitute.For<IScriptProvider> ();
            VersionTracker = Substitute.For<IJournal> ();
            ScriptExecutor = Substitute.For<IScriptExecutor> ();
            ScriptPreprocessor = Substitute.For<IScriptPreprocessor>();

            Log = Substitute.For<IUpgradeLog> ();

            var config = new UpgradeConfiguration();

            config.ScriptPreprocessors.Add(ScriptPreprocessor);
            config.ScriptProviders.Add(ScriptProvider);
            config.ScriptExecutor = ScriptExecutor;
            config.Journal = VersionTracker;
            config.Log = Log;

            DbUpgrader = new ScriptExecutingEngine(config);
        }
示例#45
0
        /// <summary>
        /// Records a database upgrade for a database specified in a given connection string.
        /// </summary>
        /// <param name="script">The script.</param>
        public void UpdateVersion(SqlScript executedScript, Func<IDbConnection> connectionFactory, IUpgradeLog log)
        {
            if (executedScript.IsAdminScript)
                return;

            DbVersion version = this.GetDbVersionFromScript(executedScript);

            using (IDbConnection connection = connectionFactory())
            {
                using (IDbCommand command = connection.CreateCommand())
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = "InsertDbVersion";

                    command.AddParameterValue("@major", version.Major);
                    command.AddParameterValue("@minor", version.Minor);
                    command.AddParameterValue("@revision", version.Revision);
                    command.AddParameterValue("@build", version.Build);
                    command.AddParameterValue("@username", version.Username);
                    command.AddParameterValue("@comments", version.Comments);
                    connection.Open();
                    command.ExecuteNonQuery();
                }
            }
        }
示例#46
0
 protected override IDbConnection CreateConnection(IUpgradeLog log)
 {
     return connection;
 }
示例#47
0
 /// <summary>
 /// Logs to a custom logger.
 /// </summary>
 /// <param name="builder"></param>
 /// <param name="log">The logger.</param>
 /// <returns>
 /// The same builder
 /// </returns>
 public static UpgradeEngineBuilder LogTo(this UpgradeEngineBuilder builder, IUpgradeLog log)
 {
     builder.Configure(c => c.Log = log);
     return builder;
 }
示例#48
0
 protected override IDbConnection CreateConnection(IUpgradeLog log)
 {
     // if we have a shared connection, return it, otherwise create a connection
     return (IDbConnection)sharedConnection ?? new SQLiteConnection(connectionString);
 }
示例#49
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;
            }
        }
示例#50
0
 public Upgrader(Context context, IUpgradeLog upgradeLog)
 {
     _context = context;
     _upgradeEngine = CreateUpgradeEngine(_context, upgradeLog);
 }
示例#51
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="DbUp.Engine.Output.IUpgradeLog"/> used to record actions.</param>
    /// <returns></returns>
    public static void SqlDatabase(this SupportedDatabasesForEnsureDatabase supported, string connectionString, IUpgradeLog logger)
    {
        if (supported == null) throw new ArgumentNullException("supported");

        if (string.IsNullOrEmpty(connectionString) || connectionString.Trim() == string.Empty)
        {
            throw new ArgumentNullException("connectionString");
        }

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

        var masterConnectionStringBuilder = new SqlConnectionStringBuilder(connectionString);

        var databaseName = masterConnectionStringBuilder.InitialCatalog;

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

        masterConnectionStringBuilder.InitialCatalog = "master";

        var logMasterConnectionStringBuilder = new SqlConnectionStringBuilder(masterConnectionStringBuilder.ConnectionString)
        {
            Password = String.Empty.PadRight(masterConnectionStringBuilder.Password.Length,'*')
        };

        logger.WriteInformation("Master ConnectionString => {0}", logMasterConnectionStringBuilder.ConnectionString);

        using (var connection = new SqlConnection(masterConnectionStringBuilder.ConnectionString))
        {
            connection.Open();

            var sqlCommandText = string.Format
                (
                    @"select case when db_id('{0}') is not null then 1 else 0 end;",
                    databaseName
                );

            // check to see if the database already exists..
            using (var command = new SqlCommand(sqlCommandText, connection)
            {
                CommandType = CommandType.Text
            })
            {
                var results = (int) command.ExecuteScalar();

                // if the database exists, we're done here...
                if (results == 1) return;
            }

            sqlCommandText = string.Format
                    (
                        @"create database [{0}];",
                        databaseName
                    );

            // Create the database...
            using (var command = new SqlCommand(sqlCommandText, connection)
            {
                CommandType = CommandType.Text
            })
            {
                command.ExecuteNonQuery();

            }

            logger.WriteInformation(@"Created database {0}", databaseName);
        }
    }
示例#52
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="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></returns>
    public static void SqlDatabase(this SupportedDatabasesForEnsureDatabase supported, string connectionString, IUpgradeLog logger, int timeout = -1)
    {
        if (supported == null) throw new ArgumentNullException("supported");

        if (string.IsNullOrEmpty(connectionString) || connectionString.Trim() == string.Empty)
        {
            throw new ArgumentNullException("connectionString");
        }

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

        var masterConnectionStringBuilder = new SqlConnectionStringBuilder(connectionString);

        var databaseName = masterConnectionStringBuilder.InitialCatalog;

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

        masterConnectionStringBuilder.InitialCatalog = "master";

        var logMasterConnectionStringBuilder = new SqlConnectionStringBuilder(masterConnectionStringBuilder.ConnectionString)
        {
            Password = String.Empty.PadRight(masterConnectionStringBuilder.Password.Length, '*')
        };

        logger.WriteInformation("Master ConnectionString => {0}", logMasterConnectionStringBuilder.ConnectionString);

        using (var connection = new SqlConnection(masterConnectionStringBuilder.ConnectionString))
        {
            connection.Open();

            var sqlCommandText = string.Format
                (
                    @"SELECT TOP 1 case WHEN dbid IS NOT NULL THEN 1 ELSE 0 end FROM sys.sysdatabases WHERE name = '{0}';",
                    databaseName
                );

            // check to see if the database already exists..
            using (var command = new SqlCommand(sqlCommandText, connection)
            {
                CommandType = CommandType.Text
            })

            {
                var results = (int?)command.ExecuteScalar();

                // if the database exists, we're done here...
                if (results.HasValue && results.Value == 1)
                {
                    return;
                }
            }

            sqlCommandText = string.Format
                    (
                        @"create database [{0}];",
                        databaseName
                    );

            // Create the database...
            using (var command = new SqlCommand(sqlCommandText, connection)
            {
                CommandType = CommandType.Text
            })
            {
                if (timeout >= 0)
                {
                    command.CommandTimeout = timeout;
                }

                command.ExecuteNonQuery();

            }

            logger.WriteInformation(@"Created database {0}", databaseName);
        }
    }
示例#53
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="DbUp.Engine.Output.IUpgradeLog"/> used to record actions.</param>
    /// <returns></returns>
    public static void PostgresqlDatabase(this SupportedDatabasesForEnsureDatabase supported, string connectionString, IUpgradeLog logger)
    {
        if (supported == null) throw new ArgumentNullException("supported");

        if (string.IsNullOrEmpty(connectionString) || connectionString.Trim() == string.Empty)
        {
            throw new ArgumentNullException("connectionString");
        }

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

        var masterConnectionStringBuilder = new NpgsqlConnectionStringBuilder(connectionString);

        var databaseName = masterConnectionStringBuilder.Database;

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

        masterConnectionStringBuilder.Database = "postgres";

        var logMasterConnectionStringBuilder = new NpgsqlConnectionStringBuilder(masterConnectionStringBuilder.ConnectionString);
        if (!string.IsNullOrEmpty(logMasterConnectionStringBuilder.Password))
        {
            logMasterConnectionStringBuilder.Password = String.Empty.PadRight(masterConnectionStringBuilder.Password.Length, '*');
        }

        logger.WriteInformation("Master ConnectionString => {0}", logMasterConnectionStringBuilder.ConnectionString);

        using (var connection = new NpgsqlConnection(masterConnectionStringBuilder.ConnectionString))
        {
            connection.Open();

            var sqlCommandText = string.Format
                (
                    @"SELECT case WHEN oid IS NOT NULL THEN 1 ELSE 0 end FROM pg_database WHERE datname = '{0}' limit 1;",
                    databaseName
                );

            // check to see if the database already exists..
            using (var command = new NpgsqlCommand(sqlCommandText, connection)
            {
                CommandType = CommandType.Text
            })
            {
                var results = (int?) command.ExecuteScalar();

                // if the database exists, we're done here...
                if (results.HasValue && results.Value == 1)
                {
                    return;
                }
            }

            sqlCommandText = string.Format
                (
                    "create database \"{0}\";",
                    databaseName
                );

            // Create the database...
            using (var command = new NpgsqlCommand(sqlCommandText, connection)
            {
                CommandType = CommandType.Text
            })
            {
                command.ExecuteNonQuery();

            }

            logger.WriteInformation(@"Created database {0}", databaseName);
        }
    }
示例#54
0
 /// <summary>
 /// Creates a new Firebird database connection.
 /// </summary>
 /// <param name="log">The upgrade log.</param>
 /// <returns>The database connection.</returns>
 protected override IDbConnection CreateConnection(IUpgradeLog log)
 {
     return new FbConnection(_connectionString);
 }
示例#55
0
 public IDbConnection CreateConnection(IUpgradeLog upgradeLog, DatabaseConnectionManager databaseConnectionManager)
 {
     return createConnection(upgradeLog, databaseConnectionManager);
 }