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

Add migrations has-pending-model-changes Command #31164

Merged
merged 2 commits into from
Jul 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/EFCore.Design/Design/Internal/MigrationsOperations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Migrations.Internal;

namespace Microsoft.EntityFrameworkCore.Design.Internal;

Expand Down Expand Up @@ -242,6 +243,26 @@ public virtual MigrationFiles RemoveMigration(
return files;
}

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual void HasPendingModelChanges(string? contextType)
{
using var context = _contextOperations.CreateContext(contextType);

var hasPendingModelChanges = context.Database.HasPendingModelChanges();

if (hasPendingModelChanges)
{
throw new OperationException(DesignStrings.PendingModelChanges);
}

_reporter.WriteInformation(DesignStrings.NoPendingModelChanges);
}

private static void EnsureServices(IServiceProvider services)
{
var migrator = services.GetService<IMigrator>();
Expand Down
34 changes: 34 additions & 0 deletions src/EFCore.Design/Design/OperationExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -683,6 +683,40 @@ public ScriptDbContext(
private string ScriptDbContextImpl(string? contextType)
=> ContextOperations.ScriptDbContext(contextType);

/// <summary>
/// Represents an operation to check if there are any pending migrations.
/// </summary>
public class HasPendingModelChanges : OperationBase
{
/// <summary>
/// Initializes a new instance of the <see cref="HasPendingModelChanges" /> class.
/// </summary>
/// <remarks>
/// <para>The arguments supported by <paramref name="args" /> are:</para>
/// <para><c>contextType</c>--The <see cref="DbContext" /> to use.</para>
/// </remarks>
/// <param name="executor">The operation executor.</param>
/// <param name="resultHandler">The <see cref="IOperationResultHandler" />.</param>
/// <param name="args">The operation arguments.</param>
public HasPendingModelChanges(
OperationExecutor executor,
IOperationResultHandler resultHandler,
IDictionary args)
: base(resultHandler)
{
Check.NotNull(executor, nameof(executor));
Check.NotNull(args, nameof(args));

var contextType = (string?)args["contextType"];

Execute(() => executor.HasPendingModelChangesImpl(contextType));
}
}

private void HasPendingModelChangesImpl(string? contextType)
=> MigrationsOperations.HasPendingModelChanges(contextType);


/// <summary>
/// Represents an operation.
/// </summary>
Expand Down
12 changes: 12 additions & 0 deletions src/EFCore.Design/Properties/DesignStrings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions src/EFCore.Design/Properties/DesignStrings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,9 @@ Change your target project to the migrations project by using the Package Manage
<data name="NonRelationalProvider" xml:space="preserve">
<value>The provider '{provider}' is not a Relational provider and therefore cannot be used with Migrations.</value>
</data>
<data name="NoPendingModelChanges" xml:space="preserve">
<value>No changes have been made to the model since the last migration.</value>
</data>
<data name="NoReferencedServices" xml:space="preserve">
<value>No referenced design-time services were found.</value>
</data>
Expand All @@ -350,6 +353,9 @@ Change your target project to the migrations project by using the Package Manage
<data name="NotExistDatabase" xml:space="preserve">
<value>Database '{name}' did not exist, no action was taken.</value>
</data>
<data name="PendingModelChanges" xml:space="preserve">
<value>Changes have been made to the model since the last migration. Add a new migration.</value>
</data>
<data name="PrefixDescription" xml:space="preserve">
<value>Prefix output with level.</value>
</data>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -952,6 +952,39 @@ public static bool IsRelational(this DatabaseFacade databaseFacade)
=> ((IDatabaseFacadeDependenciesAccessor)databaseFacade)
.Context.GetService<IDbContextOptions>().Extensions.OfType<RelationalOptionsExtension>().Any();

/// <summary>
/// Returns <see langword="true" /> if the model has pending changes to be applied.
/// </summary>
/// <param name="databaseFacade">The facade from <see cref="DbContext.Database"/>.</param>
/// <returns>
/// <see langword="true"/> if the database model has pending changes
/// and a new migration has to be added.
/// </returns>
public static bool HasPendingModelChanges(this DatabaseFacade databaseFacade)
{
var modelDiffer = databaseFacade.GetRelationalService<IMigrationsModelDiffer>();
var migrationsAssembly = databaseFacade.GetRelationalService<IMigrationsAssembly>();

var modelInitializer = databaseFacade.GetRelationalService<IModelRuntimeInitializer>();

var snapshotModel = migrationsAssembly.ModelSnapshot?.Model;
if (snapshotModel is IMutableModel mutableModel)
{
snapshotModel = mutableModel.FinalizeModel();
}

if (snapshotModel is not null)
{
snapshotModel = modelInitializer.Initialize(snapshotModel);
}

var designTimeModel = databaseFacade.GetRelationalService<IDesignTimeModel>();

return modelDiffer.HasDifferences(
snapshotModel?.GetRelationalModel(),
designTimeModel.Model.GetRelationalModel());
}

private static IRelationalDatabaseFacadeDependencies GetFacadeDependencies(DatabaseFacade databaseFacade)
{
var dependencies = ((IDatabaseFacadeDependenciesAccessor)databaseFacade).Dependencies;
Expand Down
7 changes: 7 additions & 0 deletions src/dotnet-ef/Properties/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion src/dotnet-ef/Properties/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,9 @@
<data name="MigrationsDescription" xml:space="preserve">
<value>Commands to manage migrations.</value>
</data>
<data name="MigrationsHasPendingModelChangesDescription" xml:space="preserve">
<value>Checks if any changes have been made to the model since the last migration.</value>
</data>
<data name="MigrationsListDescription" xml:space="preserve">
<value>Lists available migrations.</value>
</data>
Expand Down Expand Up @@ -345,4 +348,4 @@
<data name="WritingFile" xml:space="preserve">
<value>Writing '{file}'...</value>
</data>
</root>
</root>
1 change: 1 addition & 0 deletions src/ef/Commands/MigrationsCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public override void Configure(CommandLineApplication command)

command.Command("add", new MigrationsAddCommand().Configure);
command.Command("bundle", new MigrationsBundleCommand().Configure);
command.Command("has-pending-model-changes", new MigrationsHasPendingModelChangesCommand().Configure);
command.Command("list", new MigrationsListCommand().Configure);
command.Command("remove", new MigrationsRemoveCommand().Configure);
command.Command("script", new MigrationsScriptCommand().Configure);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.EntityFrameworkCore.Tools.Properties;

namespace Microsoft.EntityFrameworkCore.Tools.Commands;

internal partial class MigrationsHasPendingModelChangesCommand : ContextCommandBase
{
public override void Configure(CommandLineApplication command)
{
command.Description = Resources.MigrationsHasPendingModelChangesDescription;

base.Configure(command);
}
}
16 changes: 16 additions & 0 deletions src/ef/Commands/MigrationsHasPendingModelChangesCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.EntityFrameworkCore.Tools.Commands;

internal partial class MigrationsHasPendingModelChangesCommand
{
protected override int Execute(string[] args)
{
using var executor = CreateExecutor(args);

executor.HasPendingModelChanges(Context!.Value());

return base.Execute(args);
}
}
1 change: 1 addition & 0 deletions src/ef/IOperationExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,5 @@ IDictionary ScaffoldContext(
string ScriptMigration(string? fromMigration, string? toMigration, bool idempotent, bool noTransactions, string? contextType);

string ScriptDbContext(string? contextType);
void HasPendingModelChanges(string? contextType);
}
5 changes: 5 additions & 0 deletions src/ef/OperationExecutorBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -206,4 +206,9 @@ public string ScriptDbContext(string? contextType)
=> InvokeOperation<string>(
"ScriptDbContext",
new Dictionary<string, object?> { ["contextType"] = contextType });

public void HasPendingModelChanges(string? contextType)
=> InvokeOperation<string>(
"HasPendingModelChanges",
new Dictionary<string, object?> { ["contextType"] = contextType });
}
7 changes: 7 additions & 0 deletions src/ef/Properties/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion src/ef/Properties/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,9 @@
<data name="MigrationsDescription" xml:space="preserve">
<value>Commands to manage migrations.</value>
</data>
<data name="MigrationsHasPendingModelChangesDescription" xml:space="preserve">
<value>Checks if any changes have been made to the model since the last migration.</value>
</data>
<data name="MigrationsListDescription" xml:space="preserve">
<value>Lists available migrations.</value>
</data>
Expand Down Expand Up @@ -402,4 +405,4 @@
<data name="WritingFile" xml:space="preserve">
<value>Writing '{file}'...</value>
</data>
</root>
</root>
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ public void GetMigrations_works()
private class FakeIMigrationsAssembly : IMigrationsAssembly
{
public IReadOnlyDictionary<string, TypeInfo> Migrations { get; set; }
public ModelSnapshot ModelSnapshot { get; }
public ModelSnapshot ModelSnapshot { get; set; }
public Assembly Assembly { get; }

public string FindMigrationId(string nameOrId)
Expand Down Expand Up @@ -249,6 +249,86 @@ public async Task GetAppliedMigrations_works(bool async)
: context.Database.GetAppliedMigrations());
}

[ConditionalFact]
public void HasPendingModelChanges_has_no_migrations_has_dbcontext_changes_returns_true()
{
// This project has NO existing migrations right now but does have information in the DbContext
var migrationsAssembly = new FakeIMigrationsAssembly
{
ModelSnapshot = null,
Migrations = new Dictionary<string, TypeInfo>(),
};

var testHelper = FakeRelationalTestHelpers.Instance;

var contextOptions = testHelper.CreateOptions(
testHelper.CreateServiceProvider(new ServiceCollection().AddSingleton<IMigrationsAssembly>(migrationsAssembly)));

var testContext = new TestDbContext(contextOptions);

Assert.True(testContext.Database.HasPendingModelChanges());
}

[ConditionalFact]
public void HasPendingModelChanges_has_migrations_and_no_new_context_changes_returns_false()
{
var fakeModelSnapshot = new FakeModelSnapshot(builder =>
{
builder.Entity("Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensionsTests.TestDbContext.Simple", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("default_int_mapping");

b.HasKey("Id");

b.ToTable("Simples");
});
});
var migrationsAssembly = new FakeIMigrationsAssembly
{
ModelSnapshot = fakeModelSnapshot,
Migrations = new Dictionary<string, TypeInfo>(),
};

var testHelper = FakeRelationalTestHelpers.Instance;

var contextOptions = testHelper.CreateOptions(
testHelper.CreateServiceProvider(new ServiceCollection().AddSingleton<IMigrationsAssembly>(migrationsAssembly)));

var testContext = new TestDbContext(contextOptions);

Assert.False(testContext.Database.HasPendingModelChanges());
}

private class TestDbContext : DbContext
{
public TestDbContext(DbContextOptions options) : base(options)
{ }
public DbSet<Simple> Simples { get; set; }

public class Simple
{
public int Id { get; set; }
}

}

private class FakeModelSnapshot : ModelSnapshot
{
private readonly Action<ModelBuilder> _buildModel;

public FakeModelSnapshot(Action<ModelBuilder> buildModel)
{
_buildModel = buildModel;
}
protected override void BuildModel(ModelBuilder modelBuilder)
{
_buildModel(modelBuilder);
}
}


private class FakeHistoryRepository : IHistoryRepository
{
public List<HistoryRow> AppliedMigrations { get; set; }
Expand Down