1
0
mirror of https://github.com/bitwarden/server.git synced 2024-11-25 12:45:18 +01:00
bitwarden-server/util/Migrator/SqlServerDbMigrator.cs
Michał Chęciński 3e90f57797
[DEVOPS-1519] Add transition mode to mssql migrator utility (#3259)
* Add RerunableSqlTableJournal

* Add extension to use rerunable sql table journal

* Use rerunable sql journal

* format

* Enable logging

* FIx

* Disable logging

* Rename to SqlTableJournalExtensions

* Move RerunableSqlTableJournal to Extension class

* Fix usings

* Add rerunable schema

* Format

* Fix typo

* Enable logging in db migrator

* add rerunable column in dbo migrations table migration

* Trying

* Fix journal table name

* Trying to migrate first

* After migration

* Testing

* Add update from rerunable to not rerunable script

* Change name

* Add rerunable option and script folder name

* Add rerunable options and folder

* Fix

* Add transition (aka rerunable) migrations to Setup

* Parse parameters on migrator utility

* Fix sql scripts

* Remove CreateSchemaTableSql as it'll be migrated using migration

* Embed dbScripts_data_migration folder

* Remove testing sql script

* Add optins parsing nuget for msSqlMigratorUtility

* Fix sql journal

* Ran dotnet format

* Comment out index

* ▫️Revert "Comment out index"

This reverts commit df15fa91e0.

* Disable logging

* Add newline

* Rename rerunable to repeatable

* remove repeatable journal

* Remove migration adding the repeatable column in  dbo.Migrations table

* Add using

* Enable log for testing

* Disable logging in the setup

* Remove unused method

* Add migrator constants

* Use constants in yet another place

* Fix

* Add constant

* Fix

* Fix
2023-09-28 16:29:52 +02:00

110 lines
3.9 KiB
C#

using System.Data;
using System.Reflection;
using Bit.Core;
using Bit.Core.Settings;
using Bit.Core.Utilities;
using DbUp;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Logging;
namespace Bit.Migrator;
public class SqlServerDbMigrator : IDbMigrator
{
private readonly string _connectionString;
private readonly ILogger<SqlServerDbMigrator> _logger;
private readonly string _masterConnectionString;
public SqlServerDbMigrator(GlobalSettings globalSettings, ILogger<SqlServerDbMigrator> logger)
{
_connectionString = globalSettings.SqlServer.ConnectionString;
_logger = logger;
_masterConnectionString = new SqlConnectionStringBuilder(_connectionString)
{
InitialCatalog = "master"
}.ConnectionString;
}
public bool MigrateDatabase(bool enableLogging = true,
CancellationToken cancellationToken = default(CancellationToken))
{
if (enableLogging && _logger != null)
{
_logger.LogInformation(Constants.BypassFiltersEventId, "Migrating database.");
}
using (var connection = new SqlConnection(_masterConnectionString))
{
var databaseName = new SqlConnectionStringBuilder(_connectionString).InitialCatalog;
if (string.IsNullOrWhiteSpace(databaseName))
{
databaseName = "vault";
}
var databaseNameQuoted = new SqlCommandBuilder().QuoteIdentifier(databaseName);
var command = new SqlCommand(
"IF ((SELECT COUNT(1) FROM sys.databases WHERE [name] = @DatabaseName) = 0) " +
"CREATE DATABASE " + databaseNameQuoted + ";", connection);
command.Parameters.Add("@DatabaseName", SqlDbType.VarChar).Value = databaseName;
command.Connection.Open();
command.ExecuteNonQuery();
command.CommandText = "IF ((SELECT DATABASEPROPERTYEX([name], 'IsAutoClose') " +
"FROM sys.databases WHERE [name] = @DatabaseName) = 1) " +
"ALTER DATABASE " + databaseNameQuoted + " SET AUTO_CLOSE OFF;";
command.ExecuteNonQuery();
}
cancellationToken.ThrowIfCancellationRequested();
using (var connection = new SqlConnection(_connectionString))
{
// Rename old migration scripts to new namespace.
var command = new SqlCommand(
"IF OBJECT_ID('Migration','U') IS NOT NULL " +
"UPDATE [dbo].[Migration] SET " +
"[ScriptName] = REPLACE([ScriptName], 'Bit.Setup.', 'Bit.Migrator.');", connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
cancellationToken.ThrowIfCancellationRequested();
var builder = DeployChanges.To
.SqlDatabase(_connectionString)
.JournalToSqlTable("dbo", MigratorConstants.SqlTableJournalName)
.WithScriptsAndCodeEmbeddedInAssembly(Assembly.GetExecutingAssembly(),
s => s.Contains($".DbScripts.") && !s.Contains(".Archive."))
.WithTransaction()
.WithExecutionTimeout(TimeSpan.FromMinutes(5));
if (enableLogging)
{
if (_logger != null)
{
builder.LogTo(new DbUpLogger(_logger));
}
else
{
builder.LogToConsole();
}
}
var upgrader = builder.Build();
var result = upgrader.PerformUpgrade();
if (enableLogging && _logger != null)
{
if (result.Successful)
{
_logger.LogInformation(Constants.BypassFiltersEventId, "Migration successful.");
}
else
{
_logger.LogError(Constants.BypassFiltersEventId, result.Error, "Migration failed.");
}
}
cancellationToken.ThrowIfCancellationRequested();
return result.Successful;
}
}