强制DBUP在开发过程中重新运行新脚本

时间:2019-01-30 14:42:10

标签: c# sql continuous-integration continuous-deployment dbup

我们正在使用DBUP来处理数据库迁移。在每个发行版中,我们都希望使用命令行开关来运行dbup控制台应用程序,以便在开发期间我们可以在运行脚本时重新运行脚本,但是我们不希望它重新运行以前的所有脚本。释放已经出现在数据库中的脚本。如何实现?

1 个答案:

答案 0 :(得分:0)

我们在DbUp控制台应用程序中添加了“ -debug”命令行开关。如果存在,我们在与数据库对话时切换使用哪个Journal类。

DbUp中的Journal类(https://dbup.readthedocs.io/en/latest/more-info/journaling/)是与数据库进行交互以检查和记录哪些脚本已运行的类(默认存储在Schema Versions表中)。对于Dev,我们强迫它使用只读版本,可以检查已经存在的脚本(以防止您每次重新运行一切),但是会阻止记录新记录,因此下次它将尝试再次重新运行您的新脚本。

只读日记看起来像这样;

public class ReadOnlyJournal : IJournal
{

    private readonly IJournal _innerJournal;

    public ReadOnlyJournal(IJournal innerJournal)
    {
        _innerJournal = innerJournal;
    }

    public void EnsureTableExistsAndIsLatestVersion(Func<IDbCommand> dbCommandFactory)
    {
        _innerJournal.EnsureTableExistsAndIsLatestVersion(dbCommandFactory);
    }

    public string[] GetExecutedScripts()
    {
        return _innerJournal.GetExecutedScripts().ToArray();
    }

    public void StoreExecutedScript(SqlScript script, Func<IDbCommand> dbCommandFactory)
    {
        // don't store anything
    }
}

然后是一种扩展方法,使该新日记帐的使用更加容易指定;

public static class DbUpHelper
{
    public static UpgradeEngineBuilder WithReadOnlyJournal(this UpgradeEngineBuilder builder, string schema, string table)
    {
        builder.Configure(c => c.Journal = new ReadOnlyJournal(new SqlTableJournal(() => c.ConnectionManager, () => c.Log, schema, table)));
        return builder;
    }
}

最后是对DbUp控制台应用程序的更改;

var upgrader = debug 
            ? DeployChanges.To
                .SqlDatabase(connectionString)
                .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
                .WithReadOnlyJournal("dbo", "SchemaVersions")
                .LogToConsole()
                .Build()
            : DeployChanges.To
                .SqlDatabase(connectionString)
                .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
                .LogToConsole()
                .Build();

var result = upgrader.PerformUpgrade();

        if (!result.Successful)
        ....