From d83554b8500f94030ca333b87d66d8ba6ea083af Mon Sep 17 00:00:00 2001 From: Michal Checinski Date: Wed, 16 Aug 2023 17:31:41 +0200 Subject: [PATCH] Add RerunableSqlTableJournal --- util/Migrator/RerunableSqlTableJournal.cs | 58 +++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 util/Migrator/RerunableSqlTableJournal.cs diff --git a/util/Migrator/RerunableSqlTableJournal.cs b/util/Migrator/RerunableSqlTableJournal.cs new file mode 100644 index 0000000000..fa2a709f83 --- /dev/null +++ b/util/Migrator/RerunableSqlTableJournal.cs @@ -0,0 +1,58 @@ +using System; +using DbUp.Engine.Output; +using DbUp.Engine.Transactions; +using DbUp.Support; +using DbUp.Engine; +using System.Data; +using System.Collections.Generic; +using DbUp.SqlServer; + +namespace Bit.Migrator; + + public class RerunableSqlTableJournal : TableJournal + { + + public RerunableSqlTableJournal(Func connectionManager, Func logger, string schema, string table) + : base(connectionManager, logger, new SqlServerObjectParser(), schema, table) + { + } + + protected new IDbCommand GetInsertScriptCommand(Func dbCommandFactory, SqlScript script) + { + var command = dbCommandFactory(); + + var scriptNameParam = command.CreateParameter(); + scriptNameParam.ParameterName = "scriptName"; + scriptNameParam.Value = script.Name; + command.Parameters.Add(scriptNameParam); + + var appliedParam = command.CreateParameter(); + appliedParam.ParameterName = "applied"; + appliedParam.Value = DateTime.Now; + command.Parameters.Add(appliedParam); + + command.CommandText = GetInsertJournalEntrySql("@scriptName", "@applied"); + command.CommandType = CommandType.Text; + return command; + } + + protected override string GetInsertJournalEntrySql(string @scriptName, string @applied) + { + return $"insert into {FqSchemaTableName} (ScriptName, Applied) values ({@scriptName}, {@applied})"; + } + + protected override string GetJournalEntriesSql() + { + return $"select [ScriptName] from {FqSchemaTableName} order by [ScriptName]"; + } + + protected override string CreateSchemaTableSql(string quotedPrimaryKeyName) + { + return +$@"create table {FqSchemaTableName} ( + [Id] int identity(1,1) not null constraint {quotedPrimaryKeyName} primary key, + [ScriptName] nvarchar(255) not null, + [Applied] datetime not null +)"; + } + }