Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NullReferenceException when using SqlTableJournal #10

Open
RobWaterhouse95 opened this issue Jun 21, 2022 · 0 comments
Open

NullReferenceException when using SqlTableJournal #10

RobWaterhouse95 opened this issue Jun 21, 2022 · 0 comments
Labels
bug Something isn't working

Comments

@RobWaterhouse95
Copy link

I get the following error when using a SqlTableJournal or when using a custom Journal that implements TableJournal.

If I change the DeployChanges.To... code and remove the .JournalTo(journal) line, the problem goes away.

My main goals is to add more columns to the SchemaVersions table, by adding what release version a script was applied on. If there's an easier way to do this please can someone let me know.

Upgrade failed due to an unexpected exception:
System.NullReferenceException: Object reference not set to an instance of an object.
   at DbUp.Engine.Transactions.DatabaseConnectionManager.ExecuteCommandsWithManagedConnection[T](Func`2 actionWithResult)
   at DbUp.Engine.UpgradeEngine.GetScriptsToExecuteInsideOperation()
   at DbUp.Engine.UpgradeEngine.PerformUpgrade()
System.NullReferenceException: Object reference not set to an instance of an object.
   at DbUp.Engine.Transactions.DatabaseConnectionManager.ExecuteCommandsWithManagedConnection[T](Func`2 actionWithResult)
   at DbUp.Engine.UpgradeEngine.GetScriptsToExecuteInsideOperation()
   at DbUp.Engine.UpgradeEngine.PerformUpgrade()
using DbUp.Engine;
using DbUp.Engine.Output;
using DbUp.SqlServer;
using System.Data.SqlClient;

namespace SQLScriptDeploymentTool
{
    internal class Program
    {
        private static string ConnectionString => "Data Source=(local);Initial Catalog=db;User Id=dbuser;password=dbpass;";

        static void Main()
        {
            var connectionString = BuildConnectionString("(local)", "db", "dbuser", "dbpass");
            var journal = GenerateJournal(ConnectionString);

            var version = string.Empty;
            DatabaseUpgradeResult result;
            if (version != string.Empty)
            {
                result = PerformRollback(journal, ConnectionString, version);
            }
            else
            {
                result = PerformRollforward(journal, ConnectionString, version);
            }

            if (!result.Successful)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(result.Error);
                Console.ResetColor();
                Console.ReadLine();
                return;
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Success!");
            Console.ResetColor();
            Console.ReadLine();
            return;
        }

        private static DatabaseUpgradeResult PerformRollback(SqlTableJournal journal, string connectionString, string version)
        {
            var sqlScripts = RetrieveScriptstoRollback(version);

            var upgrader =
                DeployChanges.To
                    .SqlDatabase(connectionString)
                    .JournalTo(journal)
                    .WithScripts(sqlScripts)
                    .LogToConsole()
                    .Build();

            return upgrader.PerformUpgrade();
        }

        private static DatabaseUpgradeResult PerformRollforward(SqlTableJournal journal, string connectionString, string version)
        {
            var upgrader =
                DeployChanges.To
                    .SqlDatabase(connectionString)
                    .JournalTo(journal)
                    .WithScriptsFromFileSystem("C:/Projects/P-Platform/MppGlobal.BuildResources/SqlScripts/PostSSDT/P-Core/228.0/Rollforward")
                    .LogToConsole()
                    .Build();

            return upgrader.PerformUpgrade();
        }

        private static SqlTableJournal GenerateJournal(string connectionString)
        {
            var connectionManager = new SqlConnectionManager(connectionString);
            var logger = new ConsoleUpgradeLog();
            return new SqlTableJournal(() => connectionManager, () => logger, "dbo", "DeploymentScriptLog");
        }

        private static SqlScript[] RetrieveScriptstoRollback(string version)
        {
            IList<SqlScript> scriptsToRollback = new List<SqlScript>();
            SqlConnection connection = new(ConnectionString);
            connection.Open();

            var sql = $"SELECT [ScriptName], [Applied] FROM [dbo].[SchemaVersions] WHERE [Applied] > '{ConvertVersionToDateTime(version)}'";
            SqlCommand command = new(sql, connection);
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                scriptsToRollback.Add(new SqlScript(reader.GetString(0), ""));
            }

            return scriptsToRollback.ToArray();
        }

        private static string BuildConnectionString(string server, string database, string username, string password)
        {
            var conn = new SqlConnectionStringBuilder
            {
                DataSource = server,
                InitialCatalog = database
            };

            if (!String.IsNullOrEmpty(username))
            {
                conn.UserID = username;
                conn.Password = password;
                conn.IntegratedSecurity = false;
            }
            else
            {
                conn.IntegratedSecurity = true;
            }

            return conn.ToString();
        }

        private static string ConvertVersionToDateTime(string version)
        {
            var year = int.Parse(version[0..4]);
            var month = int.Parse(version[4..6]);
            var day = int.Parse(version[6..8].ToString());

            return $"{year}-{month}-{day}";
        }
    }
}
@RobWaterhouse95 RobWaterhouse95 added the bug Something isn't working label Jun 21, 2022
@droyad droyad transferred this issue from DbUp/DbUp Jan 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
Status: Bugs
Development

No branches or pull requests

1 participant