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

NuGet Commands: Drop-Database #4907

Closed
wants to merge 3 commits into from
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,18 @@ public DbContextOperations(
_runtimeServices = startup.ConfigureServices();
}

public virtual void DropDatabase([CanBeNull] string contextType, [NotNull] Func<string, string, bool> confirmCheck)
{
using (var context = CreateContext(contextType))
{
var connection = context.Database.GetDbConnection();
if (confirmCheck(connection.Database, connection.DataSource))
{
context.Database.EnsureDeleted();
}
}
}

public virtual DbContext CreateContext([CanBeNull] string contextType)
=> CreateContext(FindContextType(contextType).Value);

Expand Down Expand Up @@ -201,5 +213,6 @@ private static IDictionary<Type, Func<DbContext>> FilterTypes(
|| string.Equals(t.Key.AssemblyQualifiedName, name, comparisonType))
.ToDictionary(t => t.Key, t => t.Value);
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,27 @@ private IEnumerable<string> ReverseEngineerImpl(
}
}

public class DropDatabase : OperationBase
{
public DropDatabase(
[NotNull] OperationExecutor executor,
[NotNull] object resultHandler,
[NotNull] IDictionary args)
: base(resultHandler)
{
Check.NotNull(executor, nameof(executor));
Check.NotNull(args, nameof(args));

var contextType = (string)args["contextType"];
var confirmCheck = (Func<string, string, bool>)args["confirmCheck"];

Execute(() => executor.DropDatabaseImpl(contextType, confirmCheck));
}
}

private void DropDatabaseImpl(string contextType, Func<string, string, bool> confirmCheck)
=> _contextOperations.Value.DropDatabase(contextType, confirmCheck);

public abstract class OperationBase : MarshalByRefObject
{
private readonly IOperationResultHandler _resultHandler;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@
'Script-Migration',
'Remove-Migration',
'Enable-Migrations',
'Scaffold-DbContext'
'Scaffold-DbContext',
'Drop-Database'
)

# Cmdlets to export from this module
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ function Use-DbContext {
if ($candidates.length -gt 1 -and $exactMatch -is "String") {
$candidates = $exactMatch
}

if ($candidates.length -lt 1) {
throw "No DbContext named '$Context' was found"
} elseif ($candidates.length -gt 1 -and !($candidates -is "String")) {
Expand Down Expand Up @@ -498,7 +498,7 @@ function Scaffold-DbContext {

$artifacts | %{ $dteProject.ProjectItems.AddFromFile($_) | Out-Null }
$DTE.ItemOperations.OpenFile($artifacts[0]) | Out-Null

ShowConsole
}
}
Expand All @@ -512,6 +512,71 @@ function Enable-Migrations {
Write-Warning 'Enable-Migrations is obsolete. Use Add-Migration to start using Migrations.'
}

#
# Drop-Database
#

Register-TabExpansion Drop-Database @{
Context = { param ($tabExpansionContext) GetContextTypes $tabExpansionContext.Project $tabExpansionContext.StartupProject $tabExpansionContext.Environment }
Project = { GetProjects }
StartupProject = { GetProjects }
}

<#
.SYNOPSIS
Drops the database.

.DESCRIPTION
Drops the database.

.PARAMETER Context
Specifies the DbContext to use. If omitted, the default DbContext is used.

.PARAMETER Project
Specifies the project to use. If omitted, the default project is used.

.PARAMETER StartupProject
Specifies the startup project to use. If omitted, the solution's startup project is used.

.PARAMETER Environment
Specifies the environment to use. If omitted, "Development" is used.

.LINK
about_EntityFramework
#>
function Drop-Database {
[CmdletBinding(ConfirmImpact = 'High', SupportsShouldProcess = $true, PositionalBinding = $false)]
param (
[string] $Context,
[string] $Project,
[string] $StartupProject,
[string] $Environment)

$values = ProcessCommonParameters $StartupProject $Project $Context
$dteStartupProject = $values.StartupProject
$dteProject = $values.Project
$contextTypeName = $values.ContextTypeName

if (IsDotNetProject $dteProject) {
# TODO: Show database information
if ($PSCmdlet.ShouldProcess('the database')) {
$options = ProcessCommonDotnetParameters $dteProject $dteStartupProject $Environment $contextTypeName
$options += "--force"
InvokeDotNetEf $dteProject database drop @options | Out-Null
}
} else {
InvokeOperation $dteStartupProject $Environment $dteProject DropDatabase @{
contextType = $contextTypeName
# TODO: Get database information then prompt before invoking DropDatabase
confirmCheck = [Func[string, string, bool]]{
param ($database, $dataSource)

return $PSCmdlet.ShouldProcess("$database on $dataSource")
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bad news. This results in Cannot serialize delegates over unmanaged function pointers, dynamic methods or methods outside the delegate creator's assembly. 😞

}
}
}

#
# (Private Helpers)
#
Expand All @@ -535,7 +600,7 @@ function GetContextTypes($projectName, $startupProjectName, $environment) {
$project = $values.Project

if (IsDotNetProject $startupProject) {
$types = InvokeDotNetEf $startupProject -Json dbcontext list
$types = InvokeDotNetEf $startupProject -Json dbcontext list
return $types | %{ $_.fullName }
} else {
$contextTypes = InvokeOperation $startupProject $environment $project GetContextTypes -skipBuild
Expand Down Expand Up @@ -640,7 +705,7 @@ function InvokeDotNetEf($project, [switch] $Json) {
$arguments += "--json"
} else {
# TODO better json output parsing so we don't need to suppress verbose output
$arguments = ,"--verbose" + $arguments
$arguments = ,"--verbose" + $arguments
}
$command = "ef $($arguments -join ' ')"
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ LONG DESCRIPTION
-------------------------- ---------------------------------------------------
Add-Migration Adds a new migration.

Drop-Database Drops the database.

Remove-Migration Removes the last migration.

Scaffold-DbContext Scaffolds a DbContext and entity type classes for a specified database.
Expand All @@ -34,6 +36,7 @@ LONG DESCRIPTION

SEE ALSO
Add-Migration
Drop-Database
Remove-Migration
Scaffold-DbContext
Script-Migration
Expand Down
1 change: 1 addition & 0 deletions src/dotnet-ef/DatabaseCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public static void Configure([NotNull] CommandLineApplication command)
command.VerboseOption();

command.Command("update", DatabaseUpdateCommand.Configure);
command.Command("drop", DatabaseDropCommand.Configure);

command.OnExecute(() => command.ShowHelp());
}
Expand Down
59 changes: 59 additions & 0 deletions src/dotnet-ef/DatabaseDropCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using JetBrains.Annotations;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.Extensions.CommandLineUtils;

namespace Microsoft.EntityFrameworkCore.Commands
{
public class DatabaseDropCommand
{
public static void Configure([NotNull] CommandLineApplication command)
{
command.Description = "Drop the database for specific environment";

var startupProject = command.Option(
"-s|--startup-project <project>",
"The startup project to use. If omitted, the current project is used.");
var environment = command.Option(
"-e|--environment <environment>",
"The environment to use. If omitted, \"Development\" is used.");
var context = command.Option(
"-c|--context <context>",
"The DbContext to use. If omitted, the default DbContext is used");

var force = command.Option(
"-f|--force",
"Force confirm message. If omitted, confirm message not used");
command.HelpOption();
command.VerboseOption();

command.OnExecute(
() => Execute(context.Value(), startupProject.Value(), environment.Value(), force.HasValue()));
}

private static int Execute(string context, string startupProject, string environment, bool isForced)
{
new OperationExecutor(startupProject, environment)
.DropDatabase(
context,
(database, dataSource) =>
{
if (isForced)
{
return true;
}

Reporter.Output.WriteLine(
$"Are you sure you want to drop the database '{database}' on server '{dataSource}'? (y/N)");
var readedKey = Console.ReadKey().KeyChar;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't we skip read altogether this if --force was used?


return (readedKey == 'y') || (readedKey == 'Y');
});

return 0;
}
}
}
3 changes: 3 additions & 0 deletions src/dotnet-ef/OperationExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,9 @@ public OperationExecutor([CanBeNull] string startupProject, [CanBeNull] string e
rootNamespace));
}

public virtual void DropDatabase([CanBeNull] string contextName, [NotNull] Func<string, string, bool> confirmCheck)
=> _contextOperations.Value.DropDatabase(contextName, confirmCheck);

public virtual MigrationFiles AddMigration(
[NotNull] string name,
[CanBeNull] string outputDir,
Expand Down