Skip to content

NullReferenceException when using SqlTableJournal #10

Description

@RobWaterhouse95

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}";
        }
    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions