Skip to content

Commit

Permalink
Added unit testing and documentation, refactored code
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Hedgpeth committed Mar 8, 2015
1 parent 57ad092 commit 14ee87c
Show file tree
Hide file tree
Showing 15 changed files with 11,239 additions and 54 deletions.
67 changes: 67 additions & 0 deletions DatabaseUpgrader.Test/DatabaseUpgrader.Test.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{94300A19-82F6-4E55-AE02-919355EF159D}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>DatabaseUpgrader.Test</RootNamespace>
<AssemblyName>DatabaseUpgrader.Test</AssemblyName>
<TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="nunit.framework, Version=2.6.4.14350, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\Source\packages\NUnit.2.6.4\lib\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="DatabaseUpgraderTest.cs" />
<Compile Include="OptionsTest.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Source\DatabaseUpgrader.csproj">
<Project>{F6DD288D-8D93-49A3-8B79-02B40C46665E}</Project>
<Name>DatabaseUpgrader</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
34 changes: 34 additions & 0 deletions DatabaseUpgrader.Test/DatabaseUpgraderTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System.Linq;
using NUnit.Framework;

namespace DatabaseUpgrader.Test
{
[TestFixture]
public class DatabaseUpgraderTest
{
[TestCase("1.sql", 1)]
[TestCase("25.sql", 25)]
[TestCase("something.sql", 0)]
[Test]
public void DatabaseVersionFor_ShouldParse(string file, int expected)
{
Assert.That(DatabaseUpgrader.DatabaseVersionFor(file), Is.EqualTo(expected));
}
private static readonly string[] UpgradeFiles = { "something.sql", "3.sql", "2.sql", "1.sql" };


private static SchemaVersion CreateSchemaVersionFor(int currentSchemaVersion)
{
return new SchemaVersion() {DatabaseVersion = currentSchemaVersion};
}

[Test]
public void OrderScriptsToUpgradeDatabase_ShouldProperlyOrderScripts()
{
var result = DatabaseUpgrader.OrderScriptsToUpgradeDatabase(CreateSchemaVersionFor(1), UpgradeFiles).ToArray();
Assert.That(result, Is.Not.Contains("1.sql"));
Assert.That(result[0], Is.EqualTo("2.sql"));
Assert.That(result[1], Is.EqualTo("3.sql"));
}
}
}
38 changes: 38 additions & 0 deletions DatabaseUpgrader.Test/OptionsTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using NUnit.Framework;

namespace DatabaseUpgrader.Test
{
[TestFixture]
public class OptionsTest
{
const string Directory = ".";
const string ConnectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword";
private const string Version = "1.2.3.4";
[Test]
public void Parse_ShouldParseCheckIfUpgradeRequired()
{
var options = Options.Parse("--checkIfUpgradeRequired", string.Format("-c{0}", ConnectionString), string.Format("-d{0}", Directory));

AssertOptions(options);
}

private static void AssertOptions(Options options, bool expectedCheckIfUpgradeRequired = true, string expectedVersion = null)
{
Assert.That(options, Is.Not.Null);
Assert.That(options.CheckIfUpgradeRequired, Is.EqualTo(expectedCheckIfUpgradeRequired));
Assert.That(options.ConnectionString, Is.EqualTo(ConnectionString));
Assert.That(options.SchemaDirectory, Is.EqualTo(Directory));
Assert.That(options.SoftwareVersion, Is.EqualTo(expectedVersion));
}

[Test]
public void Parse_ShouldParseUpgrade()
{
var options = Options.Parse(string.Format("-c{0}", ConnectionString), string.Format("-d{0}", Directory),
"-v" + Version);

AssertOptions(options, false, Version);
}

}
}
36 changes: 36 additions & 0 deletions DatabaseUpgrader.Test/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DatabaseUpgrader.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("NCR Corporation")]
[assembly: AssemblyProduct("DatabaseUpgrader.Test")]
[assembly: AssemblyCopyright("Copyright © NCR Corporation 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("23b1d612-67c0-47d9-b867-e5a6aa72470d")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
4 changes: 4 additions & 0 deletions DatabaseUpgrader.Test/packages.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="NUnit" version="2.6.4" targetFramework="net451" />
</packages>
25 changes: 24 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,24 @@
# sql-schema-manager
# DatabaseUpgrader
A simple project to manage schema versions in SQL Server. Compatible with chef.

Doesn't currently use transactions, so you should be sure that your schema is good.

# Overview
This process can be used standalone or with chef. Create a scripts folder in your source and create sql files in Sql Management Studio that fit the pattern [DatabaseVersion].sql. So you'll end up with 1.sql, 2.sql, etc.

When the program runs, it checks the Version table for the latest version that is in the table. It then checks if any files are greater than that version, and runs those sql files if out of date.

# Usage
## Check if a Database Upgrade is Needed
This will be useful for a not-if condition in chef:

DatabaseUpgrader.exe --checkIfUpgradeRequired "-cServer=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword" -dscripts

Note the quotes so you can have a space in the connection string. Also, the scripts will be found in the scripts directory, relative to the executable.

## Upgrade Database to Latest Version
This will perform the upgrade, or do nothing if the schema is up to date.

DatabaseUpgrader.exe "-cServer=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword" -dscripts -v1.2.3.4

The upgrader will insert the version of the software into the version table, so you have a good history of what has been done on the database.
44 changes: 10 additions & 34 deletions Source/DatabaseUpgrader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,7 @@ public bool RequiresUpgrade()
Log.Error("You must have a version defined in the upgrade table to continue");
return false;
}
int destination = HighestFileNumberPast(currentSchemaVersion);
Log.InfoFormat("The database is currently at {0} and the highest schema available is {1}");
bool requiresUpgrade = currentSchemaVersion.DatabaseVersion < destination;
bool requiresUpgrade = OrderScriptsToUpgradeDatabase(currentSchemaVersion, m_UpgradeFiles).Length > 0;
Log.InfoFormat("This database does{0} require upgrade", requiresUpgrade ? string.Empty : " not");
return requiresUpgrade;
}
Expand All @@ -45,17 +43,16 @@ public bool UpgradeSchema()
Log.Error("You must have a version defined in the upgrade table to continue");
return false;
}
int destination = HighestFileNumberPast(currentSchemaVersion);
if (currentSchemaVersion.DatabaseVersion == destination)
var orderedScriptsToExecute = OrderScriptsToUpgradeDatabase(currentSchemaVersion, m_UpgradeFiles);
if (orderedScriptsToExecute.Length == 0)
{
Log.InfoFormat("The database version {0} is current so no upgrade is needed.", destination);
Log.InfoFormat("The database version {0} is current so no upgrade is needed.", currentSchemaVersion.DatabaseVersion);
return true;
}
var orderedScriptsToExecute = OrderScriptsToUpgradeDatabase(currentSchemaVersion, destination);
bool result = UpdateScripts(orderedScriptsToExecute);
if (result)
{
result = AddUpdatedVersionToDatabase(destination);
result = AddUpdatedVersionToDatabase(DatabaseVersionFor(orderedScriptsToExecute.LastOrDefault()));
}
return result;
}
Expand Down Expand Up @@ -117,44 +114,23 @@ private bool AddToDatabase(SchemaVersion schemaVersion)
}


private IEnumerable<string> OrderScriptsToUpgradeDatabase(SchemaVersion currentSchemaVersion, int destination)
public static string[] OrderScriptsToUpgradeDatabase(SchemaVersion currentSchemaVersion, IEnumerable<string> upgradeFiles)
{
var scriptsToProcess = new List<string>();
foreach (var file in m_UpgradeFiles)
foreach (var file in upgradeFiles)
{
int scriptVersion = DatabaseVersionFor(file);
if (scriptVersion > currentSchemaVersion.DatabaseVersion)
{
Log.InfoFormat("Processing item {0} because it should be processed after {1}", file,
destination);
currentSchemaVersion.DatabaseVersion);
scriptsToProcess.Add(file);
}
}
return scriptsToProcess.OrderBy(DatabaseVersionFor);
return scriptsToProcess.OrderBy(DatabaseVersionFor).ToArray();
}

private int HighestFileNumberPast(SchemaVersion schemaVersion)
{
int highestVersion = schemaVersion.DatabaseVersion;
foreach (var file in m_UpgradeFiles)
{
int numericPart = DatabaseVersionFor(file);
if (numericPart > highestVersion)
{
Log.DebugFormat("File {0} exists as an upgrade to existing version {1}",
file, schemaVersion.DatabaseVersion);
highestVersion = numericPart;
}
else
{
Log.DebugFormat("File {0} has already been processed against this version because it is before {1} (is version {2}",
file, schemaVersion.DatabaseVersion, numericPart);
}
}
return highestVersion;
}

private int DatabaseVersionFor(string file)
public static int DatabaseVersionFor(string file)
{
int numericPart = 0;
string fileName = file.Substring(file.IndexOf('/') + 1);
Expand Down
6 changes: 6 additions & 0 deletions Source/DatabaseUpgrader.sln
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ VisualStudioVersion = 12.0.21005.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DatabaseUpgrader", "DatabaseUpgrader.csproj", "{F6DD288D-8D93-49A3-8B79-02B40C46665E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DatabaseUpgrader.Test", "..\DatabaseUpgrader.Test\DatabaseUpgrader.Test.csproj", "{94300A19-82F6-4E55-AE02-919355EF159D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -15,6 +17,10 @@ Global
{F6DD288D-8D93-49A3-8B79-02B40C46665E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F6DD288D-8D93-49A3-8B79-02B40C46665E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F6DD288D-8D93-49A3-8B79-02B40C46665E}.Release|Any CPU.Build.0 = Release|Any CPU
{94300A19-82F6-4E55-AE02-919355EF159D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{94300A19-82F6-4E55-AE02-919355EF159D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{94300A19-82F6-4E55-AE02-919355EF159D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{94300A19-82F6-4E55-AE02-919355EF159D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
11 changes: 9 additions & 2 deletions Source/Options.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
using CommandLine;
using SqlSchemaMannager.Annotations;
using DatabaseUpgrader.Annotations;

namespace SqlSchemaMannager
namespace DatabaseUpgrader
{
public class Options
{
public static Options Parse(params string[] args)
{
var options = new Options();
var result = Parser.Default.ParseArguments(args, options);
return result ? options : null;
}

[Option(DefaultValue = false,
HelpText =
"If declared, will only check that an upgrade is required and skip the actual upgrade. This is for only-if situations"
Expand Down
26 changes: 10 additions & 16 deletions Source/Program.cs
Original file line number Diff line number Diff line change
@@ -1,35 +1,29 @@
using CommandLine;
using log4net;

namespace SqlSchemaMannager
namespace DatabaseUpgrader
{
internal class Program
{
private static readonly ILog Log = LogManager.GetLogger(typeof (Program));

private static int Main(string[] args)
{
var options = new Options();
var result = Parser.Default.ParseArguments(args, options);
if (result)
var options = Options.Parse(args);

if (options != null)
{
var upgrader = new DatabaseUpgrader.DatabaseUpgrader(options.ConnectionString, options.SoftwareVersion, options.SchemaDirectory);
var upgrader = new DatabaseUpgrader(options.ConnectionString, options.SoftwareVersion, options.SchemaDirectory);
if (options.CheckIfUpgradeRequired)
{
Log.Info("Checking if an upgrade is even needed");
result = upgrader.RequiresUpgrade();
return upgrader.RequiresUpgrade() ? 0 : -1;
}
else
{
Log.Info("Checking if an upgrade is needed, and if so, performing the upgrade");
result = upgrader.UpgradeSchema();
}
}
else
{
Log.ErrorFormat("Could not parse arguments. Check the help text");
Log.Info("Checking if an upgrade is needed, and if so, performing the upgrade");
return upgrader.UpgradeSchema() ? 0 : -2;
}
return result ? 0 : -1;
Log.ErrorFormat("Could not parse arguments. Check the help text");
return -3;
}
}
}
2 changes: 1 addition & 1 deletion Source/Properties/Annotations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
// ReSharper disable MemberCanBeProtected.Global
// ReSharper disable InconsistentNaming

namespace SqlSchemaMannager.Annotations
namespace DatabaseUpgrader.Annotations
{
/// <summary>
/// Indicates that the value of the marked element could be <c>null</c> sometimes,
Expand Down
Binary file added Source/packages/NUnit.2.6.4/NUnit.2.6.4.nupkg
Binary file not shown.
Loading

0 comments on commit 14ee87c

Please sign in to comment.