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

Database Migration feature #37

Merged
merged 17 commits into from
May 24, 2020
Merged
6 changes: 6 additions & 0 deletions Mongo.Migration.Database.Demo/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>
29 changes: 29 additions & 0 deletions Mongo.Migration.Database.Demo/Migrations/M100_AddNewCar.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using Mongo.Migration.Migrations.Database;
using MongoDB.Driver;

namespace Mongo.Migration.Database.Demo.Migrations
{
public class M100_AddNewCar : DatabaseMigration
{
public M100_AddNewCar()
: base("1.0.0")
{
}

public override void Up(IMongoDatabase db)
{
var collection = db.GetCollection<Car>("Car");
collection.InsertOne(new Car
{
Doors = 123,
Type = "AddedInMigration"
});
}

public override void Down(IMongoDatabase db)
{
var collection = db.GetCollection<Car>("Car");
collection.DeleteOne(Builders<Car>.Filter.Eq(c => c.Type, "AddedInMigration"));
}
}
}
29 changes: 29 additions & 0 deletions Mongo.Migration.Database.Demo/Migrations/M200_UpdateNewCar.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using Mongo.Migration.Migrations.Database;
using MongoDB.Driver;

namespace Mongo.Migration.Database.Demo.Migrations
{
public class M200_UpdateNewCar : DatabaseMigration
{
public M200_UpdateNewCar()
: base("2.0.0")
{
}

public override void Up(IMongoDatabase db)
{
var collection = db.GetCollection<Car>("Car");
var filter = Builders<Car>.Filter.Eq(c => c.Type, "AddedInMigration");
var update = Builders<Car>.Update.Set(c => c.Doors, 222);
collection.UpdateOne(filter, update);
}

public override void Down(IMongoDatabase db)
{
var collection = db.GetCollection<Car>("Car");
var filter = Builders<Car>.Filter.Eq(c => c.Type, "AddedInMigration");
var update = Builders<Car>.Update.Set(c => c.Doors, 123);
collection.UpdateOne(filter, update);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using Mongo.Migration.Migrations.Database;
using MongoDB.Driver;

namespace Mongo.Migration.Database.Demo.Migrations
{
public class M300_AddSparePartsCollection : DatabaseMigration
{
public M300_AddSparePartsCollection()
: base("3.0.0")
{
}

public override void Up(IMongoDatabase db)
{
db.CreateCollection(nameof(SparePart));
}

public override void Down(IMongoDatabase db)
{
db.DropCollection(nameof(SparePart));
}
}
}
13 changes: 13 additions & 0 deletions Mongo.Migration.Database.Demo/Models/Car.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using MongoDB.Bson;

namespace Mongo.Migration.Database.Demo
{
public class Car
{
public ObjectId Id { get; set; }

public string Type { get; set; }

public int Doors { get; set; }
}
}
13 changes: 13 additions & 0 deletions Mongo.Migration.Database.Demo/Models/SparePart.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using MongoDB.Bson;

namespace Mongo.Migration.Database.Demo
{
public class SparePart
{
public ObjectId Id { get; set; }

public string Title { get; set; }

public int Count { get; set; }
}
}
98 changes: 98 additions & 0 deletions Mongo.Migration.Database.Demo/Mongo.Migration.Database.Demo.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" 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>{51655B29-4A0C-4AF3-82E7-8F8332E6BE94}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>Mongo.Migration.Database.Demo</RootNamespace>
<AssemblyName>Mongo.Migration.Database.Demo</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<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' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="DnsClient, Version=1.2.0.0, Culture=neutral, PublicKeyToken=4574bb5573c51424, processorArchitecture=MSIL">
<HintPath>..\packages\DnsClient.1.2.0\lib\net471\DnsClient.dll</HintPath>
</Reference>
<Reference Include="LightInject, Version=6.2.1.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\LightInject.6.2.1\lib\net46\LightInject.dll</HintPath>
</Reference>
<Reference Include="Mongo2Go, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Mongo2Go.2.2.11\lib\netstandard1.6\Mongo2Go.dll</HintPath>
</Reference>
<Reference Include="MongoDB.Bson, Version=2.8.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MongoDB.Bson.2.8.0\lib\net452\MongoDB.Bson.dll</HintPath>
</Reference>
<Reference Include="MongoDB.Driver, Version=2.8.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MongoDB.Driver.2.8.0\lib\net452\MongoDB.Driver.dll</HintPath>
</Reference>
<Reference Include="MongoDB.Driver.Core, Version=2.8.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MongoDB.Driver.Core.2.8.0\lib\net452\MongoDB.Driver.Core.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Buffers, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Buffers.4.4.0\lib\netstandard2.0\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="System.Core" />
<Reference Include="System.IO" />
<Reference Include="System.Linq.Expressions" />
<Reference Include="System.Runtime" />
<Reference Include="System.Runtime.InteropServices.RuntimeInformation, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
<Private>True</Private>
<Private>True</Private>
</Reference>
<Reference Include="System.Threading.Tasks" />
<Reference Include="System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.ValueTuple.4.5.0\lib\net47\System.ValueTuple.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Migrations\M100_AddNewCar.cs" />
<Compile Include="Migrations\M300_AddSparePartsCollection.cs" />
<Compile Include="Migrations\M200_UpdateNewCar.cs" />
<Compile Include="Models\SparePart.cs" />
<Compile Include="Models\Car.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Mongo.Migration\Mongo.Migration.csproj">
<Project>{8dffd615-1e1a-4bed-8a96-caf4c3637e81}</Project>
<Name>Mongo.Migration</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
58 changes: 58 additions & 0 deletions Mongo.Migration.Database.Demo/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
using Mongo.Migration.Migrations.Adapters;
using Mongo.Migration.Startup;
using Mongo.Migration.Startup.Static;
using Mongo2Go;
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Linq;

namespace Mongo.Migration.Database.Demo
{
class Program
{
static void Main(string[] args)
{
// Init MongoDB
var runner = MongoDbRunner.StartForDebugging();
var client = new MongoClient(runner.ConnectionString);

client.GetDatabase("TestCars").DropCollection("Car");
client.GetDatabase("TestCars").DropCollection("_migrations");
client.GetDatabase("TestCars").DropCollection(nameof(SparePart));

// Init MongoMigration
MongoMigrationClient.Initialize(
client,
new MongoMigrationSettings()
{
ConnectionString = runner.ConnectionString,
Database = "TestCars"
},
new LightInjectAdapter(new LightInject.ServiceContainer()));

Console.WriteLine("Apply database migrations: ");
Console.WriteLine("\n");

var migrationsCollection = client.GetDatabase("TestCars").GetCollection<BsonDocument>("_migrations");
var migrations = migrationsCollection.FindAsync(_ => true).Result.ToListAsync().Result;
migrations.ForEach(r => Console.WriteLine(r + "\n"));

var carsCollection = client.GetDatabase("TestCars").GetCollection<Car>("Car");
var addedInMigration = carsCollection.FindAsync(Builders<Car>.Filter.Eq(c => c.Type, "AddedInMigration")).Result.FirstOrDefault();

Console.WriteLine("New Car was added and updated in database migrations: ");
Console.WriteLine(addedInMigration?.ToBsonDocument() + "\n");

Console.WriteLine("New collection was added in database: ");
Console.WriteLine(nameof(SparePart) + "\n");

Console.WriteLine("\n");
Console.WriteLine("Press any Key to exit...");
Console.Read();

client.GetDatabase("TestCars").DropCollection("Car");
client.GetDatabase("TestCars").DropCollection("_migrations");
}
}
}
36 changes: 36 additions & 0 deletions Mongo.Migration.Database.Demo/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("Mongo.Migration.Database.Demo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Mongo.Migration.Database.Demo")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[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("51655b29-4a0c-4af3-82e7-8f8332e6be94")]

// 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")]
12 changes: 12 additions & 0 deletions Mongo.Migration.Database.Demo/packages.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="DnsClient" version="1.2.0" targetFramework="net472" />
<package id="LightInject" version="6.2.1" targetFramework="net472" />
<package id="Mongo2Go" version="2.2.11" targetFramework="net472" />
<package id="MongoDB.Bson" version="2.8.0" targetFramework="net472" />
<package id="MongoDB.Driver" version="2.8.0" targetFramework="net472" />
<package id="MongoDB.Driver.Core" version="2.8.0" targetFramework="net472" />
<package id="System.Buffers" version="4.4.0" targetFramework="net472" />
<package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="net472" />
<package id="System.ValueTuple" version="4.5.0" targetFramework="net472" />
</packages>
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
using System;
using Mongo.Migration.Demo.Model;
using Mongo.Migration.Migrations;
using Mongo.Migration.Migrations.Document;
using Mongo.Migration.Services;
using MongoDB.Bson;

namespace Mongo.Migration.Demo.MongoMigrations.Cars.M00
{
public class M001_RenameDorsToDoors : Migration<Car>
public class M001_RenameDorsToDoors : DocumentMigration<Car>
{
private readonly IVersionService _service;
private readonly IDocumentVersionService _service;

public M001_RenameDorsToDoors(IVersionService service)
public M001_RenameDorsToDoors(IDocumentVersionService service)
: base("0.0.1")
{
_service = service;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
using System;
using Mongo.Migration.Demo.Model;
using Mongo.Migration.Migrations;
using Mongo.Migration.Migrations.Document;
using MongoDB.Bson;

namespace Mongo.Migration.Demo.MongoMigrations.Cars.M01
{
public class M011_RemoveUnnecessaryField : Migration<Car>
public class M011_RemoveUnnecessaryField : DocumentMigration<Car>
{
public M011_RemoveUnnecessaryField()
: base("0.1.1")
Expand Down
8 changes: 4 additions & 4 deletions Mongo.Migration.Demo/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ private static void Main(string[] args)
client.GetDatabase("TestCars").GetCollection<BsonDocument>("Car");

bsonCollection.InsertManyAsync(cars).Wait();


// Init MongoMigration
MongoMigrationClient.Initialize(client, new LightInjectAdapter(new LightInject.ServiceContainer()));

Expand All @@ -51,13 +51,13 @@ private static void Main(string[] args)
// Create new car and add it with current version number into MongoDB
var id = ObjectId.GenerateNewId();
var type = "Test" + id;
var car = new Car {Doors = 2, Type = type};
var car = new Car { Doors = 2, Type = type };

typedCollection.InsertOne(car);
var test = typedCollection.FindAsync(Builders<Car>.Filter.Eq(c => c.Type, type)).Result.Single();

var aggregate = typedCollection.Aggregate()
.Match(new BsonDocument {{"Dors", 3}});
.Match(new BsonDocument { { "Dors", 3 } });
var results = aggregate.ToListAsync().Result;

Console.WriteLine("New Car was created with version: " + test.Version);
Expand Down
Loading